Ejemplo n.º 1
0
        private static void AssertChangedTextLinesHelper(string originalText, params TextChange[] changes)
        {
            var changedText = SourceText.From(originalText).WithChanges(changes);

            Assert.Equal(SourceText.From(changedText.ToString()).Lines, changedText.Lines, new TextLineEqualityComparer());
        }
        public async Task TestUpdatedDocumentHasTextVersionAsync()
        {
            var pid      = ProjectId.CreateNewId();
            var text     = SourceText.From("public class C { }");
            var version  = VersionStamp.Create();
            var docInfo  = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            using var ws = new AdhocWorkspace();
            ws.AddProject(projInfo);
            var doc = ws.CurrentSolution.GetDocument(docInfo.Id);

            Assert.False(doc.TryGetText(out var currentText));
            Assert.False(doc.TryGetTextVersion(out var currentVersion));

            // cause text to load and show that TryGet now works for text and version
            currentText = await doc.GetTextAsync();

            Assert.True(doc.TryGetText(out currentText));
            Assert.True(doc.TryGetTextVersion(out currentVersion));
            Assert.Equal(version, currentVersion);

            // change document
            var root = await doc.GetSyntaxRootAsync();

            var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());

            Assert.NotSame(root, newRoot);
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.NotSame(doc, newDoc);

            // text is now unavailable since it must be constructed from tree
            Assert.False(newDoc.TryGetText(out currentText));

            // version is available because it is cached
            Assert.True(newDoc.TryGetTextVersion(out currentVersion));

            // access it the hard way
            var actualVersion = await newDoc.GetTextVersionAsync();

            // version is the same
            Assert.Equal(currentVersion, actualVersion);

            // accessing text version did not cause text to be constructed.
            Assert.False(newDoc.TryGetText(out currentText));

            // now access text directly (force it to be constructed)
            var actualText = await newDoc.GetTextAsync();

            actualVersion = await newDoc.GetTextVersionAsync();

            // prove constructing text did not introduce a new version
            Assert.Equal(currentVersion, actualVersion);
        }
