コード例 #1
0
        public void CrossLanguageException()
        {
            var csharpTree = CSharpSyntaxTree.ParseText("class A { }");
            var vbTree     = VisualBasicSyntaxTree.ParseText(
                @"Class A
End Class
"
                );
            var csc =
                CSharpCompilation.Create(
                    "CS",
                    new[] { csharpTree },
                    new MetadataReference[] { TestBase.MscorlibRef }
                    ) as Compilation;
            var Ac = csc.GlobalNamespace.GetMembers("A").First() as INamedTypeSymbol;

            var vbc =
                VisualBasicCompilation.Create(
                    "VB",
                    new[] { vbTree },
                    new MetadataReference[] { TestBase.MscorlibRef }
                    ) as Compilation;
            var Av = vbc.GlobalNamespace.GetMembers("A").First() as INamedTypeSymbol;

            Assert.Throws <ArgumentException>(() => csc.IsSymbolAccessibleWithin(Av, Av));
            Assert.Throws <ArgumentException>(() => csc.IsSymbolAccessibleWithin(Av, Ac));
            Assert.Throws <ArgumentException>(() => csc.IsSymbolAccessibleWithin(Ac, Av));
            Assert.Throws <ArgumentException>(() => csc.IsSymbolAccessibleWithin(Ac, Ac, Av));

            Assert.Throws <ArgumentException>(() => vbc.IsSymbolAccessibleWithin(Ac, Ac));
            Assert.Throws <ArgumentException>(() => vbc.IsSymbolAccessibleWithin(Ac, Av));
            Assert.Throws <ArgumentException>(() => vbc.IsSymbolAccessibleWithin(Av, Ac));
            Assert.Throws <ArgumentException>(() => vbc.IsSymbolAccessibleWithin(Av, Av, Ac));
        }
コード例 #2
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<MethodDeclarationSyntax>() //#2
            //            .Select(mds => //#3
            //            new
            //            {
            //                Name = mds.Identifier.ValueText,
            //                Switches = mds.Body
            //            .DescendantNodes()
            //            .OfType<SwitchStatementSyntax>()
            //            .Select(st =>
            //            new
            //            {
            //                SwitchStatement = st.ToFullString(),
            //                52
            ////How many switch sections are there
            ////in the switch statement.
            //                Sections = st.Sections.Count
            //            })
            //.OrderByDescending(st => st.Sections)//#4
            //            })
            //.Dump("Switch statements per functions");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #3
0
        protected void EachPositionBetweenStarsShouldProduceExpected(string code, ParserOutput expected, bool isCSharp, Profile profileOverload)
        {
            this.EnsureTwoStars(code);

            var(startPos, endPos, actualCode) = this.GetCodeAndCursorRange(code);

            var syntaxTree = isCSharp ? CSharpSyntaxTree.ParseText(actualCode)
                                      : VisualBasicSyntaxTree.ParseText(actualCode);

            Assert.IsNotNull(syntaxTree);

            var semModel = isCSharp ? CSharpCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true)
                                    : VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true);

            var positionsTested = 0;

            for (var pos = startPos; pos < endPos; pos++)
            {
                var indent = new TestVisualStudioAbstraction().XamlIndent;
                var parser = isCSharp ? new CSharpParser(DefaultTestLogger.Create(), indent, profileOverload) as IDocumentParser
                                      : new VisualBasicParser(DefaultTestLogger.Create(), indent, profileOverload);

                var actual = parser.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos);

                Assert.AreEqual(expected.OutputType, actual.OutputType, $"Failure at {pos} ({startPos}-{endPos})");
                Assert.AreEqual(expected.Name, actual.Name, $"Failure at {pos} ({startPos}-{endPos})");
                StringAssert.AreEqual(expected.Output, actual.Output, $"Failure at {pos} ({startPos}-{endPos})");

                positionsTested += 1;
            }

            this.TestContext.WriteLine($"{positionsTested} different positions tested.");
        }
