public static Assembly create_Assembly(this CommonCompilation compilation, string fileToCreate)
        {
            fileToCreate.deleteIfExists();
            if (fileToCreate.fileExists())
            {
                "[create_Assembly] targetExe could not be deleted".error();
                return(null);
            }
            fileToCreate.directoryName().createDir();
            var pdbFilename = "{0}.pdb".format(fileToCreate);

            CommonEmitResult emitResult = null;

            //compilation.
            using (var ilStream = new FileStream(fileToCreate, FileMode.OpenOrCreate))
                using (var pdbStream = new FileStream(pdbFilename, FileMode.OpenOrCreate))
                {
                    emitResult = compilation.Emit(ilStream, pdbFilename, pdbStream, null, default(CancellationToken), null, null, null);
                    if (emitResult.Success && fileToCreate.fileExists())
                    {
                        "[create_Assembly] created assembly: {0}".info(fileToCreate);
                    }
                    else
                    {
                        "[create_Assembly] could not create assembly: {0}".error(fileToCreate);
                        "[create_Assembly] Compilation errors: {1} {0}".error(emitResult.Diagnostics.errors().asString());
                    }
                }
            if (emitResult.Success)
            {
                return(Assembly.LoadFrom(fileToCreate));
            }
            return(null);
        }
예제 #2
0
 internal static CommonEmitResult EmitToMemory(this CommonCompilation compilation)
 {
     using (var stream = new MemoryStream())
     {
         return(compilation.Emit(stream));
     }
 }
예제 #3
0
        internal Submission(CommonCompilation compilation, Session session, Func <Session, T> factory)
        {
            Debug.Assert(compilation != null);

            this.compilation = compilation;
            this.session     = session;
            this.factory     = factory;
        }
예제 #4
0
파일: Session.cs 프로젝트: sperling/cskarp
 internal void SubmissionCompiled(CommonCompilation compilation)
 {
     LastSubmission    = compilation;
     pendingReferences = ReadOnlyArray <MetadataReference> .Empty;
     // TODO (tomat): shouldn't imported namespaces behave the same as references?
     // do not reset pending imported namespaces - only usings specified in
     // code are lookued up by the InteractiveUsingsBinder
 }
 /// <summary>
 /// Checks that the compilation doesn't have any references whose name start with the reserved prefix.
 /// </summary>
 internal void ValidateReferences(CommonCompilation compilation, DiagnosticBag diagnostics)
 {
     foreach (AssemblyIdentity reference in compilation.ReferencedAssemblyNames)
     {
         if (IsReservedAssemblyName(reference))
         {
             diagnostics.Add(ErrorCode.ERR_ReservedAssemblyName, null, reference.GetDisplayName());
         }
     }
 }
 internal void ValidateReferences(CommonCompilation compilation, DiagnosticBag diagnostics)
 {
     foreach (AssemblyIdentity identity in compilation.ReferencedAssemblyNames)
       {
     if (CommonScriptEngine.IsReservedAssemblyName(identity))
       DiagnosticBagExtensions.Add(diagnostics, ErrorCode.ERR_ReservedAssemblyName, (Location) null, new object[1]
       {
     (object) identity.GetDisplayName(false)
       });
       }
 }
예제 #7
0
        internal static IEventSymbol GeneratePropertyChangedEvent(CommonCompilation compilation)
        {
            var propertyChangedEventHandlerType = compilation.GetTypeByMetadataName("System.ComponentModel.PropertyChangedEventHandler");

            return(SymbolFactory.CreateEvent(
                       attributes: null,
                       accessibility: CommonAccessibility.Public,
                       modifiers: new SymbolModifiers(),
                       type: propertyChangedEventHandlerType,
                       explicitInterfaceSymbolOpt: null,
                       name: "PropertyChanged"));
        }