Ejemplo n.º 3
0
        private static int Wain(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode."
            };
            var file        = app.Argument("script", "Path to CSX script");
            var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue);

            var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue);

            var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue);

            var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);

            var verbosity = app.Option("--verbosity", " Set the verbosity level of the command. Allowed values are t[trace], d[ebug], i[nfo], w[arning], e[rror], and c[ritical].", CommandOptionType.SingleValue);

            var nocache = app.Option("--nocache", "disable DLL caching", CommandOptionType.NoValue);

            var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray();
            var argsAfterDoubleHypen   = args.SkipWhile(a => a != "--").Skip(1).ToArray();

            app.HelpOption("-? | -h | --help");

            app.VersionOption("-v | --version", GetVersion);

            var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue);

            app.Command("eval", c =>
            {
                c.Description = "Execute CSX code.";
                var code      = c.Argument("code", "Code to execute.");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(code.Value))
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                        exitCode       = await RunCode(code.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), cwd.Value(), packageSources.Values?.ToArray());
                    }
                    return(exitCode);
                });
            });

            app.Command("init", c =>
            {
                c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
                var fileName  = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    scaffolder.InitializerFolder(fileName.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("new", c =>
            {
                c.Description        = "Creates a new script file";
                var fileNameArgument = c.Argument("filename", "The script file name");
                var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }
                    scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("publish", c =>
            {
                c.Description              = "Creates a self contained executable or DLL from a script";
                var fileNameArgument       = c.Argument("filename", "The script file name");
                var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed.  Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue);
                var dllName          = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time).  Defaults to the name of the script.", CommandOptionType.SingleValue);
                var dllOption        = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue);
                var commandConfig    = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue);
                var publishDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                var runtime          = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue);

                c.OnExecute(() =>
                {
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }

                    var optimizationLevel = OptimizationLevel.Debug;
                    if (commandConfig.HasValue() && commandConfig.Value().ToLower() == "release")
                    {
                        optimizationLevel = OptimizationLevel.Release;
                    }

                    var runtimeIdentifier = runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier;
                    var absoluteFilePath  = Path.IsPathRooted(fileNameArgument.Value) ? fileNameArgument.Value : Path.Combine(Directory.GetCurrentDirectory(), fileNameArgument.Value);

                    // if a publish directory has been specified, then it is used directly, otherwise:
                    // -- for EXE {current dir}/publish/{runtime ID}
                    // -- for DLL {current dir}/publish
                    var publishDirectory = publishDirectoryOption.Value() ??
                                           (dllOption.HasValue() ? Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish") : Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish", runtimeIdentifier));

                    var absolutePublishDirectory = Path.IsPathRooted(publishDirectory) ? publishDirectory : Path.Combine(Directory.GetCurrentDirectory(), publishDirectory);

                    var logFactory    = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var compiler      = GetScriptCompiler(publishDebugMode.HasValue(), logFactory);
                    var scriptEmmiter = new ScriptEmitter(ScriptConsole.Default, compiler);
                    var publisher     = new ScriptPublisher(logFactory, scriptEmmiter);
                    var code          = SourceText.From(File.ReadAllText(absoluteFilePath));
                    var context       = new ScriptContext(code, absolutePublishDirectory, Enumerable.Empty <string>(), absoluteFilePath, optimizationLevel);

                    if (dllOption.HasValue())
                    {
                        publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, dllName.Value());
                    }
                    else
                    {
                        publisher.CreateExecutable <int, CommandLineScriptGlobals>(context, logFactory, runtimeIdentifier);
                    }

                    return(0);
                });
            });

            app.Command("exec", c =>
            {
                c.Description        = "Run a script from a DLL.";
                var dllPath          = c.Argument("dll", "Path to DLL based script");
                var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(dllPath.Value))
                    {
                        if (!File.Exists(dllPath.Value))
                        {
                            throw new Exception($"Couldn't find file '{dllPath.Value}'");
                        }

                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                        var absoluteFilePath = Path.IsPathRooted(dllPath.Value) ? dllPath.Value : Path.Combine(Directory.GetCurrentDirectory(), dllPath.Value);

                        var compiler = GetScriptCompiler(commandDebugMode.HasValue(), logFactory);
                        var runner   = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result   = await runner.Execute <int>(absoluteFilePath, app.RemainingArguments.Concat(argsAfterDoubleHypen));
                        return(result);
                    }
                    return(exitCode);
                });
            });

            app.OnExecute(async() =>
            {
                int exitCode = 0;

                if (infoOption.HasValue())
                {
                    Console.Write(GetEnvironmentInfo());
                    return(0);
                }

                var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                if (!string.IsNullOrWhiteSpace(file.Value))
                {
                    if (Debugger.IsAttached || nocache.HasValue())
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        exitCode = await RunScript(file.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), interactive.HasValue(), packageSources.Values?.ToArray());
                    }
                    else
                    {
                        string cacheFolder = Path.Combine(Path.GetTempPath(), "dotnet-scripts");
                        // create unique folder name based on the path
                        string uniqueFolderName = "";
                        using (var sha = SHA256.Create())
                        {
                            uniqueFolderName = Convert.ToBase64String(sha.ComputeHash(Encoding.Unicode.GetBytes(file.Value))).Replace("=", String.Empty).Replace("/", string.Empty);
                        }

                        string publishDirectory = Path.Combine(cacheFolder, uniqueFolderName);
                        if (!Directory.Exists(publishDirectory))
                        {
                            Directory.CreateDirectory(publishDirectory);
                        }

                        string absoluteSourcePath;
                        SourceText code;
                        if (!File.Exists(file.Value))
                        {
                            if (IsHttpUri(file.Value))
                            {
                                var downloader     = new ScriptDownloader();
                                var rawCode        = await downloader.Download(file.Value);
                                absoluteSourcePath = Path.Combine(publishDirectory, "source.csx");
                                File.WriteAllText(absoluteSourcePath, rawCode);
                                code = SourceText.From(rawCode);
                            }
                            else
                            {
                                throw new Exception($"Couldn't find file '{file}'");
                            }
                        }
                        else
                        {
                            absoluteSourcePath = Path.IsPathRooted(file.Value) ? Path.GetFullPath(file.Value) : Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), file.Value));
                            code = SourceText.From(File.ReadAllText(absoluteSourcePath));
                        }

                        // given the path to a script we create a %temp%\dotnet-scripts\{uniqueFolderName} path
                        string pathToDll = Path.Combine(publishDirectory, Path.GetFileNameWithoutExtension(absoluteSourcePath) + ".dll");

                        // source hash is the checkSum of the code
                        string sourceHash = Convert.ToBase64String(code.GetChecksum().ToArray());

                        // get hash code from previous run
                        string hashCache = Path.Combine(publishDirectory, ".hash");
                        var compiler     = GetScriptCompiler(true, logFactory);

                        // if we don't have hash
                        if (!File.Exists(hashCache) ||
                            // or we haven't created a dll
                            !Directory.Exists(publishDirectory) ||
                            // the hashcode has changed (meaning new content)
                            File.ReadAllText(hashCache) != sourceHash)
                        {
                            // then we autopublish into the %temp%\dotnet-scripts\{uniqueFolderName} path
                            var optimizationLevel = OptimizationLevel.Debug;
                            if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                            {
                                optimizationLevel = OptimizationLevel.Release;
                            }

                            var runtimeIdentifier = ScriptEnvironment.Default.RuntimeIdentifier;
                            var scriptEmmiter     = new ScriptEmitter(ScriptConsole.Default, compiler);
                            var publisher         = new ScriptPublisher(logFactory, scriptEmmiter);
                            var context           = new ScriptContext(code, publishDirectory, Enumerable.Empty <string>(), absoluteSourcePath, optimizationLevel);

                            // create the assembly in our cache folder
                            publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, Path.GetFileNameWithoutExtension(pathToDll));

                            // save sourceHash for next time, so we can know it's ok to use the generated dll next time
                            File.WriteAllText(hashCache, sourceHash);
                        }


                        // run the cached %temp%\dotnet-scripts\{uniqueFolderName}/package.dll
                        var runner = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result = await runner.Execute <int>(pathToDll, app.RemainingArguments.Concat(argsAfterDoubleHypen));
                        return(result);
                    }
                }
                else
                {
                    await RunInteractive(debugMode.HasValue(), logFactory, packageSources.Values?.ToArray());
                }
                return(exitCode);
            });


            return(app.Execute(argsBeforeDoubleHyphen));
        }