コード例 #4
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb   = new StringBuilder();
            var           tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            var classes = tree
            //            .GetRoot()
            //            .DescendantNodes()
            //            .OfType<ClassDeclarationSyntax>()//#1
            //            .Select(cds => new //#2
            //{
            //    //Name of the class
            //    Name = cds.Identifier.ValueText,
            //    //Number of members of the class
            //    MemberCount = cds.Members.Count,
            //    //Number of public properties
            //    PublicPropertyCount = cds.Members
            //            .OfType<PropertyDeclarationSyntax>()
            //            .Count(pds => pds.Modifiers
            //            .Any(m => m.ValueText == "public"))
            //            })
            //            .Where(cds => cds.MemberCount == cds.PublicPropertyCount)//#3
            //            .Dump("Data Classes");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #5
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .Where(t => t.Kind() == SyntaxKind.MethodDeclaration)
            //            .Cast<MethodDeclarationSyntax>()
            //            .Select(t =>
            //           new
            //            {
            //                Name = t.Identifier.ValueText, //#1
            //    Returns = t.Body.DescendantTokens()
            //           .Count(st => st.Kind() == SyntaxKind.ReturnKeyword)//#2
            //})
            //            //Method should ideally have one return statement
            //            //That way it is easier to refactor them later.
            //            .Where(t => t.Returns > 1).Dump("Multiple return
            //            statements");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #6
0
ファイル: AvoidBoxing.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //#1
            //                                            //There are couple of boxing calls in the provided code sample
            //                                            //These should have been avoided
            //                                            //x - Int
            //                                            //o -> object
            //var objects =
            //tree.GetRoot()
            //.DescendantNodes().OfType<VariableDeclarationSyntax>()//#2
            //.SelectMany(aes => aes.Variables.Select(v =>
            //new //#3
            //{
            //    Type = aes.GetFirstToken().ValueText,
            //    Name = v.Identifier.ValueText,
            //    Value = aes.GetLastToken().ValueText
            //})
            //);
            //var defaulters = objects //#4
            //.Where(aes => aes.Type == "object"
            //&& objects.FirstOrDefault(d => d.Name == aes.Value
            //&& d.Type != "object") != null)
            //.Dump("Boxing calls");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
        private static PortableExecutableReference GetInternalLibraryMetadataReference()
        {
            var syntaxTree = VisualBasicSyntaxTree.ParseText($@"Imports System.Runtime.CompilerServices

<Assembly: InternalsVisibleTo(""{TestProjectName}"")>
Namespace ExternalNamespace
    Public Class InternalFoo
        Friend Overridable Function Bar() As Integer
            Return 1
        End Function
    End Class
End Namespace
");

            var references         = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) };
            var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation        = VisualBasicCompilation.Create("Internal", new[] { syntaxTree }, references, compilationOptions);

            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);

                if (result.Success == false)
                {
                    var errors = result.Diagnostics.Where(diag => diag.IsWarningAsError || diag.Severity == DiagnosticSeverity.Error);
                    throw new InvalidOperationException($"Internal library compilation failed: {string.Join(",", errors)}");
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(MetadataReference.CreateFromStream(ms));
            }
        }
コード例 #8
0
        public static T Run <T>(string code)
        {
            var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var tree     = VisualBasicSyntaxTree.ParseText(PlaceCodeInsideBlock(code));
            var options  = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            var comp = VisualBasicCompilation.Create("InMemoryAssembly")
                       .WithOptions(options)
                       .AddReferences(mscorlib)
                       .AddSyntaxTrees(tree);

            using (var stream = new MemoryStream())
            {
                var response = comp.Emit(stream);
                if (response.Success)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(stream.ToArray());

                    Type type = assembly.GetType("Container");
                    return((T)type.InvokeMember("Execute", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null));
                }
            }

            return(default(T));
        }
