Exemplo n.º 1
0
        public Rewriter(CSharpCompilation compilation, AnalyzerResult result)
        {
            tree = (CSharpSyntaxTree) compilation.SyntaxTrees.Single();
            model = compilation.GetSemanticModel(tree);

            this.compilation = compilation;
            this.result = result;
        }
Exemplo n.º 2
0
    public static void ConvertRoslynToCCI(
      IMetadataHost host,
      CSharpSyntaxTree tree,
      SemanticModel semanticModel,
      out IModule module,
      out ISourceLocationProvider sourceLocationProvider) {

      sourceLocationProvider = new SourceLocationProvider();

      var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider);
      var assembly = (Module)transformer.Visit(tree.GetRoot());
      assembly.Location = Path.GetFullPath(tree.FilePath);
      module = assembly;
    }
Exemplo n.º 3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="path"></param>
        /// <param name="sourceTree"></param>
        /// <param name="loadMsCoreLib"></param>
        /// <returns></returns>
        public static CSharpCompilation RetrieveCompilation(string name, string path, CSharpSyntaxTree sourceTree, bool loadMsCoreLib = false)
        {
            var references = new List<MetadataReference>();

            var assembly = MetadataReference.CreateFromFile(path); // The target assembly we want to translate
            references.Add(assembly);

            if (loadMsCoreLib)
            {
                var mscorelib = GetMsCoreLibMetadataReference(); // .NET native
                references.Add(mscorelib);
            }

            return CSharpCompilation.Create(name, new[] { sourceTree }, references);
        }
        /// <summary>
        /// Transforms the tree.
        /// </summary>
        /// <param name="node">The node which will be impacted by the transformation.</param>
        /// <param name="compilation">The compilation containing the semantic model associated to the node.</param>
        public void Transform(ref CSharpSyntaxTree tree, ref CSharpCompilation compilation)
        {
            if (tree == null)
            {
                throw new ArgumentNullException(nameof(tree), "A tree is needed!");
            }

            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation), "A compilation is needed!");
            }

            // 1. Initialize
            this.Initialize(tree, compilation);

            var res = GetTeeSymbols(this.tree, this.compilation.GetSemanticModel(this.tree)).ToArray(); // TBR

            // 2.1. Analyze
            this.RetrieveOverridenNamespaceNames();
            // 2.2. Rearrange
            this.ProcessOverridenNamespaceNames();
            // 2.3. Using directives handling for fixing references inside namespaces
            this.RetrieveAllUsingDirectivesAndCopyAtRootLevel();
            // 2.4. Tidy up
            this.CleanUpCompilationUnit();

            // 3. Update compilation and semantics
            this.UpdateCompilation();

            // 4. Updating references
            compilation = this.newCompilation;
            tree = this.newNode.SyntaxTree as CSharpSyntaxTree;

            //var diagnostics = this.compilation.GetSemanticModel(this.tree).GetDiagnostics(); // TBR, used to check errors
            //var newDiagnostics = this.newCompilation.GetSemanticModel(this.newTree).GetDiagnostics(); // TBR, used to check errors

            // 5. Clean resources
            this.CleanUp();
        }
        public async Task <SimAnticsModule> CompileModule()
        {
            var translator = new CSTranslator();
            var objIff     = File.MainIff;
            var refs       = GetReferences().ToList();

            if (!IsGlobal)
            {
                var global = await Context.GetGlobal();

                translator.Context.GlobalRes    = global.File;
                translator.Context.GlobalModule = global.Module;
                refs.Add(MetadataReference.CreateFromFile(global.FilePath + ".dll"));
            }
            else
            {
                translator.Context.GlobalRes = File;
            }

            var sg = File.SemiGlobal;

            if (sg != null)
            {
                var sgModule = await Context.GetSemiglobal(sg);

                translator.Context.SemiGlobalRes    = sg;
                translator.Context.SemiGlobalModule = sgModule.Module;
                refs.Add(MetadataReference.CreateFromFile(sgModule.FilePath + ".dll"));
            }

            translator.Context.ObjectRes = File;

            // create the cs source
            Console.WriteLine($"Translating {objIff.Filename}");
            var objText = translator.TranslateIff(objIff);

            // compile it into an assembly with roslyn
            var options = new CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary,
                                                       optimizationLevel: Context.Debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
                                                       moduleName: translator.Context.NamespaceName,
                                                       platform: Platform.AnyCpu,
                                                       warningLevel: 0);

            if (Context.Debug)
            {
                using (var files = System.IO.File.Open(FilePath + ".cs", System.IO.FileMode.Create))
                {
                    using (var writer = new System.IO.StreamWriter(files))
                    {
                        writer.Write(objText);
                    }
                }
            }
            var file = CSharpSyntaxTree.ParseText(objText, new CSharpParseOptions(), Path.GetFullPath(FilePath + ".cs"), Encoding.UTF8);

            var compiler = CSharpCompilation.Create(translator.Context.NamespaceName, options: options, references: refs, syntaxTrees: new List <SyntaxTree>()
            {
                file
            });
            // save the assembly to disk for later use
            var emitResult = compiler.Emit(FilePath + ".dll", Context.Debug ? (FilePath + ".pdb") : null, Context.Debug ? (FilePath + ".xml") : null);

            // load the assembly
            if (!emitResult.Success)
            {
                return(null);
            }
            try
            {
                var assembly = Assembly.LoadFile(Path.GetFullPath(FilePath + ".dll"));
                return(FindModuleInAssembly(assembly));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        private void Initialize(CSharpSyntaxTree tree, CSharpCompilation compilation)
        {
            this.tree = tree;

            if (this.tree.GetRoot() as CompilationUnitSyntax == null)
            {
                throw new ArgumentException(nameof(node),
                    $"This class expects root nodes of type: {typeof(CompilationUnitSyntax).Name}!");
            }

            this.node = this.tree.GetRoot() as CompilationUnitSyntax;
            this.compilation = compilation;

            this.transformationInfos = new List<TransformationInfo>();
            this.removableNamespaces = new List<SyntaxNode>();
        }
Exemplo n.º 7
0
    /// <summary>
    /// 编译dll
    /// </summary>
    /// <param name="rootpaths"></param>
    /// <param name="output"></param>
    static public bool BuildByRoslyn(string[] dlls, string[] codefiles, string output, bool isdebug = false)
    {
        //添加语法树
        //宏解析
        var Symbols = define.Split(';');
        List <Microsoft.CodeAnalysis.SyntaxTree> codes = new List <Microsoft.CodeAnalysis.SyntaxTree>();
        var opa = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: Symbols);

        foreach (var cs in codefiles)
        {
            var content    = File.ReadAllText(cs);
            var syntaxTree = CSharpSyntaxTree.ParseText(content, opa, cs, Encoding.UTF8);
            codes.Add(syntaxTree);
        }

        //添加dll
        List <MetadataReference> assemblies = new List <MetadataReference>();

        foreach (var dll in dlls)
        {
            var metaref = MetadataReference.CreateFromFile(dll);
            if (metaref != null)
            {
                assemblies.Add(metaref);
            }
        }

        //创建目录
        var dir = Path.GetDirectoryName(output);

        Directory.CreateDirectory(dir);
        //编译参数
        CSharpCompilationOptions option = null;

        if (isdebug)
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Debug, checkOverflow: true,
                                                  allowUnsafe: true
                                                  );
        }
        else
        {
            option = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                                  optimizationLevel: OptimizationLevel.Release, checkOverflow: true,
                                                  allowUnsafe: true
                                                  );
        }

        //创建编译器代理
        var        compilation = CSharpCompilation.Create(Path.GetFileName(output), codes, assemblies, option);
        EmitResult result      = null;

        if (!isdebug)
        {
            result = compilation.Emit(output);
        }
        else
        {
            var pdbPath     = output + ".pdb";
            var emitOptions = new EmitOptions(
                debugInformationFormat: DebugInformationFormat.PortablePdb,
                pdbFilePath: pdbPath);
            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    result = compilation.Emit(dllStream, pdbStream, options: emitOptions);

                    File.WriteAllBytes(output, dllStream.GetBuffer());
                    File.WriteAllBytes(pdbPath, pdbStream.GetBuffer());
                }
        }
        // 编译失败,提示
        if (!result.Success)
        {
            IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                         diagnostic.IsWarningAsError ||
                                                                         diagnostic.Severity == DiagnosticSeverity.Error);

            foreach (var diagnostic in failures)
            {
                Debug.LogError(diagnostic.ToString());
            }
        }

        return(result.Success);
    }