Ejemplo n.º 4
0
        public async Task Project_AnalyzerOptions_Change()
        {
            using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler))
            {
                var solutionInfo = GetInitialSolutionInfo(workspace);
                workspace.OnSolutionAdded(solutionInfo);
                await WaitWaiterAsync(workspace.ExportProvider);

                var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project;
                var worker  = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution));

                Assert.Equal(5, worker.SyntaxDocumentIds.Count);
                Assert.Equal(5, worker.DocumentIds.Count);
            }
        }
Ejemplo n.º 5
0
        public async Task Document_AdditionalFileChange()
        {
            using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler))
            {
                var solution = GetInitialSolutionInfo(workspace);
                workspace.OnSolutionAdded(solution);
                await WaitWaiterAsync(workspace.ExportProvider);

                var project = solution.Projects[0];
                var ncfile  = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");

                var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));

                Assert.Equal(5, worker.SyntaxDocumentIds.Count);
                Assert.Equal(5, worker.DocumentIds.Count);

                worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));

                Assert.Equal(5, worker.SyntaxDocumentIds.Count);
                Assert.Equal(5, worker.DocumentIds.Count);

                worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));

                Assert.Equal(5, worker.SyntaxDocumentIds.Count);
                Assert.Equal(5, worker.DocumentIds.Count);
            }
        }
Ejemplo n.º 6
0
 public static StatementSyntax ParseStatement(string text)
 {
     return((StatementSyntax)Parse(SourceText.From(text), null, null, p => p.ParseStatement()).Root);
 }
