public void Test() { ParsedClass parsedClass = new ParsedClass(TestStringClassOnly, false); if (parsedClass.ParsedMethods.Count < 2) { throw new Exception("ParsedMethod count is too low"); } ParsedFile parsedFile = new ParsedFile(); parsedFile.SetFromContents(TestString, false, false); if (parsedFile.Namespaces.Count == 0) { throw new Exception("ParsedFile namespace is 0 when it shouldn't be"); } if (parsedFile.Namespaces[0].Classes.Count == 0) { throw new Exception("ParsedNamespace class count is 0 when it shouldn't be"); } if (parsedFile.Namespaces[0].Classes[0].ParsedMethods.Count < 2) { throw new Exception("ParsedMethod count is too low"); } }
public void PrintToFile(ParsedClass converted, string searchDir, string absPathToFile, string storeResultDir) { var outDir = $"{storeResultDir}\\{ProjName}\\"; switch (converted.ObjectType) { case ObjectType.Class: case ObjectType.Enum: { outDir += "Models\\"; break; } case ObjectType.Api: { outDir += "Apis\\"; break; } } if (!Directory.Exists(outDir)) { Directory.CreateDirectory(outDir); } File.WriteAllText($"{outDir}{converted.Name}.cs", PrintParsedClass(converted, absPathToFile, searchDir), Encoding.UTF8); foreach (var itm in UnknownTypes) { if (string.IsNullOrEmpty(itm.SearchDir)) { itm.SearchDir = searchDir; } } }
public string PrintParsedClass(ParsedClass parsedClass, string absPathToFile, string searchDir) { var sb = new StringBuilder(); PrinNamespace(sb, parsedClass); AddClassName(sb, parsedClass, absPathToFile, 4); string templateName = null; if (parsedClass.IsTemplate) { templateName = _cashParser.Unpack(parsedClass.Template, 1); } var doc = string.Empty; if (parsedClass.ObjectType == ObjectType.Api && !string.IsNullOrEmpty(searchDir)) { doc = File.ReadAllText(searchDir + absPathToFile); } foreach (var t in parsedClass.Fields) { if (parsedClass.ObjectType == ObjectType.Api && !string.IsNullOrEmpty(doc) && !doc.Contains($"({t.CppName})")) { continue; } PrintParsedElements(sb, parsedClass, t, 8, templateName); } CloseTag(sb, 4); CloseTag(sb, 0); return(sb.ToString()); }
public static bool HasMatchingBrackets(string text) { string contentsWithoutComments = ParsedClass.RemoveComments(text); int numberOfOpening = contentsWithoutComments.CountOf('{'); int numberOfClosing = contentsWithoutComments.CountOf('}'); return(numberOfOpening == numberOfClosing); }
/// <summary> /// Determines if a code file is valid based off of the number of opening and closing /// brackets it has. This method counts { and }, but doesn't include comments or contsts like /// "{0}". /// </summary> /// <param name="fileName">The file name to open - this should be the .cs file for C# files.</param> /// <returns>Whether the file is valid.</returns> public static bool DetermineIfCodeFileIsValid(string fileName) { string contents = FileManager.FromFileText(fileName); contents = ParsedClass.RemoveComments(contents); int numberOfOpenBrackets = ParsedClass.NumberOfValid('{', contents); int numberOfClosedBrackets = ParsedClass.NumberOfValid('}', contents); return(numberOfOpenBrackets == numberOfClosedBrackets); }
public static void AddStubsForCustomEvents(IElement element) { // EARLY OUT/////// if (element.Events.Count == 0) { return; } ////////EARLY OUT///////// string file = element.Events[0].GetSharedCodeFullFileName(); if (File.Exists(file)) { ParsedClass parsedClass = GetParsedClassFrom(file); if (parsedClass == null) { // this file is empty foreach (EventResponseSave ers in element.Events) { try { InjectTextForEventAndSaveCustomFile(element, ers, ""); } catch (Exception e) { MessageBox.Show("Failed to generate custom code stubs for event " + ers.EventName + "\n\n" + e); } } } else { foreach (EventResponseSave ers in element.Events) { ParsedMethod parsedMethod = parsedClass.GetMethod("On" + ers.EventName); if (parsedMethod == null) { // This method doesn't exist. This will cause an error // because generated code expects this to always exist. Let's // make an empty stub InjectTextForEventAndSaveCustomFile(element, ers, ""); } } } } else { // The file doesn't exist, we gotta generate it } }
public void TestCodeParser() { var parsedClass = new ParsedClass(mClassContents, false); Assert.AreEqual(parsedClass.ParsedMethods.Count, 1); var parsedMethod = parsedClass.ParsedMethods[0]; var contents = parsedMethod.MethodContents; Assert.True(contents.Contains("this.HealthStatBar.InterpolateBetween(StatBar.VariableState.Empty, StatBar.VariableState.Full, 0.5f);"), "The parsed method contents don't contain a call to InterpolateBetween - there is an error in parsing the method contents"); }
/// <summary> /// Classes /// </summary> public void Visit(ParsedClass pars) { // to code explorer var newNode = CodeItem.Factory.New(CodeExplorerIconType.Class); newNode.DisplayText = pars.Name; newNode.Flags = pars.Flags; newNode.SubText = null; newNode.DocumentOwner = pars.FilePath; newNode.GoToLine = pars.Line; newNode.GoToColumn = pars.Column; _nodeDictionary.Add(pars.Name, newNode); PushToCodeExplorer(null, newNode); }
public string GetFile(SearchTask searchTask, ParsedClass parsedClass, string funcName) { var cppFiles = Directory.GetFiles(searchTask.SearchDir, "*.cpp", SearchOption.AllDirectories); var rgx = new Regex($@"^\s*DEFINE_API\s*\(\s*{parsedClass.CppName}\s*,\s*{funcName}\s*\)", RegexOptions.Multiline); foreach (var file in cppFiles) { var testext = File.ReadAllText(file); if (rgx.IsMatch(testext)) { return(testext); } } return(string.Empty); }
public static bool DoesListOfPropertiesContainProperty(ParsedClass parsedClass, string variableName) { if (DoesListOfPropertiesContainProperty(parsedClass.ParsedProperties, variableName)) { return(true); } foreach (ParsedClass parentClass in parsedClass.ParentParsedClasses) { if (DoesListOfPropertiesContainProperty(parentClass, variableName)) { return(true); } } return(false); }
protected void ExtendPreParsedClass(ParsedClass parsedClass) { if (parsedClass == null) { return; } if (!string.IsNullOrEmpty(parsedClass.CppName)) { parsedClass.Name = _cashParser.ToTitleCase(parsedClass.CppName); } if (!string.IsNullOrEmpty(parsedClass.CppInherit)) { parsedClass.Inherit = new List <ParsedType> { GetKnownTypeOrDefault(parsedClass.CppInherit) } } ; if (parsedClass.CppConstructorParams != null && parsedClass.CppConstructorParams.Any()) { foreach (var itm in parsedClass.CppConstructorParams) { parsedClass.ConstructorParams.Add(TryParseParam(itm)); } } if (parsedClass.ObjectType != ObjectType.Enum) { string templateName = null; if (parsedClass.IsTemplate) { templateName = _cashParser.Unpack(parsedClass.Template, 1); } for (var i = 0; i < parsedClass.Fields.Count; i++) { var preParsedElement = parsedClass.Fields[i]; parsedClass.Fields[i] = TryParseElement(preParsedElement, templateName, parsedClass.ObjectType); } } parsedClass.Fields.RemoveAll(i => i == null); }
public static ParsedMethod GetParsedMethodFromAssociatedFile(string fullFileName, EventResponseSave instance) { if (File.Exists(fullFileName)) { ParsedFile file = new ParsedFile(fullFileName, false, false); if (file.Namespaces.Count != 0) { ParsedNamespace parsedNamespace = file.Namespaces[0]; if (parsedNamespace.Classes.Count != 0) { ParsedClass parsedClass = parsedNamespace.Classes[0]; return(parsedClass.GetMethod("On" + instance.EventName)); } } } return(null); }
private void PrinNamespace(StringBuilder sb, ParsedClass parsedClass) { switch (parsedClass.ObjectType) { case ObjectType.Class: { sb.AppendLine("using Ditch.Core;"); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic; "); sb.AppendLine($"using Ditch.{ProjName}.Objects;"); sb.AppendLine("using Newtonsoft.Json;"); sb.AppendLine(); sb.AppendLine($"namespace Ditch.{ProjName}.Objects"); break; } case ObjectType.Enum: { sb.AppendLine("using Ditch.Core.Helpers;"); sb.AppendLine("using Newtonsoft.Json;"); sb.AppendLine(); sb.AppendLine($"namespace Ditch.{ProjName}.Objects"); break; } case ObjectType.Api: { sb.AppendLine("using Ditch.Core;"); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic; "); sb.AppendLine("using Ditch.Core.JsonRpc;"); sb.AppendLine($"using Ditch.{ProjName}.Objects;"); sb.AppendLine(); sb.AppendLine($"namespace Ditch.{ProjName}.Api"); break; } } sb.AppendLine("{"); }
private void AddClassName(StringBuilder sb, ParsedClass parsedClass, string absPathToFile, int indentCount) { var indent = new string(' ', indentCount); if (!string.IsNullOrEmpty(parsedClass.MainComment)) { sb.AppendLine($"{indent}{parsedClass.MainComment.Replace("\r\n", "\r\n" + indent)}{Environment.NewLine}"); } sb.AppendLine($"{indent}/// <summary>"); sb.AppendLine($"{indent}/// {parsedClass.CppName}"); if (!string.IsNullOrEmpty(absPathToFile)) { sb.AppendLine($@"{indent}/// {absPathToFile}"); } sb.AppendLine($"{indent}/// </summary>"); switch (parsedClass.ObjectType) { case ObjectType.Class: { sb.AppendLine($"{indent}[JsonObject(MemberSerialization.OptIn)]"); sb.AppendLine($"{indent}public class {parsedClass.Name}{(parsedClass.IsTemplate ? parsedClass.Template : string.Empty)}{(parsedClass.Inherit.Any() ? $" : {string.Join(", ", parsedClass.Inherit)}" : string.Empty)}"); break; } case ObjectType.Enum: { sb.AppendLine($"{indent}[JsonConverter(typeof(EnumConverter))]"); sb.AppendLine($"{indent}public enum {parsedClass.Name}"); break; } case ObjectType.Api: { sb.AppendLine($"{indent}public partial class OperationManager"); break; } } sb.AppendLine($"{indent}{{"); }
private void TryParseTemplate(ParsedClass result, IList <string> text, int index, out int end) { var line = text[index]; end = index; if (TemplateRegexp.IsMatch(line)) { line = Unpack(line, 1); var itms = SplitParams(line); end++; var names = itms.Where(i => i.StartsWith("typename")).Select(i => i.Remove(0, 8).Trim()).ToArray(); result.Template = $"<{string.Join(", ", names.Select(i => ToTitleCase(i)))}> "; if (itms.Count > names.Length) { foreach (var itm in itms.Where(i => !i.StartsWith("typename"))) { result.CppConstructorParams.Add(itm); } } } }
private void PrintParsedElements(StringBuilder sb, ParsedClass parsedClass, PreParsedElement parsedElement, int indentCount, string templateName) { var indent = new string(' ', indentCount); sb.AppendLine(); Comment briefComment = null; var parsedFunc = parsedElement as ParsedFunc; if (parsedFunc != null) { briefComment = Comment.TryParseMainComment(parsedFunc.MainComment); if (briefComment != null && !briefComment.IsEmpty()) { parsedFunc.MainComment = Comment.RemoveBriefFromMainComment(parsedFunc.MainComment); } } //if (!string.IsNullOrEmpty(parsedElement.MainComment)) //{ // sb.Append(indent); // sb.AppendLine(parsedElement.MainComment); // sb.AppendLine(); //} var comment = parsedElement.Comment ?? string.Empty; //comment = comment.Replace("\\", $@"/// {Environment.NewLine}"); sb.AppendLine($"{indent}/// <summary>"); sb.AppendLine($"{indent}/// API name: {parsedElement.CppName}"); if (!string.IsNullOrWhiteSpace(briefComment?.Brief)) { sb.AppendLine($"{indent}/// {briefComment.Brief.Replace(Environment.NewLine, $"{Environment.NewLine}{indent}/// ")}"); sb.AppendLine($"{indent}///"); } if (parsedClass.ObjectType == ObjectType.Api && !string.IsNullOrWhiteSpace(parsedElement.CppName) && MethodDescriptions.ContainsKey(parsedElement.CppName)) { var text = MethodDescriptions[parsedElement.CppName]; if (!string.IsNullOrWhiteSpace(text) && (briefComment == null || !briefComment.IsBriefContainText(text))) { sb.AppendLine($"{indent}/// *{text.Trim()}"); } } sb.AppendLine($"{indent}/// {TypeCorrection(comment)}"); sb.AppendLine($"{indent}/// </summary>"); if (parsedFunc != null) { foreach (var itm in parsedFunc.Params) { sb.Append($"{indent}/// <param name=\"{itm.Name}\">API type: {TypeCorrection(itm.CppType)}"); if (briefComment != null && briefComment.Params.ContainsKey(itm.CppName)) { sb.Append(briefComment.Params[itm.CppName].Replace(Environment.NewLine, $"{Environment.NewLine}{indent}/// ")); } sb.AppendLine("</param>"); } if (parsedClass.ObjectType == ObjectType.Api) { sb.AppendLine($"{indent}/// <param name=\"token\">Throws a <see cref=\"T:System.OperationCanceledException\" /> if this token has had cancellation requested.</param>"); } } if (!string.IsNullOrWhiteSpace(briefComment?.Return) || !string.IsNullOrEmpty(parsedElement.Type?.CppName)) { sb.Append($"{indent}/// <returns>"); if (!string.IsNullOrEmpty(parsedElement.Type?.CppName)) { sb.Append($"API type: {TypeCorrection(parsedElement.Type.CppName)}"); if (!string.IsNullOrWhiteSpace(briefComment?.Return)) { sb.Append(" "); } } if (!string.IsNullOrWhiteSpace(briefComment?.Return)) { sb.Append($"{briefComment.Return.Replace(Environment.NewLine, $"{Environment.NewLine}{indent}/// ")}"); } sb.AppendLine("</returns>"); } if (parsedClass.ObjectType == ObjectType.Api) { sb.AppendLine($"{indent}/// <exception cref=\"T:System.OperationCanceledException\">The token has had cancellation requested.</exception>"); } var type = GetTypeForPrint(parsedElement.Type, templateName); if (parsedFunc != null) { sb.AppendLine($"{indent}public JsonRpcResponse{(type.Equals("void", StringComparison.OrdinalIgnoreCase) ? string.Empty : $"<{type}>")} {parsedElement.Name}({string.Join(", ", parsedFunc.Params)}{(parsedClass.ObjectType == ObjectType.Api ? $"{(parsedFunc.Params.Any() ? ", " : string.Empty)}CancellationToken token" : string.Empty)})");
public ParsedLine(string lineOfCode, ParsedClass parsedClass, ParsedClass unchangedClass, List <ParsedField> localVariables) { existingFields.Clear(); existingProperties.Clear(); unchangedFields.Clear(); unchangedProperties.Clear(); if (parsedClass != null) { parsedClass.FillWithThisAndInheitedFields(existingFields); parsedClass.FillWithThisAndInheitedProperties(existingProperties); } if (unchangedClass != null) { unchangedClass.FillWithThisAndInheitedFields(unchangedFields); unchangedClass.FillWithThisAndInheitedProperties(unchangedProperties); } int index = 0; string lastWord = ""; string word = ""; bool isInString = false; string remainderFromWord = null; CodeItem lastCodeItem = null; string wordWithoutThis = ""; bool hadBase = false; int numberOfSquareBracketsDeep; Stack <CodeItem> bracketStack = new Stack <CodeItem>(); char separator; #region Loop through all words and try to figure out what they are while (true) { #region Determine word, wordWithoutThis, and lastCodeItem if (mCodeItems.Count != 0) { lastCodeItem = mCodeItems[mCodeItems.Count - 1]; } word = ParsedClass.GetWord(lineOfCode, ref index, out separator); if (word.StartsWith("this.")) { wordWithoutThis = word.Substring("this.".Length); } else { wordWithoutThis = ""; } #endregion #region Perform tests that modify the CodeItem, but don't fully determine its type hadBase = word.StartsWith("base."); if (word.StartsWith("base.")) { word = word.Substring("base.".Length); } int openingBracketCount = word.CountOf('['); int closingBracketCount = word.CountOf(']'); int netValue = openingBracketCount - closingBracketCount; #endregion if (string.IsNullOrEmpty(word) && index == lineOfCode.Length) { break; } //todo: Add ability to take something like (variableName and split that up into two CodeItems else if (word == "if" || word == "else" || word == "while" || word == "for" || word == "foreach" || word == "case") { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.ConditionalKeyword; mCodeItems.Add(codeItem); } // Handle = separately because it's an assignment else if (word == "=" || word == "+" || word == "-") { bool combine = lastCodeItem != null && lastCodeItem.CodeType == CodeType.Operation; if (combine && (word == "-" || word == "+")) { if (lastCodeItem.Code == "=" || lastCodeItem.Code == ")") { combine = false; } } if (combine) { // This is something like += or -= and we don't want those separated by a space mCodeItems[mCodeItems.Count - 1].Code += word; if (mCodeItems.Count - 2 >= 0) { mCodeItems[mCodeItems.Count - 2].IsAssigned = true; } } else { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Operation; mCodeItems.Add(codeItem); if (word == "=") { lastCodeItem.IsAssigned = true; } } } else if ( word == "(" || word == ")" || word == "==" || word == ";" || word == "}" || word == "{" || word == "*" || word == "/" || word == "," || word == "<" || word == ">" || word == "||" || word == "&&" || word == "|=" || word == "!=" || word == "<=" || word == ">=" || word == "&" || word == "|" || word == "[" || word == "]" || word == "!" || word == "!=") { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Operation; mCodeItems.Add(codeItem); if (word == "==" || word == "!=" || word == "<=" || word == "<=") { lastCodeItem.IsCompared = true; } } else if (word == "float" || word == "int" || word == "double" || word == "string" || word == "long" || word == "uint" || word == "byte" || word == "char") { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Primitive; mCodeItems.Add(codeItem); } else if (word == "null" || word == "return" || word == "ref" || word == "out" || word == "throw" || word == "new" || word == "try" || word == "in" || word == "const" || word == "base" || word == "is" || word == "as") { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Keyword; mCodeItems.Add(codeItem); } else if (word == "true" || word == "false" || float.TryParse(word, out throwawayString) || (word.EndsWith("f") && float.TryParse(word.Substring(0, word.Length - 1), out throwawayString))) { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Constant; mCodeItems.Add(codeItem); } else if (lastCodeItem != null && lastCodeItem.CodeType == CodeType.Keyword && lastCodeItem.Code == "new") { CodeItem codeItem = new CodeItem(); codeItem.Code = word; codeItem.CodeType = CodeType.Constructor; mCodeItems.Add(codeItem); } //else if(FlatRedBall.Utilities.StringFunctions. else { CodeItem codeItem = new CodeItem(); codeItem.Code = word; bool justSetIsInString = false; if (codeItem.Code.StartsWith("@\"") || codeItem.Code.StartsWith("\"") || isInString) { codeItem.CodeType = CodeType.Constant; if (!isInString) { justSetIsInString = true; } if (!word.EndsWith("\"")) { int indexToUse = index; if (index > 0 && lineOfCode[index - 1] == ' ') { indexToUse--; } int nextQuote = lineOfCode.IndexOf('"', indexToUse) + 1; string fullString = lineOfCode.Substring(indexToUse, nextQuote - indexToUse); codeItem.Code += fullString; isInString = false; index = nextQuote; } else { isInString = true; } } else if (lastCodeItem != null) { if (lastCodeItem.CodeType == CodeType.Primitive) { codeItem.CodeType = CodeType.VariableDeclaration; } else if (lastCodeItem.CodeType == CodeType.Unknown) { lastCodeItem.CodeType = CodeType.Type; codeItem.CodeType = CodeType.VariableDeclaration; } else if (lastCodeItem.Code == "in") { codeItem.CodeType = CodeType.Variable; } else if (lastCodeItem.Code == "new") { codeItem.CodeType = CodeType.Type; } } else { codeItem.CodeType = CodeType.Unknown; } if (codeItem.Code.EndsWith("\"") && (justSetIsInString == false || codeItem.Code.Length > 1)) { isInString = false; } mCodeItems.Add(codeItem); } CodeItem lastCodeItemAdded = mCodeItems[mCodeItems.Count - 1]; if (netValue > 0) { // push this guy on the stack for (int i = 0; i < netValue; i++) { bracketStack.Push(lastCodeItemAdded); } } else if (netValue < 0) { // pop off the stack and link the code items to this for (int i = 0; i < (-netValue); i++) { CodeItem itemToPairWith = bracketStack.Pop(); itemToPairWith.PairedSquareBracket = lastCodeItemAdded; lastCodeItemAdded.PairedSquareBracket = itemToPairWith; } } if (separator != ' ') { lastCodeItemAdded.HasSpaceAfter = false; } if (hadBase) { CodeItem codeItem = new CodeItem(); codeItem.Code = "base"; codeItem.CodeType = CodeType.Keyword; codeItem.ChildCodeItem = mCodeItems[mCodeItems.Count - 1]; mCodeItems[mCodeItems.Count - 1].ParentCodeItem = codeItem; mCodeItems.Insert(mCodeItems.Count - 1, codeItem); } } #endregion CodeItem itemBefore = null; CodeItem itemAfter = null; // Do a final pass of all words and see if there are any unknowns and try to identify them for (int i = 0; i < mCodeItems.Count; i++) { CodeItem codeItem = mCodeItems[i]; if (codeItem.CodeType == CodeType.Unknown) { #region Determine information about this CodeItem if (i > 0) { itemBefore = mCodeItems[i - 1]; } if (i < mCodeItems.Count - 1) { itemAfter = mCodeItems[i + 1]; } else { itemAfter = null; } bool canBeVariable = itemAfter == null || itemAfter.CodeType != CodeType.Unknown; wordWithoutThis = ""; if (codeItem.Code.StartsWith("this.")) { wordWithoutThis = codeItem.Code.Substring("this.".Length); } #endregion if (itemAfter != null && (itemAfter.Code == "==" || itemAfter.Code == "!=")) { CodeItem otherSideOfOperation = mCodeItems[i + 2]; if (otherSideOfOperation.CodeType == CodeType.Constant || otherSideOfOperation.CodeType == CodeType.Keyword) { codeItem.CodeType = CodeType.Variable; } } if (itemAfter != null && itemAfter.Code == "(") { codeItem.CodeType = CodeType.MethodCall; } else if (canBeVariable && (DoesListOfFieldsContainsField(existingFields, codeItem.Code) || DoesListOfFieldsContainsField(existingFields, wordWithoutThis) )) { codeItem.CodeType = CodeType.Variable; } else if (canBeVariable && (DoesListOfPropertiesContainProperty(existingProperties, codeItem.Code) || DoesListOfPropertiesContainProperty(existingProperties, wordWithoutThis))) { codeItem.CodeType = CodeType.Variable; } else if (canBeVariable && (DoesListOfFieldsContainsField(unchangedFields, codeItem.Code) || DoesListOfFieldsContainsField(unchangedFields, wordWithoutThis))) { codeItem.CodeType = CodeType.Variable; } else if (canBeVariable && (DoesListOfPropertiesContainProperty(unchangedProperties, codeItem.Code) || DoesListOfPropertiesContainProperty(unchangedProperties, wordWithoutThis))) { codeItem.CodeType = CodeType.Variable; } else if (canBeVariable && localVariables != null && DoesListOfFieldsContainsField(localVariables, codeItem.Code)) { codeItem.CodeType = CodeType.Variable; } } } }
public void Visit(ParsedClass pars) { AppendEverything(pars); }
internal static void InsertMethodCallInElementIfNecessary(IElement iElement, string methodName) { string currentFileName = FileManager.RelativeDirectory + iElement.Name + ".Events.cs"; string className = FileManager.RemovePath(iElement.Name); string fullFileContents = null; if (!FileManager.FileExists(currentFileName)) { string startingTemplate = Resources.Resource1.EventTemplate; startingTemplate = startingTemplate.Replace("CLASS___NAME", className); string namespaceName = ProjectManager.ProjectNamespace + '.' + FileManager.GetDirectoryKeepRelative(iElement.Name).Replace("\\", "."); // remove the ending slash: namespaceName = namespaceName.Substring(0, namespaceName.Length - 1); startingTemplate = startingTemplate.Replace("NAMESPACE___NAME", namespaceName); FileManager.SaveText(startingTemplate, currentFileName); ProjectManager.CodeProjectHelper.CreateAndAddPartialCodeFile(currentFileName, false); fullFileContents = startingTemplate; } else { fullFileContents = FileManager.FromFileText(currentFileName); } #region Find the parsedClassToUse ParsedNamespace parsedNamespace = new ParsedNamespace(fullFileContents); ParsedClass parsedClassToUse = null; foreach (ParsedClass parsedClass in parsedNamespace.Classes) { if (parsedClass.Name == className) { parsedClassToUse = parsedClass; break; } } #endregion if (parsedClassToUse != null) { // See if there is already a method here if (parsedClassToUse.GetMethod(methodName) == null) { DialogResult result = MessageBox.Show("The method\n\n" + methodName + "\n\ndoes not exist. Create this " + "method in your .Event.cs code file?", "Create method?", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { string newMethodCode = "\r\n\t\tvoid " + methodName + "(object sender, EventArgs e)\r\n" + "\t\t{\r\n" + "\t\t\t\r\n" + "\t\t}\r\n"; int indexToInsertAt = EventManager.GetLastLocationInClass(fullFileContents, startOfLine: true); fullFileContents = fullFileContents.Insert(indexToInsertAt, newMethodCode); FileManager.SaveText(fullFileContents, currentFileName); } } } }
/// <summary> /// Matches a procedure definition /// </summary> private ParsedClass CreateParsedClass(Token classToken) { /* * CLASS class-type-name [ INHERITS super-type-name ] * [ IMPLEMENTS interface-type-name [ , interface-type-name ] ... ] * [ USE-WIDGET-POOL ] * [ ABSTRACT | FINAL ] : * [ class-body ] */ // info we will extract from the current statement : string name = ""; string Inherits = ""; ParseFlag flags = 0; List <string> Implements = new List <string>(); Token token; int state = 0; do { token = PeekAt(1); // next token if (token is TokenEos) { break; } if (token is TokenComment) { continue; } if (token is TokenWord) { if (state == 0) { name = token.Value; state++; } else { switch (token.Value.ToLower()) { case "inherits": state = 2; break; case "implements": state = 3; break; case "abstract": flags |= ParseFlag.Abstract; break; case "final": flags |= ParseFlag.Final; break; default: if (state == 2) { Inherits = token.Value; state--; } else if (state == 3) { Implements.Add(token.Value); } break; } } continue; } if (token is TokenString) { if (state == 0) { name = GetTokenStrippedValue(token); state++; } continue; } } while (MoveNext()); if (state < 1) { return(null); } var newClass = new ParsedClass(name, classToken, Inherits, Implements) { // = end position of the EOS of the statement Flags = flags, EndPosition = token.EndPosition }; AddParsedItem(newClass, classToken.OwnerNumber); return(newClass); }
public virtual ParsedClass TryParseClass(SearchTask searchTask, IList <string> text, bool isApi) { if (!text.Any()) { return(null); } int index; if (text.Count == 1) { var typedef = TryParseTypedefClass(text[0]); if (typedef != null) { return(typedef); } } var result = new ParsedClass(); if (isApi) { result.ObjectType = ObjectType.Api; } result.MainComment = TryParseComment(text, 0, out index); TryParseTemplate(result, text, index, out index); var headerSb = new StringBuilder(); do { headerSb.Append(" " + text[index]); } while (!StartBodyRegex.IsMatch(text[index++])); var header = headerSb.ToString(); var name = TryParseClassName(header); result.CppName = name; result.Name = ToTitleCase(name); result.ObjectType = EnumRegex.IsMatch(header) ? ObjectType.Enum : result.ObjectType; var inherit = TryParseInherit(header).Trim(); if (!string.IsNullOrEmpty(inherit)) { result.CppInherit = inherit; } while (index < text.Count) { if (StartPrivateRegex.IsMatch(text[index]) || (index + 1 == text.Count && text[index].Trim().StartsWith("}"))) { break; } if (result.ObjectType == ObjectType.Api && GoToDeclareApiSection(text, index, out index)) { continue; } var comm = TryParseComment(text, index, out index); if (index == text.Count) { break; } if (StartPrivateRegex.IsMatch(text[index])) { break; } PreParsedElement field = null; switch (result.ObjectType) { case ObjectType.Enum: { field = TryParseEnum(text, index, out index); break; } case ObjectType.Class: { field = TryParseElement(text, index, out index, isApi); break; } case ObjectType.Api: { field = TryParseMethod(text, index, out index); break; } } if (field != null) { field.MainComment = comm; result.Fields.Add(field); } } return(result); }