Exemplo n.º 8
0
    private void ConvertDialog()
    {
        var dialogFiles = Tig.FS.ListDirectory("dlg")
                          .Where(f => f.EndsWith(".dlg"))
                          .Distinct()
                          .ToList();

        Console.WriteLine($"Found {dialogFiles.Count} dialog files.");

        var dlgFilePattern = new Regex(@"(\d{5}).*");

        foreach (var dialogFile in dialogFiles)
        {
            var m = dlgFilePattern.Match(dialogFile);
            if (!m.Success)
            {
                Console.WriteLine($"Skipping dialog file that doesn't match expected pattern: {dialogFile}'.");
                continue;
            }

            var scriptId         = int.Parse(m.Groups[1].Value);
            var associatedScript = _convertedScripts.FirstOrDefault(s => s.Type == ScriptType.Object &&
                                                                    s.ScriptId == scriptId);
            if (associatedScript == null)
            {
                Console.WriteLine($"Dialog file {dialogFile} with id {scriptId} has no associated script!");
                continue;
            }

            var outputDir = Path.Join(
                Path.GetDirectoryName(associatedScript.OutputPath),
                "Dialog"
                );
            Directory.CreateDirectory(Path.Combine(_outputDirectory, outputDir));

            var outputPath = Path.Join(outputDir,
                                       Path.GetFileNameWithoutExtension(associatedScript.OutputPath) + "Dialog.cs");
            if (_writeDialog)
            {
                File.Delete(Path.Combine(_outputDirectory, outputPath));
            }

            var dialogContent = Tig.FS.ReadTextFile("dlg/" + dialogFile);
            var parser        = new DialogScriptParser(dialogFile, dialogContent);

            // We're going to build a class file for the dialog script that contains two methods,
            // and extends from the object script of the same script id

            var conditions  = new List <(int, string, string)>();
            var effects     = new List <(int, string, string)>();
            var skillChecks = new List <(int, SkillCheck)>();

            while (parser.GetSingleLine(out var dialogLine, out var fileLine))
            {
                var effectPython = dialogLine.effectField;
                if (effectPython == "pc.barter(npc)" &&
                    dialogLine.txt.StartsWith("b:", StringComparison.OrdinalIgnoreCase))
                {
                    continue; // Skip bogus barter effect (this is implied by B:)
                }

                try
                {
                    if (!string.IsNullOrEmpty(effectPython))
                    {
                        var converted = converter.ConvertSnippet(effectPython, associatedScript, DialogContext);
                        effects.Add((dialogLine.key, effectPython, converted));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        $"[e] Failed to convert effect for line {dialogLine.key} ({effectPython}): {e}");
                    effects.Add((dialogLine.key, effectPython, null));
                }

                if (dialogLine.IsPcLine)
                {
                    var conditionPython = dialogLine.testField;
                    try
                    {
                        if (!string.IsNullOrEmpty(conditionPython))
                        {
                            foreach (var skillCheck in converter.FindSkillChecks(conditionPython))
                            {
                                skillChecks.Add((dialogLine.key, skillCheck));
                            }

                            var converted =
                                converter.ConvertSnippet(conditionPython, associatedScript, DialogContext);
                            conditions.Add((dialogLine.key, conditionPython, converted));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            $"[e] Failed to convert condition for line {dialogLine.key} ({conditionPython}): {e}");
                        conditions.Add((dialogLine.key, conditionPython, null));
                    }
                }
            }

            if (_writeDialog)
            {
                var dialogScript = new StringBuilder();

                dialogScript.AppendLine(@"
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenTemple.Core.GameObject;
using OpenTemple.Core.Systems;
using OpenTemple.Core.Systems.Dialog;
using OpenTemple.Core.Systems.Feats;
using OpenTemple.Core.Systems.D20;
using OpenTemple.Core.Systems.Script;
using OpenTemple.Core.Systems.Spells;
using OpenTemple.Core.Systems.GameObjects;
using OpenTemple.Core.Systems.D20.Conditions;
using OpenTemple.Core.Location;
using OpenTemple.Core.Systems.ObjScript;
using OpenTemple.Core.Ui;
using System.Linq;
using OpenTemple.Core.Systems.Script.Extensions;
using OpenTemple.Core.Utils;
using static OpenTemple.Core.Systems.Script.ScriptUtilities;
");
                dialogScript.AppendLine("namespace " + associatedScript.Namespace + ".Dialog");
                dialogScript.AppendLine("{");
                dialogScript.Append("[DialogScript(").Append(associatedScript.ScriptId).AppendLine(")]");
                dialogScript.AppendLine("public class " + associatedScript.ClassName + "Dialog : " +
                                        associatedScript.ClassName + ", IDialogScript");
                dialogScript.AppendLine("{");

                WriteDialogMethod(dialogScript, conditions, false);
                WriteDialogMethod(dialogScript, effects, true);
                WriteSkillChecksMethod(dialogScript, skillChecks);

                dialogScript.AppendLine("}");
                dialogScript.AppendLine("}");

                var parseOptions  = new CSharpParseOptions(LanguageVersion.Latest);
                var syntaxTree    = CSharpSyntaxTree.ParseText(dialogScript.ToString(), parseOptions);
                var formattedNode = Formatter.Format(syntaxTree.GetRoot(), workspace);

                File.WriteAllText(Path.Join(_outputDirectory, outputPath), formattedNode.ToFullString());
            }
        }
    }
Exemplo n.º 9
0
        public static bool TryGetJsonForAnonymousType(this string anonymousTypeString, out string json)
        {
            json = null;

            foreach (var substitution in Substitutions)
            {
                anonymousTypeString = anonymousTypeString.Replace(substitution.Key, substitution.Value);
            }

            var text =
                $@"
					using System;
                    using System.Collections.Generic;
					using System.ComponentModel;
					using Newtonsoft.Json;
					using Newtonsoft.Json.Linq;

					namespace Temporary
					{{
						public class Json
						{{
							public string Write()
							{{
								var o = {anonymousTypeString};
								var json = JsonConvert.SerializeObject(o, Formatting.Indented);
								return json;
							}}
						}}
					}}"                    ;

            var syntaxTree   = CSharpSyntaxTree.ParseText(text);
            var assemblyName = Path.GetRandomFileName();
            var references   = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(JsonConvert).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ITypedList).GetTypeInfo().Assembly.Location),
            };
            var systemReferences = new string[]
            {
                "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
                "System.ObjectModel, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
                "System.Dynamic.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
                "System.Linq.Expressions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
            };

            foreach (var r in systemReferences)
            {
                var location = Assembly.Load(r).Location;
                references.Add(MetadataReference.CreateFromFile(location));
            }

            var compilation =
                CSharpCompilation.Create(
                    assemblyName,
                    new[] { syntaxTree },
                    references,
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

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

                if (!result.Success)
                {
                    var failures = result.Diagnostics.Where(diagnostic =>
                                                            diagnostic.IsWarningAsError ||
                                                            diagnostic.Severity == DiagnosticSeverity.Error);

                    var builder = new StringBuilder($"Unable to serialize the following C# anonymous type string to json: {anonymousTypeString}");
                    foreach (var diagnostic in failures)
                    {
                        builder.AppendLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
                    }
                    builder.AppendLine(new string('-', 30));

                    Console.Error.WriteLine(builder.ToString());
                    return(false);
                }

                ms.Seek(0, SeekOrigin.Begin);

                var assembly = Assembly.Load(ms.ToArray());
                var type     = assembly.GetType("Temporary.Json");
                var obj      = Activator.CreateInstance(type);

                var output = type.InvokeMember("Write",
                                               BindingFlags.Default | BindingFlags.InvokeMethod,
                                               null,
                                               obj,
                                               new object[] { });

                json = output.ToString();
                return(true);
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Creates a CSharpSyntaxTree instance.
 /// </summary>
 /// <param name="sourceCode"></param>
 /// <param name="sourceCodePath"></param>
 /// <returns></returns>
 public override Microsoft.CodeAnalysis.SyntaxTree GetSyntaxTree(string sourceCode, string sourceCodePath)
 {
     return(CSharpSyntaxTree.ParseText(sourceCode, path: sourceCodePath, encoding: System.Text.Encoding.UTF8));
 }
Exemplo n.º 11
0
 private static SyntaxTree Parse(string snippet) => CSharpSyntaxTree.ParseText(snippet);
        static Dictionary <string, IPropertyAccessor> GetAccessorTypes(Type type, string code)
        {
            var sourceCode = $"using System;\r\nusing Olive.Entities;\r\nusing System.Data;{code}";
            var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);

            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            var assemblyName = Path.GetRandomFileName();

            var references2 = Cache.GetOrAdd(type.Assembly, assembly =>
            {
                var references = new List <PortableExecutableReference>
                {
                    MetadataReference.CreateFromFile(typeof(IEntity).Assembly.Location),
                    MetadataReference.CreateFromFile(type.Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(Guid).Assembly.Location),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Data.Common.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Console.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "netstandard.dll")),
                };

                foreach (var item in type.Assembly.GetReferencedAssemblies())
                {
                    references.Add(MetadataReference.CreateFromFile(Assembly.Load(item).Location));
                }
                return(references);
            });

            var compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references2,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var stream = new MemoryStream())
            {
                var emitResult = compilation.Emit(stream);

                if (!emitResult.Success)
                {
                    var error = new Exception("DataProviderMetaDataGenerator failed." +
                                              emitResult.Diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error)
                                              .Select(v => v.GetMessage()).Distinct().ToLinesString().WithPrefix(Environment.NewLine));
                    Console.WriteLine(error.Message);
                    throw error;
                }

                stream.Seek(0, SeekOrigin.Begin);
                var assembly = Assembly.Load(stream.ToArray());

                var result = new Dictionary <string, IPropertyAccessor>();

                foreach (var accessorType in assembly.GetTypes())
                {
                    result.Add(accessorType.Name, (IPropertyAccessor)Activator.CreateInstance(accessorType));
                }

                return(result);
            }
        }