コード例 #9
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<ClassDeclarationSyntax>()
            //            .Select(cds =>
            //           new
            //            {
            //                ClassName = cds.Identifier.ValueText,//#1
            //    Methods = cds.Members.OfType<MethodDeclarationSyntax>()
            //           .Select(mds => new {
            //                MethodName = mds.Identifier.ValueText//#2
            //          ,
            //                Parameters = mds.ParameterList.Parameters.Count//#3
            //})
            //            }).Dump();

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #10
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<ClassDeclarationSyntax>()//#2
            //            .Select(cds => new //#3
            //{
            //                ClassName = cds.Identifier.ValueText,
            //                Properties = cds.Members
            //            .OfType<PropertyDeclarationSyntax>()
            //            .Select(pds => new //#4
            //{
            //                PropertyName = pds.Identifier.ValueText,
            //                PropertyType = pds.Type.ToFullString()
            //            .Trim()
            //            })
            //            })
            //.Where(cds => cds.Properties //#5
            //.Any(p => p.PropertyType.Contains("[")))
            //.Dump("Properties returning an array");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #11
0
ファイル: LotsOfMethodOverloads.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //        tree.GetRoot()
            //        .DescendantNodes()
            //        .Where(t => t.Kind == SyntaxKind.ClassDeclaration)
            //        .Cast<ClassDeclarationSyntax>()
            //        .Select(cds =>
            //       new
            //        {
            //            ClassName = cds.Identifier.ValueText,//#1
            //Methods = cds.Members.OfType < MethodDeclarationSy
            //       ntax > ()//#2
            //       .Select(mds => mds.Identifier.ValueText)
            //        })
            //        .Select(cds => new {
            //            ClassName = cds.ClassName,
            //            Overloads = cds.Methods
            //       .ToLookup(m => m)
            //       .ToDictionary(m => m.Key, m => m.Count())
            //        })//#3
            //        .Dump("Overloaded Methods");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #12
0
        protected void EachPositionBetweenStarsShouldProduceExpected(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload)
        {
            var startPos = code.IndexOf("*", StringComparison.Ordinal);
            var endPos   = code.LastIndexOf("*", StringComparison.Ordinal) - 1;

            var syntaxTree = isCSharp ? CSharpSyntaxTree.ParseText(code.Replace("*", string.Empty))
                                      : VisualBasicSyntaxTree.ParseText(code.Replace("*", string.Empty));

            Assert.IsNotNull(syntaxTree);

            var semModel = isCSharp ? CSharpCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true)
                                    : VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true);

            var positionsTested = 0;

            for (var pos = startPos; pos < endPos; pos++)
            {
                var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create()) as IDocumentAnalyzer : new VisualBasicAnalyzer(DefaultTestLogger.Create());

                var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, new TestVisualStudioAbstraction().XamlIndent, profileOverload);

                Assert.AreEqual(expected.OutputType, actual.OutputType, $"Failure at {pos} ({startPos}-{endPos})");
                Assert.AreEqual(expected.Name, actual.Name, $"Failure at {pos} ({startPos}-{endPos})");
                StringAssert.AreEqual(expected.Output, actual.Output, $"Failure at {pos} ({startPos}-{endPos})");

                positionsTested += 1;
            }

            this.TestContext.WriteLine($"{positionsTested} different positions tested.");
        }
コード例 #13
0
ファイル: LocalClasses.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            // tree
            // .GetRoot()
            // .DescendantNodes()
            // .OfType<ClassDeclarationSyntax>()//#1
            // .Select(cds =>
            //new
            // {
            //     ClassName = cds.Identifier.ValueText,
            //     LocalClasses = cds.Members
            //.OfType<ClassDeclarationSyntax>()
            //.Select(m => m.Identifier.ValueText)
            // }
            // )
            // .Where(cds => cds.LocalClasses.Count() >= 1)//#3
            // .Dump("Local Classes");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #14