예제 #8
0
        internal static IEventSymbol GeneratePropertyChangedEvent(CommonCompilation compilation)
        {
            var propertyChangedEventHandlerType = compilation.GetTypeByMetadataName("System.ComponentModel.PropertyChangedEventHandler");

            return SymbolFactory.CreateEvent(
                attributes: null,
                accessibility: CommonAccessibility.Public,
                modifiers: new SymbolModifiers(),
                type: propertyChangedEventHandlerType,
                explicitInterfaceSymbolOpt: null,
                name: "PropertyChanged");
        }
 internal void ValidateReferences(CommonCompilation compilation, DiagnosticBag diagnostics)
 {
     foreach (AssemblyIdentity identity in compilation.ReferencedAssemblyNames)
     {
         if (CommonScriptEngine.IsReservedAssemblyName(identity))
         {
             DiagnosticBagExtensions.Add(diagnostics, ErrorCode.ERR_ReservedAssemblyName, (Location)null, new object[1]
             {
                 (object)identity.GetDisplayName(false)
             });
         }
     }
 }
예제 #10
0
        internal static IMethodSymbol GenerateSetPropertyMethod(CommonCompilation compilation)
        {
            var body = Syntax.ParseStatement(
                @"if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(field, value))
            {
            field = value;

            var handler = PropertyChanged;
            if (handler != null)
            {
            handler(this, new System.ComponentModel.PropertyChangedEventArgs(name));
            }
            }");

            body = body.WithAdditionalAnnotations(CodeAnnotations.Simplify);

            var stringType = compilation.GetSpecialType(SpecialType.System_String);
            var voidType = compilation.GetSpecialType(SpecialType.System_Void);

            var typeParameter = SymbolFactory.CreateTypeParameter("T");

            var parameter1 = SymbolFactory.CreateParameter(
                attributes: null,
                refKind: RefKind.Ref,
                isParams: false,
                type: typeParameter,
                name: "field");

            var parameter2 = SymbolFactory.CreateParameter(typeParameter, "value");
            var parameter3 = SymbolFactory.CreateParameter(stringType, "name");

            return SymbolFactory.CreateMethod(
                attributes: null,
                accessibility: CommonAccessibility.Private,
                modifiers: new SymbolModifiers(),
                returnType: voidType,
                explicitInterfaceSymbolOpt: null,
                name: "SetProperty",
                typeParameters: new[] { typeParameter },
                parameters: new[] { parameter1, parameter2, parameter3 },
                statements: new[] { body });
        }
예제 #11
0
        internal static IMethodSymbol GenerateSetPropertyMethod(CommonCompilation compilation)
        {
            var body = Syntax.ParseStatement(
                @"if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(field, value))
{
    field = value;

    var handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new System.ComponentModel.PropertyChangedEventArgs(name));
    }
}");

            body = body.WithAdditionalAnnotations(CodeAnnotations.Simplify);

            var stringType = compilation.GetSpecialType(SpecialType.System_String);
            var voidType   = compilation.GetSpecialType(SpecialType.System_Void);

            var typeParameter = SymbolFactory.CreateTypeParameter("T");

            var parameter1 = SymbolFactory.CreateParameter(
                attributes: null,
                refKind: RefKind.Ref,
                isParams: false,
                type: typeParameter,
                name: "field");

            var parameter2 = SymbolFactory.CreateParameter(typeParameter, "value");
            var parameter3 = SymbolFactory.CreateParameter(stringType, "name");

            return(SymbolFactory.CreateMethod(
                       attributes: null,
                       accessibility: CommonAccessibility.Private,
                       modifiers: new SymbolModifiers(),
                       returnType: voidType,
                       explicitInterfaceSymbolOpt: null,
                       name: "SetProperty",
                       typeParameters: new[] { typeParameter },
                       parameters: new[] { parameter1, parameter2, parameter3 },
                       statements: new[] { body }));
        }
예제 #12
0
        public static object invokeFirstMethod(this CommonCompilation compiler)
        {
            if (compiler.hasErrors())
            {
                "[invokeFirstMethod] compiler errors: {0}".error(compiler.errors_Details());
                return(null);
            }

            var assembly = compiler.create_Assembly();

            if (assembly.isNull())
            {
                "[invokeFirstMethod] failed to create assembly".error();
                return(null);
            }
            return(assembly.types()
                   .methods()
                   .first()
                   .invoke());
        }