Exemplo n.º 13
0
        public static void Document(Action shouldMethod, ITestOutputHelper testOutputHelper, Action <ShouldMatchConfigurationBuilder>?additionConfig = null)
        {
            var stackTrace     = new StackTrace(true);
            var caller         = stackTrace.GetFrame(1) !;
            var callerFileName = caller.GetFileName() !;
            var callerMethod   = caller.GetMethod() !;

            var testMethod = FileMethodsLookup.GetOrAdd(callerFileName, fn =>
            {
                var callerFile = File.ReadAllText(fn);
                var syntaxTree = CSharpSyntaxTree.ParseText(callerFile);
                return(syntaxTree.GetRoot()
                       .DescendantNodes()
                       .OfType <MethodDeclarationSyntax>().ToList());
            }).Single(m => m.Identifier.ValueText == callerMethod.Name);

            var documentCall = testMethod.DescendantNodes()
                               .OfType <InvocationExpressionSyntax>()
                               .First();

            var shouldMethodCallSyntax = documentCall.ArgumentList.Arguments[0];
            var blockSyntax            = shouldMethodCallSyntax.DescendantNodes()
                                         .OfType <BlockSyntax>()
                                         .First();
            var enumerable = blockSyntax
                             .Statements
                             .Select(s => s.WithoutLeadingTrivia().ToFullString());
            var body          = string.Join(string.Empty, enumerable).Trim();
            var exceptionText = Should.Throw <Exception>(shouldMethod).Message;

            testOutputHelper.WriteLine("Docs body:");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine(body);
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("Exception text:");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine(exceptionText);

            Func <string, string> scrubber = v => Regex.Replace(v, @"\w:.+?shouldly\\src", "C:\\PathToCode\\shouldly\\src");

            try
            {
                body.ShouldMatchApproved(configurationBuilder =>
                {
                    configurationBuilder
                    .WithDiscriminator("codeSample")
                    .UseCallerLocation()
                    .SubFolder("CodeExamples")
                    .WithScrubber(scrubber).WithFileExtension(".cs");

                    additionConfig?.Invoke(configurationBuilder);
                });
            }
            finally
            {
                exceptionText = $@"```
{exceptionText}
```
";
                exceptionText.ShouldMatchApproved(configurationBuilder =>
                {
                    configurationBuilder
                    .WithDiscriminator("exceptionText")
                    .UseCallerLocation()
                    .SubFolder("CodeExamples")
                    .WithScrubber(scrubber);

                    additionConfig?.Invoke(configurationBuilder);
                });
            }
        }
Exemplo n.º 14
0
        private static Type[] LoadCSScript(string file)
        {
            var text = File.ReadAllText(file);

            // define source code, then parse it (to the type used for compilation)
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(text);

            // define other necessary objects for compilation
            string assemblyName = Path.GetRandomFileName();
            List <MetadataReference> references = new()
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(IPerformanceTest).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(HttpRequestMessage).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(GCLatencyMode).Assembly.Location),
                MetadataReference.CreateFromFile(Assembly.GetEntryAssembly() !.Location)
            };

            Assembly.GetEntryAssembly() !.GetReferencedAssemblies().ToList()
            .ForEach(a => references.Add(MetadataReference.CreateFromFile(Assembly.Load(a).Location)));

            // analyse and generate IL code from syntax tree
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                                             optimizationLevel: OptimizationLevel.Release));

            using var ms = new MemoryStream();
            // write IL code into memory
            EmitResult result = compilation.Emit(ms);

            if (!result.Success)
            {
                // handle exceptions
                IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                             diagnostic.IsWarningAsError ||
                                                                             diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                }
            }
            else
            {
                // load this 'virtual' DLL so that we can use
                ms.Seek(0, SeekOrigin.Begin);
                Assembly assembly = Assembly.Load(ms.ToArray());

                return((from type in assembly.GetTypes()
                        where type.BaseType == typeof(IPerformanceTest)
                        select type).ToArray());
            }

            return(Array.Empty <Type>());
        }
        public void TestSetup()
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(Source);

            methods = syntaxTree.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>().ToList();
        }
        public SyntaxTree ParseText(string text)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(text);

            return(syntaxTree);
        }
Exemplo n.º 17
0
        public static AssemblyDefinition GenerateSerializationAssembly(PlatformType platformType, BaseAssemblyResolver assemblyResolver, AssemblyDefinition assembly, string serializationAssemblyLocation, string signKeyFile, List <string> references, List <AssemblyDefinition> memoryReferences, ILogger log)
        {
            // Create the serializer code generator
            var serializerGenerator = new ComplexSerializerCodeGenerator(assemblyResolver, assembly, log);

            // Register default serialization profile (to help AOT generic instantiation of serializers)
            RegisterDefaultSerializationProfile(assemblyResolver, assembly, serializerGenerator);

            // Generate serializer code
            var serializerGeneratedCode = serializerGenerator.TransformText();

            var syntaxTree = CSharpSyntaxTree.ParseText(serializerGeneratedCode);

            // Add reference from source assembly
            // Use a hash set because it seems including twice mscorlib (2.0 and 4.0) seems to be a problem.
            var skipWindows = "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null";

            var compilerOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);

            // Sign the serialization assembly the same way the source was signed
            // TODO: Transmit over command line
            if (assembly.Name.HasPublicKey)
            {
                // TODO: If delay signed, we could actually extract the public key and apply it ourself maybe?
                if (signKeyFile == null)
                {
                    throw new InvalidOperationException("Generating serialization code for signed assembly, but no key was specified.");
                }

                compilerOptions = compilerOptions.WithCryptoKeyFile(signKeyFile).WithStrongNameProvider(new DesktopStrongNameProvider());
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) != ModuleAttributes.StrongNameSigned)
                {
                    // Delay signed
                    compilerOptions = compilerOptions.WithDelaySign(true);
                }
            }

            // Add references (files and in-memory PE data)
            var metadataReferences = new List <MetadataReference>();

            foreach (var reference in references)
            {
                metadataReferences.Add(MetadataReference.CreateFromFile(reference));
            }

            foreach (var reference in memoryReferences)
            {
                metadataReferences.Add(CreateMetadataReference(assemblyResolver, reference));
            }

            // typeof(Dictionary<,>)
            // Special case for 4.5: Because Dictionary<,> is forwarded, we need to add a reference to the actual assembly
            var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, mscorlibAssembly));
            var collectionType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(Dictionary <,>).FullName);

            metadataReferences.Add(CreateMetadataReference(assemblyResolver, collectionType.Module.Assembly));
            metadataReferences.Add(CreateMetadataReference(assemblyResolver, assembly));

            // In case SiliconStudio.Core was not referenced, let's add it.
            if (assembly.Name.Name != "SiliconStudio.Core" && !references.Any(x => string.Compare(Path.GetFileNameWithoutExtension(x), "SiliconStudio.Core", StringComparison.OrdinalIgnoreCase) == 0))
            {
                metadataReferences.Add(CreateMetadataReference(assemblyResolver, assemblyResolver.Resolve("SiliconStudio.Core")));
            }

            // Create roslyn compilation object
            var assemblyName = assembly.Name.Name + ".Serializers";
            var compilation  = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, metadataReferences, compilerOptions);

            // Do the actual compilation, and check errors
            using (var peStream = new FileStream(serializationAssemblyLocation, FileMode.Create, FileAccess.Write))
            {
                var compilationResult = compilation.Emit(peStream);

                if (!compilationResult.Success)
                {
                    var errors = new StringBuilder();
                    errors.AppendLine(string.Format("Serialization assembly compilation: {0} error(s)", compilationResult.Diagnostics.Count(x => x.Severity >= DiagnosticSeverity.Error)));
                    foreach (var error in compilationResult.Diagnostics)
                    {
                        if (error.Severity >= DiagnosticSeverity.Warning)
                        {
                            errors.AppendLine(error.ToString());
                        }
                    }
                    throw new InvalidOperationException(errors.ToString());
                }
            }

            var repackOptions = new ILRepacking.RepackOptions(new string[0])
            {
                OutputFile     = assembly.MainModule.FullyQualifiedName,
                DebugInfo      = true,
                CopyAttributes = true,
                AllowMultipleAssemblyLevelAttributes = true,
                XmlDocumentation  = false,
                NoRepackRes       = true,
                InputAssemblies   = new[] { serializationAssemblyLocation },
                SearchDirectories = assemblyResolver.GetSearchDirectories(),
                SearchAssemblies  = references,
            };

            // Run ILMerge
            var merge = new ILRepacking.ILRepack(repackOptions)
            {
                PrimaryAssemblyDefinition = assembly,
                MemoryOnly = true,
                //KeepFirstOfMultipleAssemblyLevelAttributes = true,
                //Log = true,
                //LogFile = "ilmerge.log",
            };

            try
            {
                merge.Repack();
            }
            catch (Exception)
            {
                log.Log(new LogMessage("ILRepack", LogMessageType.Error, string.Format("Error while ILRepacking {0}", assembly.Name.Name)));
                throw;
            }

            // Copy name
            merge.TargetAssemblyDefinition.Name.Name    = assembly.Name.Name;
            merge.TargetAssemblyDefinition.Name.Version = assembly.Name.Version;

            // Add assembly signing info
            if (assembly.Name.HasPublicKey)
            {
                merge.TargetAssemblyDefinition.Name.PublicKey      = assembly.Name.PublicKey;
                merge.TargetAssemblyDefinition.Name.PublicKeyToken = assembly.Name.PublicKeyToken;
                merge.TargetAssemblyDefinition.Name.Attributes    |= AssemblyAttributes.PublicKey;
                if ((assembly.MainModule.Attributes & ModuleAttributes.StrongNameSigned) == ModuleAttributes.StrongNameSigned)
                {
                    merge.TargetAssemblyMainModule.Attributes |= ModuleAttributes.StrongNameSigned;
                }
            }

            try
            {
                // Delete serializer dll
                File.Delete(serializationAssemblyLocation);

                var serializationAssemblyPdbFilePath = Path.ChangeExtension(serializationAssemblyLocation, "pdb");
                if (File.Exists(serializationAssemblyPdbFilePath))
                {
                    File.Delete(serializationAssemblyPdbFilePath);
                }
            }
            catch (IOException)
            {
                // Mute IOException
            }

            return(merge.TargetAssemblyDefinition);
        }
Exemplo n.º 18
0
        private static bool DoHandleDrop([NotNull] Store store, [NotNull] string filename)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store));
            }

            if (filename == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }

            try
            {
                if (string.IsNullOrEmpty(filename))
                {
                    return(false);
                }

                // read the file
                string fileContents = File.ReadAllText(filename);

                // parse the contents
                SyntaxTree tree = CSharpSyntaxTree.ParseText(fileContents);

                if (tree.GetRoot() is CompilationUnitSyntax root)
                {
                    List <ClassDeclarationSyntax> classDecls = root.DescendantNodes().OfType <ClassDeclarationSyntax>().Where(classDecl => classDecl.BaseList == null || classDecl.BaseList.Types.FirstOrDefault()?.ToString() != "DbContext").ToList();
                    List <EnumDeclarationSyntax>  enumDecls  = root.DescendantNodes().OfType <EnumDeclarationSyntax>().ToList();

                    if (!classDecls.Any() && !enumDecls.Any())
                    {
                        WarningDisplay.Show($"Couldn't find any classes or enums to add to the model in {filename}");

                        return(false);
                    }

                    // keep this order: enums, classes, class properties

                    foreach (EnumDeclarationSyntax enumDecl in enumDecls)
                    {
                        ProcessEnum(store, enumDecl);
                    }

                    List <ModelClass> processedClasses = new List <ModelClass>();
                    foreach (ClassDeclarationSyntax classDecl in classDecls)
                    {
                        processedClasses.Add(ProcessClass(store, classDecl));
                    }

                    // process last so all classes and enums are already in the model
                    foreach (ClassDeclarationSyntax classDecl in classDecls)
                    {
                        ProcessProperties(store, classDecl);
                    }

                    // now that all the properties are in, go through the classes again and ensure identities are present based on convention
                    // ReSharper disable once LoopCanBePartlyConvertedToQuery
                    foreach (ModelClass modelClass in processedClasses.Where(c => !c.AllIdentityAttributes.Any()))
                    {
                        // no identity attribute. Only look in current class for attributes that could be identity by convention
                        List <ModelAttribute> identitiesByConvention = modelClass.Attributes.Where(a => a.Name == "Id" || a.Name == $"{modelClass.Name}Id").ToList();

                        // if both 'Id' and '[ClassName]Id' are present, don't do anything since we don't know which to make the identity
                        if (identitiesByConvention.Count == 1)
                        {
                            using (Transaction transaction = store.TransactionManager.BeginTransaction("Add identity"))
                            {
                                identitiesByConvention[0].IsIdentity = true;
                                transaction.Commit();
                            }
                        }
                    }
                }
            }
            catch
            {
                ErrorDisplay.Show("Error interpreting " + filename);

                return(false);
            }

            return(true);
        }
Exemplo n.º 19
0
        private byte[] CompileByte(string originalClassName, string originalText)
        {
            Console.WriteLine(assemblieslist);
            if (assemblieslist == null)
            {
                string replstr    = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "file:///" : "file://";
                var    assemblies = CompilerServicesUtility
                                    .GetLoadedAssemblies()
                                    .Where(a => !a.IsDynamic && File.Exists(a.CodeBase.Replace(replstr, "")))
                                    .Select(a => (a.CodeBase.Replace(replstr, "")));

                int c = assemblies.Count();

                assemblieslist = new MetadataReference[c];

                int i = 0;
                foreach (string item in assemblies)
                {
                    assemblieslist[i] = (MetadataReference.CreateFromFile(item));
                    i++;
                }
            }
            CSharpCompilation compilation = null;
            var syntaxTree = CSharpSyntaxTree.ParseText(originalText);
            // 指定编译选项。
            var assemblyName = $"{originalClassName}.g";

            compilation = CSharpCompilation.Create(assemblyName, new[] { syntaxTree },
                                                   options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                          .AddReferences(
                // 这算是偷懒了吗?我把 .NET Core 运行时用到的那些引用都加入到引用了。
                // 加入引用是必要的,不然连 object 类型都是没有的,肯定编译不通过。
                //AppDomain.CurrentDomain.GetAssemblies().Select(x => MetadataReference.CreateFromFile(x.Location))
                assemblieslist
                );
            // 编译到内存流中。
            byte [] buff = null;
            using (var ms = new MemoryStream())
            {
                var result = compilation.Emit(ms);
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    buff = ms.ToArray();
                }
                else
                {
                    string errmsg = "";
                    for (int i1 = 0; i1 < result.Diagnostics.Length; i1++)
                    {
                        errmsg += result.Diagnostics[i1] + "\r\n";
                    }
                    throw new Exception(errmsg);
                }
                ms.Close();
            }

            /*
             * for (int i1=0;i1< list.Length;i1++)
             * {
             *  list[i1] = null;
             * }
             */
            return(buff);

            // }
            //catch (Exception e)
            //{

            //}
            return(null);
        }
Exemplo n.º 20
0
 public static CSharpSyntaxTree ParseText(string code)
 {
     return((CSharpSyntaxTree)CSharpSyntaxTree.ParseText(code));
 }
Exemplo n.º 21
0
 protected static CSharpSyntaxTree Parse(string text, string path = null)
 {
     return((CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, CSharpParseOptions, path: path));
 }
Exemplo n.º 22
0
        public async Task ReturnsDefinitionInMetadata_FromMetadata_WhenSymbolIsType(string filename)
        {
            var testFile = new TestFile(filename, @"
using System;
class Bar {
    public void Baz() {
        var number = in$$t.MaxValue;
    }
}");

            using (var host = CreateOmniSharpHost(testFile))
            {
                var point = testFile.Content.GetPointFromPosition();

                // 1. start by asking for definition of "int"
                var gotoDefinitionRequest = new GotoDefinitionRequest
                {
                    FileName     = testFile.FileName,
                    Line         = point.Line,
                    Column       = point.Offset,
                    WantMetadata = true
                };
                var gotoDefinitionRequestHandler = GetRequestHandler(host);
                var gotoDefinitionResponse       = await gotoDefinitionRequestHandler.Handle(gotoDefinitionRequest);

                // 2. now, based on the response information
                // go to the metadata endpoint, and ask for "int" specific metadata
                var metadataRequest = new MetadataRequest
                {
                    AssemblyName = gotoDefinitionResponse.MetadataSource.AssemblyName,
                    TypeName     = gotoDefinitionResponse.MetadataSource.TypeName,
                    ProjectName  = gotoDefinitionResponse.MetadataSource.ProjectName,
                    Language     = gotoDefinitionResponse.MetadataSource.Language
                };
                var metadataRequestHandler = host.GetRequestHandler <MetadataService>(OmniSharpEndpoints.Metadata);
                var metadataResponse       = await metadataRequestHandler.Handle(metadataRequest);

                // 3. the metadata response contains SourceName (metadata "file") and SourceText (syntax tree)
                // use the source to locate "IComparable" which is an interface implemented by Int32 struct
                var metadataTree = CSharpSyntaxTree.ParseText(metadataResponse.Source);
                var iComparable  = metadataTree.GetCompilationUnitRoot().
                                   DescendantNodesAndSelf().
                                   OfType <BaseTypeDeclarationSyntax>().First().
                                   BaseList.Types.FirstOrDefault(x => x.Type.ToString() == "IComparable");
                var relevantLineSpan = iComparable.GetLocation().GetLineSpan();

                // 4. now ask for the definition of "IComparable"
                // pass in the SourceName (metadata "file") as FileName - since it's not a regular file in our workspace
                var metadataNavigationRequest = new GotoDefinitionRequest
                {
                    FileName     = metadataResponse.SourceName,
                    Line         = relevantLineSpan.StartLinePosition.Line,
                    Column       = relevantLineSpan.StartLinePosition.Character,
                    WantMetadata = true
                };
                var metadataNavigationResponse = await gotoDefinitionRequestHandler.Handle(metadataNavigationRequest);

                // 5. validate the response to be matching the expected IComparable meta info
                Assert.NotNull(metadataNavigationResponse.MetadataSource);
                Assert.Equal(AssemblyHelpers.CorLibName, metadataNavigationResponse.MetadataSource.AssemblyName);
                Assert.Equal("System.IComparable", metadataNavigationResponse.MetadataSource.TypeName);

                Assert.NotEqual(0, metadataNavigationResponse.Line);
                Assert.NotEqual(0, metadataNavigationResponse.Column);
            }
        }
Exemplo n.º 23
0
        private static void Main(string[] args)
        {
            string attribute       = "";
            string csvOutputFile   = "";
            string directoryToScan = "";
            string negativeSearch  = "";
            Dictionary <String, List <Result> > results = new Dictionary <string, List <Result> >();

            try
            {
                var  options     = new Options();
                bool isFlagValid = options.OptionParser(args, out csvOutputFile, out attribute, out directoryToScan, out negativeSearch);

                // If Command-line options not set correctly, show default message and exit
                if (!isFlagValid)
                {
                    System.Environment.Exit(0);
                }

                if (String.IsNullOrEmpty(csvOutputFile))
                {
                    DateTime dt        = DateTime.Now;
                    String   timestamp = dt.ToString("yyyyMMddHHmmss");
                    csvOutputFile = "enumerated_controllers_" + timestamp + ".csv";
                }

                string curDir = Directory.GetCurrentDirectory();
                if (String.IsNullOrEmpty(directoryToScan))
                {
                    directoryToScan = curDir;
                }
                string[] paths = Directory.GetFiles(directoryToScan, "*.cs", SearchOption.AllDirectories);

                if (paths.Length > 0)
                {
                    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, attribute))
                            {
                                controllerchk.enumerateEntrypoints(root, attribute, negativeSearch, path, results);
                            }
                        }
                    }

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

                    if (!String.IsNullOrEmpty(attribute) || !String.IsNullOrEmpty(negativeSearch))
                    {
                        printCommandLineResults(results, pathToTrim);
                    }

                    printCSVResults(results, csvOutputFile, pathToTrim);
                }
            }
            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)
            {
                Console.WriteLine("Unexpected error");
            }
        }
Exemplo n.º 24
0
        public void ReportErrors()
        {
            string text =
                @"class C
{
}";

            using (var directory = new DisposableDirectory(Temp))
            {
                var file = directory.CreateFile("c.cs");
                file.WriteAllText(text);

                // Error only.
                var diagnostics = DiagnosticBag.GetInstance();
                RunCompiler(
                    directory.Path,
                    file.Path,
                    diagnostics,
                    ImmutableArray.Create <SourceGenerator>(
                        new SimpleSourceGenerator(
                            c =>
                {
                    c.ReportDiagnostic(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IntDivByZero), Location.None));
                })));
                diagnostics.Verify(
                    Diagnostic(ErrorCode.ERR_IntDivByZero).WithLocation(1, 1));
                diagnostics.Free();

                // Error and valid tree.
                diagnostics = DiagnosticBag.GetInstance();
                RunCompiler(
                    directory.Path,
                    file.Path,
                    diagnostics,
                    ImmutableArray.Create <SourceGenerator>(
                        new SimpleSourceGenerator(
                            c =>
                {
                    c.AddCompilationUnit("S", CSharpSyntaxTree.ParseText(@"struct S { }"));
                    c.ReportDiagnostic(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IntDivByZero), Location.None));
                })));
                diagnostics.Verify(
                    Diagnostic(ErrorCode.ERR_IntDivByZero).WithLocation(1, 1));
                diagnostics.Free();

                // Error and tree with parse error.
                diagnostics = DiagnosticBag.GetInstance();
                RunCompiler(
                    directory.Path,
                    file.Path,
                    diagnostics,
                    ImmutableArray.Create <SourceGenerator>(
                        new SimpleSourceGenerator(
                            c =>
                {
                    c.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(@"class { }"));
                    c.ReportDiagnostic(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IntDivByZero), Location.None));
                })));
                diagnostics.Verify(
                    Diagnostic(ErrorCode.ERR_IntDivByZero).WithLocation(1, 1),
                    Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(1, 7));
                diagnostics.Free();
            }
        }
        public static void ValidateProperty(CSharpSyntaxTree tree, SemanticModel model, Property propertyToValidate)
        {
            var treeProperties = GetTreeProperties(tree, model);

            GetPropertyValidationError(treeProperties, propertyToValidate);
        }
Exemplo n.º 26
0
        private static Assembly CompileScript(string[] path)
        {
            var scriptPath  = path.Length > 1 ? Path.GetDirectoryName(path[0]) : path[0];
            var scriptName  = Path.GetFileName(scriptPath);
            var symbolsName = Path.ChangeExtension(scriptName, "pdb");

            try
            {
                var syntaxTrees = path.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), null, file, Encoding.UTF8));
                var compilation = CSharpCompilation.Create(
                    scriptName,
                    syntaxTrees,
                    References,
                    CompilationOptions);

                var emitOptions = new EmitOptions(
                    debugInformationFormat: DebugInformationFormat.PortablePdb,
                    pdbFilePath: symbolsName);

                var assemblyStream = new MemoryStream();
                var symbolsStream  = new MemoryStream();

                var result = compilation.Emit(
                    assemblyStream,
                    symbolsStream,
                    options: emitOptions);

                if (result.Success)
                {
                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    symbolsStream.Seek(0, SeekOrigin.Begin);

                    var script = Assembly.Load(assemblyStream.ToArray(), symbolsStream.ToArray());
                    // in netcore:
                    //var script = AssemblyLoadContext.Default.LoadFromStream(ms);
                    if (script == null)
                    {
                        Trace.TraceWarning($"Script {scriptPath} could not be loaded into the process.");
                    }
                    return(script);
                }
                else
                {
                    var errors = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

                    var errorString = new StringBuilder();
                    errorString.AppendFormat("Skipped script {0} with error:", scriptPath);
                    errorString.Append(Environment.NewLine);
                    foreach (var error in errors)
                    {
                        var textSpan = error.Location.SourceSpan;
                        var fileName = Path.GetFileName(error.Location.SourceTree.FilePath);
                        var lineSpan = error.Location.SourceTree.GetLineSpan(textSpan);
                        var line     = lineSpan.StartLinePosition.Line + 1;
                        var column   = lineSpan.StartLinePosition.Character + 1;
                        errorString.AppendFormat("\t{0}: {1}, ", error.Id, error.GetMessage());
                        if (path.Length > 1)
                        {
                            errorString.AppendFormat("file: {0}, ", fileName);
                        }
                        errorString.AppendFormat("line: {0}, column: {1}", line, column);
                        errorString.Append(Environment.NewLine);
                    }

                    Trace.TraceWarning(errorString.ToString());
                    return(null);
                }
            }
            catch (InvalidDataException error)
            {
                Trace.TraceWarning("Skipped script {0} with error: {1}", scriptPath, error.Message);
                return(null);
            }
            catch (Exception error)
            {
                if (File.Exists(scriptPath) || Directory.Exists(scriptPath))
                {
                    Trace.WriteLine(new FileLoadException(scriptPath, error));
                }
                else
                {
                    Trace.TraceWarning("Ignored missing script {0}", scriptPath);
                }
                return(null);
            }
        }
        public static void ValidateClass(CSharpSyntaxTree tree, SemanticModel model, string className)
        {
            var classDeclarations = GetClassDeclarations(tree, model);

            GetClassValidationError(classDeclarations, className);
        }
 protected override SyntaxTree ParseText(string code)
 {
     return(CSharpSyntaxTree.ParseText(code));
 }
        public static void ValidateMethod(CSharpSyntaxTree tree, SemanticModel model, string methodName)
        {
            var treeMethods = GetTreeMethods(tree, model);

            GetVoidMethodValidationError(treeMethods, methodName);
        }
        /// <summary>
        /// Transforms the tree.
        /// </summary>
        /// <param name="node">The node which will be impacted by the transformation.</param>
        public void Transform(ref CSharpSyntaxTree tree)
        {
            if (tree == null)
            {
                throw new ArgumentNullException(nameof(tree), "A tree is needed!");
            }

            // 1. Initialize
            this.Initialize(tree, compilation);

            // 2.1. Analyze
            this.RetrieveOverridenNamespaceNames();
            // 2.2. Rearrange
            this.ProcessOverridenNamespaceNames();
            // We don't perform using directives rearrangement like in other method as that is meaningful only when having a semantic model
            // 2.3. Tidy up
            this.CleanUpCompilationUnit();

            // 3. Updating references
            tree = this.newNode.SyntaxTree as CSharpSyntaxTree;

            // 4. Clean resources
            this.CleanUp();
        }
 public static List <IMethodSymbol> GetTreeMethods(CSharpSyntaxTree tree, SemanticModel model)
 {
     return(tree.GetCompilationUnitRoot().DescendantNodes().OfType <MethodDeclarationSyntax>()
            .Select(p => model.GetDeclaredSymbol(p))
            .ToList());
 }
        /// <summary>
        /// Updates the semantic model after all the changes.
        /// </summary>
        private void UpdateCompilation()
        {
            this.newTree = this.newNode.SyntaxTree as CSharpSyntaxTree;

            this.newCompilation = this.compilation.ReplaceSyntaxTree(this.tree, this.newTree);
            this.newCompilation.GetSemanticModel(this.newTree); // NOT NEEDED
        }
Exemplo n.º 33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="name"></param>
 /// <param name="path"></param>
 /// <param name="sourceTree"></param>
 /// <param name="loadMsCoreLib"></param>
 /// <returns></returns>
 public static SemanticModel RetrieveSemanticModel(string name, string path, CSharpSyntaxTree sourceTree, bool loadMsCoreLib = false)
 {
     return RetrieveCompilation(name, path, sourceTree, loadMsCoreLib).GetSemanticModel(sourceTree);
 }
Exemplo n.º 34
0
        void ExecuteCore(GeneratorExecutionContext context)
        {
            context.AddSource("EnumWithValues.cs", SourceText.From(AttributeClassesSource, Encoding.UTF8));
            if (context.SyntaxReceiver is not SyntaxReceiver receiver)
            {
                return;
            }
            if (context.Compilation is not Compilation compilation)
            {
                return;
            }
            var options = (compilation as CSharpCompilation) !.SyntaxTrees[0].Options as CSharpParseOptions;

            compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(AttributeClassesSource, Encoding.UTF8), options));
            var enumWithValuesAttributeSymbol = compilation.GetTypeByMetadataName("EnumWithValues.EnumWithValuesAttribute");
            var enumValueAttributeSymbol      = compilation.GetTypeByMetadataName("EnumWithValues.EnumValueAttribute");
            var enums = new List <EnumDeclaration>();

            foreach (var syntax in receiver.EnumDeclarationSyntaxes)
            {
                var model  = compilation.GetSemanticModel(syntax.SyntaxTree);
                var symbol = (ModelExtensions.GetDeclaredSymbol(model, syntax) as INamedTypeSymbol) !;
                var attrs  = symbol.GetAttributes();
                var(name, convertEnumValue, throwIfCastFails) = attrs
                                                                .Where(attr => attr.AttributeClass !.Equals(enumWithValuesAttributeSymbol, SymbolEqualityComparer.Default))
                                                                .Select(attr => (
                                                                            (string)attr.ConstructorArguments[0].Value !,
                                                                            (bool)attr.ConstructorArguments[1].Value !,
                                                                            (bool)attr.ConstructorArguments[2].Value !
                                                                            ))
                                                                .FirstOrDefault();
                if (name is null)
                {
                    continue;
                }
                var enumDeclaration = new EnumDeclaration()
                {
                    Accessibility    = symbol.DeclaredAccessibility,
                    EnumType         = GetEnumValueTypeString(syntax),
                    EnumName         = symbol.Name,
                    EnumFullname     = symbol.ToString(),
                    StructName       = name,
                    ConvertEnumValue = convertEnumValue,
                    ThrowIfCastFails = throwIfCastFails,
                };
                foreach (var memberSyntax in syntax.Members)
                {
                    var memberModel  = compilation.GetSemanticModel(memberSyntax.SyntaxTree);
                    var memberSymbol = (ModelExtensions.GetDeclaredSymbol(memberModel, memberSyntax) as IFieldSymbol) !;
                    var memberAttrs  = memberSymbol.GetAttributes();
                    ImmutableArray <TypedConstant>?valueConstants = memberAttrs.Length == 0 ? null : memberAttrs
                                                                    .Where(attr => attr.AttributeClass !.Equals(enumValueAttributeSymbol, SymbolEqualityComparer.Default))
                                                                    .Select(attr => attr.ConstructorArguments[0].Values !)
                                                                    .FirstOrDefault();
                    if (valueConstants is not null)
                    {
                        enumDeclaration.Members.Add(new() { EnumName = symbol.Name, Name = memberSymbol.Name, EnumValue = GetNumericObjectValue(memberSymbol.ConstantValue), Values = valueConstants });
                    }
                }
                enums.Add(enumDeclaration);
            }
            foreach (var e in enums)
            {
                e.DetectTypes();
                var code = StructCode(e);
                if (e.Namespace is string ns)
                {
                    code = Namespaced(ns, code);
                }
                context.AddSource($"{e.StructFullname}.cs", SourceText.From(code, Encoding.UTF8));
            }
        }
Exemplo n.º 35
0
 private void LoadSemanticModel(string path, CSharpSyntaxTree sourceTree)
 {
     this.semanticModel = SemanticUtils.RetrieveSemanticModel("LoadedAssembly", path, sourceTree, true);
 }
Exemplo n.º 36
0
        /// <summary>
        /// Use Roslyn to create an assembly.
        /// </summary>
        /// <param name="fn">File to compile. Also used for assembly name.</param>
        /// <returns></returns>
        public bool Compile(string fn)
        {
            CompiledAssembly = null;
            Errors.Clear();

            string sc          = File.ReadAllText(fn);
            string newAssyName = Path.GetFileNameWithoutExtension(fn);

            // Assemble references.
            var mr = new List <MetadataReference>();

            // Remarks:
            //     Performance considerations:
            //     It is recommended to use Microsoft.CodeAnalysis.AssemblyMetadata.CreateFromFile(System.String)
            //     API when creating multiple references to the same assembly. Reusing Microsoft.CodeAnalysis.AssemblyMetadata
            //     object allows for sharing data across these references.

            //var myAssy = Assembly.GetExecutingAssembly();
            //var refAssys = myAssy.GetReferencedAssemblies();

            // Add reference to almost everything we have loaded now.
            var           loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            List <string> ignore           = new List <string> {
                "Dex9.exe", "Microsoft.CodeAnalysis.dll", "Microsoft.CodeAnalysis.CSharp.dll"
            };

            foreach (var lassy in loadedAssemblies)
            {
                string loc = lassy.Location;

                if (ignore.TrueForAll(i => !loc.Contains(i)))
                {
                    Debug.WriteLine(loc);
                    AssemblyMetadata amd = AssemblyMetadata.CreateFromFile(loc);
                    mr.Add(amd.GetReference());
                }
            }

            // Parse the source.
            SyntaxTree syntaxTree                = CSharpSyntaxTree.ParseText(sc);
            CSharpCompilationOptions opts        = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            CSharpCompilation        compilation = CSharpCompilation.Create(newAssyName, new[] { syntaxTree }, mr, opts);

            // Compile the source.
            using (var memoryStream = new MemoryStream())
            {
                var result = compilation.Emit(memoryStream);

                if (result.Success)
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    CompiledAssembly = Assembly.Load(memoryStream.ToArray());
                }
                else
                {
                    foreach (var diag in result.Diagnostics)
                    {
                        Errors.Add(FormatDiagnostic(diag, fn));
                    }
                }
            }

            return(Errors.Count == 0 && CompiledAssembly != null);
        }
Exemplo n.º 37
0
 private CSharpCompilation GetCompilation(string path, CSharpSyntaxTree sourceTree)
 {
     return SemanticUtils.RetrieveCompilation("LoadedAssembly", path, sourceTree, true);
 }
Exemplo n.º 38
0
 private static SyntaxTree BuildSyntaxTree(string code)
 {
     return(CSharpSyntaxTree.ParseText(code));
 }
Exemplo n.º 39
0
        private void Initialize()
        {
            // Getting the AST node
            this.tree = ASTExtractor.Extract(this.source);

            // Loading the semantic model
            CSharpCompilation compilation = null;
            if (this.assemblyPath != null)
            {
                compilation = this.GetCompilation(this.assemblyPath, this.tree);
            }

            IASTTransformer transformer = new ScriptNamespaceBasedASTTransformer();
            if (compilation != null)
            {
                transformer.Transform(ref this.tree, ref compilation);
                this.semanticModel = SemanticUtils.RetrieveSemanticModel(compilation, this.tree);
            }
            else
            {
                transformer.Transform(ref this.tree);
            }

            // Creating the walker
            // If no semantic model was loaded, null will just be passed
            var node = this.tree.GetRoot();
            this.walker = ProgramDefinitionASTWalker.Create(node, null, this.semanticModel);

            // Translating
            this.output = this.walker.Walk().Translate();

            this.initialized = true;
        }
Exemplo n.º 40
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="compilation"></param>
 /// <param name="sourceTree"></param>
 /// <returns></returns>
 public static SemanticModel RetrieveSemanticModel(Compilation compilation, CSharpSyntaxTree sourceTree)
 {
     return compilation.GetSemanticModel(sourceTree);
 }
Exemplo n.º 41
0
        public void TestSourceGenerators()
        {
            string source0 =
                @"partial class C
{
    D F() { return (D)G; }
}
class P
{
    static void Main()
    {
    }
}";
            string source1 =
                @"partial class C
{
    const object G = null;
}
class D
{
}";
            var generator          = new MyGenerator(c => c.AddCompilationUnit("__c", CSharpSyntaxTree.ParseText(source1)));
            var generatorReference = new MyGeneratorReference(ImmutableArray.Create <SourceGenerator>(generator));

            using (var directory = new DisposableDirectory(Temp))
            {
                var outputPath = Path.Combine(directory.Path, "obj", "debug");
                Directory.CreateDirectory(outputPath);

                var projectId   = ProjectId.CreateNewId();
                var docId       = DocumentId.CreateNewId(projectId);
                var workspace   = new AdhocWorkspace();
                var projectInfo = ProjectInfo.Create(
                    projectId,
                    VersionStamp.Default,
                    name: "C",
                    assemblyName: "C.dll",
                    language: LanguageNames.CSharp,
                    outputFilePath: outputPath + Path.DirectorySeparatorChar);
                var solution = workspace.CurrentSolution
                               .AddProject(projectInfo)
                               .AddMetadataReference(projectId, MscorlibRef)
                               .AddDocument(docId, "C.cs", source0)
                               .AddAnalyzerReference(projectId, generatorReference);

                bool ok = workspace.TryApplyChanges(solution);
                Assert.True(ok);

                var actualAnalyzerReferences = solution.GetProject(projectId).AnalyzerReferences;
                Assert.Equal(1, actualAnalyzerReferences.Count);
                Assert.Equal(generatorReference, actualAnalyzerReferences[0]);
                var actualGenerators = actualAnalyzerReferences[0].GetSourceGenerators(LanguageNames.CSharp);
                Assert.Equal(1, actualGenerators.Length);
                Assert.Equal(generator, actualGenerators[0]);

                // Before generating source.
                solution = workspace.CurrentSolution;
                var project = solution.GetProject(projectId);
                Assert.Equal(1, project.DocumentIds.Count);
                var doc   = solution.GetDocument(docId);
                var model = doc.GetSemanticModelAsync().Result;
                Assert.NotNull(model);
                var compilation = model.Compilation;
                var trees       = compilation.SyntaxTrees.ToArray();
                Assert.Equal(1, trees.Length);

                // After generating source.
                workspace.UpdateGeneratedDocumentsIfNecessary(projectId);
                solution = workspace.CurrentSolution;
                project  = solution.GetProject(projectId);
                Assert.Equal(2, project.DocumentIds.Count);
                doc   = solution.GetDocument(docId);
                model = doc.GetSemanticModelAsync().Result;
                Assert.NotNull(model);
                compilation = model.Compilation;
                trees       = compilation.SyntaxTrees.ToArray();
                Assert.Equal(2, trees.Length);
                var tree = trees[1];
                doc = solution.GetDocument(tree);
                Assert.NotNull(doc);
                Assert.True(doc.State.IsGenerated);
                var actualSource = tree.GetText().ToString();
                Assert.Equal(source1, actualSource);
                var filePath = doc.FilePath;
                Assert.NotNull(filePath);
                Assert.Equal(outputPath, Path.GetDirectoryName(filePath));
                // Workspace should not write files to disk.
                Assert.False(File.Exists(filePath));
            }
        }
Exemplo n.º 42
0
        private void Initialize()
        {
            // Getting the AST node
            this.tree = ASTExtractor.Extract(this.source);
            var node = this.tree.GetRoot();

            // Loading the semantic model
            if (this.assemblyPath != null)
            {
                this.LoadSemanticModel(this.assemblyPath, this.tree);
            }

            // Creating the walker
            // If no semantic model was loaded, null will just be passed
            this.walker = ProgramASTWalker.Create(node, null, this.semanticModel);

            // Translating
            this.output = this.walker.Walk().Translate();

            this.initialized = true;
        }
Exemplo n.º 43
0
        public static string CompileAndRun(string code)
        {
            //baaa
            //code = code.Replace("[!DOUBLE-QUOTES-REPLACED-HERE!]", @"""");



            // define source code, then parse it (to the type used for compilation)
            //SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
            //    using System;

            //    namespace RoslynCompileSample
            //    {
            //        public class Writer
            //        {
            //            public string Write()
            //            {
            //                return ""message"";
            //            }
            //        }
            //    }");
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);

            // define other necessary objects for compilation
            string assemblyName = Path.GetRandomFileName();

            //paths to all the framework.dll files
            var allPathsToFrameworkDllFiles     = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator);
            List <MetadataReference> references = new List <MetadataReference>();

            foreach (var dllPath in allPathsToFrameworkDllFiles)
            {
                references.Add(MetadataReference.CreateFromFile(dllPath));
            }

            //MetadataReference[] references = new MetadataReference[]
            //{
            //    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            //    MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            //};

            // analyse and generate IL code from syntax tree
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                // write IL code into memory
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    // handle exceptions
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    var errors = new List <Error>();
                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());

                        var error = new Error();

                        error.Location = code.Substring(diagnostic.Location.SourceSpan.Start, diagnostic.Location.SourceSpan.Length);
                        error.Message  = "{" + diagnostic.Id + "}: {" + diagnostic.GetMessage() + "}";
                        //errors.Add("{" + diagnostic.Id + "}: {" + diagnostic.GetMessage() + "}");
                        //errors.Add(diagnostic.ToString());
                        errors.Add(error);
                    }
                    var ceResult = new CodeExecutionResult();
                    ceResult.EcounteredCompilerErrors = true;
                    ceResult.CompilerErrors           = errors;
                    return(JsonSerializer.Serialize(ceResult));
                }
                else
                {
                    // load this 'virtual' DLL so that we can use
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    // create instance of the desired class and call the desired function
                    Type   type = assembly.GetType("TeacherTestingNameSpace.TeacherTestingClass");
                    object obj  = Activator.CreateInstance(type);
                    //string asdf = (string) type.InvokeMember("Write",
                    //    BindingFlags.Default | BindingFlags.InvokeMethod,
                    //    null,
                    //    obj,
                    //    new object[] { "Hello World" });

                    try
                    {
                        string executionResult = (string)type.InvokeMember("TeacherTestingFunction",
                                                                           BindingFlags.Default | BindingFlags.InvokeMethod,
                                                                           null,
                                                                           obj,
                                                                           null);
                        return("{\"Tests\":" + executionResult + "}");
                    }
                    catch (Exception ex)
                    {
                        var errors = new List <Error>();
                        var error  = new Error();
                        error.Location = "";
                        error.Message  = ex.InnerException?.Message;
                        errors.Add(error);
                        var ceResult = new CodeExecutionResult();
                        ceResult.EcounteredCompilerErrors = true;
                        ceResult.CompilerErrors           = errors;
                        return(JsonSerializer.Serialize(ceResult));
                    }
                }
            }
        }