Ejemplo n.º 7
0
        private void GenerateCode(GeneratorExecutionContext context, TypeDeclarationSyntax tds, Type attributeType)
        {
            // Field symbol
            var symbol = context.ParseSyntaxNode <INamedTypeSymbol>(tds);

            if (symbol == null || context.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            // Attribute data
            var attributeData = symbol.GetAttributeData(attributeType.FullName);

            // Snake case
            var snakeCase = attributeData?.GetValue <bool>(nameof(AutoToParametersAttribute.SnakeCase));

            // Name space and class name
            var(ns, className) = (symbol.ContainingNamespace.ToDisplayString(), symbol.Name);

            // Keyword
            var keyword = tds.Keyword.ToString();

            // Is Public
            var isPublic = tds.HasToken(SyntaxKind.PublicKeyword);

            // Name
            var name = tds.Identifier.ToString();

            // Inheritance
            var externals = new List <string>();

            // Body
            var body = GenerateBody(context, tds, snakeCase.GetValueOrDefault(), externals, ns);

            if (context.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            externals.Add($"com.etsoo.Utils.Serialization.IDictionaryParser<{name}>");

            // Source code
            var source = $@"#nullable enable
                using com.etsoo.Utils.String;
                using System;
                using System.Collections.Generic;
                using System.Linq;

                namespace {ns}
                {{
                    {(isPublic ? "public" : "internal")} partial {keyword} {className} : {string.Join(", ", externals)}
                    {{
                        public static {name} Create(StringKeyDictionaryObject dic)
                        {{
                            return new {name} {body};
                        }}
                    }}
                }}
            ";

            context.AddSource($"{ns}.{className}.Dictionary.Generated.cs", SourceText.From(source, Encoding.UTF8));
        }
Ejemplo n.º 8
0
        public void Execute(GeneratorExecutionContext context)
        {
            var fields = GetAircraftFields(context).ToList();

            var builder = new StringBuilder();

            builder.Append(@"
using System;
using Microsoft.Extensions.Logging;
using Microsoft.FlightSimulator.SimConnect;

namespace FlightRecorder.Client.SimConnectMSFS
{
    public partial class Connector
    {");

            builder.Append(@"
        private void RegisterAircraftPositionDefinition()
        {
            RegisterDataDefinition<AircraftPositionStruct>(DEFINITIONS.AircraftPosition");
            foreach ((_, _, var variable, var unit, var type, _, _) in fields)
            {
                builder.Append($@",
                (""{variable}"", ""{unit}"", (SIMCONNECT_DATATYPE){type})");
            }
            builder.Append(@"
            );
        }
");

            builder.Append(@"
        private void RegisterAircraftPositionSetDefinition()
        {
            RegisterDataDefinition<AircraftPositionSetStruct>(DEFINITIONS.AircraftPositionSet");
            foreach ((_, _, var variable, var unit, var type, var setType, _) in fields)
            {
                if (setType == null || setType == SetTypeDefault)
                {
                    builder.Append($@",
                (""{variable}"", ""{unit}"", (SIMCONNECT_DATATYPE){type})");
                }
            }
            builder.Append(@"
            );
        }
");

            builder.Append(@"
        private void RegisterEvents()
        {");
            var eventId = InitialEventID;

            foreach ((_, _, var variable, var unit, var type, var setType, var setBy) in fields)
            {
                if (setType == SetTypeEvent)
                {
                    // TODO: warning if setBy is empty
                    builder.Append($@"
            logger.LogDebug(""Register event {{eventName}} to ID {{eventID}}"", ""{setBy}"", {eventId});
            simconnect.MapClientEventToSimEvent((EVENTS){eventId}, ""{setBy}"");");
                    eventId++;
                }
            }
            builder.Append(@"
        }
");
            builder.Append(@"
        public void TriggerEvents(AircraftPositionStruct current, AircraftPositionStruct expected)
        {");
            eventId = InitialEventID;
            foreach ((_, var name, var variable, var unit, var type, var setType, var setBy) in fields)
            {
                if (setType == SetTypeEvent)
                {
                    // TODO: warning if setBy is empty
                    builder.Append($@"
            if (current.{name} != expected.{name})
            {{
                logger.LogDebug(""Trigger event {{eventName}}"", ""{setBy}"");
                simconnect.TransmitClientEvent(SimConnect.SIMCONNECT_OBJECT_ID_USER, (EVENTS){eventId}, 0, GROUPS.GENERIC, SIMCONNECT_EVENT_FLAG.GROUPID_IS_PRIORITY);
            }}
");
                    eventId++;
                }
            }
            builder.Append(@"
        }
");

            builder.Append(@"
    }
}");

            context.AddSource("ConnectorGenerator", SourceText.From(builder.ToString(), Encoding.UTF8));
        }
Ejemplo n.º 9
0
        private TextLine GetLine(string codeLine)
        {
            var text = SourceText.From(codeLine);

            return(text.Lines[0]);
        }
Ejemplo n.º 10
0
 public override SourceText GetText(CancellationToken cancellationToken)
 {
     return(SourceText.From(string.Empty, Encoding.UTF8));
 }
Ejemplo n.º 11
0
 public override bool TryGetText(out SourceText text)
 {
     text = SourceText.From(string.Empty, Encoding.UTF8);
     return(true);
 }
Ejemplo n.º 12
0
 public void UpdateText(DocumentId documentId, string text)
 {
     OnDocumentTextChanged(documentId, SourceText.From(text, Encoding.UTF8), PreservationMode.PreserveValue);
 }
Ejemplo n.º 13
0
        public DocumentId AddProjectWithDocument(string documentFileName, string text)
        {
            var fileName = Path.GetFileName(documentFileName);
            var name     = Path.GetFileNameWithoutExtension(documentFileName);
            var language = Path.GetExtension(documentFileName) == ".vb" ? LanguageNames.VisualBasic : LanguageNames.CSharp;

            var projectId = ProjectId.CreateNewId();

            // ValueTuple needs a separate assembly in .NET 4.6.x. But it is not needed anymore in .NET 4.7+ as it is included in mscorelib.
            var references = defaultReferences.Distinct().Select(CreateReference).ToList();

            references.Add(CreateReference(Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")));
            if (language == LanguageNames.VisualBasic)
            {
                references.Add(CreateReference(typeof(VBMath).Assembly));
            }
            else if (language == LanguageNames.CSharp)
            {
                references.Add(CreateReference(typeof(RuntimeBinderException).Assembly));
            }

            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, name, name + ".dll", language, metadataReferences: references,
                                                 parseOptions: language == LanguageNames.CSharp ? (ParseOptions) new CSharpParseOptions(languageVersion: Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest)
                    : new VisualBasicParseOptions(Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest));

            OnProjectAdded(projectInfo);

            var documentId   = DocumentId.CreateNewId(projectId);
            var documentInfo = DocumentInfo.Create(documentId, fileName,
                                                   loader: TextLoader.From(TextAndVersion.Create(SourceText.From(text, Encoding.UTF8), VersionStamp.Create())));

            OnDocumentAdded(documentInfo);
            return(documentId);
        }
Ejemplo n.º 14
0
        private Task <Project> CreateProject()
        {
            var fileNamePrefix  = "Test";
            var fileExt         = ".cs";
            var testProjectName = "TestProject";

            var projectId = ProjectId.CreateNewId(debugName: testProjectName);

            switch (TargetFramework)
            {
            case TargetFramework.NetStandard2_0:
                AddNuGetReference("NETStandard.Library", "2.0.3", "build/netstandard2.0/ref/");
                break;

            case TargetFramework.NetStandard2_1:
                AddNuGetReference("NETStandard.Library.Ref", "2.1.0", "ref/netstandard2.1/");
                break;

            case TargetFramework.Net48:
                AddNuGetReference("Microsoft.NETFramework.ReferenceAssemblies.net48", "1.0.0", "build/.NETFramework/v4.8/");
                break;

            case TargetFramework.Net50:
                AddNuGetReference("Microsoft.NETCore.App.Ref", "5.0.0", "ref/net5.0/");
                break;

            case TargetFramework.AspNetCore50:
                AddNuGetReference("Microsoft.NETCore.App.Ref", "5.0.0", "ref/net5.0/");
                AddNuGetReference("Microsoft.AspNetCore.App.Ref", "5.0.0", "ref/net5.0/");
                break;

            case TargetFramework.WindowsDesktop50:
                AddNuGetReference("Microsoft.WindowsDesktop.App.Ref", "5.0.0", "ref/net5.0/");
                break;
            }

            AddNuGetReference("System.Collections.Immutable", "1.5.0", "lib/netstandard2.0/");
            AddNuGetReference("System.Numerics.Vectors", "4.5.0", "ref/netstandard2.0/");
            AddNuGetReference("Microsoft.CSharp", "4.7.0", "lib/netstandard2.0/");  // To support dynamic type

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, testProjectName, testProjectName, LanguageNames.CSharp)
                           .WithProjectParseOptions(projectId, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion))
                           .AddMetadataReferences(projectId, References);

            var count = 0;

            AppendFile(FileName, SourceCode);

            foreach (var source in ApiReferences)
            {
                var newFileName = fileNamePrefix + count + fileExt;
                AppendFile(newFileName, source);
            }

            return(Task.FromResult(solution.GetProject(projectId)));

            void AppendFile(string filename, string content)
            {
                filename ??= fileNamePrefix + count + fileExt;
                var documentId = DocumentId.CreateNewId(projectId, debugName: filename);

                solution = solution.AddDocument(documentId, filename, SourceText.From(content), filePath: filename);
                count++;
            }
        }
Ejemplo n.º 15
0
 public static AnalyzerConfig Parse(string text, string pathToFile)
 {
     return(Parse(SourceText.From(text), pathToFile));
 }
        internal CompletionList CreateProvider(string input, SourceCodeKind?sourceCodeKind = null, bool usePreviousCharAsTrigger = false)
        {
            int cursorPosition = input.IndexOf("$$", StringComparison.Ordinal);
            var parsedText     = input.Substring(0, cursorPosition) + input.Substring(cursorPosition + 2);

            var workspace = new InspectionActionTestBase.TestWorkspace();

            var projectId = ProjectId.CreateNewId();
            //var solutionId = SolutionId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "TestProject",
                               "TestProject",
                               LanguageNames.CSharp,
                               null,
                               null,
                               new CSharpCompilationOptions(
                                   OutputKind.DynamicallyLinkedLibrary,
                                   false,
                                   "",
                                   "",
                                   "Script",
                                   null,
                                   OptimizationLevel.Debug,
                                   false,
                                   false
                                   ),
                               new CSharpParseOptions(
                                   LanguageVersion.CSharp6,
                                   DocumentationMode.None,
                                   SourceCodeKind.Regular,
                                   ImmutableArray.Create("DEBUG", "TEST")
                                   ),
                               new [] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(parsedText), VersionStamp.Create()))
                    )
            },
                               null,
                               InspectionActionTestBase.DefaultMetadataReferences
                               )
                           );
            var engine = new MonoDevelop.CSharp.Completion.RoslynParameterHintingEngine();

            var compilation = workspace.CurrentSolution.GetProject(projectId).GetCompilationAsync().Result;

            var document      = workspace.CurrentSolution.GetDocument(documentId);
            var semanticModel = document.GetSemanticModelAsync().Result;

            char triggerChar = cursorPosition > 0 ? document.GetTextAsync().Result [cursorPosition - 1] : '\0';

            var cs = (CSharpCompletionService)workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService <CompletionService> ();

            cs.SetTestProviders(CreateCompletionProvider());

            var trigger = CompletionTrigger.Invoke;

            if (usePreviousCharAsTrigger)
            {
                trigger = new CompletionTrigger(CompletionTriggerKind.Insertion, triggerChar);
            }
            return(cs.GetCompletionsAsync(document, cursorPosition, trigger, null, null, default(CancellationToken)).Result);
        }
Ejemplo n.º 17
0
 public static SyntaxTree ParseExpression(string text)
 {
     return(Parse(SourceText.From(text), null, null, p => p.ParseExpression()));
 }
Ejemplo n.º 18
0
 public AdditionalTextFile(string path)
 {
     Path  = path;
     _text = SourceText.From(File.ReadAllText(path));
 }
Ejemplo n.º 19
0
 public static SyntaxToken ParseToken(string text)
 {
     return(new HlslLexer(new SourceFile(SourceText.From(text), null)).Lex(LexerMode.Syntax));
 }
 public AdditionalTextHelper(string path, string text)
 {
     this.Path       = path;
     this.sourceText = SourceText.From(text);
 }
Ejemplo n.º 21
0
        private static void Processor(Options o)
        {
            try
            {
                var results = new Dictionary <string, List <Result> >();

                if (string.IsNullOrEmpty(o.CsvOutput))
                {
                    DateTime dt        = DateTime.Now;
                    string   timestamp = dt.ToString("yyyyMMddHHmmss");
                    o.CsvOutput = "enumerated_controllers_" + timestamp + ".csv";
                }

                //var documents = LoadSolution(o.SolutionPath);

                string[] paths = Directory.GetFiles(o.Directory, "*.cs", SearchOption.AllDirectories);

                if (paths.Any())
                {
                    foreach (var path in paths)
                    {
                        using (var stream = File.OpenRead(path))
                        {
                            var        tree = CSharpSyntaxTree.ParseText(SourceText.From(stream), path: path);
                            SyntaxNode root = tree.GetRoot();

                            // Check if the Class inherits Apicontroller or Controller and print out all the public entry points
                            ControllerChecker controllerchk = new ControllerChecker();
                            if (controllerchk.inheritsFromController(root, o.AttributeSearch))
                            {
                                controllerchk.enumerateEntrypoints(root, o.AttributeSearch, o.NegativeSearch, path, results);
                            }
                        }
                    }

                    string[] controllerPaths = results.Keys.ToArray();
                    string   pathToTrim      = getPathToTrim(controllerPaths);

                    if (!string.IsNullOrEmpty(o.AttributeSearch) || !string.IsNullOrEmpty(o.NegativeSearch))
                    {
                        printCommandLineResults(results, pathToTrim);
                    }

                    printCSVResults(results, o.CsvOutput, pathToTrim);
                }
                else
                {
                    Console.WriteLine("Unable to find any document from solution line");
                }
            }
            catch (DirectoryNotFoundException)
            {
                Console.WriteLine("Invalid Path");
            }
            catch (IndexOutOfRangeException)
            {
                //Shoudn't Reach this, but in case
                Console.WriteLine("No Arguments passed");
            }
            catch (UnauthorizedAccessException e)
            {
                e.GetBaseException();
                Console.WriteLine("You do not seem to have appropiate Permissions on this direcctory");
            }
            catch (NotSupportedException)
            {
                Console.WriteLine("The operating system is Windows CE, which does not have current directory functionality.");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Illegal characters passed as arguments! ");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unexpected error {e}");
            }
        }
Ejemplo n.º 22
0
 private static Document CreateDoc(AdhocWorkspace workspace, string source) =>
 workspace.AddProject("TestProject", "C#").AddDocument("TestDocument", SourceText.From(source));
Ejemplo n.º 23
0
        public async Task Document_Change()
        {
            using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler))
            {
                var solution = GetInitialSolutionInfo(workspace);
                workspace.OnSolutionAdded(solution);
                await WaitWaiterAsync(workspace.ExportProvider);

                var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];

                var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//")));

                Assert.Equal(1, worker.SyntaxDocumentIds.Count);
            }
        }
Ejemplo n.º 24
0
        public static Task <OmnisharpWorkspace> AddProjectToWorkspace(OmnisharpWorkspace workspace, string filePath, string[] frameworks, Dictionary <string, string> sourceFiles)
        {
            var versionStamp = VersionStamp.Create();
            var mscorlib     = MetadataReference.CreateFromFile(AssemblyFromType(typeof(object)).Location);
            var systemCore   = MetadataReference.CreateFromFile(AssemblyFromType(typeof(Enumerable)).Location);
            var references   = new[] { mscorlib, systemCore };

            foreach (var framework in frameworks)
            {
                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), versionStamp,
                                                     "OmniSharp+" + framework, "AssemblyName",
                                                     LanguageNames.CSharp, filePath, metadataReferences: references);

                workspace.AddProject(projectInfo);
                foreach (var file in sourceFiles)
                {
                    var document = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), file.Key,
                                                       null, SourceCodeKind.Regular,
                                                       TextLoader.From(TextAndVersion.Create(SourceText.From(file.Value), versionStamp)), file.Key);

                    workspace.AddDocument(document);
                }
            }

            return(Task.FromResult(workspace));
        }
Ejemplo n.º 25
0
        protected static Project CreateProject(
            FileAndSource[] sources,
            string language = LanguageNames.CSharp,
            bool addLanguageSpecificCodeAnalysisReference = true,
            Solution addToSolution = null,
            string projectName     = _testProjectName)
        {
            string             fileNamePrefix = DefaultFilePathPrefix;
            string             fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
            CompilationOptions options        = language == LanguageNames.CSharp ? s_CSharpDefaultOptions : s_visualBasicDefaultOptions;

            ProjectId projectId = ProjectId.CreateNewId(debugName: projectName);

            Project project = (addToSolution ?? new AdhocWorkspace().CurrentSolution)
                              .AddProject(projectId, projectName, projectName, language)
                              .AddMetadataReference(projectId, s_corlibReference)
                              .AddMetadataReference(projectId, s_systemCoreReference)
                              .AddMetadataReference(projectId, s_systemXmlReference)
                              .AddMetadataReference(projectId, s_systemXmlDataReference)
                              .AddMetadataReference(projectId, s_codeAnalysisReference)
                              .AddMetadataReference(projectId, SystemRuntimeFacadeRef)
                              .AddMetadataReference(projectId, SystemThreadingFacadeRef)
                              .AddMetadataReference(projectId, SystemThreadingTaskFacadeRef)
                              //.AddMetadataReference(projectId, TestBase.SystemRef)
                              //.AddMetadataReference(projectId, TestBase.SystemRuntimeFacadeRef)
                              //.AddMetadataReference(projectId, TestBase.SystemThreadingFacadeRef)
                              //.AddMetadataReference(projectId, TestBase.SystemThreadingTaskFacadeRef)
                              .AddMetadataReference(projectId, s_immutableCollectionsReference)
                              .AddMetadataReference(projectId, s_workspacesReference)
                              .AddMetadataReference(projectId, s_systemDiagnosticsDebugReference)
                              .AddMetadataReference(projectId, s_systemDataReference)
                              .WithProjectCompilationOptions(projectId, options)
                              .GetProject(projectId);

            // Enable IOperation Feature on the project
            var parseOptions = project.ParseOptions.WithFeatures(project.ParseOptions.Features.Concat(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create("IOperation", "true"))));

            project = project.WithParseOptions(parseOptions);

            if (addLanguageSpecificCodeAnalysisReference)
            {
                MetadataReference symbolsReference = language == LanguageNames.CSharp ? s_csharpSymbolsReference : s_visualBasicSymbolsReference;
                project = project.AddMetadataReference(symbolsReference);
            }

            if (language == LanguageNames.VisualBasic)
            {
                project = project.AddMetadataReference(s_visualBasicReference);
            }

            int count = 0;

            foreach (FileAndSource source in sources)
            {
                string     newFileName = source.FilePath ?? fileNamePrefix + count++ + "." + fileExt;
                DocumentId documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                project = project.AddDocument(newFileName, SourceText.From(source.Source)).Project;
            }

            return(project);
        }
