Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,362 @@
//------------------------------------------------------------------------------
// <copyright file="CodeDOMProvider.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.ComponentModel;
using System.IO;
using System.Security.Permissions;
using System.Configuration;
using System.Collections;
using System.Runtime.InteropServices;
[
ToolboxItem(false)
]
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
[ComVisible(true)]
public abstract class CodeDomProvider : Component {
[ComVisible(false)]
public static CodeDomProvider CreateProvider(String language, System.Collections.Generic.IDictionary<String, String> providerOptions) {
CompilerInfo compilerInfo = GetCompilerInfo(language);
return compilerInfo.CreateProvider(providerOptions);
}
[ComVisible(false)]
public static CodeDomProvider CreateProvider(String language) {
CompilerInfo compilerInfo = GetCompilerInfo(language);
return compilerInfo.CreateProvider();
}
[ComVisible(false)]
public static String GetLanguageFromExtension(String extension) {
CompilerInfo compilerInfo = (CompilerInfo)GetCompilerInfoForExtensionNoThrow(extension);
if (compilerInfo == null)
throw new ConfigurationErrorsException(SR.GetString(SR.CodeDomProvider_NotDefined));
return compilerInfo._compilerLanguages[0]; // Return the first language name. There has to be one.
}
[ComVisible(false)]
public static bool IsDefinedLanguage(String language) {
return (GetCompilerInfoForLanguageNoThrow(language) != null);
}
[ComVisible(false)]
public static bool IsDefinedExtension(String extension) {
return (GetCompilerInfoForExtensionNoThrow(extension) != null);
}
[ComVisible(false)]
public static CompilerInfo GetCompilerInfo(String language) {
CompilerInfo compilerInfo = GetCompilerInfoForLanguageNoThrow(language);
if (compilerInfo == null)
throw new ConfigurationErrorsException(SR.GetString(SR.CodeDomProvider_NotDefined));
return compilerInfo;
}
// Do argument validation but don't throw if there's no compiler defined for a language.
private static CompilerInfo GetCompilerInfoForLanguageNoThrow(String language) {
if (language == null)
throw new ArgumentNullException("language");
CompilerInfo compilerInfo = (CompilerInfo)Config._compilerLanguages[language.Trim()];
return compilerInfo;
}
// Do argument validation but don't throw if there's no compiler defined for a language.
private static CompilerInfo GetCompilerInfoForExtensionNoThrow(String extension) {
if (extension == null)
throw new ArgumentNullException("extension");
CompilerInfo compilerInfo = (CompilerInfo)Config._compilerExtensions[extension.Trim()];
return compilerInfo;
}
[ComVisible(false)]
public static CompilerInfo[] GetAllCompilerInfo() {
ArrayList values = Config._allCompilerInfo;
CompilerInfo[] compilerInfos = (CompilerInfo[])values.ToArray(typeof(CompilerInfo));
return compilerInfos;
}
// Don't cache the configuration since things are different for asp.net scenarios.
private static CodeDomCompilationConfiguration Config {
get {
CodeDomCompilationConfiguration _configuration= (CodeDomCompilationConfiguration)PrivilegedConfigurationManager.GetSection(CodeDomCompilationConfiguration.sectionName);
if (_configuration == null) {
return CodeDomCompilationConfiguration.Default;
}
return _configuration;
}
}
/// <devdoc>
/// <para>Retrieves the default extension to use when saving files using this code dom provider.</para>
/// </devdoc>
public virtual string FileExtension {
get {
return string.Empty;
}
}
/// <devdoc>
/// <para>Returns flags representing language variations.</para>
/// </devdoc>
public virtual LanguageOptions LanguageOptions {
get {
return LanguageOptions.None;
}
}
[Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public abstract ICodeGenerator CreateGenerator();
#pragma warning disable 618
public virtual ICodeGenerator CreateGenerator(TextWriter output) {
return CreateGenerator();
}
public virtual ICodeGenerator CreateGenerator(string fileName) {
return CreateGenerator();
}
#pragma warning restore 618
[Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public abstract ICodeCompiler CreateCompiler();
[Obsolete("Callers should not use the ICodeParser interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")]
public virtual ICodeParser CreateParser() {
return null;
}
/// <devdoc>
/// This method allows a code dom provider implementation to provide a different type converter
/// for a given data type. At design time, a designer may pass data types through this
/// method to see if the code dom provider wants to provide an additional converter.
/// As typical way this would be used is if the language this code dom provider implements
/// does not support all of the values of MemberAttributes enumeration, or if the language
/// uses different names (Protected instead of Family, for example). The default
/// implementation just calls TypeDescriptor.GetConverter for the given type.
/// </devdoc>
public virtual TypeConverter GetConverter(Type type) {
return TypeDescriptor.GetConverter(type);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from the compile units
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits) {
return CreateCompilerHelper().CompileAssemblyFromDomBatch(options, compilationUnits);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the contents of the files
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames) {
return CreateCompilerHelper().CompileAssemblyFromFileBatch(options, fileNames);
}
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from sources
/// </para>
/// </devdoc>
public virtual CompilerResults CompileAssemblyFromSource(CompilerParameters options, params string[] sources) {
return CreateCompilerHelper().CompileAssemblyFromSourceBatch(options, sources);
}
/// <devdoc>
/// <para>
/// Gets a value indicating whether
/// the specified value is a valid identifier for this language.
/// </para>
/// </devdoc>
public virtual bool IsValidIdentifier(string value) {
return CreateGeneratorHelper().IsValidIdentifier(value);
}
public virtual string CreateEscapedIdentifier(string value) {
return CreateGeneratorHelper().CreateEscapedIdentifier(value);
}
public virtual string CreateValidIdentifier(string value) {
return CreateGeneratorHelper().CreateValidIdentifier(value);
}
public virtual string GetTypeOutput(CodeTypeReference type) {
return CreateGeneratorHelper().GetTypeOutput(type);
}
public virtual bool Supports(GeneratorSupport generatorSupport) {
return CreateGeneratorHelper().Supports(generatorSupport);
}
/// <devdoc>
/// <para>
/// Generates code from the specified expression and
/// outputs it to the specified textwriter.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromExpression(CodeExpression expression, TextWriter writer, CodeGeneratorOptions options) {
CreateGeneratorHelper().GenerateCodeFromExpression(expression, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by statement, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options) {
CreateGeneratorHelper().GenerateCodeFromStatement(statement, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by codeNamespace, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromNamespace(CodeNamespace codeNamespace, TextWriter writer, CodeGeneratorOptions options) {
CreateGeneratorHelper().GenerateCodeFromNamespace(codeNamespace, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by compileUnit, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromCompileUnit(CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options) {
CreateGeneratorHelper().GenerateCodeFromCompileUnit(compileUnit, writer, options);
}
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by codeType, into writer.
/// </para>
/// </devdoc>
public virtual void GenerateCodeFromType(CodeTypeDeclaration codeType, TextWriter writer, CodeGeneratorOptions options) {
CreateGeneratorHelper().GenerateCodeFromType(codeType, writer, options);
}
public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) {
throw new NotImplementedException(SR.GetString(SR.NotSupported_CodeDomAPI));
}
/// <devdoc>
/// <para>
/// Compiles the given text stream into a CodeCompile unit.
/// </para>
/// </devdoc>
public virtual CodeCompileUnit Parse(TextReader codeStream) {
return CreateParserHelper().Parse(codeStream);
}
#pragma warning disable 618
private ICodeCompiler CreateCompilerHelper() {
ICodeCompiler compiler = CreateCompiler();
if (compiler == null) {
throw new NotImplementedException(SR.GetString(SR.NotSupported_CodeDomAPI));
}
return compiler;
}
private ICodeGenerator CreateGeneratorHelper() {
ICodeGenerator generator = CreateGenerator();
if (generator == null) {
throw new NotImplementedException(SR.GetString(SR.NotSupported_CodeDomAPI));
}
return generator;
}
private ICodeParser CreateParserHelper() {
ICodeParser parser = CreateParser();
if (parser == null) {
throw new NotImplementedException(SR.GetString(SR.NotSupported_CodeDomAPI));
}
return parser;
}
#pragma warning restore 618
/// <summary>
/// This method returns a reference to mscorlib.dll or System.Runtime.dll that coresponds to
/// the version of the framework referenced by ReferencedAssemblies property if it appears
/// that these references point to a multi-targeting pack. VBCodeProvider and CSharpCodeProvider
/// use this method to provide a value for CoreAssemblyFileName if it was not set so the default
/// mscorlib.dll is not used in cases where it looks like the developer intended to do multi-targeting.
///
/// The huristic here is as follows:
/// If there is a reference that contains "\Reference Assemblies\Microsoft\Framework\<SkuName>\v<Version>"
/// and for each reference of the above form, they all share the same set of directories starting with
/// Reference Assemblies, then the probable core assembly is mscorlib.dll in that directory.
/// Otherwise, we do not have a probable core assembly.
///
/// Note that we do no validation to ensure SkuName or Version are actually valid sku names or versions.
/// The version component must start with a v but otherwise can be in any arbitrary form.
/// </summary>
internal static bool TryGetProbableCoreAssemblyFilePath(CompilerParameters parameters, out string coreAssemblyFilePath) {
string multiTargetingPackRoot = null;
char[] pathSeperators = new char[] { Path.DirectorySeparatorChar };
// Valid paths look like "...\Reference Assemblies\Microsoft\Framework\<SkuName>\v<Version>\..."
string referenceAssemblyFolderPrefix = Path.Combine("Reference Assemblies", "Microsoft", "Framework");
foreach (string s in parameters.ReferencedAssemblies) {
if (Path.GetFileName(s).Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)) {
// They already have their own mscorlib.dll, so let's not add another one.
coreAssemblyFilePath = string.Empty;
return false;
}
if (s.IndexOf(referenceAssemblyFolderPrefix, StringComparison.OrdinalIgnoreCase) >= 0) {
String[] dirs = s.Split(pathSeperators, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < dirs.Length - 5; i++) {
if (String.Equals(dirs[i], "Reference Assemblies", StringComparison.OrdinalIgnoreCase)) {
// Here i+5 is the index of the thing after the vX.XXX folder (if one exists) and i+4 should look like a version.
// (i.e. start with a v).
if (dirs[i + 4].StartsWith("v", StringComparison.OrdinalIgnoreCase)) {
if (multiTargetingPackRoot != null) {
if (!String.Equals(multiTargetingPackRoot, Path.GetDirectoryName(s), StringComparison.OrdinalIgnoreCase)) {
// We found one reference to one targeting pack and one referece to another. Bail out.
coreAssemblyFilePath = string.Empty;
return false;
}
} else {
multiTargetingPackRoot = Path.GetDirectoryName(s);
}
}
}
}
}
}
if (multiTargetingPackRoot != null) {
coreAssemblyFilePath = Path.Combine(multiTargetingPackRoot, "mscorlib.dll");
return true;
}
coreAssemblyFilePath = string.Empty;
return false;
}
}
}

View File

@@ -0,0 +1,489 @@
//------------------------------------------------------------------------------
// <OWNER>[....]</OWNER>
//
// <copyright file="CodeDomCompilationConfiguration.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Code related to the <assemblies> config section
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using System.Xml;
using System.Globalization;
internal class CodeDomCompilationConfiguration {
internal const String sectionName = "system.codedom";
static readonly char[] s_fieldSeparators = new char[] {';'};
// _compilerLanguages : Hashtable <string, CompilerInfo>
internal Hashtable _compilerLanguages;
// _compilerExtensions : Hashtable <string, CompilerInfo>
internal Hashtable _compilerExtensions;
internal ArrayList _allCompilerInfo;
private static CodeDomCompilationConfiguration defaultInstance = new CodeDomCompilationConfiguration();
internal static CodeDomCompilationConfiguration Default {
get {
return defaultInstance;
}
}
internal CodeDomCompilationConfiguration() {
// First time initialization. This must be kept consistent with machine.config.comments in that it
// must initialize the config system as if that block was present.
_compilerLanguages = new Hashtable(StringComparer.OrdinalIgnoreCase);
_compilerExtensions = new Hashtable(StringComparer.OrdinalIgnoreCase);
_allCompilerInfo = new ArrayList();
CompilerInfo compilerInfo;
CompilerParameters compilerParameters;
String typeName;
// C#
compilerParameters = new CompilerParameters();
compilerParameters.WarningLevel = 4;
typeName = "Microsoft.CSharp.CSharpCodeProvider, " + AssemblyRef.System;
compilerInfo = new CompilerInfo(compilerParameters, typeName);
compilerInfo._compilerLanguages = new string[] {"c#", "cs", "csharp"};
compilerInfo._compilerExtensions = new string[] {".cs", "cs"};
compilerInfo._providerOptions = new Dictionary<string, string>();
compilerInfo._providerOptions[RedistVersionInfo.NameTag] = RedistVersionInfo.DefaultVersion;
AddCompilerInfo(compilerInfo);
// VB
compilerParameters = new CompilerParameters();
compilerParameters.WarningLevel = 4;
typeName = "Microsoft.VisualBasic.VBCodeProvider, " + AssemblyRef.System;
compilerInfo = new CompilerInfo(compilerParameters, typeName);
compilerInfo._compilerLanguages = new string[] {"vb", "vbs", "visualbasic", "vbscript"};
compilerInfo._compilerExtensions = new string[] {".vb", "vb"};
compilerInfo._providerOptions = new Dictionary<string, string>();
compilerInfo._providerOptions[RedistVersionInfo.NameTag] = RedistVersionInfo.DefaultVersion;
AddCompilerInfo(compilerInfo);
// JScript
compilerParameters = new CompilerParameters();
compilerParameters.WarningLevel = 4;
typeName = "Microsoft.JScript.JScriptCodeProvider, " + AssemblyRef.MicrosoftJScript;
compilerInfo = new CompilerInfo(compilerParameters, typeName);
compilerInfo._compilerLanguages = new string[] {"js", "jscript", "javascript"};
compilerInfo._compilerExtensions = new string[] {".js", "js"};
compilerInfo._providerOptions = new Dictionary<string, string>();
AddCompilerInfo(compilerInfo);
// C++
compilerParameters = new CompilerParameters();
compilerParameters.WarningLevel = 4;
typeName = "Microsoft.VisualC.CppCodeProvider, " + AssemblyRef.MicrosoftVisualCCppCodeProvider;
compilerInfo = new CompilerInfo(compilerParameters, typeName);
compilerInfo._compilerLanguages = new string[] {"c++", "mc", "cpp"};
compilerInfo._compilerExtensions = new string[] {".h", "h"};
compilerInfo._providerOptions = new Dictionary<string, string>();
AddCompilerInfo(compilerInfo);
}
private CodeDomCompilationConfiguration(CodeDomCompilationConfiguration original) {
if (original._compilerLanguages != null)
_compilerLanguages = (Hashtable)original._compilerLanguages.Clone();
if (original._compilerExtensions != null)
_compilerExtensions = (Hashtable)original._compilerExtensions.Clone();
if (original._allCompilerInfo != null)
_allCompilerInfo = (ArrayList)original._allCompilerInfo.Clone();
}
private void AddCompilerInfo(CompilerInfo compilerInfo) {
foreach (string language in compilerInfo._compilerLanguages) {
_compilerLanguages[language] = compilerInfo;
}
foreach (string extension in compilerInfo._compilerExtensions) {
_compilerExtensions[extension] = compilerInfo;
}
_allCompilerInfo.Add(compilerInfo);
}
private void RemoveUnmapped() {
// Allow config compilers to replace redundant compiler entries
// clear out the mapped marker
for (int i = 0; i < _allCompilerInfo.Count; i++) {
((CompilerInfo)_allCompilerInfo[i])._mapped = false;
}
// Re-mark only the ones that still have a mapping
foreach (CompilerInfo destinationCompilerInfo in _compilerLanguages.Values) {
destinationCompilerInfo._mapped = true;
}
foreach (CompilerInfo destinationCompilerInfo in _compilerExtensions.Values) {
destinationCompilerInfo._mapped = true;
}
// Remove the ones that were not marked
for (int i = _allCompilerInfo.Count - 1; i >= 0; i--) {
if (!((CompilerInfo)_allCompilerInfo[i])._mapped) {
_allCompilerInfo.RemoveAt(i);
}
}
}
internal class SectionHandler {
private SectionHandler () {
}
internal static object CreateStatic(object inheritedObject, XmlNode node) {
CodeDomCompilationConfiguration inherited = (CodeDomCompilationConfiguration)inheritedObject;
CodeDomCompilationConfiguration result;
if (inherited == null)
result = new CodeDomCompilationConfiguration();
else
result = new CodeDomCompilationConfiguration(inherited);
HandlerBase.CheckForUnrecognizedAttributes(node);
//
// Handle child elements (if they exist)
// - compilers
//
foreach (XmlNode child in node.ChildNodes) {
// skip whitespace and comments
// reject nonelements
if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
continue;
// handle <compilers>
if (child.Name == "compilers") {
ProcessCompilersElement(result, child);
}
else {
HandlerBase.ThrowUnrecognizedElement(child);
}
}
return result;
}
private static IDictionary<string, string> GetProviderOptions(XmlNode compilerNode) {
Dictionary<string, string> res = new Dictionary<string, string>();
foreach (XmlNode child in compilerNode) {
if (child.Name != "providerOption") {
HandlerBase.ThrowUnrecognizedElement(child);
}
string name = null, value = null;
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "name", ref name);
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "value", ref value);
HandlerBase.CheckForUnrecognizedAttributes(child);
HandlerBase.CheckForChildNodes(child);
res[name] = value;
}
return res;
}
private static void ProcessCompilersElement(CodeDomCompilationConfiguration result, XmlNode node) {
// reject attributes
HandlerBase.CheckForUnrecognizedAttributes(node);
String configFile = ConfigurationErrorsException.GetFilename(node);
foreach(XmlNode child in node.ChildNodes) {
int configLineNumber = ConfigurationErrorsException.GetLineNumber(child);
// skip whitespace and comments
// reject nonelements
if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
continue;
if (child.Name != "compiler") {
HandlerBase.ThrowUnrecognizedElement(child);
}
String languages = String.Empty;
XmlNode languageNode = HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "language", ref languages);
String extensions = String.Empty;
HandlerBase.GetAndRemoveRequiredNonEmptyStringAttribute(child, "extension", ref extensions);
String compilerTypeName = null;
HandlerBase.GetAndRemoveStringAttribute(child, "type", ref compilerTypeName);
// Create a CompilerParameters for this compiler.
CompilerParameters compilerParams = new CompilerParameters();
int warningLevel = 0;
if (HandlerBase.GetAndRemoveNonNegativeIntegerAttribute(child, "warningLevel", ref warningLevel) != null) {
compilerParams.WarningLevel = warningLevel;
// Need to be false if the warning level is 0
compilerParams.TreatWarningsAsErrors = (warningLevel>0);
}
String compilerOptions = null;
if (HandlerBase.GetAndRemoveStringAttribute(child, "compilerOptions", ref compilerOptions) != null) {
compilerParams.CompilerOptions = compilerOptions;
}
IDictionary<string, string> provOptions = GetProviderOptions(child);
HandlerBase.CheckForUnrecognizedAttributes(child);
// Parse the semicolon separated lists
string[] languageList = languages.Split(s_fieldSeparators);
string[] extensionList = extensions.Split(s_fieldSeparators);
for( int i =0 ; i < languageList.Length; i++) {
languageList[i] = languageList[i].Trim();
}
for( int i =0 ; i < extensionList.Length; i++) {
extensionList[i] = extensionList[i].Trim();
}
// Validate language names, language names must have length and extensions must start with a period.
foreach (string language in languageList) {
if (language.Length == 0)
throw new ConfigurationErrorsException(SR.GetString(SR.Language_Names_Cannot_Be_Empty));
}
foreach (string extension in extensionList) {
if (extension.Length == 0 || extension[0] != '.')
throw new ConfigurationErrorsException(SR.GetString(SR.Extension_Names_Cannot_Be_Empty_Or_Non_Period_Based));
}
// Create a CompilerInfo structure for this compiler, or get
// an existing one if no type was provided
CompilerInfo compilerInfo = null;
if (compilerTypeName != null) {
compilerInfo = new CompilerInfo(compilerParams, compilerTypeName);
} else {
// reconfiguring an existing entry
compilerInfo = result.FindExistingCompilerInfo(languageList, extensionList);
if (compilerInfo == null)
throw new ConfigurationErrorsException();
}
compilerInfo.configFileName = configFile;
compilerInfo.configFileLineNumber = configLineNumber;
if (compilerTypeName != null) {
compilerInfo._compilerLanguages = languageList;
compilerInfo._compilerExtensions = extensionList;
compilerInfo._providerOptions = provOptions;
result.AddCompilerInfo(compilerInfo);
} else {
// merge in new options, replacing any previous values w/
// new ones.
foreach (KeyValuePair<string, string> kvp in provOptions) {
compilerInfo._providerOptions[kvp.Key] = kvp.Value;
}
}
}
// Allow config options to replace redundant compiler entries
result.RemoveUnmapped();
}
}
private CompilerInfo FindExistingCompilerInfo(string[] languageList, string[] extensionList) {
CompilerInfo compilerInfo = null;
foreach (CompilerInfo ci in _allCompilerInfo) {
if (ci._compilerExtensions.Length == extensionList.Length &&
ci._compilerLanguages.Length == languageList.Length) {
bool differ = false;
for (int i = 0; i < ci._compilerExtensions.Length; i++) {
if (ci._compilerExtensions[i] != extensionList[i]) {
differ = true;
break;
}
}
for (int i = 0; i < ci._compilerLanguages.Length; i++) {
if (ci._compilerLanguages[i] != languageList[i]) {
differ = true;
break;
}
}
if (!differ) {
compilerInfo = ci;
break;
}
}
}
return compilerInfo;
}
}
internal class CodeDomConfigurationHandler : IConfigurationSectionHandler {
internal CodeDomConfigurationHandler() {
}
public virtual object Create(object inheritedObject, object configContextObj, XmlNode node) {
return CodeDomCompilationConfiguration.SectionHandler.CreateStatic(inheritedObject, node);
}
}
internal static class HandlerBase {
//
// XML Attribute Helpers
//
private static XmlNode GetAndRemoveAttribute(XmlNode node, string attrib, bool fRequired) {
XmlNode a = node.Attributes.RemoveNamedItem(attrib);
// If the attribute is required and was not present, throw
if (fRequired && a == null) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_missing_required_attribute, attrib, node.Name), node);
}
return a;
}
private static XmlNode GetAndRemoveStringAttributeInternal(XmlNode node, string attrib, bool fRequired, ref string val) {
XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired);
if (a != null)
val = a.Value;
return a;
}
internal static XmlNode GetAndRemoveStringAttribute(XmlNode node, string attrib, ref string val) {
return GetAndRemoveStringAttributeInternal(node, attrib, false /*fRequired*/, ref val);
}
internal static XmlNode GetAndRemoveRequiredNonEmptyStringAttribute(XmlNode node, string attrib, ref string val) {
return GetAndRemoveNonEmptyStringAttributeInternal(node, attrib, true /*fRequired*/, ref val);
}
private static XmlNode GetAndRemoveNonEmptyStringAttributeInternal(XmlNode node, string attrib, bool fRequired, ref string val) {
XmlNode a = GetAndRemoveStringAttributeInternal(node, attrib, fRequired, ref val);
if (a != null && val.Length == 0) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Empty_attribute, attrib), a);
}
return a;
}
private static XmlNode GetAndRemoveIntegerAttributeInternal(XmlNode node, string attrib, bool fRequired, ref int val) {
XmlNode a = GetAndRemoveAttribute(node, attrib, fRequired);
if (a != null) {
if (a.Value.Trim() != a.Value) {
throw new ConfigurationErrorsException(SR.GetString(SR.Config_invalid_integer_attribute, a.Name),a);
}
try {
val = int.Parse(a.Value, CultureInfo.InvariantCulture);
}
catch (Exception e) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_invalid_integer_attribute, a.Name), e, a);
}
}
return a;
}
private static XmlNode GetAndRemoveNonNegativeAttributeInternal(XmlNode node, string attrib, bool fRequired, ref int val) {
XmlNode a = GetAndRemoveIntegerAttributeInternal(node, attrib, fRequired, ref val);
if (a != null && val < 0) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Invalid_nonnegative_integer_attribute, attrib), a);
}
return a;
}
internal static XmlNode GetAndRemoveNonNegativeIntegerAttribute(XmlNode node, string attrib, ref int val) {
return GetAndRemoveNonNegativeAttributeInternal(node, attrib, false /*fRequired*/, ref val);
}
internal static void CheckForUnrecognizedAttributes(XmlNode node) {
if (node.Attributes.Count != 0) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_base_unrecognized_attribute, node.Attributes[0].Name),
node.Attributes[0]);
}
}
//
// XML Element Helpers
//
internal static void CheckForNonElement(XmlNode node) {
if (node.NodeType != XmlNodeType.Element) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_base_elements_only),
node);
}
}
internal static bool IsIgnorableAlsoCheckForNonElement(XmlNode node) {
if (node.NodeType == XmlNodeType.Comment || node.NodeType == XmlNodeType.Whitespace) {
return true;
}
CheckForNonElement(node);
return false;
}
internal static void CheckForChildNodes(XmlNode node) {
if (node.HasChildNodes) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_base_no_child_nodes),
node.FirstChild);
}
}
internal static void ThrowUnrecognizedElement(XmlNode node) {
throw new ConfigurationErrorsException(
SR.GetString(SR.Config_base_unrecognized_element),
node);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,108 @@
//------------------------------------------------------------------------------
// <copyright file="CodeGeneratorOptions.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Specialized;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// Represents options used in code generation
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public class CodeGeneratorOptions {
private IDictionary options = new ListDictionary();
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CodeGeneratorOptions() {
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object this[string index] {
get {
return options[index];
}
set {
options[index] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string IndentString {
get {
object o = options["IndentString"];
return ((o == null) ? " " : (string)o);
}
set {
options["IndentString"] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string BracingStyle {
get {
object o = options["BracingStyle"];
return ((o == null) ? "Block" : (string)o);
}
set {
options["BracingStyle"] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool ElseOnClosing {
get {
object o = options["ElseOnClosing"];
return ((o == null) ? false : (bool)o);
}
set {
options["ElseOnClosing"] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool BlankLinesBetweenMembers {
get {
object o = options["BlankLinesBetweenMembers"];
return ((o == null) ? true : (bool)o);
}
set {
options["BlankLinesBetweenMembers"] = value;
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public bool VerbatimOrder {
get {
object o = options["VerbatimOrder"];
return ((o == null) ? false : (bool)o);
}
set {
options["VerbatimOrder"] = value;
}
}
}
}

View File

@@ -0,0 +1,38 @@
//------------------------------------------------------------------------------
// <copyright file="CodeParser.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Text;
using System.Diagnostics;
using System;
using Microsoft.Win32;
using System.IO;
using System.Collections;
using System.Reflection;
using System.CodeDom;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// Provides a code parsing abstract base class.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public abstract class CodeParser : ICodeParser {
/// <devdoc>
/// <para>
/// Compiles the given text stream into a CodeCompile unit.
/// </para>
/// </devdoc>
public abstract CodeCompileUnit Parse(TextReader codeStream);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,166 @@
//------------------------------------------------------------------------------
// <copyright file="CompilerError.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Security.Permissions;
using System.Globalization;
/// <devdoc>
/// <para>
/// Represents a compiler error.
/// </para>
/// </devdoc>
[Serializable()]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public class CompilerError {
private int line;
private int column;
private string errorNumber;
private bool warning = false;
private string errorText;
private string fileName;
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerError'/>.
/// </para>
/// </devdoc>
public CompilerError() {
this.line = 0;
this.column = 0;
this.errorNumber = string.Empty;
this.errorText = string.Empty;
this.fileName = string.Empty;
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerError'/> using the specified
/// filename, line, column, error number and error text.
/// </para>
/// </devdoc>
public CompilerError(string fileName, int line, int column, string errorNumber, string errorText) {
this.line = line;
this.column = column;
this.errorNumber = errorNumber;
this.errorText = errorText;
this.fileName = fileName;
}
/// <devdoc>
/// <para>
/// Gets or sets the line number where the source of the error occurs.
/// </para>
/// </devdoc>
public int Line {
get {
return line;
}
set {
line = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the column number where the source of the error occurs.
/// </para>
/// </devdoc>
public int Column {
get {
return column;
}
set {
column = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the error number.
/// </para>
/// </devdoc>
public string ErrorNumber {
get {
return errorNumber;
}
set {
errorNumber = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the text of the error message.
/// </para>
/// </devdoc>
public string ErrorText {
get {
return errorText;
}
set {
errorText = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets
/// a value indicating whether the error is a warning.
/// </para>
/// </devdoc>
public bool IsWarning {
get {
return warning;
}
set {
warning = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the filename of the source that caused the error.
/// </para>
/// </devdoc>
public string FileName {
get {
return fileName;
}
set {
fileName = value;
}
}
/// <devdoc>
/// <para>
/// Overrides Object's ToString.
/// </para>
/// </devdoc>
public override string ToString() {
if (FileName.Length > 0) {
return string.Format(CultureInfo.InvariantCulture, "{0}({1},{2}) : {3} {4}: {5}",
new object[] {
FileName,
Line,
Column,
IsWarning ? "warning" : "error",
ErrorNumber,
ErrorText});
}
else
return string.Format(CultureInfo.InvariantCulture, "{0} {1}: {2}",
IsWarning ? "warning" : "error",
ErrorNumber,
ErrorText);
}
}
}

View File

@@ -0,0 +1,174 @@
// ------------------------------------------------------------------------------
// <copyright file="CompilerErrorCollection.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------
//
namespace System.CodeDom.Compiler {
using System;
using System.Collections;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// A collection that stores <see cref='System.CodeDom.Compiler.CompilerError'/> objects.
/// </para>
/// </devdoc>
[Serializable()]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public class CompilerErrorCollection : CollectionBase {
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/>.
/// </para>
/// </devdoc>
public CompilerErrorCollection() {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> based on another <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/>.
/// </para>
/// </devdoc>
public CompilerErrorCollection(CompilerErrorCollection value) {
this.AddRange(value);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> containing any array of <see cref='System.CodeDom.Compiler.CompilerError'/> objects.
/// </para>
/// </devdoc>
public CompilerErrorCollection(CompilerError[] value) {
this.AddRange(value);
}
/// <devdoc>
/// <para>Represents the entry at the specified index of the <see cref='System.CodeDom.Compiler.CompilerError'/>.</para>
/// </devdoc>
public CompilerError this[int index] {
get {
return ((CompilerError)(List[index]));
}
set {
List[index] = value;
}
}
/// <devdoc>
/// <para>Adds a <see cref='System.CodeDom.Compiler.CompilerError'/> with the specified value to the
/// <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> .</para>
/// </devdoc>
public int Add(CompilerError value) {
return List.Add(value);
}
/// <devdoc>
/// <para>Copies the elements of an array to the end of the <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/>.</para>
/// </devdoc>
public void AddRange(CompilerError[] value) {
if (value == null) {
throw new ArgumentNullException("value");
}
for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) {
this.Add(value[i]);
}
}
/// <devdoc>
/// <para>
/// Adds the contents of another <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> to the end of the collection.
/// </para>
/// </devdoc>
public void AddRange(CompilerErrorCollection value) {
if (value == null) {
throw new ArgumentNullException("value");
}
int currentCount = value.Count;
for (int i = 0; i < currentCount; i = ((i) + (1))) {
this.Add(value[i]);
}
}
/// <devdoc>
/// <para>Gets a value indicating whether the
/// <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> contains the specified <see cref='System.CodeDom.Compiler.CompilerError'/>.</para>
/// </devdoc>
public bool Contains(CompilerError value) {
return List.Contains(value);
}
/// <devdoc>
/// <para>Copies the <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the
/// specified index.</para>
/// </devdoc>
public void CopyTo(CompilerError[] array, int index) {
List.CopyTo(array, index);
}
/// <devdoc>
/// <para>
/// Gets or sets
/// a value indicating whether the collection contains errors.
/// </para>
/// </devdoc>
public bool HasErrors {
get {
if (Count > 0) {
foreach (CompilerError e in this) {
if (!e.IsWarning) {
return true;
}
}
}
return false;
}
}
/// <devdoc>
/// <para>
/// Gets or sets
/// a value indicating whether the collection contains warnings.
/// </para>
/// </devdoc>
public bool HasWarnings {
get {
if (Count > 0) {
foreach (CompilerError e in this) {
if (e.IsWarning) {
return true;
}
}
}
return false;
}
}
/// <devdoc>
/// <para>Returns the index of a <see cref='System.CodeDom.Compiler.CompilerError'/> in
/// the <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> .</para>
/// </devdoc>
public int IndexOf(CompilerError value) {
return List.IndexOf(value);
}
/// <devdoc>
/// <para>Inserts a <see cref='System.CodeDom.Compiler.CompilerError'/> into the <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> at the specified index.</para>
/// </devdoc>
public void Insert(int index, CompilerError value) {
List.Insert(index, value);
}
/// <devdoc>
/// <para> Removes a specific <see cref='System.CodeDom.Compiler.CompilerError'/> from the
/// <see cref='System.CodeDom.Compiler.CompilerErrorCollection'/> .</para>
/// </devdoc>
public void Remove(CompilerError value) {
List.Remove(value);
}
}
}

View File

@@ -0,0 +1,177 @@
//------------------------------------------------------------------------------
// <copyright file="CompilerInfo.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.Reflection;
using System.Security.Permissions;
using System.CodeDom.Compiler;
using System.Configuration;
using System.Collections.Generic;
using System.Diagnostics;
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
public sealed class CompilerInfo {
internal String _codeDomProviderTypeName; // This can never by null
internal CompilerParameters _compilerParams; // This can never by null
internal String[] _compilerLanguages; // This can never by null
internal String[] _compilerExtensions; // This can never by null
internal String configFileName;
internal IDictionary<string, string> _providerOptions; // This can never be null
internal int configFileLineNumber;
internal Boolean _mapped;
private Type type;
private CompilerInfo() {} // Not createable
public String[] GetLanguages() {
return CloneCompilerLanguages();
}
public String[] GetExtensions() {
return CloneCompilerExtensions();
}
public Type CodeDomProviderType {
get {
if( type == null) {
lock(this) {
if( type == null) {
type = Type.GetType(_codeDomProviderTypeName);
if (type == null) {
if( configFileName == null) {
throw new ConfigurationErrorsException(SR.GetString(SR.Unable_To_Locate_Type,
_codeDomProviderTypeName, string.Empty, 0));
}
else {
throw new ConfigurationErrorsException(SR.GetString(SR.Unable_To_Locate_Type,
_codeDomProviderTypeName), configFileName, configFileLineNumber);
}
}
}
}
}
return type;
}
}
public bool IsCodeDomProviderTypeValid {
get {
Type type = Type.GetType(_codeDomProviderTypeName);
return (type != null);
}
}
public CodeDomProvider CreateProvider() {
// if the provider defines an IDictionary<string, string> ctor and
// provider options have been provided then call that and give it the
// provider options dictionary. Otherwise call the normal one.
Debug.Assert(_providerOptions != null, "Created CompilerInfo w/ null _providerOptions");
if (_providerOptions.Count > 0) {
ConstructorInfo ci = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary<string, string>) });
if (ci != null) {
return (CodeDomProvider)ci.Invoke(new object[] { _providerOptions });
}
}
return (CodeDomProvider)Activator.CreateInstance(CodeDomProviderType);
}
public CodeDomProvider CreateProvider(IDictionary<String, String> providerOptions)
{
if (providerOptions == null)
throw new ArgumentNullException("providerOptions");
ConstructorInfo constructor = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary<string, string>) });
if (constructor != null) {
return (CodeDomProvider)constructor.Invoke(new object[] { providerOptions });
}
else
throw new InvalidOperationException(SR.GetString(SR.Provider_does_not_support_options, CodeDomProviderType.ToString()));
}
public CompilerParameters CreateDefaultCompilerParameters() {
return CloneCompilerParameters();
}
internal CompilerInfo(CompilerParameters compilerParams, String codeDomProviderTypeName, String[] compilerLanguages, String[] compilerExtensions) {
_compilerLanguages = compilerLanguages;
_compilerExtensions = compilerExtensions;
_codeDomProviderTypeName = codeDomProviderTypeName;
if (compilerParams == null)
compilerParams = new CompilerParameters();
_compilerParams = compilerParams;
}
internal CompilerInfo(CompilerParameters compilerParams, String codeDomProviderTypeName) {
_codeDomProviderTypeName = codeDomProviderTypeName;
if (compilerParams == null)
compilerParams = new CompilerParameters();
_compilerParams = compilerParams;
}
public override int GetHashCode() {
return _codeDomProviderTypeName.GetHashCode();
}
public override bool Equals(Object o) {
CompilerInfo other = o as CompilerInfo;
if (o == null)
return false;
return CodeDomProviderType == other.CodeDomProviderType &&
CompilerParams.WarningLevel == other.CompilerParams.WarningLevel &&
CompilerParams.IncludeDebugInformation == other.CompilerParams.IncludeDebugInformation &&
CompilerParams.CompilerOptions == other.CompilerParams.CompilerOptions;
}
private CompilerParameters CloneCompilerParameters() {
CompilerParameters copy = new CompilerParameters();
copy.IncludeDebugInformation = _compilerParams.IncludeDebugInformation;
copy.TreatWarningsAsErrors = _compilerParams.TreatWarningsAsErrors;
copy.WarningLevel = _compilerParams.WarningLevel;
copy.CompilerOptions = _compilerParams.CompilerOptions;
return copy;
}
private String[] CloneCompilerLanguages() {
String[] compilerLanguages = new String[_compilerLanguages.Length];
Array.Copy(_compilerLanguages, compilerLanguages, _compilerLanguages.Length);
return compilerLanguages;
}
private String[] CloneCompilerExtensions() {
String[] compilerExtensions = new String[_compilerExtensions.Length];
Array.Copy(_compilerExtensions, compilerExtensions, _compilerExtensions.Length);
return compilerExtensions;
}
internal CompilerParameters CompilerParams {
get {
return _compilerParams;
}
}
// @
internal IDictionary<string, string> ProviderOptions {
get {
return _providerOptions;
}
}
}
}

View File

@@ -0,0 +1,351 @@
//------------------------------------------------------------------------------
// <copyright file="CompilerParameters.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security.Policy;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// Represents the parameters used in to invoke the compiler.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
[Serializable]
public class CompilerParameters {
[OptionalField]
private string coreAssemblyFileName = String.Empty;
private StringCollection assemblyNames = new StringCollection();
[OptionalField]
private StringCollection embeddedResources = new StringCollection();
[OptionalField]
private StringCollection linkedResources = new StringCollection();
private string outputName;
private string mainClass;
private bool generateInMemory = false;
private bool includeDebugInformation = false;
private int warningLevel = -1; // -1 means not set (use compiler default)
private string compilerOptions;
private string win32Resource;
private bool treatWarningsAsErrors = false;
private bool generateExecutable = false;
private TempFileCollection tempFiles;
[NonSerializedAttribute]
private SafeUserTokenHandle userToken;
private Evidence evidence = null;
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/>.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CompilerParameters() :
this(null, null) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames) :
this(assemblyNames, null, false) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names and output name.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames, string outputName) :
this(assemblyNames, outputName, false) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names, output name and a whether to include debug information flag.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
public CompilerParameters(string[] assemblyNames, string outputName, bool includeDebugInformation) {
if (assemblyNames != null) {
ReferencedAssemblies.AddRange(assemblyNames);
}
this.outputName = outputName;
this.includeDebugInformation = includeDebugInformation;
}
/// <summary>
/// The "core" or "standard" assembly that contains basic types such as <code>Object</code>, <code>Int32</code> and the like
/// that is to be used for the compilation.<br />
/// If the value of this property is an empty string (or <code>null</code>), the default core assembly will be used by the
/// compiler (depending on the compiler version this may be <code>mscorlib.dll</code> or <code>System.Runtime.dll</code> in
/// a Framework or reference assembly directory).<br />
/// If the value of this property is not empty, CodeDOM will emit compiler options to not reference <em>any</em> assemblies
/// implicitly during compilation. It will also explicitly reference the assembly file specified in this property.<br />
/// For compilers that only implicitly reference the "core" or "standard" assembly by default, this option can be used on its own.
/// For compilers that implicitly reference more assemblies on top of the "core" / "standard" assembly, using this option may require
/// specifying additional entries in the <code>System.CodeDom.Compiler.<bold>ReferencedAssemblies</bold></code> collection.<br />
/// Note: An <code>ICodeCompiler</code> / <code>CoodeDomProvider</code> implementation may choose to ignore this property.
/// </summary>
public string CoreAssemblyFileName {
get {
return coreAssemblyFileName;
}
set {
coreAssemblyFileName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate an executable.
/// </para>
/// </devdoc>
public bool GenerateExecutable {
get {
return generateExecutable;
}
set {
generateExecutable = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate in memory.
/// </para>
/// </devdoc>
public bool GenerateInMemory {
get {
return generateInMemory;
}
set {
generateInMemory = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the assemblies referenced by the source to compile.
/// </para>
/// </devdoc>
public StringCollection ReferencedAssemblies {
get {
return assemblyNames;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the main class.
/// </para>
/// </devdoc>
public string MainClass {
get {
return mainClass;
}
set {
mainClass = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the output assembly.
/// </para>
/// </devdoc>
public string OutputAssembly {
[ResourceExposure(ResourceScope.Machine)]
get {
return outputName;
}
[ResourceExposure(ResourceScope.Machine)]
set {
outputName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the temp files.
/// </para>
/// </devdoc>
public TempFileCollection TempFiles {
get {
if (tempFiles == null)
tempFiles = new TempFileCollection();
return tempFiles;
}
set {
tempFiles = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to include debug information in the compiled
/// executable.
/// </para>
/// </devdoc>
public bool IncludeDebugInformation {
get {
return includeDebugInformation;
}
set {
includeDebugInformation = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool TreatWarningsAsErrors {
get {
return treatWarningsAsErrors;
}
set {
treatWarningsAsErrors = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int WarningLevel {
get {
return warningLevel;
}
set {
warningLevel = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CompilerOptions {
get {
return compilerOptions;
}
set {
compilerOptions = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Win32Resource {
get {
return win32Resource;
}
set {
win32Resource = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the resources to be compiled into the target
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection EmbeddedResources {
get {
return embeddedResources;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the linked resources
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection LinkedResources {
get {
return linkedResources;
}
}
/// <devdoc>
/// <para>
/// Gets or sets user token to be employed when creating the compiler process.
/// </para>
/// </devdoc>
public IntPtr UserToken {
get {
if (userToken != null)
return userToken.DangerousGetHandle();
else
return IntPtr.Zero;
}
set {
if (userToken != null)
userToken.Close();
userToken = new SafeUserTokenHandle(value, false);
}
}
internal SafeUserTokenHandle SafeUserToken {
get {
return userToken;
}
}
/// <devdoc>
/// <para>
/// Set the evidence for partially trusted scenarios.
/// </para>
/// </devdoc>
[Obsolete("CAS policy is obsolete and will be removed in a future release of the .NET Framework."
+ " Please see http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public Evidence Evidence {
get {
Evidence e = null;
if (evidence != null)
e = evidence.Clone();
return e;
}
[SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )]
set {
if (value != null)
evidence = value.Clone();
else
evidence = null;
}
}
}
}

View File

@@ -0,0 +1,180 @@
//------------------------------------------------------------------------------
// <copyright file="CompilerResults.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System;
using System.CodeDom;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.IO;
/// <devdoc>
/// <para>
/// Represents the results
/// of compilation from the compiler.
/// </para>
/// </devdoc>
[Serializable()]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public class CompilerResults {
private CompilerErrorCollection errors = new CompilerErrorCollection();
private StringCollection output = new StringCollection();
private Assembly compiledAssembly;
private string pathToAssembly;
private int nativeCompilerReturnValue;
private TempFileCollection tempFiles;
private Evidence evidence;
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerResults'/>
/// that uses the specified
/// temporary files.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
public CompilerResults(TempFileCollection tempFiles) {
this.tempFiles = tempFiles;
}
/// <devdoc>
/// <para>
/// Gets or sets the temporary files to use.
/// </para>
/// </devdoc>
public TempFileCollection TempFiles {
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
get {
return tempFiles;
}
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
set {
tempFiles = value;
}
}
/// <devdoc>
/// <para>
/// Set the evidence for partially trusted scenarios.
/// </para>
/// </devdoc>
[Obsolete("CAS policy is obsolete and will be removed in a future release of the .NET Framework. Please see http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public Evidence Evidence {
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
get {
Evidence e = null;
if (evidence != null)
e = evidence.Clone();
return e;
}
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[SecurityPermissionAttribute( SecurityAction.Demand, ControlEvidence = true )]
set {
if (value != null)
evidence = value.Clone();
else
evidence = null;
}
}
/// <devdoc>
/// <para>
/// The compiled assembly.
/// </para>
/// </devdoc>
public Assembly CompiledAssembly {
[SecurityPermissionAttribute(SecurityAction.Assert, Flags=SecurityPermissionFlag.ControlEvidence)]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
if (compiledAssembly == null && pathToAssembly != null) {
AssemblyName assemName = new AssemblyName();
assemName.CodeBase = pathToAssembly;
#pragma warning disable 618 // Load with evidence is obsolete - this warning is passed on via the Evidence property
compiledAssembly = Assembly.Load(assemName,evidence);
#pragma warning restore 618
}
return compiledAssembly;
}
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
set {
compiledAssembly = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the collection of compiler errors.
/// </para>
/// </devdoc>
public CompilerErrorCollection Errors {
get {
return errors;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the compiler output messages.
/// </para>
/// </devdoc>
public StringCollection Output {
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
get {
return output;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the path to the assembly.
/// </para>
/// </devdoc>
public string PathToAssembly {
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[ResourceExposure(ResourceScope.Machine)]
get {
return pathToAssembly;
}
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[ResourceExposure(ResourceScope.Machine)]
set {
pathToAssembly = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the compiler's return value.
/// </para>
/// </devdoc>
public int NativeCompilerReturnValue {
get {
return nativeCompilerReturnValue;
}
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
set {
nativeCompilerReturnValue = value;
}
}
}
}

View File

@@ -0,0 +1,351 @@
//------------------------------------------------------------------------------
// <copyright file="Executor.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Runtime.InteropServices;
using System.CodeDom;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// Provides command execution functions for the CodeDom compiler.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
public static class Executor {
// How long (in milliseconds) do we wait for the program to terminate
private const int ProcessTimeOut = 600000;
/// <devdoc>
/// <para>
/// Gets the runtime install directory.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static string GetRuntimeInstallDirectory() {
return RuntimeEnvironment.GetRuntimeDirectory();
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static FileStream CreateInheritedFile(string file) {
return new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
}
/// <devdoc>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void ExecWait(string cmd, TempFileCollection tempFiles) {
string outputName = null;
string errorName = null;
ExecWaitWithCapture(cmd, tempFiles, ref outputName, ref errorName);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(null, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) {
return ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) {
int retValue = 0;
// Undo any current impersonation, call ExecWaitWithCaptureUnimpersonated, and reimpersonate
#if !FEATURE_PAL
// the extra try-catch is here to mitigate exception filter injection attacks.
try {
WindowsImpersonationContext impersonation = RevertImpersonation();
try {
#endif
// Execute the process
retValue = ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine);
#if !FEATURE_PAL
} finally {
ReImpersonate(impersonation);
}
}
catch {
throw;
}
#endif
return retValue;
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) {
IntSecurity.UnmanagedCode.Demand();
FileStream output;
FileStream error;
int retValue = 0;
if (outputName == null || outputName.Length == 0)
outputName = tempFiles.AddExtension("out");
if (errorName == null || errorName.Length == 0)
errorName = tempFiles.AddExtension("err");
// Create the files
output = CreateInheritedFile(outputName);
error = CreateInheritedFile(errorName);
bool success = false;
SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION();
SafeProcessHandle procSH = new SafeProcessHandle();
SafeThreadHandle threadSH = new SafeThreadHandle();
SafeUserTokenHandle primaryToken = null;
try {
// Output the command line...
StreamWriter sw = new StreamWriter(output, Encoding.UTF8);
sw.Write(currentDir);
sw.Write("> ");
// 'true' command line is used in case the command line points to
// a response file
sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd);
sw.WriteLine();
sw.WriteLine();
sw.Flush();
NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO();
si.cb = Marshal.SizeOf(si);
#if FEATURE_PAL
si.dwFlags = NativeMethods.STARTF_USESTDHANDLES;
#else //!FEATURE_PAL
si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW;
si.wShowWindow = NativeMethods.SW_HIDE;
#endif //!FEATURE_PAL
si.hStdOutput = output.SafeFileHandle;
si.hStdError = error.SafeFileHandle;
si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false);
//
// Prepare the environment
//
#if PLATFORM_UNIX
StringDictionary environment = new CaseSensitiveStringDictionary();
#else
StringDictionary environment = new StringDictionary ();
#endif // PLATFORM_UNIX
// Add the current environment
foreach ( DictionaryEntry entry in Environment.GetEnvironmentVariables () )
environment[(string) entry.Key] = (string) entry.Value;
// Add the flag to indicate restricted security in the process
environment["_ClrRestrictSecAttributes"] = "1";
#if DEBUG
environment["OANOCACHE"] = "1";
#endif
// set up the environment block parameter
byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false);
fixed (byte* environmentBytesPtr = environmentBytes) {
IntPtr environmentPtr = new IntPtr((void*)environmentBytesPtr);
if (userToken == null || userToken.IsInvalid) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
success = NativeMethods.CreateProcess(
null, // String lpApplicationName,
new StringBuilder(cmd), // String lpCommandLine,
null, // SECURITY_ATTRIBUTES lpProcessAttributes,
null, // SECURITY_ATTRIBUTES lpThreadAttributes,
true, // bool bInheritHandles,
0, // int dwCreationFlags,
environmentPtr, // IntPtr lpEnvironment,
currentDir, // String lpCurrentDirectory,
si, // STARTUPINFO lpStartupInfo,
pi); // PROCESS_INFORMATION lpProcessInformation);
if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(pi.hProcess);
if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(pi.hThread);
}
}
else {
#if FEATURE_PAL
throw new NotSupportedException();
#else
success = SafeUserTokenHandle.DuplicateTokenEx(
userToken,
NativeMethods.TOKEN_ALL_ACCESS,
null,
NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation,
NativeMethods.TOKEN_TYPE_TokenPrimary,
out primaryToken
);
if (success) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
success = NativeMethods.CreateProcessAsUser(
primaryToken, // int token,
null, // String lpApplicationName,
cmd, // String lpCommandLine,
null, // SECURITY_ATTRIBUTES lpProcessAttributes,
null, // SECURITY_ATTRIBUTES lpThreadAttributes,
true, // bool bInheritHandles,
0, // int dwCreationFlags,
new HandleRef(null, environmentPtr), // IntPtr lpEnvironment,
currentDir, // String lpCurrentDirectory,
si, // STARTUPINFO lpStartupInfo,
pi); // PROCESS_INFORMATION lpProcessInformation);
if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
procSH.InitialSetHandle(pi.hProcess);
if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE)
threadSH.InitialSetHandle(pi.hThread);
}
}
#endif // !FEATURE_PAL
}
}
}
finally {
// Close the file handles
if (!success && (primaryToken != null && !primaryToken.IsInvalid)) {
primaryToken.Close();
primaryToken = null;
}
output.Close();
error.Close();
}
if (success) {
try {
bool signaled;
ProcessWaitHandle pwh = null;
try {
pwh = new ProcessWaitHandle(procSH);
signaled = pwh.WaitOne(ProcessTimeOut, false);
} finally {
if (pwh != null)
pwh.Close();
}
// Check for timeout
if (!signaled) {
throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT);
}
// Check the process's exit code
int status = NativeMethods.STILL_ACTIVE;
if (!NativeMethods.GetExitCodeProcess(procSH, out status)) {
throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error());
}
retValue = status;
}
finally {
procSH.Close();
threadSH.Close();
if (primaryToken != null && !primaryToken.IsInvalid)
primaryToken.Close();
}
}
else {
int err = Marshal.GetLastWin32Error();
if (err == NativeMethods.ERROR_NOT_ENOUGH_MEMORY)
throw new OutOfMemoryException();
Win32Exception win32Exception = new Win32Exception(err);
ExternalException ex = new ExternalException(SR.GetString(SR.ExecCantExec, cmd), win32Exception);
throw ex;
}
return retValue;
}
#if !FEATURE_PAL
[PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)]
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
[SecurityPermission(SecurityAction.Assert, ControlPrincipal = true, UnmanagedCode = true)]
internal static WindowsImpersonationContext RevertImpersonation() {
return WindowsIdentity.Impersonate(new IntPtr(0));
}
#endif // !FEATURE_PAL
#if !FEATURE_PAL
internal static void ReImpersonate(WindowsImpersonationContext impersonation){
impersonation.Undo();
}
#endif // !FEATURE_PAL
}
}

View File

@@ -0,0 +1,28 @@
//------------------------------------------------------------------------------
// <copyright file="GeneratedCodeAttribute.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public sealed class GeneratedCodeAttribute : Attribute {
private readonly string tool;
private readonly string version;
public GeneratedCodeAttribute(string tool, string version) {
this.tool = tool;
this.version = version;
}
public string Tool {
get { return this.tool; }
}
public string Version {
get { return this.version; }
}
}
}

View File

@@ -0,0 +1,127 @@
//------------------------------------------------------------------------------
// <copyright file="GeneratorSupport.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.ComponentModel;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
Flags,
Serializable,
]
public enum GeneratorSupport {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
ArraysOfArrays = 0x1,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
EntryPointMethod = 0x2,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
GotoStatements = 0x4,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
MultidimensionalArrays = 0x8,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
StaticConstructors = 0x10,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
TryCatchStatements = 0x20,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
ReturnTypeAttributes = 0x40,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
DeclareValueTypes = 0x80,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
DeclareEnums = 0x0100,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
DeclareDelegates = 0x0200,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
DeclareInterfaces = 0x0400,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
DeclareEvents = 0x0800,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
AssemblyAttributes = 0x1000,
/// <devdoc>
/// <para>Supports custom metadata attributes declared on parameters for methods and constructors. Allows
/// use of CodeParameterDeclarationExpress.CustomAttributes.</para>
/// </devdoc>
ParameterAttributes = 0x2000,
/// <devdoc>
/// <para>Supports declaring and calling parameters with a FieldDirection of Out or Ref, meaning that
/// the value is a type of reference parameter.</para>
/// </devdoc>
ReferenceParameters = 0x4000,
/// <devdoc>
/// <para>Supports contructors that call other constructors within the same class. Allows use of the
/// CodeConstructor.ChainedConstructorArgs collection.</para>
/// </devdoc>
ChainedConstructorArguments = 0x8000,
/// <devdoc>
/// <para>Supports declaring types that are nested within other types. This allows the insertion of a
/// CodeTypeReference into the Members collection of another CodeTypeReference.</para>
/// </devdoc>
NestedTypes = 0x00010000,
/// <devdoc>
/// <para>Supports declaring methods, properties or events that simultaneously implement more than one interface of
/// a type that have a matching name. This allows insertion of more than one entry into the ImplementationTypes
/// collection or CodeMemberProperty, CodeMemberMethod and CodeMemberEvent.</para>
/// </devdoc>
MultipleInterfaceMembers = 0x00020000,
/// <devdoc>
/// <para>Supports the declaration of public static fields, properties, methods and events. This allows use of
/// MemberAttributes.Static in combination with access values other than MemberAttributes.Private.</para>
/// </devdoc>
PublicStaticMembers = 0x00040000,
/// <devdoc>
/// <para>Supports the generation arbitarily nested expressions. Not all generators may be able to deal with
/// multiple function calls or binary operations in the same expression. Without this, CodeMethodInvokeExpression and
/// CodeBinaryOperatorExpression should only be used (a) as the Right value of a CodeAssignStatement or (b) in a
/// CodeExpressionStatement.</para>
/// </devdoc>
ComplexExpressions = 0x00080000,
/// <devdoc>
/// <para>Supports linking with Win32 resources.</para>
/// </devdoc>
Win32Resources = 0x00100000,
/// <devdoc>
/// <para>Supports linking with CLR resources (both linked and embedded).</para>
/// </devdoc>
Resources = 0x00200000,
/// <devdoc>
/// <para>Supports partial classes.</para>
/// </devdoc>
PartialTypes = 0x00400000,
GenericTypeReference = 0x00800000,
GenericTypeDeclaration = 0x01000000,
DeclareIndexerProperties = 0x02000000,
}
}

View File

@@ -0,0 +1,86 @@
//------------------------------------------------------------------------------
// <copyright file="ICodeCompiler.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// Provides a
/// code compilation
/// interface.
/// </para>
/// </devdoc>
public interface ICodeCompiler {
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from the compile units
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit);
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the contents of
/// fileName.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName);
/// <devdoc>
/// <para>
/// Creates an assembly based on options, with the information from
/// source.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source);
/// <devdoc>
/// <para>
/// Compiles an assembly based on the specified options and
/// information.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits);
/// <devdoc>
/// <para>
/// Compiles
/// an
/// assembly based on the specified options and contents of the specified
/// filenames.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames);
/// <devdoc>
/// <para>
/// Compiles an assembly based on the specified options and information from the specified
/// sources.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources);
}
}

View File

@@ -0,0 +1,108 @@
//------------------------------------------------------------------------------
// <copyright file="ICodeGenerator.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// Provides an
/// interface for code generation.
/// </para>
/// </devdoc>
public interface ICodeGenerator {
/// <devdoc>
/// <para>
/// Gets a value indicating whether
/// the specified value is a valid identifier for this language.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
bool IsValidIdentifier(string value);
/// <devdoc>
/// <para>
/// Throws an exception if value is not a valid identifier.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void ValidateIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string CreateEscapedIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string CreateValidIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string GetTypeOutput(CodeTypeReference type);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
bool Supports(GeneratorSupport supports);
/// <devdoc>
/// <para>
/// Generates code from the specified expression and
/// outputs it to the specified textwriter.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o);
}
}

View File

@@ -0,0 +1,28 @@
//------------------------------------------------------------------------------
// <copyright file="ICodeParser.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System.IO;
/// <devdoc>
/// <para>
/// Provides a code parsing interface.
/// </para>
/// </devdoc>
public interface ICodeParser {
/// <devdoc>
/// <para>
/// Compiles the given text stream into a CodeCompile unit.
/// </para>
/// </devdoc>
CodeCompileUnit Parse(TextReader codeStream);
}
}

View File

@@ -0,0 +1,463 @@
//------------------------------------------------------------------------------
// <copyright file="IndentTextWriter.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Globalization;
/// <devdoc>
/// <para>Provides a text writer that can indent new lines by a tabString token.</para>
/// </devdoc>
public class IndentedTextWriter : TextWriter {
private TextWriter writer;
private int indentLevel;
private bool tabsPending;
private string tabString;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public const string DefaultTabString = " ";
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.IndentedTextWriter'/> using the specified
/// text writer and default tab string.
/// </para>
/// </devdoc>
public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) {
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.Compiler.IndentedTextWriter'/> using the specified
/// text writer and tab string.
/// </para>
/// </devdoc>
public IndentedTextWriter(TextWriter writer, string tabString): base(CultureInfo.InvariantCulture) {
this.writer = writer;
this.tabString = tabString;
indentLevel = 0;
tabsPending = false;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override Encoding Encoding {
get {
return writer.Encoding;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the new line character to use.
/// </para>
/// </devdoc>
public override string NewLine {
get {
return writer.NewLine;
}
set {
writer.NewLine = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the number of spaces to indent.
/// </para>
/// </devdoc>
public int Indent {
get {
return indentLevel;
}
set {
Debug.Assert(value >= 0, "Bogus Indent... probably caused by mismatched Indent++ and Indent--");
if (value < 0) {
value = 0;
}
indentLevel = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the TextWriter to use.
/// </para>
/// </devdoc>
public TextWriter InnerWriter {
get {
return writer;
}
}
internal string TabString {
get { return tabString; }
}
/// <devdoc>
/// <para>
/// Closes the document being written to.
/// </para>
/// </devdoc>
public override void Close() {
writer.Close();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void Flush() {
writer.Flush();
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected virtual void OutputTabs() {
if (tabsPending) {
for (int i=0; i < indentLevel; i++) {
writer.Write(tabString);
}
tabsPending = false;
}
}
/// <devdoc>
/// <para>
/// Writes a string
/// to the text stream.
/// </para>
/// </devdoc>
public override void Write(string s) {
OutputTabs();
writer.Write(s);
}
/// <devdoc>
/// <para>
/// Writes the text representation of a Boolean value to the text stream.
/// </para>
/// </devdoc>
public override void Write(bool value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes a character to the text stream.
/// </para>
/// </devdoc>
public override void Write(char value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes a
/// character array to the text stream.
/// </para>
/// </devdoc>
public override void Write(char[] buffer) {
OutputTabs();
writer.Write(buffer);
}
/// <devdoc>
/// <para>
/// Writes a subarray
/// of characters to the text stream.
/// </para>
/// </devdoc>
public override void Write(char[] buffer, int index, int count) {
OutputTabs();
writer.Write(buffer, index, count);
}
/// <devdoc>
/// <para>
/// Writes the text representation of a Double to the text stream.
/// </para>
/// </devdoc>
public override void Write(double value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes the text representation of
/// a Single to the text
/// stream.
/// </para>
/// </devdoc>
public override void Write(float value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes the text representation of an integer to the text stream.
/// </para>
/// </devdoc>
public override void Write(int value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes the text representation of an 8-byte integer to the text stream.
/// </para>
/// </devdoc>
public override void Write(long value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes the text representation of an object
/// to the text stream.
/// </para>
/// </devdoc>
public override void Write(object value) {
OutputTabs();
writer.Write(value);
}
/// <devdoc>
/// <para>
/// Writes out a formatted string, using the same semantics as specified.
/// </para>
/// </devdoc>
public override void Write(string format, object arg0) {
OutputTabs();
writer.Write(format, arg0);
}
/// <devdoc>
/// <para>
/// Writes out a formatted string,
/// using the same semantics as specified.
/// </para>
/// </devdoc>
public override void Write(string format, object arg0, object arg1) {
OutputTabs();
writer.Write(format, arg0, arg1);
}
/// <devdoc>
/// <para>
/// Writes out a formatted string,
/// using the same semantics as specified.
/// </para>
/// </devdoc>
public override void Write(string format, params object[] arg) {
OutputTabs();
writer.Write(format, arg);
}
/// <devdoc>
/// <para>
/// Writes the specified
/// string to a line without tabs.
/// </para>
/// </devdoc>
public void WriteLineNoTabs(string s) {
writer.WriteLine(s);
}
/// <devdoc>
/// <para>
/// Writes the specified string followed by
/// a line terminator to the text stream.
/// </para>
/// </devdoc>
public override void WriteLine(string s) {
OutputTabs();
writer.WriteLine(s);
tabsPending = true;
}
/// <devdoc>
/// <para>
/// Writes a line terminator.
/// </para>
/// </devdoc>
public override void WriteLine() {
OutputTabs();
writer.WriteLine();
tabsPending = true;
}
/// <devdoc>
/// <para>
/// Writes the text representation of a Boolean followed by a line terminator to
/// the text stream.
/// </para>
/// </devdoc>
public override void WriteLine(bool value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(char value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(char[] buffer) {
OutputTabs();
writer.WriteLine(buffer);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(char[] buffer, int index, int count) {
OutputTabs();
writer.WriteLine(buffer, index, count);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(double value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(float value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(int value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(long value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(object value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(string format, object arg0) {
OutputTabs();
writer.WriteLine(format, arg0);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(string format, object arg0, object arg1) {
OutputTabs();
writer.WriteLine(format, arg0, arg1);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void WriteLine(string format, params object[] arg) {
OutputTabs();
writer.WriteLine(format, arg);
tabsPending = true;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[CLSCompliant(false)]
public override void WriteLine(UInt32 value) {
OutputTabs();
writer.WriteLine(value);
tabsPending = true;
}
internal void InternalOutputTabs() {
for (int i=0; i < indentLevel; i++) {
writer.Write(tabString);
}
}
}
internal class Indentation {
private IndentedTextWriter writer;
private int indent;
private string s;
internal Indentation(IndentedTextWriter writer, int indent) {
this.writer = writer;
this.indent = indent;
s = null;
}
internal string IndentationString {
get {
if ( s == null) {
string tabString = writer.TabString;
StringBuilder sb = new StringBuilder(indent * tabString.Length);
for( int i = 0; i < indent; i++) {
sb.Append(tabString);
}
s = sb.ToString();
}
return s;
}
}
}
}

View File

@@ -0,0 +1,28 @@
//------------------------------------------------------------------------------
// <copyright file="LanguageOptions.cs" company="Microsoft">
//
// <OWNER>[....]</OWNER>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
Flags,
Serializable,
]
public enum LanguageOptions {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
None = 0x0,
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
CaseInsensitive = 0x1,
}
}

Some files were not shown because too many files have changed in this diff Show More