예제 #13
0
        /// <summary>
        /// Executes the preprocessor.
        /// </summary>
        /// <param name="compilation">The compilation.</param>
        /// <returns>The processed compilation.</returns>
        public CommonCompilation ProcessCompilation(CommonCompilation compilation)
        {
            var cSharpComp = compilation as Compilation;
            if (cSharpComp == null)
                return compilation;

            var newTrees = new List<SyntaxTree>();

            foreach (var tree in cSharpComp.SyntaxTrees)
            {
                Semantics = compilation.GetSemanticModel(tree);
                var newRoot = (CompilationUnitSyntax)Visit(tree.GetRoot());

                newTrees.Add(SyntaxTree.Create(tree.FilePath, newRoot, tree.Options));
            }

            return compilation
                .RemoveAllSyntaxTrees()
                .AddSyntaxTrees(newTrees);
        }
예제 #14
0
        /// <summary>
        /// Executes the compilation process.
        /// </summary>
        /// <param name="compilation">The compilation object.</param>
        /// <param name="outputStream">The output stream to write to.</param>
        /// <returns>The compilation result.</returns>
        public CompilationResult Compile(CommonCompilation compilation, Stream outputStream)
        {
            var context = new CompilationContext
            {
                Compilation = compilation,
                OutputStream = outputStream,
                Result = new CompilationResult()
            };

            // this locks the current scope
            ModelRegistry.BeginRegistration();
            var profiler = new ProcessProfiler();

            try
            {
                foreach (var proc in _processes)
                {
                    profiler.Execute(proc, context);
                    if (context.Result.HasErrors)
                        break;
                }
            }
            catch (CompilationException compEx)
            {
                context.Result.AddError(compEx.ToErrorMessage());
            }
            catch (Exception ex)
            {
                context.Result.AddError("Unexpected Error: " + ex.Message);
            }
            finally
            {
                // release lock
                ModelRegistry.EndRegistration();
                profiler.End();
            }

            return context.Result;
        }
    public static INamedTypeSymbol FindSymbol(this CommonCompilation compilation, Type searchedType)
    {
        var splitFullName  = searchedType.FullName.Split('.');
        var namespaceNames = splitFullName.Take(splitFullName.Length - 1).ToArray();
        var className      = splitFullName.Last();

        if (namespaceNames.Length == 0)
        {
            return(compilation.GlobalNamespace.GetAllTypes(new CancellationToken()).First(n => n.Name == className));
        }

        var namespaces = compilation.GlobalNamespace.GetNamespaceMembers();
        INamespaceSymbol namespaceContainingType = null;

        foreach (var name in namespaceNames)
        {
            namespaceContainingType = namespaces.First(n => n.Name == name);
            namespaces = namespaceContainingType.GetNamespaceMembers();
        }

        return(namespaceContainingType.GetAllTypes(new CancellationToken()).First(n => n.Name == className));
    }
예제 #16
0
        private bool TryEmitSubmission(CommonCompilation compilation, DiagnosticBag diagnostics, Type delegateType, bool collectible,
                                       CancellationToken cancellationToken, out Delegate factory)
        {
            // Note that we migth be giving the emitter a collectible module but if the code contains uncollectible features
            // it will be generated to a separate new uncollectible assembly.
            var emitResult = compilation.Emit(
                GetOrCreateDynamicModule(collectible),
                assemblyLoader: GetAssemblyLoader(collectible),
                assemblySymbolMapper: symbol => MapAssemblySymbol(symbol, collectible),
                cancellationToken: cancellationToken
                );

            diagnostics.Add(emitResult.Diagnostics);

            // emit can fail due to compilation errors or because there is nothing to emit:
            if (!emitResult.Success)
            {
                factory = null;
                return(!diagnostics.HasAnyErrors());
            }

            Debug.Assert(emitResult.EntryPoint != null);

            if (emitResult.IsUncollectible)
            {
                // Ref.Emit wasn't able to emit the assembly
                uncollectibleCodeManager.AddFallBackAssembly(emitResult.EntryPoint.DeclaringType.Assembly);
            }
#if DEBUG
            if (SaveCompiledAssemblies)
            {
                this.uncollectibleCodeManager.Save(UncollectibleModuleFileName);
                this.collectibleCodeManager.Save(CollectibleModuleFileName);
            }
#endif
            factory = Delegate.CreateDelegate(delegateType, emitResult.EntryPoint);
            return(true);
        }