0
        public void CanDetectWhereAndWhenToInsertConstructorAndPageContentWhenConstructorExists()
        {
            var pageContent = "Public ReadOnly Property ViewModel As $viewmodelclass$"
                              + Environment.NewLine + "    Get"
                              + Environment.NewLine + "        Return New $viewmodelclass$"
                              + Environment.NewLine + "    End Get"
                              + Environment.NewLine + "End Property";

            var profile = TestProfile.CreateEmpty();

            profile.ViewGeneration.XamlFileSuffix            = "Page";
            profile.ViewGeneration.ViewModelFileSuffix       = "ViewModel";
            profile.Datacontext.CodeBehindConstructorContent = "DataContext = ViewModel";
            profile.Datacontext.CodeBehindPageContent        = pageContent;

            var logger = DefaultTestLogger.Create();

            var fs = new TestFileSystem
            {
                FileText = @"Public NotInheritable Class TestPage
    Inherits Page

    Sub New()
        InitializeComponent()
    End Sub
End Class",
            };

            var synTree = VisualBasicSyntaxTree.ParseText(fs.FileText);

            var vs = new TestVisualStudioAbstraction
            {
                ActiveDocumentFileName = "TestPage.xaml.vb",
                ActiveDocumentText     = fs.FileText,
                SyntaxTree             = synTree,
                DocumentIsCSharp       = false,
            };

            var sut = new SetDataContextCommandLogic(profile, logger, vs, fs);

            var documentRoot = synTree.GetRoot();

            var result = sut.GetCodeBehindContentToAdd("TestPage", "TestViewModel", "TestVmNamespace", documentRoot);

            Assert.IsTrue(result[0].anythingToAdd);
            Assert.AreEqual(5, result[0].lineNoToAddAfter);
            StringAssert.AreEqual($"{Environment.NewLine}{Environment.NewLine}DataContext = ViewModel", result[0].contentToAdd);

            var expectedContent = ""
                                  + Environment.NewLine + ""
                                  + Environment.NewLine + "Public ReadOnly Property ViewModel As TestViewModel"
                                  + Environment.NewLine + "    Get"
                                  + Environment.NewLine + "        Return New TestViewModel"
                                  + Environment.NewLine + "    End Get"
                                  + Environment.NewLine + "End Property";

            Assert.IsTrue(result[1].anythingToAdd);
            Assert.AreEqual(8, result[1].lineNoToAddAfter);
            StringAssert.AreEqual(expectedContent, result[1].contentToAdd);
        }
コード例 #15
0
        public void CanBeReferencedByName()
        {
            var vbText = @"
Public Interface I
    Property P(x As Integer)
End Interface
";
            var vbcomp = VisualBasicCompilation.Create(
                "Test",
                new[] { VisualBasicSyntaxTree.ParseText(vbText) },
                new[] { MscorlibRef_v4_0_30316_17626 },
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var metaDataArray = vbcomp.EmitToArray();

            var ref1 = new MetadataImageReference(metaDataArray, embedInteropTypes: true);

            var text = @"class C : I {}";
            var tree = Parse(text);
            var comp = CreateCompilation(new [] { tree }, new [] { ref1 });

            var t = comp.GetTypeByMetadataName("I");

            Assert.Empty(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Method && !x.CanBeReferencedByName));
            Assert.False(t.GetMembersUnordered().Where(x => x.Kind == SymbolKind.Property).First().CanBeReferencedByName); //there's only one.
        }
コード例 #16
0
ファイル: LargeClass.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            var classAndMembers = tree.GetRoot()
            //            .DescendantNodes()
            //            .Where(t => t.Kind() == SyntaxKind.ClassDeclaration)
            //            .Cast<ClassDeclarationSyntax>()//#1
            //            .Select(cds =>
            //           new {
            //                ClassName = cds.Identifier.ValueText,//#2
            //    Size = cds.Members.Count//#3
            //});

            //            var averageLength =
            //            classAndMembers
            //            .Select(classDetails => classDetails.Size)
            //            .Average();//#4

            //            classAndMembers
            //            .Where(am => am.Size > averageLength)//#5
            //            .Dump("Large Class");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #17
