本文整理汇总了C#中CSharpCompilationOptions类的典型用法代码示例。如果您正苦于以下问题:C# CSharpCompilationOptions类的具体用法?C# CSharpCompilationOptions怎么用?C# CSharpCompilationOptions使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CSharpCompilationOptions类属于命名空间,在下文中一共展示了CSharpCompilationOptions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CSharpSerializableCompilationOptions
private CSharpSerializableCompilationOptions(SerializationInfo info, StreamingContext context)
{
this.options = new CSharpCompilationOptions(
outputKind: (OutputKind)info.GetInt32(OutputKindString),
moduleName: info.GetString(ModuleNameString),
mainTypeName: info.GetString(MainTypeNameString),
scriptClassName: info.GetString(ScriptClassNameString),
usings: (string[])info.GetValue(UsingsString, typeof(string[])),
cryptoKeyContainer: info.GetString(CryptoKeyContainerString),
cryptoKeyFile: info.GetString(CryptoKeyFileString),
delaySign: (bool?)info.GetValue(DelaySignString, typeof(bool?)),
optimizationLevel: (OptimizationLevel)info.GetInt32(OptimizeString),
checkOverflow: info.GetBoolean(CheckOverflowString),
allowUnsafe: info.GetBoolean(AllowUnsafeString),
fileAlignment: info.GetInt32(FileAlignmentString),
baseAddress: info.GetUInt64(BaseAddressString),
platform: (Platform)info.GetInt32(PlatformString),
generalDiagnosticOption: (ReportDiagnostic)info.GetInt32(GeneralDiagnosticOptionString),
warningLevel: info.GetInt32(WarningLevelString),
specificDiagnosticOptions: ((Dictionary<string, ReportDiagnostic>)info.GetValue(SpecificDiagnosticOptionsString, typeof(Dictionary<string, ReportDiagnostic>))).ToImmutableDictionary(),
highEntropyVirtualAddressSpace: info.GetBoolean(HighEntropyVirtualAddressSpaceString),
subsystemVersion: SubsystemVersion.Create(info.GetInt32(SubsystemVersionMajorString), info.GetInt32(SubsystemVersionMinorString)),
runtimeMetadataVersion: info.GetString(RuntimeMetadataVersionString),
concurrentBuild: info.GetBoolean(ConcurrentBuildString),
xmlReferenceResolver: XmlFileResolver.Default,
sourceReferenceResolver: SourceFileResolver.Default,
metadataReferenceResolver: MetadataFileReferenceResolver.Default,
metadataReferenceProvider: MetadataFileReferenceProvider.Default,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
strongNameProvider: new DesktopStrongNameProvider(),
metadataImportOptions: (MetadataImportOptions)info.GetByte(MetadataImportOptionsString),
features: ((string[])info.GetValue(FeaturesString, typeof(string[]))).AsImmutable());
}
示例2: CompileAndVerify
private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, TestEmitters emitOptions = TestEmitters.All, CSharpCompilationOptions compOptions = null)
{
SynchronizationContext.SetSynchronizationContext(null);
var compilation = this.CreateCompilation(source, references: references, compOptions: compOptions);
return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: emitOptions);
}
示例3: MyScriptCompiler
public MyScriptCompiler()
{
AddReferencedAssemblies(
this.GetType().Assembly.Location,
typeof(int).Assembly.Location,
typeof(System.Xml.XmlEntity).Assembly.Location,
typeof(System.Collections.Generic.HashSet<>).Assembly.Location,
typeof(System.Uri).Assembly.Location
);
AddImplicitIngameNamespacesFromTypes(
typeof(System.Object),
typeof(System.Text.StringBuilder),
typeof(System.Collections.IEnumerable),
typeof(System.Collections.Generic.IEnumerable<>)
);
AddUnblockableIngameExceptions(typeof(ScriptOutOfRangeException));
m_debugCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, platform: Platform.X64);
m_runtimeCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, platform: Platform.X64);
m_whitelist = new MyScriptWhitelist(this);
m_ingameWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.Ingame);
m_modApiWhitelistDiagnosticAnalyzer = new WhitelistDiagnosticAnalyzer(m_whitelist, MyWhitelistTarget.ModApi);
m_conditionalParseOptions = new CSharpParseOptions();
}
示例4: GetCompilation
public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
{
var options = new CSharpParseOptions(_languageVersion);
trees = files.Select(x =>
{
var text = x.Value;
var tree = CSharpSyntaxTree.ParseText(text, options: options);
if (tree.GetDiagnostics().Any())
throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
return tree;
}).ToArray();
// adding everything is going to cause issues with dynamic assemblies
// so we would want to filter them anyway... but we don't need them really
//var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
// though that one is not ok either since we want our own reference
//var refs = Enumerable.Empty<MetadataReference>();
// so use the bare minimum
var asms = ReferencedAssemblies;
var a1 = typeof(Builder).Assembly;
asms.Add(a1);
foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(
assemblyName,
/*syntaxTrees:*/ trees,
/*references:*/ refs,
compilationOptions);
return compilation;
}
示例5: CreateTestAssembly
public static Assembly CreateTestAssembly(List<SyntaxTree> syntaxTrees)
{
var systemAssemblyLocation = typeof(object).GetTypeInfo().Assembly.Location;
var systemDirectory = Directory.GetParent(systemAssemblyLocation);
var assemblyName = Path.GetRandomFileName();
var metadataReferences = new List<MetadataReference>
{
MetadataReference.CreateFromFile(systemAssemblyLocation),
MetadataReference.CreateFromFile(typeof(CommandModule).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(systemDirectory.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(systemDirectory.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll")
};
var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, metadataReferences, compilationOptions);
using (var assemblyStream = new MemoryStream())
{
var result = compilation.Emit(assemblyStream);
if (!result.Success)
{
throw new Exception(string.Join("\n", result.Diagnostics.Select(x => x.GetMessage())));
}
assemblyStream.Seek(0, SeekOrigin.Begin);
return LoadAssembly(assemblyStream);
}
}
示例6: GetDispatcher
/// <summary>
/// Gets a dispatcher for the provided <paramref name="actors"/>.
/// </summary>
/// <param name="actors">
/// The actors.
/// </param>
/// <param name="source">
/// The generated source code.
/// </param>
/// <returns>
/// A dispatcher for the provided <paramref name="actors"/>.
/// </returns>
/// <exception cref="CodeGenerationException">
/// A code generation error occurred.
/// </exception>
public static IEventDispatcher GetDispatcher(IList<ActorDescription> actors, out string source)
{
var assemblies =
AppDomain.CurrentDomain.GetAssemblies()
.Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
.Select(MetadataReference.CreateFromAssembly)
.ToArray();
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var syntax = GenerateCompilationUnit(actors).NormalizeWhitespace();
source = syntax.ToFullString();
var compilation =
CSharpCompilation.Create("CodeGen_" + ClassSuffix + DateTime.UtcNow.Ticks.ToString("X") + ".dll")
.AddSyntaxTrees(GenerateCompilationUnit(actors).SyntaxTree)
.AddReferences(assemblies)
.WithOptions(options);
Assembly compiledAssembly;
using (var stream = new MemoryStream())
{
var compilationResult = compilation.Emit(stream);
if (!compilationResult.Success)
{
throw new CodeGenerationException(
string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString())));
}
compiledAssembly = Assembly.Load(stream.GetBuffer());
}
var dispatcher = compiledAssembly.GetTypes().Single(typeof(IEventDispatcher).IsAssignableFrom);
return (IEventDispatcher)Activator.CreateInstance(dispatcher);
}
示例7: CompileExtensions
protected Assembly CompileExtensions(string toolsDirectory, string assemblyFileName, IEnumerable<string> sourceFileNames)
{
Console.WriteLine("Compiling extensions...");
var syntaxTrees = sourceFileNames.Select(File.ReadAllText).Select(code => CSharpSyntaxTree.ParseText(code)).ToList();
var references = AppDomain.CurrentDomain.GetAssemblies().Select(assembly => MetadataReference.CreateFromFile(assembly.Location)).ToList();
// todo: add references from scconfig.json
references.Add(MetadataReference.CreateFromFile(typeof(XDocument).Assembly.Location)); // add System.Xml.Linq assembly
Directory.CreateDirectory(Path.GetDirectoryName(assemblyFileName) ?? string.Empty);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(Path.GetFileNameWithoutExtension(assemblyFileName), syntaxTrees, references, options);
EmitResult result;
using (var stream = new FileStream(assemblyFileName, FileMode.Create))
{
result = compilation.Emit(stream);
}
if (result.Success)
{
return Assembly.LoadFrom(assemblyFileName);
}
var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
foreach (var diagnostic in failures)
{
Console.WriteLine(@"scc.cmd(0,0): {0} {1}: {2}", diagnostic.Severity, diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
示例8: GetCompilationOptions
private static CSharpCompilationOptions GetCompilationOptions(CommonCompilerOptions compilerOptions, string projectDirectory)
{
var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ?
OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary;
var options = new CSharpCompilationOptions(outputKind);
string platformValue = compilerOptions.Platform;
bool allowUnsafe = compilerOptions.AllowUnsafe ?? false;
bool optimize = compilerOptions.Optimize ?? false;
bool warningsAsErrors = compilerOptions.WarningsAsErrors ?? false;
Platform platform;
if (!Enum.TryParse(value: platformValue, ignoreCase: true, result: out platform))
{
platform = Platform.AnyCpu;
}
options = options
.WithAllowUnsafe(allowUnsafe)
.WithPlatform(platform)
.WithGeneralDiagnosticOption(warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default)
.WithOptimizationLevel(optimize ? OptimizationLevel.Release : OptimizationLevel.Debug);
return AddSigningOptions(options, compilerOptions, projectDirectory);
}
示例9: CompileAndVerify
private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null)
{
SynchronizationContext.SetSynchronizationContext(null);
var compilation = CreateCompilation(source, references: references, options: options);
return base.CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
示例10: CSharpSerializableCompilationOptions
private CSharpSerializableCompilationOptions(SerializationInfo info, StreamingContext context)
{
_options = new CSharpCompilationOptions(
outputKind: (OutputKind)info.GetInt32(OutputKindString),
moduleName: info.GetString(ModuleNameString),
mainTypeName: info.GetString(MainTypeNameString),
scriptClassName: info.GetString(ScriptClassNameString),
usings: (string[])info.GetValue(UsingsString, typeof(string[])),
cryptoKeyContainer: info.GetString(CryptoKeyContainerString),
cryptoKeyFile: info.GetString(CryptoKeyFileString),
delaySign: (bool?)info.GetValue(DelaySignString, typeof(bool?)),
optimizationLevel: (OptimizationLevel)info.GetInt32(OptimizeString),
checkOverflow: info.GetBoolean(CheckOverflowString),
allowUnsafe: info.GetBoolean(AllowUnsafeString),
platform: (Platform)info.GetInt32(PlatformString),
generalDiagnosticOption: (ReportDiagnostic)info.GetInt32(GeneralDiagnosticOptionString),
warningLevel: info.GetInt32(WarningLevelString),
specificDiagnosticOptions: ((Dictionary<string, ReportDiagnostic>)info.GetValue(SpecificDiagnosticOptionsString, typeof(Dictionary<string, ReportDiagnostic>))).ToImmutableDictionary(),
concurrentBuild: info.GetBoolean(ConcurrentBuildString),
extendedCustomDebugInformation: info.GetBoolean(ExtendedCustomDebugInformationString),
xmlReferenceResolver: XmlFileResolver.Default,
sourceReferenceResolver: SourceFileResolver.Default,
metadataReferenceResolver: new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default),
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
strongNameProvider: new DesktopStrongNameProvider(),
metadataImportOptions: (MetadataImportOptions)info.GetByte(MetadataImportOptionsString),
features: ((string[])info.GetValue(FeaturesString, typeof(string[]))).AsImmutable());
}
示例11: GetSymbolsForReferences
internal static AssemblySymbol[] GetSymbolsForReferences(
CSharpCompilation[] compilations = null,
byte[][] bytes = null,
MetadataReference[] mrefs = null,
CSharpCompilationOptions options = null)
{
var refs = new List<MetadataReference>();
if (compilations != null)
{
foreach (var c in compilations)
{
refs.Add(new CSharpCompilationReference(c));
}
}
if (bytes != null)
{
foreach (var b in bytes)
{
refs.Add(new MetadataImageReference(b.AsImmutableOrNull()));
}
}
if (mrefs != null)
{
refs.AddRange(mrefs);
}
var tc1 = CSharpCompilation.Create(assemblyName: "Dummy", options: options ?? TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[0], references: refs);
return (from @ref in refs select tc1.GetReferencedAssemblySymbol(@ref)).ToArray();
}
示例12: Test1
public void Test1()
{
var test = @"
class C
{
public void M()
{
}
}";
var expected = new DiagnosticResult
{
Id = DiagnosticIds.CompilationAnalyzerRuleId,
Message = string.Format(Resources.CompilationAnalyzerMessageFormat, DiagnosticIds.SymbolAnalyzerRuleId),
Severity = DiagnosticSeverity.Warning
};
var specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Error);
var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication,
specificDiagnosticOptions: new[]{ specificOption });
VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions);
specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Suppress);
compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(new[] { specificOption });
VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions, expected: expected);
}
示例13: CompileAssembly
/// <summary>
/// Generates and compiles an assembly for the provided grains.
/// </summary>
/// <param name="generatedSyntax">
/// The generated code.
/// </param>
/// <param name="assemblyName">
/// The name for the generated assembly.
/// </param>
/// <returns>
/// The raw assembly.
/// </returns>
/// <exception cref="CodeGenerationException">
/// An error occurred generating code.
/// </exception>
public static byte[] CompileAssembly(GeneratedSyntax generatedSyntax, string assemblyName)
{
// Add the generated code attribute.
var code = AddGeneratedCodeAttribute(generatedSyntax);
// Reference everything which can be referenced.
var assemblies =
AppDomain.CurrentDomain.GetAssemblies()
.Where(asm => !asm.IsDynamic && !string.IsNullOrWhiteSpace(asm.Location))
.Select(asm => MetadataReference.CreateFromFile(asm.Location))
.Cast<MetadataReference>()
.ToArray();
var logger = TraceLogger.GetLogger("CodeGenerator");
// Generate the code.
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
string source = null;
if (logger.IsVerbose3)
{
source = GenerateSourceCode(code);
// Compile the code and load the generated assembly.
if (logger.IsVerbose3)
{
logger.LogWithoutBulkingAndTruncating(
Severity.Verbose3,
ErrorCode.CodeGenSourceGenerated,
"Generating assembly {0} with source:\n{1}",
assemblyName,
source);
}
}
var compilation =
CSharpCompilation.Create(assemblyName)
.AddSyntaxTrees(code.SyntaxTree)
.AddReferences(assemblies)
.WithOptions(options);
using (var stream = new MemoryStream())
{
var compilationResult = compilation.Emit(stream);
if (!compilationResult.Success)
{
source = source ?? GenerateSourceCode(code);
var errors = string.Join("\n", compilationResult.Diagnostics.Select(_ => _.ToString()));
logger.Warn(
ErrorCode.CodeGenCompilationFailed,
"Compilation of assembly {0} failed with errors:\n{1}\nGenerated Source Code:\n{2}",
assemblyName,
errors,
source);
throw new CodeGenerationException(errors);
}
logger.Verbose(ErrorCode.CodeGenCompilationSucceeded, "Compilation of assembly {0} succeeded.", assemblyName);
return stream.ToArray();
}
}
示例14: CreateWorkspaceFromFilesAsync
public static Task<TestWorkspace> CreateWorkspaceFromFilesAsync(
string[] files,
CSharpParseOptions[] parseOptions = null,
CSharpCompilationOptions compilationOptions = null,
ExportProvider exportProvider = null)
{
return CreateWorkspaceFromFilesAsync(LanguageNames.CSharp, compilationOptions, parseOptions, files, exportProvider);
}
示例15: CreateCompilation
internal static Compilation CreateCompilation(string source, MetadataReference[] references, string assemblyName, CSharpCompilationOptions options = null)
{
return CSharpCompilation.Create(
assemblyName,
new[] { SyntaxFactory.ParseSyntaxTree(source) },
references,
options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}