예제 #17
0
        private AssemblyReferenceAlias[] CalculateAssemblyReferenceAliases(EmitContext context)
        {
            var result = new List <AssemblyReferenceAlias>();

            foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases())
            {
                var assembly = assemblyAndAliases.assemblie;
                var aliases  = assemblyAndAliases.names;

                for (int i = 0; i < aliases.Length; i++)
                {
                    string alias = aliases[i];

                    // filter out duplicates and global aliases:
                    if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0)
                    {
                        result.Add(new AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics)));
                    }
                }
            }

            return(result.ToArray());
        }
예제 #18
0
        private ImmutableArray <Cci.AssemblyReferenceAlias> CalculateAssemblyReferenceAliases(EmitContext context)
        {
            var result = ArrayBuilder <Cci.AssemblyReferenceAlias> .GetInstance();

            foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases())
            {
                var assembly = assemblyAndAliases.Item1;
                var aliases  = assemblyAndAliases.Item2;

                for (int i = 0; i < aliases.Length; i++)
                {
                    string alias = aliases[i];

                    // filter out duplicates and global aliases:
                    if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0)
                    {
                        result.Add(new Cci.AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics)));
                    }
                }
            }

            return(result.ToImmutableAndFree());
        }
예제 #19
0
        /// <summary>
        /// Executes the preprocessor.
        /// </summary>
        /// <param name="compilation">The compilation.</param>
        /// <returns>The processed compilation.</returns>
        public CommonCompilation ProcessCompilation(CommonCompilation compilation)
        {
            var cSharpComp = compilation as Compilation;

            if (cSharpComp == null)
            {
                return(compilation);
            }

            var newTrees = new List <SyntaxTree>();

            foreach (var tree in cSharpComp.SyntaxTrees)
            {
                Semantics = compilation.GetSemanticModel(tree);
                var newRoot = (CompilationUnitSyntax)Visit(tree.GetRoot());

                newTrees.Add(SyntaxTree.Create(tree.FilePath, newRoot, tree.Options));
            }

            return(compilation
                   .RemoveAllSyntaxTrees()
                   .AddSyntaxTrees(newTrees));
        }
예제 #20
0
 public static bool hasErrors(this CommonCompilation compilation)
 {
     return(compilation.errors().size() > 0);
 }
예제 #21
0
        public static CommonCompilation set_Platform_x86(this CommonCompilation compiler)
        {
            var options = (compiler.Options as CompilationOptions).WithPlatform(Roslyn.Compilers.Common.Platform.x86);

            return(compiler.set_Options(options));
        }
예제 #22
0
 public static CommonCompilation set_Options(this CommonCompilation compiler, CompilationOptions compilationOptions)
 {
     compiler.field("options", compilationOptions);
     return(compiler);
 }
예제 #23
0
 public static CommonCompilation makeAssemblyNameUnique(this CommonCompilation compilation)
 {
     //make the assembly unique (or we wont be able to load this assembly more than one per process
     compilation.Assembly.field("baseNameNoExtension", compilation.Assembly.field("baseNameNoExtension").str().add_RandomLetters(5));
     return(compilation);
 }
 public LexicalOrderSymbolComparerImpl(CommonCompilation compilation)
 {
     this.compilation = compilation;
 }