Ejemplo n.º 26
0
        /// <inheritdoc/>
        public byte[] Compile(string code, IEnumerable <string> metadataPropertyKeys)
        {
            _ = code ?? throw new ArgumentNullException(nameof(code));

            // Parse the code
            code = Parse(code, metadataPropertyKeys, _executionState);

            // Get the compilation
            CSharpParseOptions       parseOptions       = new CSharpParseOptions();
            SourceText               sourceText         = SourceText.From(code, Encoding.UTF8);
            SyntaxTree               syntaxTree         = CSharpSyntaxTree.ParseText(sourceText, parseOptions, AssemblyName);
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).
                                                          WithSpecificDiagnosticOptions(new Dictionary <string, ReportDiagnostic>
            {
                // ensure that specific warnings about assembly references are always suppressed
                // https://github.com/dotnet/roslyn/issues/5501
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress },

                // we don't care about unreachable code
                { "CS0162", ReportDiagnostic.Suppress },
            });

            // For some reason, Roslyn really wants these added by filename
            // See http://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime
            string            assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            CSharpCompilation compilation  = CSharpCompilation.Create(
                AssemblyName,
                new[] { syntaxTree },
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !string.IsNullOrEmpty(x.Location))
                .Select(x => MetadataReference.CreateFromFile(x.Location)), compilationOptions)
                                             .AddReferences(
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
                MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")));

            // Emit the assembly
            ILogger logger = _executionState.Services.GetRequiredService <ILogger <ScriptHelper> >();

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

                // Log warnings
                List <string> warningMessages = result.Diagnostics
                                                .Where(x => x.Severity == DiagnosticSeverity.Warning)
                                                .Select(GetCompilationErrorMessage)
                                                .ToList();
                if (warningMessages.Count > 0)
                {
                    logger.LogWarning(
                        "{0} warnings compiling script:{1}{2}",
                        warningMessages.Count,
                        Environment.NewLine,
                        string.Join(Environment.NewLine, warningMessages));
                }

                // Log errors
                List <string> errorMessages = result.Diagnostics
                                              .Where(x => x.Severity == DiagnosticSeverity.Error)
                                              .Select(GetCompilationErrorMessage)
                                              .ToList();
                if (errorMessages.Count > 0)
                {
                    logger.LogError(
                        "{0} errors compiling script:{1}{2}",
                        errorMessages.Count,
                        Environment.NewLine,
                        string.Join(Environment.NewLine, errorMessages));
                }

                // Throw for errors or not success
                if (!result.Success || errorMessages.Count > 0)
                {
                    throw new ScriptCompilationException(errorMessages);
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(ms.ToArray());
            }
        }
 public override SourceText GetText(CancellationToken cancellationToken = default(CancellationToken))
 {
     return(SourceText.From(File.ReadAllText(Path)));
 }