0
        /// <summary>
        /// Build script
        /// </summary>
        /// <param name="filenames">File names</param>
        /// <param name="references">References</param>
        /// <param name="releaseMode">Release mode (default=true)</param>
        /// <returns>Assembly</returns>
        public static Assembly CompileVBFile(string[] filenames, string[] references, bool releaseMode = true)
        {
            var tree = filenames.Select(u => VisualBasicSyntaxTree.ParseText(File.ReadAllText(u))).ToArray();
            var op   = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: releaseMode ? OptimizationLevel.Release : OptimizationLevel.Debug);

            return(Assembly.Create(VisualBasicCompilation.Create("SmartContract", tree, CreateReferences(references), op)));
        }
コード例 #18
0
        private static SyntaxTree ParseFile(string sourceFilePath)
        {
            // Read the source file content
            SourceText fileContent = null;

            using (var stream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 1, options: FileOptions.None))
            {
                fileContent = SourceText.From(stream);
            }

            // Build a SyntaxTree to return
            string extension = Path.GetExtension(sourceFilePath).ToLowerInvariant();

            switch (extension)
            {
            case ".cs":
                return(CSharpSyntaxTree.ParseText(fileContent, path: sourceFilePath));

            case ".vb":
                return(VisualBasicSyntaxTree.ParseText(fileContent, path: sourceFilePath));

            default:
                throw new NotImplementedException(String.Format("Unable to build definition finder for unknown file extension of file '{0}'", sourceFilePath));
            }
        }
コード例 #19
0
ファイル: ObjectObsession.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            var result = tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<MethodDeclarationSyntax>()//#1
            //            .Where(thisMethod => //#2
            //                                 //This method is not an event declaration
            //            !thisMethod.IsEventDeclaration()
            //            && thisMethod.TakesOrReturnsObject())
            //            .Select(thisMethod =>
            //            thisMethod.Identifier.ValueText); //#3

            //            if (result.Count() > 0)
            //            {
            //                result.Dump(@"Methods that aren't event handlers but takes or
            //returns objects");
            //            }

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #20
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //tree.GetRoot()
            //.DescendantNodes()
            //.OfType<BracketedArgumentListSyntax>()
            //.Select(bals =>
            //new
            //{
            //    Method = bals.Ancestors()
            //.OfType<MethodDeclarationSyntax>()
            //.First()
            //.Identifier.ValueText,
            //    Indices = bals.Arguments
            //.Select(a => a.GetText()
            //.Container
            //.CurrentText
            //.ToString())
            //})
            ////Find defaulter methods that use magic indices
            //.Where(bals =>
            //bals.Indices
            //.Any(i => Regex.Match(i, "[0-9]+").Success))
            //.Dump("Methods using magic indices");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #21
0
 public Compilation Compile(string assemblyInfoText)
 {
     return(VisualBasicCompilation.Create("Fake.dll")
            .WithOptions(new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: "Fake"))
            .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
            .AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(assemblyInfoText)));
 }
コード例 #22
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<FieldDeclarationSyntax>()//#2
            //            .Where(vds => vds.Modifiers
            //            .Any(m => m.ValueText == "volatile"))//#3
            //            .Select(vds => new //#4
            //{
            //                ClassName = vds.Ancestors()
            //            .OfType<ClassDeclarationSyntax>()
            //            .First()?.Identifier.ValueText,
            //                VolatileDeclaration = vds.ToFullString()
            //            })
            //            .Dump();

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #23
0
        public void Parse(string sourceCode)
        {
            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);
            var node = tree.GetRoot();

            Visit(node);
        }
コード例 #24
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //                                            //The recommended value is 64;
            //                                            //But for deomonstration purpose it is changed to 4
            //const int MAX_LOCALS_ALLOWED = 4; //#2
            //tree.GetRoot()
            //.DescendantNodes()
            //.OfType<MethodDeclarationSyntax>() //#3
            //.Where(mds =>
            //mds.Body.Statements
            //.OfType<LocalDeclarationStatementSyntax>()
            //.Count() >= MAX_LOCALS_ALLOWED) //#4
            //.Select(mds => mds.Identifier.ValueText)//#5
            //.Dump("Methods with many local variable declarations");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #25