예제 #25
0
        private static IMethodSymbol FindSetPropertyMethod(this INamedTypeSymbol classSymbol, CommonCompilation compilation)
        {
            // Find SetProperty<T>(ref T, T, string) method.
            var setPropertyMethod = classSymbol
                .GetMembers("SetProperty")
                .OfType<IMethodSymbol>()
                .FirstOrDefault(m => m.Parameters.Count == 3 && m.TypeParameters.Count == 1);

            if (setPropertyMethod != null)
            {
                var parameters = setPropertyMethod.Parameters;
                var typeParameter = setPropertyMethod.TypeParameters[0];
                var stringType = compilation.GetSpecialType(SpecialType.System_String);

                if (setPropertyMethod.ReturnsVoid &&
                    parameters[0].RefKind == RefKind.Ref &&
                    parameters[0].Type.Equals(typeParameter) &&
                    parameters[1].Type.Equals(typeParameter) &&
                    parameters[2].Type.Equals(stringType))
                {
                    return setPropertyMethod;
                }
            }

            return null;
        }
예제 #26
0
        private static IMethodSymbol FindSetPropertyMethod(this INamedTypeSymbol classSymbol, CommonCompilation compilation)
        {
            // Find SetProperty<T>(ref T, T, string) method.
            var setPropertyMethod = classSymbol
                                    .GetMembers("SetProperty")
                                    .OfType <IMethodSymbol>()
                                    .FirstOrDefault(m => m.Parameters.Count == 3 && m.TypeParameters.Count == 1);

            if (setPropertyMethod != null)
            {
                var parameters    = setPropertyMethod.Parameters;
                var typeParameter = setPropertyMethod.TypeParameters[0];
                var stringType    = compilation.GetSpecialType(SpecialType.System_String);

                if (setPropertyMethod.ReturnsVoid &&
                    parameters[0].RefKind == RefKind.Ref &&
                    parameters[0].Type.Equals(typeParameter) &&
                    parameters[1].Type.Equals(typeParameter) &&
                    parameters[2].Type.Equals(stringType))
                {
                    return(setPropertyMethod);
                }
            }

            return(null);
        }
예제 #27
0
        private ISemanticModel GetSemanticModelFromSyntaxTree(CommonSyntaxTree syntaxTree, string code, bool includeDocumentation = false)
        {
            _systemXmlFilesDir = GetSystemXmlFilesDir();

            MetadataReference mscorlib = CreateMetadataReference("mscorlib", includeDocumentation);
            var metaDllReferences      = new List <MetadataReference> {
                mscorlib
            };

            if (this.Language == Language.VbNet)
            {
                //Need to add vb or getting error
                //Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined.
                MetadataReference vb = CreateMetadataReference("Microsoft.VisualBasic", includeDocumentation);
                metaDllReferences.Add(vb);
            }


            //Eric: this doesn't seem to work so using mscorlib only for now.

            List <string> gacDlls = GetGacDlls(code);

            foreach (string dllName in gacDlls)
            {
                string dllNameWithoutExtension = dllName.Substring(0, dllName.Length - 4);                 //remove .dll

                MetadataReference metaRef = CreateMetadataReference(dllNameWithoutExtension, includeDocumentation);
                metaDllReferences.Add(metaRef);
            }

            Dictionary <string, string> nugGetXmlFileNameToPath = new Dictionary <string, string>();

            if (includeDocumentation)
            {
                foreach (var nuGetxmlFilePath in NuGetXmlFileReferences)
                {
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(nuGetxmlFilePath);
                    nugGetXmlFileNameToPath[fileNameWithoutExtension] = nuGetxmlFilePath;
                }
            }


            foreach (var path in GetNonGacDlls())
            {
                string fileName = Path.GetFileNameWithoutExtension(path);

                RoslynDocumentationProvider documentationProvider = null;
                if (includeDocumentation && nugGetXmlFileNameToPath.ContainsKey(fileName))
                {
                    documentationProvider = new RoslynDocumentationProvider(nugGetXmlFileNameToPath[fileName]);
                }

                var reference = new MetadataFileReference(path, MetadataReferenceProperties.Assembly, documentationProvider);
                metaDllReferences.Add(reference);
            }



            //http://msdn.microsoft.com/en-us/vstudio/hh500769.aspx#Toc306015688

            CommonCompilation compilation = this.CreateCompilation("Compilation_For_AutoComplete",
                                                                   syntaxTrees: new[] { syntaxTree },
                                                                   matadataReferences: metaDllReferences);

            ISemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);

            return(semanticModel);
        }
 public static string errors_Details(this CommonCompilation compilation)
 {
     return(compilation.errors().asString());
 }