Ejemplo n.º 28
0
        public Test()
        {
            this.ReferenceAssemblies = ReferencesHelper.DefaultReferences;
            this.TestBehaviors      |= Microsoft.CodeAnalysis.Testing.TestBehaviors.SkipGeneratedCodeCheck;

            this.SolutionTransforms.Add((solution, projectId) =>
            {
                var parseOptions = (CSharpParseOptions)solution.GetProject(projectId) !.ParseOptions !;
                solution         = solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(LanguageVersion.CSharp7_3));

                return(solution);
            });

            this.TestState.AdditionalFilesFactories.Add(() =>
            {
                const string additionalFilePrefix = "AdditionalFiles.";
                return(from resourceName in Assembly.GetExecutingAssembly().GetManifestResourceNames()
                       where resourceName.StartsWith(additionalFilePrefix, StringComparison.Ordinal)
                       let content = ReadManifestResource(Assembly.GetExecutingAssembly(), resourceName)
                                     select(filename: resourceName.Substring(additionalFilePrefix.Length), SourceText.From(content)));
            });
        }
Ejemplo n.º 29
0
        public async Task CreateSolutionSnapshotId()
        {
            var code = "class A { }";

            var document = new AdhocWorkspace().CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code));

            var snapshotService = (new RemotableDataServiceFactory()).CreateService(document.Project.Solution.Workspace.Services) as IRemotableDataService;

            using (var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                var syncObject     = snapshot.GetRemotableData(snapshot.SolutionChecksum, CancellationToken.None);
                var solutionObject = await snapshotService.GetValueAsync <SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false);

                VerifySynchronizationObjectInService(snapshotService, syncObject);
                VerifyChecksumInService(snapshotService, solutionObject.Info, WellKnownSynchronizationKind.SolutionAttributes);
                VerifyChecksumInService(snapshotService, solutionObject.Projects.Checksum, WellKnownSynchronizationKind.Projects);

                Assert.Equal(solutionObject.Projects.Count, 1);
                VerifySnapshotInService(snapshotService, solutionObject.Projects.ToProjectObjects(snapshotService)[0], 1, 0, 0, 0, 0);
            }
        }