0
        public async Task FileJustContainsComments()
        {
            var profile = this.GetDefaultTestProfile();

            profile.ViewGeneration.AllInSameProject       = true;
            profile.ViewGeneration.ViewModelDirectoryName = "Files";
            profile.ViewGeneration.ViewModelFileSuffix    = "ViewModel";
            profile.ViewGeneration.XamlFileDirectoryName  = "Files";
            profile.ViewGeneration.XamlFileSuffix         = "Page";

            var fs = new TestFileSystem
            {
                FileExistsResponse = false,
                FileText           = @" ' Just comments in this file",
            };

            var synTree  = VisualBasicSyntaxTree.ParseText(fs.FileText);
            var semModel = VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(synTree).GetSemanticModel(synTree, ignoreAccessibility: true);

            var vsa = new TestVisualStudioAbstraction
            {
                SyntaxTree    = synTree,
                SemanticModel = semModel,
                ActiveProject = new ProjectWrapper()
                {
                    Name = "App", FileName = @"C:\Test\App\App.vbproj"
                },
            };

            var sut = new CreateViewCommandLogic(DefaultTestLogger.Create(), vsa, fs, profile);

            await sut.ExecuteAsync(@"C:\Test\App\Files\TestViewModel.vb");

            Assert.IsFalse(sut.CreateView);
        }
コード例 #26
0
        public override void Process(string path, string basePath, LocalizableStringCollection strings)
        {
            /* VB */
            var codeMetadataProvider = new CodeMetadataProvider(basePath);
            var csharpWalker         = new ExtractingCodeWalker(
                new IStringExtractor <SyntaxNode>[]
            {
                new SingularStringExtractor(codeMetadataProvider),
                new PluralStringExtractor(codeMetadataProvider),
                new DataAnnotationStringExtractor(codeMetadataProvider)
            }, strings);

            foreach (var file in Directory.EnumerateFiles(path, "*.vb", SearchOption.AllDirectories).OrderBy(file => file))
            {
                if (Path.GetFileName(file).EndsWith(".cshtml.g.cs"))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var syntaxTree = VisualBasicSyntaxTree.ParseText(reader.ReadToEnd(), path: file);

                        csharpWalker.Visit(syntaxTree.GetRoot());
                    }
                }
            }

            base.Process(path, basePath, strings);
        }
コード例 #27
0
        private static Compilation CreateCompilation(string source, string language, DiagnosticAnalyzer[] analyzers, string rootNamespace)
        {
            string fileName    = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb";
            string projectName = "TestProject";

            var syntaxTree = language == LanguageNames.CSharp ?
                             CSharpSyntaxTree.ParseText(source, path: fileName) :
                             VisualBasicSyntaxTree.ParseText(source, path: fileName);

            if (language == LanguageNames.CSharp)
            {
                return(CSharpCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree },
                           references: new[] { TestBase.MscorlibRef }));
            }
            else
            {
                return(VisualBasicCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree },
                           references: new[] { TestBase.MscorlibRef },
                           options: new VisualBasicCompilationOptions(
                               OutputKind.DynamicallyLinkedLibrary,
                               rootNamespace: rootNamespace)));
            }
        }
コード例 #28
0
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            var abstractTypes =
            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .OfType<ClassDeclarationSyntax>()
            //            .Where(cds => cds.Modifiers
            //            .Any(m => m.ValueText == "abstract"))//#1
            //            .Select(cds => new //#2
            //{
            //                ClassName = cds.Identifier.ValueText,
            //                PublicConstructors =
            //            cds.Members
            //            .OfType<ConstructorDeclarationSyntax>()
            //            .Any(c => c.Modifiers
            //            .Any(m => m.ValueText == "public"))
            //            })
            //            .Where(cds => cds.PublicConstructors)//#3
            //            .Dump("AbstractTypesShouldNotHaveConstructors Violators");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #29
