public static bool IsIdentifierValid(this string s) { return(provider.IsValidIdentifier(s) || string.IsNullOrWhiteSpace(s)); }
internal static CodeNamespaceCollection GenerateCodeFromXomlDocument(Activity rootActivity, string filePath, string rootNamespace, SupportedLanguages language, IServiceProvider serviceProvider) { CodeNamespaceCollection codeNamespaces = new CodeNamespaceCollection(); CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language); // generate activity class string activityFullClassName = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; CodeTypeDeclaration activityTypeDeclaration = null; if (codeDomProvider != null && !string.IsNullOrEmpty(activityFullClassName)) { // get class and namespace names string activityNamespaceName, activityClassName; Helpers.GetNamespaceAndClassName(activityFullClassName, out activityNamespaceName, out activityClassName); if (codeDomProvider.IsValidIdentifier(activityClassName)) { DesignerSerializationManager designerSerializationManager = new DesignerSerializationManager(serviceProvider); using (designerSerializationManager.CreateSession()) { ActivityCodeDomSerializationManager codeDomSerializationManager = new ActivityCodeDomSerializationManager(designerSerializationManager); TypeCodeDomSerializer typeCodeDomSerializer = codeDomSerializationManager.GetSerializer(rootActivity.GetType(), typeof(TypeCodeDomSerializer)) as TypeCodeDomSerializer; // get all activities bool generateCode = true; ArrayList allActivities = new ArrayList(); allActivities.Add(rootActivity); if (rootActivity is CompositeActivity) { foreach (Activity activity in Helpers.GetNestedActivities((CompositeActivity)rootActivity)) { if (Helpers.IsActivityLocked(activity)) { continue; } if (codeDomProvider.IsValidIdentifier(codeDomSerializationManager.GetName(activity))) { // WinOE Bug 14561. This is to fix a performance problem. When an activity is added to the activity // tree at the runtime, it's much faster if the ID of the activity is already set. The code that // the CodeDomSerializer generates will add the activity first before it sets the ID for the child // activity. We can change that order by always serializing the children first. Therefore, we // construct a list where we guarantee that the child will be serialized before its parent. allActivities.Insert(0, activity); } else { generateCode = false; break; } } } if (generateCode) { // Work around!! TypeCodeDomSerializer checks that root component has a site or not, otherwise it // does not serialize it look at ComponentTypeCodeDomSerializer.cs DummySite dummySite = new DummySite(); foreach (Activity nestedActivity in allActivities) { ((IComponent)nestedActivity).Site = dummySite; } ((IComponent)rootActivity).Site = dummySite; // create activity partial class activityTypeDeclaration = typeCodeDomSerializer.Serialize(codeDomSerializationManager, rootActivity, allActivities); activityTypeDeclaration.IsPartial = true; // add checksum attribute if (filePath != null && filePath.Length > 0) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] checksumBytes = null; using (StreamReader streamReader = new StreamReader(filePath)) checksumBytes = md5.ComputeHash(streamReader.BaseStream); string checksum = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}", new object[] { checksumBytes[0].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[1].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[2].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[3].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[4].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[5].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[6].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[7].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[8].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[9].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[10].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[11].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[12].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[13].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[14].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[15].ToString("X2", CultureInfo.InvariantCulture) }); CodeAttributeDeclaration xomlSourceAttribute = new CodeAttributeDeclaration(typeof(WorkflowMarkupSourceAttribute).FullName); xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(filePath))); xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(checksum))); activityTypeDeclaration.CustomAttributes.Add(xomlSourceAttribute); } // create a new namespace and add activity class into that CodeNamespace activityCodeNamespace = new CodeNamespace(activityNamespaceName); activityCodeNamespace.Types.Add(activityTypeDeclaration); codeNamespaces.Add(activityCodeNamespace); } } } } // generate code for x:Code if (activityTypeDeclaration != null) { Queue activitiesQueue = new Queue(new object[] { rootActivity }); while (activitiesQueue.Count > 0) { Activity activity = (Activity)activitiesQueue.Dequeue(); if (Helpers.IsActivityLocked(activity)) { continue; } Queue childActivities = new Queue(new object[] { activity }); while (childActivities.Count > 0) { Activity childActivity = (Activity)childActivities.Dequeue(); if (childActivity is CompositeActivity) { foreach (Activity nestedChildActivity in ((CompositeActivity)childActivity).Activities) { childActivities.Enqueue(nestedChildActivity); } } // generate x:Code CodeTypeMemberCollection codeSegments = childActivity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection; if (codeSegments != null) { foreach (CodeSnippetTypeMember codeSegmentMember in codeSegments) { activityTypeDeclaration.Members.Add(codeSegmentMember); } } } } if (language == SupportedLanguages.CSharp) { activityTypeDeclaration.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1)); } //Now make sure we that we also emit line pragma around the constructor CodeConstructor constructor = null; CodeMemberMethod method = null; foreach (CodeTypeMember typeMember in activityTypeDeclaration.Members) { if (constructor == null && typeMember is CodeConstructor) { constructor = typeMember as CodeConstructor; } if (method == null && typeMember is CodeMemberMethod && typeMember.Name.Equals("InitializeComponent", StringComparison.Ordinal)) { method = typeMember as CodeMemberMethod; } if (constructor != null && method != null) { break; } } if (constructor != null) { constructor.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1)); } if (method != null && language == SupportedLanguages.CSharp) { method.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1)); } } // generate mappings List <String> clrNamespaces = rootActivity.GetValue(WorkflowMarkupSerializer.ClrNamespacesProperty) as List <String>; if (clrNamespaces != null) { // foreach namespace add these mappings foreach (CodeNamespace codeNamespace in codeNamespaces) { foreach (string clrNamespace in clrNamespaces) { if (!String.IsNullOrEmpty(clrNamespace)) { CodeNamespaceImport codeNamespaceImport = new CodeNamespaceImport(clrNamespace); codeNamespaceImport.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1)); codeNamespace.Imports.Add(codeNamespaceImport); } } } } // return namespaces return(codeNamespaces); }
private static SortedList <string, ResourceData> VerifyResourceNames( Dictionary <String, ResourceData> resourceList, CodeDomProvider codeProvider, List <string> errors, out Dictionary <string, string> reverseFixupTable) { reverseFixupTable = new Dictionary <string, string>(0, StringComparer.InvariantCultureIgnoreCase); var cleanedResourceList = new SortedList <string, ResourceData>(StringComparer.InvariantCultureIgnoreCase) { Capacity = resourceList.Count }; foreach (KeyValuePair <String, ResourceData> entry in resourceList) { String key = entry.Key; // Disallow a property named ResourceManager or Culture - we add // those. (Any other properties we add also must be listed here) // Also disallow resource values of type Void. if (String.Equals(key, ResMgrPropertyName) || String.Equals(key, CultureInfoPropertyName) || typeof(void) == entry.Value.Type) { errors.Add(key); continue; } // Ignore WinForms design time and hierarchy information. // Skip resources starting with $ or >>, like "$this.Text", // ">>$this.Name" or ">>treeView1.Parent". if ((key.Length > 0 && key[0] == '$') || (key.Length > 1 && key[0] == '>' && key[1] == '>')) { continue; } if (!codeProvider.IsValidIdentifier(key)) { String newKey = VerifyResourceName(key, codeProvider, false); if (newKey == null) { errors.Add(key); continue; } // Now see if we've already mapped another key to the // same name. if (reverseFixupTable.TryGetValue(newKey, out string oldDuplicateKey)) { // We can't handle this key nor the previous one. // Remove the old one. if (!errors.Contains(oldDuplicateKey)) { errors.Add(oldDuplicateKey); } cleanedResourceList.Remove(newKey); errors.Add(key); continue; } reverseFixupTable[newKey] = key; key = newKey; } ResourceData value = entry.Value; if (!cleanedResourceList.ContainsKey(key)) { cleanedResourceList.Add(key, value); } else { // There was a case-insensitive conflict between two keys. // Or possibly one key was fixed up in a way that conflicts // with another key (ie, "A B" and "A_B"). if (reverseFixupTable.TryGetValue(key, out string fixedUp)) { if (!errors.Contains(fixedUp)) { errors.Add(fixedUp); } reverseFixupTable.Remove(key); } errors.Add(entry.Key); cleanedResourceList.Remove(key); } } return(cleanedResourceList); }
static bool NameIsLanguageKeyword(CodeDomProvider codeDomProvider, string[] names) { return(names.Any(name => !codeDomProvider.IsValidIdentifier(name))); }
// Declaration -> BuiltInType Identifier | BuiltInType Identifier ConstantDeclaration | BuiltInType ArrayDeclaration Identifier // Declaration -> DefinedType Identifier | DefinedType ArrayDeclaration Identifier // Declaration -> Header Identifier private void Declaration() { string declaration = ""; // Type MessageToken peeked = Peek(); string type = ""; bool canHaveConstDecl = false; declaration += MsgAutoGenUtilities.TWO_TABS + "public "; if (PeekType(MessageTokenType.BuiltInType)) { type = builtInTypeMapping[MatchByType(MessageTokenType.BuiltInType)]; if (!type.Equals("Time") && !type.Equals("Duration")) { // Time and Duration can't have constant declaration // See <wiki.ros.org/msg> canHaveConstDecl = true; } else { // Need to import Standard imports.Add("Std"); } } else if (PeekType(MessageTokenType.DefinedType)) { type = MatchByType(MessageTokenType.DefinedType); string[] hierarchy = type.Split(new char[] { '/', '\\' }); // Assume type can only be either: // Type // package/Type switch (hierarchy.Length) { case 1: break; case 2: if (hierarchy[0].Equals("") || hierarchy[1].Equals("")) { throw new MessageParserException( "Invalid field type '" + type + "'. + " + "(" + inFilePath + ":" + lineNum + ")"); } string package = MsgAutoGenUtilities.ResolvePackageName(hierarchy[0]); imports.Add(package); type = hierarchy[1]; break; default: throw new MessageParserException( "Invalid field type '" + type + "'. + " + "(" + inFilePath + ":" + lineNum + ")"); } } else { type = MatchByType(MessageTokenType.Header); if (PeekType(MessageTokenType.FixedSizeArray) || PeekType(MessageTokenType.VariableSizeArray)) { Warn( "By convention, there is only one header for each message." + "(" + inFilePath + ":" + lineNum + ")"); } if (PeekType(MessageTokenType.Identifier) && !Peek().content.Equals("header")) { Warn( "By convention, a ros message Header will be named 'header'. '" + Peek().content + "'. (" + inFilePath + ":" + lineNum + ")"); } imports.Add("Std"); } // Array Declaration int arraySize = -1; if (PeekType(MessageTokenType.FixedSizeArray)) { type += "[]"; canHaveConstDecl = false; arraySize = int.Parse(MatchByType(MessageTokenType.FixedSizeArray)); } if (PeekType(MessageTokenType.VariableSizeArray)) { type += "[]"; canHaveConstDecl = false; MatchByType(MessageTokenType.VariableSizeArray); arraySize = 0; } // Identifier string identifier = MatchByType(MessageTokenType.Identifier); // Check for duplicate declaration if (symbolTable.ContainsKey(identifier)) { throw new MessageParserException( "Field '" + identifier + "' at " + inFilePath + ":" + lineNum + " already declared!"); } // Check if identifier is a ROS message built-in type if (builtInTypeMapping.ContainsKey(identifier) && identifier.Equals("time") && identifier.Equals("duration")) { throw new MessageParserException( "Invalid field identifier '" + identifier + "' at " + inFilePath + ":" + lineNum + ". '" + identifier + "' is a ROS message built-in type."); } #if NETFRAMEWORK CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); // Check if identifier is a C# keyword if (!provider.IsValidIdentifier(identifier)) { Warn( "'" + identifier + "' is a C# keyword. We have appended \"_\" at the front to avoid C# compile-time issues." + "(" + inFilePath + ":" + lineNum + ")"); declaration = MsgAutoGenUtilities.TWO_TABS + "[JsonProperty(\"" + identifier + "\")]\n" + declaration; identifier = "_" + identifier; } #else Warn( "'CodeDomProvider class might not exist on your platform. We did not check whether " + identifier + "' is a C# keyword." + "(" + inFilePath + ":" + lineNum + ")"); #endif symbolTable.Add(identifier, type); // Array declaration table if (arraySize > -1) { arraySizes.Add(identifier, arraySize); } // Constant Declaration if (PeekType(MessageTokenType.ConstantDeclaration)) { if (canHaveConstDecl) { declaration += "const " + type + " " + identifier + " = "; declaration += ConstantDeclaration(type); constants.Add(identifier); } else { throw new MessageParserException( "Type " + type + "' at " + inFilePath + ":" + lineNum + " cannot have constant declaration"); } } else { declaration += type + " " + identifier + MsgAutoGenUtilities.PROPERTY_EXTENSION + "\n"; } body += declaration; }
private static CodeCompileUnit InternalCreate(Dictionary <string, ResourceData> resourceList, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable) { Hashtable hashtable; if (baseName == null) { throw new ArgumentNullException("baseName"); } if (codeProvider == null) { throw new ArgumentNullException("codeProvider"); } ArrayList errors = new ArrayList(0); SortedList list2 = VerifyResourceNames(resourceList, codeProvider, errors, out hashtable); string str = baseName; if (!codeProvider.IsValidIdentifier(str)) { string str2 = VerifyResourceName(str, codeProvider); if (str2 != null) { str = str2; } } if (!codeProvider.IsValidIdentifier(str)) { throw new ArgumentException(System.Design.SR.GetString("InvalidIdentifier", new object[] { str })); } if (!string.IsNullOrEmpty(generatedCodeNamespace) && !codeProvider.IsValidIdentifier(generatedCodeNamespace)) { string str3 = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (str3 != null) { generatedCodeNamespace = str3; } } CodeCompileUnit e = new CodeCompileUnit(); e.ReferencedAssemblies.Add("System.dll"); e.UserData.Add("AllowLateBound", false); e.UserData.Add("RequireVariableDeclaration", true); CodeNamespace namespace2 = new CodeNamespace(generatedCodeNamespace); namespace2.Imports.Add(new CodeNamespaceImport("System")); e.Namespaces.Add(namespace2); CodeTypeDeclaration declaration = new CodeTypeDeclaration(str); namespace2.Types.Add(declaration); AddGeneratedCodeAttributeforMember(declaration); TypeAttributes attributes = internalClass ? TypeAttributes.AnsiClass : TypeAttributes.Public; declaration.TypeAttributes = attributes; declaration.Comments.Add(new CodeCommentStatement("<summary>", true)); declaration.Comments.Add(new CodeCommentStatement(System.Design.SR.GetString("ClassDocComment"), true)); declaration.Comments.Add(new CodeCommentStatement("</summary>", true)); CodeTypeReference attributeType = new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(attributeType)); CodeTypeReference reference2 = new CodeTypeReference(typeof(CompilerGeneratedAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; declaration.CustomAttributes.Add(new CodeAttributeDeclaration(reference2)); bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); bool supportsTryCatch = codeProvider.Supports(GeneratorSupport.TryCatchStatements); EmitBasicClassMembers(declaration, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic, supportsTryCatch); foreach (DictionaryEntry entry in list2) { string key = (string)entry.Key; string resourceName = (string)hashtable[key]; if (resourceName == null) { resourceName = key; } if (!DefineResourceFetchingProperty(key, resourceName, (ResourceData)entry.Value, declaration, internalClass, useStatic)) { errors.Add(entry.Key); } } unmatchable = (string[])errors.ToArray(typeof(string)); CodeGenerator.ValidateIdentifiers(e); return(e); }
private DriverInfo <Control> CreateDriverInfo(Control targetControl, string fileName) { var driverInfo = new DriverInfo <Control>(targetControl); var mappedControls = new List <Control>(); var names = new List <string>(); var ancesters = WindowUtilityInTarget.GetAncesters(targetControl); var controlAndDefines = new List <ControlAndDefine>(); //フィールドから検索 foreach (var field in GetFields(targetControl)) { //たまにフィールドに親を持っているのがいるのではじく if (CollectionUtility.HasReference(ancesters, field.Control)) { continue; } //不正なフィールド名のものは取得できない if (!_dom.IsValidIdentifier(field.Name)) { continue; } //すでにマップされているかチェック if (CollectionUtility.HasReference(mappedControls, field.Control)) { continue; } //コントロールドライバ var driver = DriverCreatorUtils.GetDriverTypeFullName(field.Control, DriverCreatorAdapter.TypeFullNameAndControlDriver); if (!string.IsNullOrEmpty(driver)) { mappedControls.Add(field.Control); var typeName = DriverCreatorUtils.GetTypeName(driver); var nameSpace = DriverCreatorUtils.GetTypeNamespace(driver); var name = _customNameGenerator.MakeDriverPropName(field.Control, field.Name, names); var key = $"Core.Dynamic().{field.Name}"; controlAndDefines.Add(new ControlAndDefine(field.Control, $"public {typeName} {name} => new {typeName}({key});")); DriverCreatorAdapter.AddCodeLineSelectInfo(fileName, key, field.Control); if (!driverInfo.Usings.Contains(nameSpace)) { driverInfo.Usings.Add(nameSpace); } } //ユーザーコントロールドライバ else if (field.Control is UserControl) { mappedControls.Add(field.Control); var name = _customNameGenerator.MakeDriverPropName(field.Control, field.Name, names); names.Add(name); var typeName = _driverTypeNameManager.MakeDriverType(field.Control, out var nameSpace); if (!string.IsNullOrEmpty(nameSpace) && (nameSpace != DriverCreatorAdapter.SelectedNamespace) && !driverInfo.Usings.Contains(nameSpace)) { driverInfo.Usings.Add(nameSpace); } var key = $"new WindowControl(Core.Dynamic().{field.Name}"; controlAndDefines.Add(new ControlAndDefine(field.Control, $"public {typeName} {name} => new {typeName}({key}));")); DriverCreatorAdapter.AddCodeLineSelectInfo(fileName, key, field.Control); } } //フィールド上に現れないオブジェクトを検索 CreateDriverInfoFindFromControlTree(-1, targetControl, targetControl, driverInfo, controlAndDefines, mappedControls, names, new int[0], fileName); //Sortのロジックがイマイチわかっていない。念のため try { // タブオーダー順のコントロールリスト取得 var controlList = GetTabOrderChildControls(targetControl); // フィールドをタブオーダーでソート controlAndDefines.Sort((l, r) => controlList.IndexOf(l.Control) - controlList.IndexOf(r.Control)); } catch { } foreach (var e in controlAndDefines) { driverInfo.Members.Add(e.Define); } return(driverInfo); }
private bool IsValidIdentifier(string text) { CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); return(provider.IsValidIdentifier(text)); }
/// <summary> /// Handles CODE GENERATION for items selected in the <see cref="PopupSearchList"/>. /// </summary> /// <param name="selecteditems">What items have been selected in the <see cref="PopupSearchList"/></param> private void GenerateCodeFromPopupSearchListSelection(List <SearchListItem> selecteditems) { if (selecteditems.Count == 0) { return; } //Read code generation template. //TODO: make this path configurable. string template = File.ReadAllText(Path.Combine(Application.dataPath, "MachinationsUP/GeneratorTemplates", "Template.cst")); //Create up a unique class name. string className = "GeneratedSO_" + DateTime.Now.ToString("yyyyMMdd_HHmmss").Replace(" ", ""); template = template.Replace("<<CLASS NAME>>", className); //List of identifiers we already used in the code. On collision, the incoming identifier will be appended a number. List <string> currentlyUsedIdentifiers = new List <string>(); //Used to replace things in the code generation template. string constants = ""; string variables = ""; string diagramMappings = ""; string initFunction = ""; //Now go through all items and generate code that will be inserted in the template. foreach (SearchListItem sli in selecteditems) { DiagramMapping dm = (DiagramMapping)sli.AttachedObject; //All code will be generated based on the selected Diagram Mappings. //Figure out what identifier name we should use for this selected item. //By default, the identifier name to use for generating this item is taken from the label. string identifierName = dm.Label.Replace(" ", ""); //If, however, it is not a valid identifier, the fun starts. if (!_cdp.IsValidIdentifier(identifierName)) { string formingIdentifier = ""; int startPosition = 0; //Get the first LETTER from the label that is a valid identifier. while (!_cdp.IsValidIdentifier(formingIdentifier) && startPosition < identifierName.Length) { //Advance character by charater. When the first valid character is found, it will be taken as the start of the identifier name. formingIdentifier = identifierName.Substring(startPosition++, 1); } //Step back to whatever character was found to be valid. if (startPosition > 0) { startPosition--; } //Now get the following characters for the identifier name, starting from where we left off. int endPosition = startPosition + 1; //Loop until the end. while (endPosition < identifierName.Length) { string candidateIdentifier = identifierName.Substring(startPosition, endPosition++ - startPosition); if (_cdp.IsValidIdentifier(candidateIdentifier)) { formingIdentifier = candidateIdentifier; } else { break; } } if (_cdp.IsValidIdentifier(formingIdentifier)) { identifierName = formingIdentifier; } else { identifierName = "MElementID_" + dm.DiagramElementID + "_" + dm.Type.Replace(" ", ""); } } //Handle situations when this identifier already exists. string originalIdentifierName = identifierName; int nextAvailableName = 1; while (currentlyUsedIdentifiers.Contains(identifierName)) { identifierName = originalIdentifierName + "_" + nextAvailableName++; } //Memorize that this identifier was used. currentlyUsedIdentifiers.Add(identifierName); //Generate code using the above-computed identifier name. //Constants declaration: //private const string M_HEALTH = "Health"; constants += "\tprivate const string M_" + identifierName.ToUpper() + " = " + "\"" + identifierName + " [" + dm.Label + "]\";\r\n"; //Variables delcaration: //public ElementBase Health; variables += "\tpublic ElementBase " + identifierName + ";\r\n"; //Diagram Mappings: //new DiagramMapping //{ // PropertyName = M_HEALTH, // DiagramElementID = 215, // EditorElementBase = Health, //}, if (diagramMappings.Length > 0) { diagramMappings += ",\r\n"; } diagramMappings += "\tnew DiagramMapping\r\n"; diagramMappings += "\t{\r\n"; diagramMappings += "\t\tPropertyName = M_" + identifierName.ToUpper() + ",\r\n"; diagramMappings += "\t\tDiagramElementID = " + dm.DiagramElementID + ",\r\n"; diagramMappings += "\t\tEditorElementBase = " + identifierName + "\r\n"; diagramMappings += "\t}"; //Init Function: //Health = binders[M_HEALTH].CurrentElement; initFunction += "\t" + identifierName + " = " + "binders[M_" + identifierName.ToUpper() + "].CurrentElement;\r\n"; } template = template.Replace("<<CONSTANTS DECLARATION>>", constants); template = template.Replace("<<VARIABLES DECLARATION>>", variables); template = template.Replace("<<DIAGRAM MAPPINGS>>", diagramMappings); template = template.Replace("<<INIT FUNCTION>>", initFunction); //Make sure the directory exists & write file. Directory.CreateDirectory(Path.Combine(Application.dataPath, "MachinationsOut")); //TODO: make this path configurable. File.WriteAllText(Path.Combine(Application.dataPath, "MachinationsUP/GeneratedCode", className + ".cs"), template); //Notify of GREAT SUCCESS. ShowNotification(new GUIContent("Class " + className + " created in your Assets/MachinationsUP/GeneratedCode directory."), 10); }
private DriverInfo <DependencyObject> CreateDriverInfo(DependencyObject targetControl, string fileName) { var driverInfo = new DriverInfo <DependencyObject>(targetControl); var mappedControls = new List <DependencyObject>(); var names = new List <string>(); var ancesters = WPFUtility.GetVisualTreeAncestor(targetControl); var controlAndDefines = new List <ControlAndDefine>(); //フィールドから検索 foreach (var e in GetFields(targetControl)) { //たまに親を持っているのがいるのではじく if (CollectionUtility.HasReference(ancesters, e.Control)) { continue; } //不正なフィールド名のものは取得できない if (!_dom.IsValidIdentifier(e.Name)) { continue; } //すでにマップされているかチェック if (CollectionUtility.HasReference(mappedControls, e.Control)) { continue; } //コントロールドライバ var driver = DriverCreatorUtils.GetDriverTypeFullName(e.Control, DriverCreatorAdapter.TypeFullNameAndControlDriver, DriverCreatorAdapter.TypeFullNameAndUserControlDriver); if (!string.IsNullOrEmpty(driver)) { mappedControls.Add(e.Control); var name = _customNameGenerator.MakeDriverPropName(e.Control, e.Name, names); var typeName = DriverCreatorUtils.GetTypeName(driver); var nameSpace = DriverCreatorUtils.GetTypeNamespace(driver); var key = $"Core.Dynamic().{e.Name}"; controlAndDefines.Add(new ControlAndDefine(e.Control, name, $"public {typeName} {name} => {key};")); DriverCreatorAdapter.AddCodeLineSelectInfo(fileName, key, e.Control); if (!driverInfo.Usings.Contains(nameSpace)) { driverInfo.Usings.Add(nameSpace); } } //ユーザーコントロールドライバ else if (((e.Control is UserControl) && (e.Control.GetType() != typeof(UserControl))) || ((e.Control is Page) && (e.Control.GetType() != typeof(Page)))) { mappedControls.Add(e.Control); var name = _customNameGenerator.MakeDriverPropName(e.Control, e.Name, names); var typeName = _driverTypeNameManager.MakeDriverType(e.Control, out var nameSpace); var key = $"Core.Dynamic().{e.Name}"; controlAndDefines.Add(new ControlAndDefine(e.Control, name, $"public {typeName} {name} => {key};")); if (!string.IsNullOrEmpty(nameSpace) && (nameSpace != DriverCreatorAdapter.SelectedNamespace) && !driverInfo.Usings.Contains(nameSpace)) { driverInfo.Usings.Add(nameSpace); } DriverCreatorAdapter.AddCodeLineSelectInfo(fileName, key, e.Control); } } //フィールド上に現れないオブジェクトを検索 CreateDriverInfoFindFromControlTree(targetControl, driverInfo, controlAndDefines, mappedControls, names, fileName); //Sortのロジックがイマイチわかっていない。念のため try { // LogicalTree順のコントロールリスト取得 var controlList = WPFUtility.GetLogicalTreeDescendants(targetControl, true, true, 0); // フィールドをタブオーダーでソート controlAndDefines.Sort((l, r) => controlList.IndexOf(l.Control) - controlList.IndexOf(r.Control)); } catch { } //コンテキストメニュー特別処理 foreach (var e in controlAndDefines) { driverInfo.Members.Add(e.Define); var frameworkElement = e.Control as FrameworkElement; if (frameworkElement != null && frameworkElement.ContextMenu != null) { var core = (frameworkElement is Window || frameworkElement is UserControl || frameworkElement is Page) ? ".Core" : string.Empty; var code = $"public WPFContextMenu {e.Name}ContextMenu => new WPFContextMenu{{Target = {e.Name}{core}.AppVar}};"; driverInfo.Members.Add(code); } } return(driverInfo); }
// CodeDOM generation void DomFromResource(string resfile, CodeCompileUnit unit, Dictionary <string, bool> assemblies, CodeDomProvider provider) { if (String.IsNullOrEmpty(resfile)) { return; } string fname, nsname, classname; fname = Path.GetFileNameWithoutExtension(resfile); nsname = Path.GetFileNameWithoutExtension(fname); classname = Path.GetExtension(fname); if (classname == null || classname.Length == 0) { classname = nsname; nsname = "Resources"; } else { if (!nsname.StartsWith("Resources", StringComparison.InvariantCulture)) { nsname = String.Concat("Resources.", nsname); } classname = classname.Substring(1); } if (!String.IsNullOrEmpty(classname)) { classname = classname.Replace('.', '_'); } if (!String.IsNullOrEmpty(nsname)) { nsname = nsname.Replace('.', '_'); } if (!provider.IsValidIdentifier(nsname) || !provider.IsValidIdentifier(classname)) { throw new ApplicationException("Invalid resource file name."); } ResourceReader res; try { res = new ResourceReader(resfile); } catch (ArgumentException) { // invalid stream, probably empty - ignore silently and abort return; } CodeNamespace ns = new CodeNamespace(nsname); CodeTypeDeclaration cls = new CodeTypeDeclaration(classname); cls.IsClass = true; cls.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; CodeMemberField cmf = new CodeMemberField(typeof(CultureInfo), "_culture"); cmf.InitExpression = new CodePrimitiveExpression(null); cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static; cls.Members.Add(cmf); cmf = new CodeMemberField(typeof(ResourceManager), "_resourceManager"); cmf.InitExpression = new CodePrimitiveExpression(null); cmf.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static; cls.Members.Add(cmf); // Property: ResourceManager CodeMemberProperty cmp = new CodeMemberProperty(); cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static; cmp.Name = "ResourceManager"; cmp.HasGet = true; cmp.Type = new CodeTypeReference(typeof(ResourceManager)); CodePropertyResourceManagerGet(cmp.GetStatements, resfile, classname); cls.Members.Add(cmp); // Property: Culture cmp = new CodeMemberProperty(); cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static; cmp.Name = "Culture"; cmp.HasGet = true; cmp.HasSet = true; cmp.Type = new CodeTypeReference(typeof(CultureInfo)); CodePropertyGenericGet(cmp.GetStatements, "_culture", classname); CodePropertyGenericSet(cmp.SetStatements, "_culture", classname); cls.Members.Add(cmp); // Add the resource properties Dictionary <string, bool> imports = new Dictionary <string, bool> (); try { foreach (DictionaryEntry de in res) { Type type = de.Value.GetType(); if (!imports.ContainsKey(type.Namespace)) { imports [type.Namespace] = true; } string asname = new AssemblyName(type.Assembly.FullName).Name; if (!assemblies.ContainsKey(asname)) { assemblies [asname] = true; } cmp = new CodeMemberProperty(); cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static; cmp.Name = SanitizeResourceName(provider, (string)de.Key); cmp.HasGet = true; CodePropertyResourceGet(cmp.GetStatements, (string)de.Key, type, classname); cmp.Type = new CodeTypeReference(type); cls.Members.Add(cmp); } } catch (Exception ex) { throw new ApplicationException("Failed to compile global resources.", ex); } foreach (KeyValuePair <string, bool> de in imports) { ns.Imports.Add(new CodeNamespaceImport(de.Key)); } ns.Types.Add(cls); unit.Namespaces.Add(ns); }
/** * Determine if the given character is part of a proposition symbol. * * @param ch * a character. * @return true if the given character is part of a proposition symbols * representation, false otherwise. */ public static bool isPropositionSymbolIdentifierPart(char ch) { CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); return(provider.IsValidIdentifier("a" + ch)); }
/** * Determine if the given symbol is a legal proposition symbol. * * @param symbol * a symbol to be tested. * @return true if the given symbol is a legal proposition symbol, false * otherwise. */ public static bool isPropositionSymbol(String symbol) { CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); return(provider.IsValidIdentifier(symbol)); }
/// <summary> /// Determines whether [is class name valid] [the specified class name]. /// </summary> /// <param name="className">Name of the class.</param> /// <returns> /// <c>true</c> if [is class name valid] [the specified class name]; otherwise, <c>false</c>. /// </returns> public bool IsClassNameValid(string className) { return(CodeDomProvider.IsValidIdentifier(className)); }
public static bool IsValidVariable(string VariableName) { return(provider.IsValidIdentifier(VariableName)); }
void InitializeList() { var colors = new Color[] { Color.red, Color.blue, Color.white, Color.yellow, Color.green }; _objectsInfo = new ReorderableList(serializedObject, serializedObject.FindProperty("ObjectsList"), false, true, true, true) { drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width / 2 - 15, EditorGUIUtility.singleLineHeight), "Name"); EditorGUI.LabelField( new Rect(rect.x + rect.width / 2, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), "Object"); } }; _objectsInfo.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { var element = _objectsInfo.serializedProperty.GetArrayElementAtIndex(index); rect.y += 2; var prevName = element.FindPropertyRelative("Name").stringValue; var prevObject = element.FindPropertyRelative("Object").objectReferenceValue; EditorGUI.PropertyField( new Rect(rect.x, rect.y, rect.width / 2 - 15, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Name"), GUIContent.none); EditorGUI.PropertyField( new Rect(rect.x + rect.width / 2, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("Object"), GUIContent.none); if (prevName != element.FindPropertyRelative("Name").stringValue) { CheckName(index, prevName); } if (prevObject != element.FindPropertyRelative("Object").objectReferenceValue) { CheckObject(index); } if (element.FindPropertyRelative("Object").objectReferenceValue != null && string.IsNullOrEmpty(element.FindPropertyRelative("Name").stringValue)) { element.FindPropertyRelative("Name").stringValue = element.FindPropertyRelative("Object").objectReferenceValue.name; } }; if (_objectsInfo.count > 0) { _objectsInfo.drawElementBackgroundCallback = (rect, index, active, focused) => { var element = _objectsInfo.serializedProperty.GetArrayElementAtIndex(index); var prevName = element.FindPropertyRelative("Name").stringValue; var nameColor = string.IsNullOrEmpty(prevName) ? colors[0] : (_provider.IsValidIdentifier(prevName) ? colors[2] : colors[3]); var objectColor = element.FindPropertyRelative("Object").objectReferenceValue == null ? colors[0] : colors[2]; if (nameColor == colors[2] && objectColor == colors[2]) { nameColor = objectColor = colors[4]; } if (index == _selectedObject) { nameColor = objectColor = colors[1]; } SetHightLightBackgroundImage(nameColor, objectColor); EditorGUI.DrawTextureTransparent(rect, backgroundImage, ScaleMode.ScaleAndCrop); }; } _objectsInfo.onAddCallback = (ReorderableList l) => { var index = l.serializedProperty.arraySize; l.serializedProperty.arraySize++; l.index = index; var element = l.serializedProperty.GetArrayElementAtIndex(index); element.FindPropertyRelative("Name").stringValue = ""; element.FindPropertyRelative("Object").objectReferenceValue = null; }; _objectsInfo.onSelectCallback = (ReorderableList l) => { _selectedObject = l.index; }; }
public static bool IsValidDefineName(this string defineName) { return(Provider.IsValidIdentifier(defineName)); }
public static bool IsNameObfuscated(this string name) { return(!CodeDomProvider.IsValidIdentifier(name) && IsCompilerGenerated(name) || !CodeDomProvider.IsValidIdentifier(name) && name.StartsWith("#=")); }
private static SortedList VerifyResourceNames(Dictionary <string, ResourceData> resourceList, CodeDomProvider codeProvider, ArrayList errors, out Hashtable reverseFixupTable) { reverseFixupTable = new Hashtable(0, StringComparer.InvariantCultureIgnoreCase); SortedList list = new SortedList(StringComparer.InvariantCultureIgnoreCase, resourceList.Count); foreach (KeyValuePair <string, ResourceData> pair in resourceList) { string key = pair.Key; if ((string.Equals(key, "ResourceManager") || string.Equals(key, "Culture")) || (typeof(void) == pair.Value.Type)) { errors.Add(key); } else { if (((key.Length <= 0) || (key[0] != '$')) && (((key.Length <= 1) || (key[0] != '>')) || (key[1] != '>'))) { if (!codeProvider.IsValidIdentifier(key)) { string str2 = VerifyResourceName(key, codeProvider, false); if (str2 == null) { errors.Add(key); goto Label_0185; } string item = (string)reverseFixupTable[str2]; if (item != null) { if (!errors.Contains(item)) { errors.Add(item); } if (list.Contains(str2)) { list.Remove(str2); } errors.Add(key); goto Label_0185; } reverseFixupTable[str2] = key; key = str2; } ResourceData data = pair.Value; if (!list.Contains(key)) { list.Add(key, data); } else { string str4 = (string)reverseFixupTable[key]; if (str4 != null) { if (!errors.Contains(str4)) { errors.Add(str4); } reverseFixupTable.Remove(key); } errors.Add(pair.Key); list.Remove(key); } } Label_0185 :; } } return(list); }
/** * Determina si el símbolo dado es un símbolo de proposición legal. * * @param symbol * un símbolo para comprobarlo. * @return cierto si el símbolo dado es un símbolo de proposición legal, falso en caso contrario. */ public static bool IsPropositionSymbol(string symbol) { CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); // En Java era SourceVersion.isIdentifier(symbol); return(provider.IsValidIdentifier(symbol)); }
public static bool IsSafeName(string name) { return(_provider.IsValidIdentifier(name)); }
public IList <ResourceMapping> Map(CodeTypeDeclaration @class, IList <IResource> resourceSet) { var members = new HashSet <string> ( ); foreach (CodeTypeMember member in @class.Members) { members.Add(member.Name); } var map = new SortedList <string, ResourceMapping> (resourceSet.Count, StringComparer.InvariantCultureIgnoreCase); foreach (var resource in resourceSet) { var name = resource.Name; var property = name; if (members.Contains(name)) { AddError(resource, Format(PropertyAlreadyExists, name)); continue; } if (resource.Type == TypeNames.Void) { AddError(resource, Format(InvalidPropertyType, resource.Type, name)); continue; } var isWinFormsLocalizableResource = name.Length > 0 && name [0] == '$' || name.Length > 1 && name [0] == '>' && name [1] == '>'; if (isWinFormsLocalizableResource) { AddWarning(resource, Format(SkippingWinFormsResource, name)); continue; } var isBaseName = ResourceNamingStrategy == null || ResourceNamingStrategy.ParseArguments(PluralRules.Invariant, name, out _) == name; if (!isBaseName) { continue; } if (!CodeDomProvider.IsValidIdentifier(property)) { property = CodeDomProvider.ValidateIdentifier(property); if (property == null) { AddError(resource, Format(CannotCreateResourceProperty, name)); continue; } } if (map.TryGetValue(property, out var duplicate)) { AddError(duplicate.Resource, Format(CannotCreateResourceProperty, duplicate.Resource.Name)); AddError(resource, Format(CannotCreateResourceProperty, name)); map.Remove(property); continue; } map.Add(property, new ResourceMapping(resource) { Property = property }); members.Add(property); } foreach (var mapping in map.Values) { mapping.NumberOfArguments = GetNumberOfArguments(mapping.Resource); if (mapping.NumberOfArguments <= 0) { continue; } var methodName = mapping.Property + FormatMethodSuffix; var isUnique = !members.Contains(methodName); if (isUnique && CodeDomProvider.IsValidIdentifier(methodName)) { mapping.FormatMethod = methodName; members.Add(methodName); } else { AddError(mapping.Resource, Format(CannotCreateFormatMethod, methodName, mapping.Resource.Name)); } } return(map.Values.ToList( )); }
private void dgvVariablesArguments_CellEndEdit(object sender, DataGridViewCellEventArgs e) { try { DataGridView dgv = (DataGridView)sender; var nameCell = dgv.Rows[e.RowIndex].Cells[0]; var typeCell = dgv.Rows[e.RowIndex].Cells[1]; var valueCell = dgv.Rows[e.RowIndex].Cells[2]; //variable/argument name column if (e.ColumnIndex == 0) { var cellValue = nameCell.Value; CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); //deletes an empty row if it's created without assigning values if ((cellValue == null && _preEditVarArgName != null) || (cellValue != null && string.IsNullOrEmpty(cellValue.ToString().Trim())) || (cellValue != null && !provider.IsValidIdentifier(cellValue.ToString()))) { dgv.Rows.RemoveAt(e.RowIndex); return; } //removes an empty uncommitted row else if (nameCell.Value == null) { return; } //trims any space characters before reassigning the value to the cell string variableName = nameCell.Value.ToString().Trim(); nameCell.Value = variableName; //prevents user from creating a new variable/argument with an already used name if (_existingVarArgSearchList.Contains(variableName) && variableName != _preEditVarArgName) { dgv.Rows.RemoveAt(e.RowIndex); return; } //if the variable/argument name is valid, set value cell's readonly as false else { foreach (DataGridViewCell cell in dgv.Rows[e.RowIndex].Cells) { cell.ReadOnly = false; } nameCell.Value = variableName.Trim(); } } else if (e.ColumnIndex == 2) { EvaluateVariableArgumentValue(nameCell, typeCell, valueCell); } //marks the script as unsaved with changes if (uiScriptTabControl.SelectedTab != null && !uiScriptTabControl.SelectedTab.Text.Contains(" *")) { uiScriptTabControl.SelectedTab.Text += " *"; } } catch (Exception ex) { //datagridview event failure Console.WriteLine(ex); } }
/// <summary> /// token inside an eval expression /// </summary> protected internal virtual Token NextEval() { char c1 = input[position]; char c2 = position < input.Length - 1 ? input[position + 1] : (char)0; switch (c1) { case '*': return(@fixed(Symbol.MUL)); case '/': return(@fixed(Symbol.DIV)); case '%': return(@fixed(Symbol.MOD)); case '+': return(@fixed(Symbol.PLUS)); case '-': return(@fixed(Symbol.MINUS)); case '?': return(@fixed(Symbol.QUESTION)); case ':': return(@fixed(Symbol.COLON)); case '[': return(@fixed(Symbol.LBRACK)); case ']': return(@fixed(Symbol.RBRACK)); case '(': return(@fixed(Symbol.LPAREN)); case ')': return(@fixed(Symbol.RPAREN)); case ',': return(@fixed(Symbol.COMMA)); case '.': if (!IsDigit(c2)) { return(@fixed(Symbol.DOT)); } break; case '=': if (c2 == '=') { return(@fixed(Symbol.EQ)); } break; case '&': if (c2 == '&') { return(@fixed(Symbol.AND)); } break; case '|': if (c2 == '|') { return(@fixed(Symbol.OR)); } break; case '!': if (c2 == '=') { return(@fixed(Symbol.NE)); } return(@fixed(Symbol.NOT)); case '<': if (c2 == '=') { return(@fixed(Symbol.LE)); } return(@fixed(Symbol.LT)); case '>': if (c2 == '=') { return(@fixed(Symbol.GE)); } return(@fixed(Symbol.GT)); case '"': case '\'': return(NextString()); } if (IsDigit(c1) || c1 == '.') { return(NextNumber()); } if (_provider.IsValidIdentifier(c1.ToString())) { int i = position + 1; int l = input.Length; //while (i < l && _provider.IsValidIdentifier(input[i].ToString())) while (i < l && IsValidIdentifierPart(input[i])) { i++; } string name = input.Substring(position, i - position); Token keyword = Keyword(name); return(keyword == null?NewToken(Symbol.IDENTIFIER, name, i - position) : keyword); } throw new ScanException(position, "invalid character '" + c1 + "'", "expression token"); }
private static bool IsValidClassName(string name) => _csharpCodeDomProvider.IsValidIdentifier(name);
internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier) { if (context == null) { throw new ArgumentNullException("context"); } ValidationError error = null; if ((identifier == null) || (identifier.Length == 0)) { error = new ValidationError(SR.GetString("Error_PropertyNotSet", new object[] { propName }), 0x116); } else { System.Workflow.Activities.Common.SupportedLanguages supportedLanguage = System.Workflow.Activities.Common.CompilerHelpers.GetSupportedLanguage(context); CodeDomProvider codeDomProvider = System.Workflow.Activities.Common.CompilerHelpers.GetCodeDomProvider(supportedLanguage); if ((((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.CSharp) && identifier.StartsWith("@", StringComparison.Ordinal)) || (((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.VB) && identifier.StartsWith("[", StringComparison.Ordinal)) && identifier.EndsWith("]", StringComparison.Ordinal))) || !codeDomProvider.IsValidIdentifier(codeDomProvider.CreateEscapedIdentifier(identifier))) { error = new ValidationError(SR.GetString("Error_InvalidIdentifier", new object[] { propName, SR.GetString("Error_InvalidLanguageIdentifier", new object[] { identifier }) }), 0x119); } } if (error != null) { error.PropertyName = propName; } return(error); }
private static CodeCompileUnit InternalCreate(Dictionary <String, ResourceData> resourceList, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable) { if (baseName == null) { throw new ArgumentNullException(nameof(baseName)); } if (codeProvider == null) { throw new ArgumentNullException(nameof(codeProvider)); } // Keep a list of errors describing known strings that couldn't be // fixed up (like "4"), as well as listing all duplicate resources that // were fixed up to the same name (like "A B" and "A-B" both going to // "A_B"). var errors = new List <string>(); // Verify the resource names are valid property names, and they don't // conflict. This includes checking for language-specific keywords, // translating spaces to underscores, etc. SortedList <string, ResourceData> cleanedResourceList = VerifyResourceNames(resourceList, codeProvider, errors, out Dictionary <string, string> reverseFixupTable); // Verify the class name is legal. String className = baseName; // Attempt to fix up class name, and throw an exception if it fails. if (!codeProvider.IsValidIdentifier(className)) { String fixedClassName = VerifyResourceName(className, codeProvider); if (fixedClassName != null) { className = fixedClassName; } } if (!codeProvider.IsValidIdentifier(className)) { throw new ArgumentException(SR.GetString(SR.InvalidIdentifier, className)); } // If we have a namespace, verify the namespace is legal, // attempting to fix it up if needed. if (!String.IsNullOrEmpty(generatedCodeNamespace)) { if (!codeProvider.IsValidIdentifier(generatedCodeNamespace)) { String fixedNamespace = VerifyResourceName(generatedCodeNamespace, codeProvider, true); if (fixedNamespace != null) { generatedCodeNamespace = fixedNamespace; } } // Note we cannot really ensure that the generated code namespace // is a valid identifier, as namespaces can have '.' and '::', but // identifiers cannot. } var ccu = new CodeCompileUnit(); ccu.ReferencedAssemblies.Add("System.dll"); ccu.UserData.Add("AllowLateBound", false); ccu.UserData.Add("RequireVariableDeclaration", true); var ns = new CodeNamespace(generatedCodeNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ccu.Namespaces.Add(ns); // Generate class var srClass = new CodeTypeDeclaration(className); ns.Types.Add(srClass); AddGeneratedCodeAttributeforMember(srClass); TypeAttributes ta = internalClass ? TypeAttributes.NotPublic : TypeAttributes.Public; // ta |= TypeAttributes.Sealed; srClass.TypeAttributes = ta; srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); srClass.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ClassDocComment), true)); var comment = new CodeCommentStatement(SR.GetString(SR.ClassComments1), true); srClass.Comments.Add(comment); comment = new CodeCommentStatement(SR.GetString(SR.ClassComments3), true); srClass.Comments.Add(comment); srClass.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true)); var debuggerAttrib = new CodeTypeReference(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(debuggerAttrib)); var compilerGenedAttrib = new CodeTypeReference(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)) { Options = CodeTypeReferenceOptions.GlobalReference }; srClass.CustomAttributes.Add(new CodeAttributeDeclaration(compilerGenedAttrib)); // Figure out some basic restrictions to the code generation bool useStatic = internalClass || codeProvider.Supports(GeneratorSupport.PublicStaticMembers); EmitBasicClassMembers(srClass, generatedCodeNamespace, baseName, resourcesNamespace, internalClass, useStatic); // Now for each resource, add a property foreach (KeyValuePair <string, ResourceData> entry in cleanedResourceList) { String propertyName = entry.Key; // The resourceName will be the original value, before fixups, if any. if (!reverseFixupTable.TryGetValue(propertyName, out string resourceName)) { resourceName = propertyName; } bool r = DefineResourceFetchingProperty(propertyName, resourceName, entry.Value, srClass, internalClass, useStatic); if (!r) { errors.Add(propertyName); } } unmatchable = errors.ToArray(); // Validate the generated class now CodeGenerator.ValidateIdentifiers(ccu); return(ccu); }
internal static void ValidateIdentifier(IServiceProvider serviceProvider, string identifier) { if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } System.Workflow.Activities.Common.SupportedLanguages supportedLanguage = System.Workflow.Activities.Common.CompilerHelpers.GetSupportedLanguage(serviceProvider); CodeDomProvider codeDomProvider = System.Workflow.Activities.Common.CompilerHelpers.GetCodeDomProvider(supportedLanguage); if ((((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.CSharp) && identifier.StartsWith("@", StringComparison.Ordinal)) || (((supportedLanguage == System.Workflow.Activities.Common.SupportedLanguages.VB) && identifier.StartsWith("[", StringComparison.Ordinal)) && identifier.EndsWith("]", StringComparison.Ordinal))) || !codeDomProvider.IsValidIdentifier(identifier)) { throw new Exception(SR.GetString("Error_InvalidLanguageIdentifier", new object[] { identifier })); } }
/// <summary> /// Check whether a given identifier is a valid C# identifier /// </summary> /// <param name="identifier">The string to validate</param> /// <returns>Whether or not the input is a valid C# identifier</returns> public static bool IsValidName(string identifier) { return(_provider.IsValidIdentifier(identifier)); }
//Generate a list of types that corresponds Sharpmake projects. One project is created for each file matching the search pattern (.cpp, .cs, etc). // For example, this allows each cpp file to have its own main() function. // To do this we create a dynamic assembly and generate custom types at runtime. These types are children of the passed in types, // such as CGFPuzzleProject. This is needed as you cannot add multiple instances of the same project type in a Sharpmake solution, // which makes sense to resolve project dependencies. // Projects can be placed in sub-folders which will be used to create filters within the project. // rootPath: Expected to point to the path where all project folders are. Expected structure: // rootPath/ProjectA/source/ProjectA.cpp // rootPath/ProjectB/source/ProjectB.cpp // rootPath/FilterA/ProjectC/source/ProjectC.cpp // rootPath/FilterB/FilterC/ProjectD/source/ProjectD.cpp // ... // projectGenerationParam: The list of project types to generate with their search pattern // CGFPuzzleProject - *.cpp // CGFPuzzleCSharpProject - *.cs // Note: This assumes a constructor of type ProjectType(string projectName, string folderName, string filterName) public List <Type>[] GenerateCodinGamePuzzleProjects(string rootPath, CGFPuzzleProjectGenerationParam[] projectGenerationParam) { //Create a dynamic assembly to which will host a child type of the types passed in projectGenerationParam for each file found matching the provided search pattern // Example, one CGFPuzzleProject for each cpp AssemblyName assemblyName = new AssemblyName("CGFGeneratedPuzzlesProjects"); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); List <Type>[] generatedTypes = new List <Type> [projectGenerationParam.Length]; for (int i = 0; i < generatedTypes.Length; ++i) { generatedTypes[i] = new List <Type>(); } //Get path to search for CodinGame puzzle files from string codingamePuzzlesPath = rootPath + @"\" + CodinGameRootPath + @"\" + CGFPuzzleProject.RootFolderName; { Resolver resolver = new Resolver(); resolver.SetParameter("project", this); codingamePuzzlesPath = resolver.Resolve(codingamePuzzlesPath); } string resolvedCodinGamePuzzlesPath = Util.GetCapitalizedPath(codingamePuzzlesPath); DirectoryInfo codingamePuzzlesDirectoryInfo = new DirectoryInfo(resolvedCodinGamePuzzlesPath); string resolvedCodinGamePuzzlesDirectoryPath = Util.GetCapitalizedPath(codingamePuzzlesDirectoryInfo.FullName); //Create a csharpProvider to validate generated project type names CodeDomProvider csharpProvider = CodeDomProvider.CreateProvider("C#"); //Create the attribute builder that will add the [Generate] attribute to the project CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(typeof(Sharpmake.Generate).GetConstructor(Type.EmptyTypes), new object[] { }); for (int i = 0; i < projectGenerationParam.Length; ++i) { CGFPuzzleProjectGenerationParam generationParam = projectGenerationParam[i]; // Query files in path puzzle directory string[] filePathList = Util.DirectoryGetFiles(resolvedCodinGamePuzzlesDirectoryPath, generationParam.FileSearchPattern, SearchOption.AllDirectories); List <string> relativeFilePathList = Util.PathGetRelative(resolvedCodinGamePuzzlesDirectoryPath, new Strings(filePathList)); //Get ProjectType(string projectName, string folderName, string filterName) constructor ConstructorInfo codingamePuzzleProjectConstructor = generationParam.ProjectType.GetConstructor(new Type[] { typeof(string), typeof(string), typeof(string) }); //Generate project types foreach (string relativeFilePath in relativeFilePathList) { string fileName; string pathName; Util.PathSplitFileNameFromPath(relativeFilePath, out fileName, out pathName); fileName = Path.GetFileNameWithoutExtension(fileName); //Remove /source from pathName if (pathName.EndsWith(Path.DirectorySeparatorChar + "source") || pathName.EndsWith(Path.AltDirectorySeparatorChar + "source")) { pathName = Path.GetDirectoryName(pathName); } string filterName = Path.GetDirectoryName(pathName); string projectName = Path.GetFileName(pathName); //Use GetFileName to get the last directory name... string projectTypeName = projectName + fileName; //Note: This means that conflicts can occur if the same project folder/filename combination in different sub-folders exists if (!csharpProvider.IsValidIdentifier(projectTypeName)) { throw new Error("Project name ({0}) generated from ({1}) does not comply with C# identifer rules. Update your path/filename to remove illegal characters in order to create a valid type name.", projectTypeName, relativeFilePath); } //Generate a type of the following format: //[Generate] //class GeneratedProjectType : ProjectType //{ // GeneratedProjectType() : ProjectType("fileName", "pathName", "filterName") { } //} TypeBuilder typeBuilder = moduleBuilder.DefineType(projectTypeName, TypeAttributes.Public | TypeAttributes.Class, generationParam.ProjectType); typeBuilder.SetCustomAttribute(customAttributeBuilder); //Generate constructor + the constructor code ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, Type.EmptyTypes); ILGenerator constructorIL = constructorBuilder.GetILGenerator(); // Generate constructor code constructorIL.Emit(OpCodes.Ldarg_0); //push "this" onto stack. constructorIL.Emit(OpCodes.Ldstr, projectName); //push the project name onto the stack constructorIL.Emit(OpCodes.Ldstr, pathName); //push the folder name onto the stack constructorIL.Emit(OpCodes.Ldstr, filterName); //push the filterName name onto the stack constructorIL.Emit(OpCodes.Call, codingamePuzzleProjectConstructor); //call ProjectType(string projectName, string folderName, string filterName) constructor constructorIL.Emit(OpCodes.Ret); //return Type generatedProjectType = typeBuilder.CreateType(); generatedTypes[i].Add(generatedProjectType); } } return(generatedTypes); }