private Workspace CreateWorkspace(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileExtension = language == LanguageNames.CSharp ? CSharpFileExtension : VBFileExtension;
            var projectId = ProjectId.CreateNewId(TestProjectName);

            var workspace = new AdhocWorkspace();

            var solution = workspace
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .AddMetadataReferences(projectId, GetSolutionMetadataReferences());

            int count = 0;
            foreach (var source in sources)
            {
                var fileName = FileNamePrefix + count + fileExtension;
                var documentId = DocumentId.CreateNewId(projectId, fileName);
                solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
                count++;
            }

            workspace.TryApplyChanges(solution);

            return workspace;
        }
Beispiel #2
0
        /// <summary>
        /// Creates a new P# project using the specified references.
        /// </summary>
        /// <param name="references">MetadataReferences</param>
        /// <returns>Project</returns>
        private Project CreateProject(ISet<MetadataReference> references)
        {
            var workspace = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());
            var solution = workspace.AddSolution(solutionInfo);
            var project = workspace.AddProject("Test", "C#");

            CompilationOptions options = null;
            if (this.Configuration.OptimizationTarget == OptimizationTarget.Debug)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }
            else if (this.Configuration.OptimizationTarget == OptimizationTarget.Release)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
            }

            project = project.WithCompilationOptions(options);
            project = project.AddMetadataReferences(references);

            workspace.TryApplyChanges(project.Solution);

            return project;
        }
Beispiel #3
0
        public async Task TestGetInteriorSymbolsDoesNotCrashOnSpeculativeSemanticModel()
        {
            var markup = @"
class C
{
    void foo()
    {
        System.Func<int> lambda = () => 
        {
        int x;
        $$
        }
    }
}";
            int position;
            string text;
            MarkupTestFile.GetPosition(markup, out text, out position);

            var sourceText = SourceText.From(text);
            var workspace = new AdhocWorkspace();
            var project = workspace.AddProject("Test", LanguageNames.CSharp);
            var document = workspace.AddDocument(project.Id, "testdocument", sourceText);

            var firstModel = await document.GetSemanticModelAsync();
            var tree1 = await document.GetSyntaxTreeAsync();
            var basemethod1 = tree1.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();

            // Modify the document so we can use the old semantic model as a base.
            var updated = sourceText.WithChanges(new TextChange(new TextSpan(position, 0), "insertion"));
            workspace.TryApplyChanges(document.WithText(updated).Project.Solution);

            document = workspace.CurrentSolution.GetDocument(document.Id);
            var tree2 = await document.GetSyntaxTreeAsync();
            var basemethod2 = tree2.FindTokenOnLeftOfPosition(position, CancellationToken.None).GetAncestor<CSharp.Syntax.BaseMethodDeclarationSyntax>();

            var service = new CSharp.CSharpSemanticFactsService();
            SemanticModel testModel;
            var m = service.TryGetSpeculativeSemanticModel(firstModel, basemethod1, basemethod2, out testModel);

            var xSymbol = testModel.LookupSymbols(position).First(s => s.Name == "x");

            // This should not throw an exception.
            Assert.NotNull(SymbolKey.Create(xSymbol));
        }
Beispiel #4
0
        public int Main(string[] args)
        {
            try
            {

                // how do dnu commands installs really work?
                if (args.FirstOrDefault() == "RoslynLinqRewrite") args = args.Skip(1).ToArray();

                NoRewrite = args.Contains("--norewrite");
                ForProjBuild = args.Contains("--projbuild");
                var posargs = args.Where(x => !x.StartsWith("-")).ToList();
                if (posargs.Count >= 1)
                {
                    WriteFiles = false;
                    var dir = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), posargs.First()));
                    if (Directory.Exists(dir) || Path.GetExtension(dir) == ".json")
                    {
#if false
                        CompileProjectJson(Directory.Exists(dir) ? Path.Combine(dir, "project.json") : dir);
#else
                        throw new Exception("Compiling project.json projects is not supported.");
#endif
                    }
                    else
                    {
                        CompileSolution(posargs.First(), posargs.ElementAtOrDefault(1));
                    }
                }
                return 0;
            }
            catch (ExitException ex)
            {
                return ex.Code;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return 1;
            }



            if (!args.Contains("--VisualStudio"))
            {
                Console.WriteLine("LinqRewrite <path-to-sln> [project-name]");
                return 1;
            }
            if (true)
            {
                //CompileSolution(@"D:\Repositories\shaman-fizzler\Fizzler.sln", "Fizzler", false);
                //CompileSolution(@"C:\Repositories\Awdee\Shaman.ApiServer.sln", "Shaman.Core", true);
                CompileSolution(@"C:\Repositories\Awdee\Shaman.ApiServer.sln", "Shaman.Inferring.FullLogic");
                return 0;
            }



            var code = @"
using System;
using System.Collections.Generic;
using System.Linq;

static class Meow
{
    static void Main()
    {
var sdfsdf = (new Exception()).RecursiveEnumeration(x => x.InnerException).Last();
        var arr = new []{ 5, 457, 7464, 66 };
        var arr2 = new []{ ""a"", ""b"" };
        var capture = 5;
        var meow = 2;
var k = arr2.Where(x => x.StartsWith(""t"")).Select(x=>x==""miao"").LastOrDefault();
         //var k = arr.Where(x =>x > capture).Where(x =>x != 0).Select(x =>{return (double)x - 4;}).Where(x => x < 99).Any(x => x == 100);
       // var ka = arr.Sum();
    }
    public static IEnumerable<T> RecursiveEnumeration<T>(this T first, Func<T, T> parent)
        {
            var current = first;
            while (current != null)
            {
                yield return current;
                current = parent(current);
            }
        }
}
";
            //var syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code);


#if !CORECLR

            var workspace = new AdhocWorkspace();
            var proj = workspace.AddProject("LinqRewriteExample", "C#").WithMetadataReferences(
                new[] {
                MetadataReference.CreateFromFile(typeof(int).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().Assembly.Location),
                }
                ).WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            var doc = proj.AddDocument("source.cs", code);
            if (!workspace.TryApplyChanges(doc.Project.Solution)) throw new Exception();
            proj = doc.Project;
            var comp = proj.GetCompilationAsync().Result;

            var hasErrs = false;
            foreach (var item in comp.GetDiagnostics())
            {
                if (item.Severity == DiagnosticSeverity.Error) hasErrs = true;
                PrintDiagnostic(item);
            }

            if (hasErrs) return 1;

            var syntaxTree = doc.GetSyntaxTreeAsync().Result;
            var rewriter = new LinqRewriter(proj, comp.GetSemanticModel(syntaxTree), doc.Id);
            var rewritten = rewriter.Visit(syntaxTree.GetRoot());
            proj = doc.WithSyntaxRoot(rewritten).Project;


            foreach (var item in proj.GetCompilationAsync().Result.GetDiagnostics())
            {
                PrintDiagnostic(item);
            }
#endif
        }