0
ファイル: DeeplyNestedIfBlocks.cs プロジェクト: chrhodes/VNC
        public static StringBuilder Check(string sourceCode)
        {
            StringBuilder sb = new StringBuilder();

            var tree = VisualBasicSyntaxTree.ParseText(sourceCode);

            //            tree.GetRoot()
            //            .DescendantNodes()
            //            .Where(t => loopTypes.Any(l => t.Kind() == l))//#3
            //            .Select(t => new //#4
            //{
            //                Method = t.Ancestors()
            //            .OfType<MethodDeclarationSyntax>()
            //            .First()
            //            .Identifier.ValueText,
            //                Nesting = 1 + t.Ancestors()
            //            .Count(z => loopTypes
            //            .Any(l => z.Kind() == l))
            //            })
            //            .ToLookup(t => t.Method)
            //            //#5
            //            .ToDictionary(t => t.Key,
            //            t => t.Select(m => m.Nesting).Max())
            //            .Select(t => new { Method = t.Key, Nesting = t.Value })
            //            //Find only if blocks that are deeper than 3 levels.
            //            .Where(t => t.Nesting >= 3)//#6
            //            .Dump("Deeply nested if-statements");

            sb.AppendLine(MethodBase.GetCurrentMethod().DeclaringType
                          + "." + MethodBase.GetCurrentMethod().Name
                          + " Not Implemented Yet");

            return(sb);
        }
コード例 #30
0
        private static CompilationUnit[] ExtractCompilationUnits(Project project)
        {
            using (var logger = LogManager.GetLogger("Test execution"))
            {
                var csharpTrees      = new List <SyntaxTree>(project.CompileItems.Length);
                var visualBasicTrees = new List <SyntaxTree>(project.CompileItems.Length);
                foreach (var item in project.CompileItems)
                {
                    if (!File.Exists(item))
                    {
                        logger.Error($"File {item} doesn't exist");
                        continue;
                    }

                    var code = File.ReadAllText(item);
                    if (Path.GetExtension(item).EqualsNoCase(".vb"))
                    {
                        visualBasicTrees.Add(VisualBasicSyntaxTree.ParseText(code, VisualBasicParseOptions.Default, item));
                    }
                    else
                    {
                        // NOTE: currently is assumed that all this files is C#
                        // TODO: fix it in the future
                        csharpTrees.Add(CSharpSyntaxTree.ParseText(code, CSharpParseOptions.Default, item));
                    }
                }

                var references = new List <MetadataReference>(project.AssemblyReferences.Length + project.ProjectReferences.Length);
                foreach (var item in project.AssemblyReferences)
                {
                    references.Add(MetadataReference.CreateFromFile(item));
                }
                foreach (var item in project.ProjectReferences)
                {
                    foreach (var unit in ExtractCompilationUnits(item))
                    {
                        references.Add(unit.Compilation.ToMetadataReference());
                    }
                }

                var visualBasicOptions = new VisualBasicCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    rootNamespace: project.RootNamespace,
                    globalImports: project.Imports.Select(GlobalImport.Parse),
                    optionCompareText: project.OptionCompare,
                    optionExplicit: project.OptionExplicit,
                    optionInfer: project.OptionInfer,
                    optionStrict: project.OptionStrict ? OptionStrict.On : OptionStrict.Off);
                return(new CompilationUnit[]
                {
                    CSharpCompilation.Create($"{project.ProjectName}_{LanguageNames.CSharp}")
                    .AddSyntaxTrees(csharpTrees)
                    .AddReferences(references),

                    VisualBasicCompilation.Create($"{project.ProjectName}_{LanguageNames.VisualBasic}", options: visualBasicOptions)
                    .AddSyntaxTrees(visualBasicTrees)
                    .AddReferences(references)
                });
            }
        }