Ejemplo n.º 30
0
        public async Task TestAdditionalFile_DocumentChanged()
        {
            using (var workspace = CreateWorkspace())
            {
                var startText     = @"<setting value = ""goo""";
                var newText       = @"<setting value = ""goo1""";
                var document      = new TestHostDocument("public class C { }");
                var additionalDoc = new TestHostDocument(startText);
                var project1      = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });

                workspace.AddTestProject(project1);
                var buffer = additionalDoc.GetTextBuffer();
                workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());

                var project    = workspace.CurrentSolution.Projects.Single();
                var oldVersion = await project.GetSemanticVersionAsync();

                // fork the solution to introduce a change.
                var oldSolution = workspace.CurrentSolution;
                var newSolution = oldSolution.WithAdditionalDocumentText(additionalDoc.Id, SourceText.From(newText));
                workspace.TryApplyChanges(newSolution);

                var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);

                // new text should have been pushed into buffer
                Assert.Equal(newText, buffer.CurrentSnapshot.GetText());

                // Text changes are considered top level changes and they change the project's semantic version.
                Assert.Equal(await doc.GetTextVersionAsync(), await doc.GetTopLevelChangeTextVersionAsync());
                Assert.NotEqual(oldVersion, await doc.Project.GetSemanticVersionAsync());
            }
        }