예제 #29
0
		public RoslynCompilation(CommonCompilation compilation)
		{
			Contract.Requires(compilation == null);

			_compilation = compilation;
		}
        public static Assembly create_Assembly_IntoDisk(this CommonCompilation compilation)
        {
            var fileToCreate = PublicDI.config.O2TempDir.pathCombine("_dynamicDll_{0}.dll".format(5.randomLetters()));

            return(compilation.create_Assembly(fileToCreate));
        }
예제 #31
0
 /// <summary>
 /// Checks that the compilation doesn't have any references whose name start with the reserved prefix.
 /// </summary>
 internal void ValidateReferences(CommonCompilation compilation, DiagnosticBag diagnostics)
 {
     foreach (AssemblyIdentity reference in compilation.ReferencedAssemblyNames)
     {
         if (IsReservedAssemblyName(reference))
         {
             diagnostics.Add(ErrorCode.ERR_ReservedAssemblyName, null, reference.GetDisplayName());
         }
     }
 }
예제 #32
0
        private bool Compile(
            string code,
            string path,
            DiagnosticBag diagnostics,
            Session session,
            Type delegateType,
            Type returnType,
            CancellationToken cancellationToken,
            bool isInteractive,
            bool isExecute,
            out CommonCompilation compilation,
            out Delegate factory)
        {
            Debug.Assert(delegateType != null);
            Debug.Assert(session != null);
            Debug.Assert(code != null);

            DiagnosticBag localDiagnostics = diagnostics ?? DiagnosticBag.GetInstance();
            IText         text             = new StringText(code);

            try
            {
                CommonCompilation localCompilation = CreateCompilation(text, path, isInteractive, session, returnType, localDiagnostics);
                if (localCompilation == null)
                {
                    Debug.Assert(localDiagnostics.HasAnyErrors());
                    CompilationError(localDiagnostics, diagnostics);
                    factory     = null;
                    compilation = null;
                    return(false);
                }

                // throw away all syntax warnings, they will be reported again by emit:
                localDiagnostics.Clear();

                // If we compile just in time for execution the user doesn't have access to the submission compilation just created.
                // If the previous submission hasn't been executed yet the execution would blow up when invoking the submission factory,
                // and after that the session would become unusable since there is no way how the user can re-execute the current submission.
                // So throw here before we save the submission into the session.
                if (isExecute)
                {
                    int slotIndex = localCompilation.GetSubmissionSlotIndex();
                    SessionHelpers.RequirePreviousSubmissionExecuted(session, slotIndex);
                }

                // TODO: (tomat)
                // Current CLR implementation of collectible assemblies doesn't support
                // references from uncollectible to collectible code.
                //
                // We can't emit collectible code if there is a possibility that we will
                // compile another submission in the session.
                //
                // A workaround might be to regenerate all collectible dependencies of an uncollectible
                // submission as uncollectible.
                //
                // For now we explicitly mark sessions as collectible in tests to keep test coverage.
                bool collectible = session.isCollectible;
                if (!TryEmitSubmission(localCompilation, localDiagnostics, delegateType, collectible, cancellationToken, out factory))
                {
                    Debug.Assert(localDiagnostics.HasAnyErrors());
                    CompilationError(localDiagnostics, diagnostics);
                    factory     = null;
                    compilation = null;
                    return(false);
                }

                session.SubmissionCompiled(localCompilation);

                compilation = localCompilation;
                return(true);
            }
            finally
            {
                if (localDiagnostics != diagnostics)
                {
                    localDiagnostics.Free();
                }
            }
        }
 public static List <Roslyn.Compilers.Common.CommonDiagnostic> errors(this CommonCompilation compilation)
 {
     return(compilation.GetDiagnostics(default(CancellationToken)).errors());
 }