public IBindingMethod CreateBindingMethod(CodeFunction codeFunction)
 {
     var parameters = codeFunction.Parameters.Cast<CodeParameter>().Select(CreateBindingParameter).ToArray();
     var type = CreateBindingType((CodeClass)codeFunction.Parent);
     var returnType = CreateBindingType(codeFunction.Type);
     return new BindingMethod(type, codeFunction.Name, parameters, returnType);
 }
Ejemplo n.º 2
0
 private static string GetMethodName(CodeFunction function)
 {
     var typeName = GetTypeName(function.Parent);
     var typename = GenericNameMangler.MangleTypeName(typeName);
     string method;
     switch (function.FunctionKind)
     {
         case vsCMFunction.vsCMFunctionConstructor:
             method = function.IsShared ? ".cctor" : ".ctor";
             break;
         case vsCMFunction.vsCMFunctionDestructor:
             method = "Finalize";
             break;
         case vsCMFunction.vsCMFunctionPropertyGet:
             method = "get_" + function.Name;
             break;
         case vsCMFunction.vsCMFunctionPropertySet:
             method = "set_" + function.Name;
             break;
         default:
             method = GenericNameMangler.MangleMethodName(function.Name);
             break;
     }
     AutoTest.Core.DebugLog.Debug.WriteDebug("Method name is " + typename + "::" + method);
     return typename + "::" + method;
 }
		public static string CreateCommnent(CodeFunction codeFunction)
		{
			if (codeFunction.HasReturnType("boolean")
				&& codeFunction.HasName("AreEqual")
				&& codeFunction.HasTwoParameters()
				&& codeFunction.HasParametertsOfType("IPropertyValueProvider"))
			{
				return "<c>true</c> if the two entities are equal; otherwise, <c>false</c>".ToBoolReturnText();
			}

			if (codeFunction.HasReturnType("boolean")
				&& codeFunction.NameStartsWith("Try")
				&& codeFunction.Name.Remove("Try").StartsWithAVerb(Verbs))
			{
				string name = codeFunction.Name.Remove("Try");
				var verb = Verbs.First(v => name.StartsWith(v.Item1));
				return $"<c>true</c>, if the {name.CamelCaseSplit()} could be {verb.Item2}; <c>false</c>, otherwise.".ToBoolReturnText();
			}

			if (codeFunction.HasReturnType("boolean")
				&& codeFunction.Name == "Contains"
				&& codeFunction.HasParameterCount(1))
			{
				string paramName = codeFunction.GetParameterName(1);
				return $"<c>true</c> if this instance contains the specified {paramName.CamelCaseSplit()}; otherwise, <c>false</c>";
			}

			if (codeFunction.NameStartsWith("TryGet")
				&& codeFunction.HasReturnType("boolean"))
			{
				return
					$"<c>true</c> if getting the {codeFunction.Name.CamelCaseSplit("TryGet")} was successful; otherwise, <c>false</c>"
						.ToBoolReturnText();
			}

			if (codeFunction.NameStartsWith("Get"))
			{
				return ("The " + codeFunction.Name.CamelCaseSplit("Get")).ToReturnText();
			}

			if (codeFunction.NameStartsWith("Can")
				&& codeFunction.HasReturnType("boolean"))
			{
				return
					$"<c>true</c> if this instance {codeFunction.Name.CamelCaseSplit()}; otherwise, <c>false</c>".ToBoolReturnText();
			}

			if (codeFunction.NameStartsWithAVerb(Verbs))
			{
				var verb = Verbs.First(v => codeFunction.NameStartsWith(v.Item1));
				return ((verb.Item2.ToLower() + " " + codeFunction.Name.Remove(verb.Item1).CamelCaseSplit()).AddArticle()).ToReturnText();
			}


			if (codeFunction.HasReturnType("boolean"))
			{
				return "<c>true</c> if ..........; otherwise, <c>false</c>".ToBoolReturnText();
			}
			return null;
		}
Ejemplo n.º 4
0
      internal static bool CanGenerateHandleCodeFunction(string testClassFixturePostFix, CodeClass parentCodeClass, CodeFunction codeFunction, Project unitTestProject)
      {
         foreach (ProjectItem projectItem in unitTestProject.ProjectItems)
         {
            List<CodeClass> lstProjectCodeClasses = UTGManagerAndExaminor.ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel);

            foreach (CodeClass codeClass in lstProjectCodeClasses)
            {
               if ((parentCodeClass.Name + testClassFixturePostFix).Equals(codeClass.Name))
               {
                  foreach (CodeElement codeElement in codeClass.Members)
                  {
                     if (codeElement is CodeFunction)
                     {
                        if (codeFunction.Name.Equals(((CodeFunction)codeElement).Name))
                           return false;

                     }
                  }
               }
            }
         }

         return true;
      }
Ejemplo n.º 5
0
 private static string GetMethodStringFromElement(CodeFunction justfunction)
 {
     string all = null;
     var first = true;
     if (justfunction != null)
     {
         if (justfunction.FunctionKind == vsCMFunction.vsCMFunctionPropertySet)
             return GetSetterNameFrom(justfunction);
         all = GetReturnType(justfunction) + " " + GetMethodName(justfunction) + "(";
         foreach (CodeParameter2 param in justfunction.Parameters)
         {
             if (!first) all += ",";
             var type = param.Type.AsFullName;
             if (param.Type.TypeKind == vsCMTypeRef.vsCMTypeRefArray)
                 type = getArray(param.Type);
             type = GenericNameMangler.MangleParameterName(type);
             if(param.ParameterKind == vsCMParameterKind.vsCMParameterKindOut || param.ParameterKind == vsCMParameterKind.vsCMParameterKindRef)
             {
                 type += "&";
             }
             all += type;
             first = false;
         }
         all += ")";
     }
     return all;
 }
 private IEnumerable<StepBindingNew> GetSuggestionsFromCodeFunctionForScope(CodeFunction codeFunction, BindingScopeNew bindingScope)
 {
     return codeFunction.Attributes.Cast<CodeAttribute2>()
         .Select(codeAttribute => GetBingingFromAttribute(codeAttribute, codeFunction, BindingType.Given, bindingScope) ??
                                  GetBingingFromAttribute(codeAttribute, codeFunction, BindingType.When, bindingScope) ??
                                  GetBingingFromAttribute(codeAttribute, codeFunction, BindingType.Then, bindingScope))
         .Where(binding => binding != null);
 }
 public string GetMethodCall(CodeFunction codeFunction)
 {
     string result = codeFunction.get_Prototype(Convert.ToInt32(vsCMPrototype.vsCMPrototypeParamNames));
     result = result.Replace("ByVal ", string.Empty);
     result = result.Replace("ByRef ", string.Empty);
     result = result.Replace(" )", ")");
     return result;
 }
Ejemplo n.º 8
0
        private static string GetSetterNameFrom(CodeFunction justfunction)
        {
            var ret = "System.Void ";
            ret += GetMethodName(justfunction) + "(";

            var type = justfunction.Type.AsFullName;
            if (justfunction.Type.TypeKind == vsCMTypeRef.vsCMTypeRefArray)
                type = getArray(justfunction.Type);
            type = GenericNameMangler.MangleParameterName(type);
            ret += type + ")";
            return ret;
        }
Ejemplo n.º 9
0
        public static VsMethod Parse(CodeFunction function)
        {
            var startPoint = function.StartPoint.CreateEditPoint();
            var endPoint = function.EndPoint.CreateEditPoint();
            int i = 1;
            while (startPoint.LessThan(endPoint))
            {
                i++;
                startPoint.LineDown(1);
            }

            return new VsMethod { Name = function.Name,Loc=i };
        }
Ejemplo n.º 10
0
 private BindingSourceMethod CreateBindingSourceMethod(CodeFunction codeFunction, BindingSourceType bindingSourceType, IdeBindingSourceProcessor bindingSourceProcessor)
 {
     try
     {
         var filteredAttributes = codeFunction.Attributes.Cast<CodeAttribute2>().Where(attr => bindingSourceProcessor.CanProcessTypeAttribute(attr.FullName)).ToArray();
         return bindingReflectionFactory.CreateBindingSourceMethod(codeFunction, bindingSourceType, filteredAttributes);
     }
     catch (Exception ex)
     {
         tracer.Trace("CreateBindingSourceMethod error: {0}", this, ex);
         return null;
     }
 }
Ejemplo n.º 11
0
        public MethodType(CodeFunction codeType)
        {
            if (codeType == null)
            {
                throw new ArgumentNullException("codeType");
            }

            CodeType = codeType;
            TypeName = codeType.FullName;
            ShortName = codeType.Name;

            DisplayName = ShortName;
        }
Ejemplo n.º 12
0
 private static string GetMethodStringFromElement(CodeFunction justfunction)
 {
     string all = null;
     var first = true;
     if (justfunction != null)
     {
         if (justfunction.FunctionKind == vsCMFunction.vsCMFunctionConstant) return null;
         if (justfunction.FunctionKind == vsCMFunction.vsCMFunctionPropertySet)
             return GetSetterNameFrom(justfunction);
         all = GetReturnType(justfunction) + " " + GetMethodName(justfunction) + "(";
         foreach (CodeParameter2 param in justfunction.Parameters)
         {
             if (!first) all += ",";
             
             all += GetParameterName(param);
             first = false;
         }
         all += ")";
     }
     return all;
 }
        private IEnumerable<StepBindingNew> GetSuggestionsFromCodeFunction(CodeFunction codeFunction, IEnumerable<BindingScopeNew> classBindingScopes)
        {
            var bindingScopes = classBindingScopes.Concat(codeFunction.Attributes.Cast<CodeAttribute2>().Select(GetBingingScopeFromAttribute).Where(s => s != null)).ToArray();

            if (bindingScopes.Any())
            {
                foreach (var bindingScope in bindingScopes)
                {
                    foreach (var stepBinding in GetSuggestionsFromCodeFunctionForScope(codeFunction, bindingScope))
                    {
                        yield return stepBinding;
                    }
                }
            }
            else
            {
                foreach (var stepBinding in GetSuggestionsFromCodeFunctionForScope(codeFunction, null))
                {
                    yield return stepBinding;
                }
            }
        }
Ejemplo n.º 14
0
        static string GetMemberName(CodeFunction member)
        {
            var sb = new StringBuilder();
            sb.Append (GetChainName (GetChain (member)));

            var prop = member.Parent as CodeProperty;
            if (prop == null) {
                sb.Append ("(");
                var head = "";
                foreach (CodeParameter p in member.Parameters) {
                    sb.Append (head);
                    sb.Append (GetTypeName (p.Type));
                    head = ", ";
                }
                sb.Append (")");
            }
            return sb.ToString ();
        }
 private StepBindingNew GetBingingFromAttribute(CodeAttribute2 codeAttribute, CodeFunction codeFunction, BindingType bindingType, BindingScopeNew bindingScope)
 {
     try
     {
         if (codeAttribute.FullName.Equals(string.Format("TechTalk.SpecFlow.{0}Attribute", bindingType)))
             return CreateStepBinding(codeAttribute, codeFunction, bindingType, bindingScope);
         return null;
     }
     catch(Exception)
     {
         return null;
     }
 }
Ejemplo n.º 16
0
 private static string GetReturnType(CodeFunction n)
 {
     if (n.Type.TypeKind == vsCMTypeRef.vsCMTypeRefArray)
         return GenericNameMangler.MangleParameterName(getArray(n.Type));
     if (n.Type.AsFullName == "") return "System.Void";
     return GenericNameMangler.MangleParameterName(n.Type.AsFullName);
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Tries to generate brief summary of the code element.
        /// </summary>
        /// <param name="codeElement">Code element for which to generate brief summary.</param>
        /// <returns>Generated text.</returns>
        private string TryGenerateBriefDesc(CodeElement codeElement)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            string desc = "";

            if (codeElement != null && codeElement is CodeFunction)
            {
                CodeFunction function = codeElement as CodeFunction;

                if ((function.FunctionKind & vsCMFunction.vsCMFunctionConstructor) != 0)
                {
                    desc = "Constructor.";
                }
                else if ((function.FunctionKind & vsCMFunction.vsCMFunctionDestructor) != 0)
                {
                    desc = "Destructor.";
                }
                else
                {
                    string[] funcNameWords = StringHelper.SplitCamelCase(function.Name);

                    // Retrieve the parent class's name.
                    string className = "";
                    string owner     = "";

                    if (function.Parent is CodeClass)
                    {
                        var codeClass = function.Parent as CodeClass;
                        className = GetClassName(codeClass.Name);
                        owner     = className + "'s ";
                    }

                    // Determine if the function is a setter or getter.
                    bool setter     = funcNameWords[0] == "set";
                    bool getter     = funcNameWords[0] == "get";
                    bool boolGetter = funcNameWords[0] == "is" || funcNameWords[0] == "has";

                    if (getter || setter || boolGetter)
                    {
                        // Generate the proper brief description.
                        if (funcNameWords.Length > 1)
                        {
                            if (getter)
                            {
                                desc = String.Format(Config.BriefGetterDescFormat, UnabbreviateAndJoin(funcNameWords, 1), owner);
                            }
                            else if (setter)
                            {
                                desc = String.Format(Config.BriefSetterDescFormat, UnabbreviateAndJoin(funcNameWords, 1), owner);
                            }
                            else if (boolGetter)
                            {
                                desc = String.Format(Config.BriefBoolGetterDescFormat, UnabbreviateAndJoin(funcNameWords, 1), className + " ", funcNameWords[0]);
                            }
                        }
                    }
                    else if (Config.SmartCommentsForAllFunctions)
                    {
                        // Allow smart comments for single word functions only in case they are class members.
                        // All other functions are supported.
                        if (funcNameWords.Length > 1 || function.Parent is CodeClass)
                        {
                            // We'll use the first word as the verb in the general case.
                            // Determine the third person verb ending for the verb.
                            string verb = StringHelper.GetThirdPersonVerb(Unabbreviate(funcNameWords[0]));

                            // In case a single word function name, we assume the object of the verb is the class itself.
                            string dest;
                            if (funcNameWords.Length == 1)
                            {
                                dest = className;
                            }
                            // Otherwise the object is the part which comes in the next words.
                            else
                            {
                                dest = UnabbreviateAndJoin(funcNameWords, 1);
                            }

                            desc = StringHelper.Capitalize(String.Format("{0} the {1}.", verb, dest));
                        }
                    }
                }
            }

            return(desc);
        }
Ejemplo n.º 18
0
      public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeFunction originalClassCodeFuntion)
      {
         vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction;
         object functionType = null;

         functionKind = vsCMFunction.vsCMFunctionSub;
         functionType = vsCMTypeRef.vsCMTypeRefVoid;

         string nextAvailableName = originalClassCodeFuntion.Name;

         if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass,
            nextAvailableName))
         {
            nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject);
         }

         CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction(
            nextAvailableName,
            functionKind,
            functionType,
            -1,
            originalClassCodeFuntion.Access,
            -1);

         bool tvIsStatic = originalClassCodeFuntion.IsShared;

         //add the NUnit attribute to the function
         unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1);

         try
         {
            unitTestCodeFunction.Comment = originalClassCodeFuntion.Comment;
            unitTestCodeFunction.DocComment = originalClassCodeFuntion.DocComment;
         }
         catch (Exception ex)
         {
            //ignore, for some reason the doc throws in vb
            Logger.LogException(ex);
         }

         string tvFunctionCallTemplate = string.Empty; //"iv{0}Type.{1}(";
         string tvFunctionReturnTemplate = string.Empty; //"{0} iv{1}Return = ";

         tvFunctionCallTemplate = "iv{0}Type.{1}(";

         if (tvIsStatic)
         {
            tvFunctionCallTemplate = "{0}.{1}(";
         }

         tvFunctionReturnTemplate = "Dim iv{1}Return As {0} = ";

         string tvTempParameterList = string.Empty;
         string tvFunctionCall = tvFunctionCallTemplate;
         string tvFunctionReturn = tvFunctionReturnTemplate;


         if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
         {
            CodeElements tvParameters = originalClassCodeFuntion.Parameters;

            foreach (CodeElement tvCodeElement in tvParameters)
            {
               if (!tvFunctionCall.Equals(tvFunctionCallTemplate))
               {
                  tvFunctionCall += ", ";
               }

               CodeParameter2 tvCodeParameter = (CodeParameter2)tvCodeElement;

               string parameterName = tvCodeParameter.Name;

               CodeTypeRef tvParameterType = tvCodeParameter.Type;

               vsCMParameterKind tvParameterKind = tvCodeParameter.ParameterKind;

               string parameterTypeAsString = tvParameterType.AsString;

               tvTempParameterList += "Dim " + parameterName + " As " + parameterTypeAsString + " = New " + parameterTypeAsString + "()" + Environment.NewLine + StringHelper.GetTabString();

               if (tvParameterKind == vsCMParameterKind.vsCMParameterKindRef)
               {
                  tvFunctionCall += parameterName;
               }
               else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindOut)
               {
                  tvFunctionCall += parameterName;
               }
               else if (tvParameterKind == vsCMParameterKind.vsCMParameterKindIn)
               {
                  tvFunctionCall += parameterName;
               }
               else
               {
                  tvFunctionCall += parameterName;
               }
            }

            tvFunctionCall = string.Format(tvFunctionCall + ")" + Environment.NewLine, ((CodeClass)originalClassCodeFuntion.Parent).Name, originalClassCodeFuntion.Name);
         }

         if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
         {
            tvFunctionReturn = string.Format(tvFunctionReturn, originalClassCodeFuntion.Type.AsString, originalClassCodeFuntion.Name);
            tvFunctionCall = tvFunctionReturn + tvFunctionCall;
         }

         TextPoint bodyStartingPoint =
            unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

         EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint();

         if (!originalClassCodeFuntion.FunctionKind.ToString().Equals("vsCMFunctionConstructor"))
         {
            boydEditPoint.Insert("\t\t\t' TODO: Update variable/s' defaults to meet test needs" + Environment.NewLine);

            boydEditPoint.Insert(StringHelper.GetTabString() + tvTempParameterList + Environment.NewLine);
            boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine);
         }

         if (originalClassCodeFuntion.Type.TypeKind != vsCMTypeRef.vsCMTypeRefVoid)
         {
            string stringHolder = "iv{0}Return";
            stringHolder = string.Format(stringHolder, originalClassCodeFuntion.Name);
            //FIX ME (tabing)
            //boydEditPoint.Insert(string.Format("\t\t\tAssert.AreEqual({0}, default({1}));\r\n", stringHolder, originalClassCodeFuntion.Type.AsString));
         }

          
         boydEditPoint.Insert(Environment.NewLine);
         boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine);
         boydEditPoint.Insert("\t\t\t'Assert.AreEqual( , )" + Environment.NewLine);
         boydEditPoint.Insert("\t\t\t" + Environment.NewLine);
         boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine);

         return unitTestCodeFunction;
      }
Ejemplo n.º 19
0
        public void FunctionKind_Function()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Equal(vsCMFunction.vsCMFunctionFunction, testObject.FunctionKind);
        }
Ejemplo n.º 20
0
        public void Kind()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Equal(vsCMElement.vsCMElementFunction, testObject.Kind);
        }
Ejemplo n.º 21
0
        public void Name()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodC");

            Assert.Equal("MethodC", testObject.Name);
        }
Ejemplo n.º 22
0
        public void IsShared_False()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.False(testObject.IsShared);
        }
Ejemplo n.º 23
0
        public void IsShared_True()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodC");

            Assert.True(testObject.IsShared);
        }
Ejemplo n.º 24
0
        public void IsOverloaded_True()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodE");

            Assert.True(testObject.IsOverloaded);
        }
Ejemplo n.º 25
0
        public void FunctionKind_Finalizer()
        {
            CodeFunction testObject = GetCodeFunction("A", 2);

            Assert.Equal(vsCMFunction.vsCMFunctionDestructor, testObject.FunctionKind);
        }
Ejemplo n.º 26
0
        public void FunctionKind_Constructor()
        {
            CodeFunction testObject = GetCodeFunction("A", 1);

            Assert.Equal(vsCMFunction.vsCMFunctionConstructor, testObject.FunctionKind);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Joins the specified multi-line method onto a single line.
        /// </summary>
        /// <param name="method">The method to update.</param>
        private void JoinMultiLineMethodOntoSingleLine(CodeFunction method)
        {
            var start = method.StartPoint.CreateEditPoint();
            var end = method.EndPoint.CreateEditPoint();

            string pattern = _package.UsePOSIXRegEx ? @":b*\n:b*" : @"[ \t]*\r?\n[ \t]*";
            const string replacement = @" ";

            // Substitute all new lines (and optional surrounding whitespace) with a single space.
            TextDocumentHelper.SubstituteAllStringMatches(start, end, pattern, replacement);
        }
Ejemplo n.º 28
0
        public void Parameters_Count()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodD");

            Assert.Equal(3, testObject.Parameters.Count);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Updates the specified accessors to both be single-line or multi-line.
        /// </summary>
        /// <param name="first">The first accessor.</param>
        /// <param name="second">The second accessor.</param>
        private void UpdateAccessorsToBothBeSingleLineOrMultiLine(CodeFunction first, CodeFunction second)
        {
            if (first == null || second == null) return;

            bool isFirstSingleLine = first.StartPoint.Line == first.EndPoint.Line;
            bool isSecondSingleLine = second.StartPoint.Line == second.EndPoint.Line;

            if (isFirstSingleLine == isSecondSingleLine) return;

            var multiLineMethod = isFirstSingleLine ? second : first;
            var singleLineMethod = isFirstSingleLine ? first : second;

            try
            {
                var multiLineBodyStart = multiLineMethod.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                var multiLineBodyEnd = multiLineMethod.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                // Move the body end back one character to account for new-lines.
                multiLineBodyEnd.CharLeft();

                bool multiLineHasSingleLineBody = multiLineBodyStart.Line == multiLineBodyEnd.Line;

                if (multiLineHasSingleLineBody)
                {
                    JoinMultiLineMethodOntoSingleLine(multiLineMethod);
                }
                else
                {
                    SpreadSingleLineMethodOntoMultipleLines(singleLineMethod);
                }
            }
            catch (Exception)
            {
                // Accessor without a body can be ignored.
            }
        }
Ejemplo n.º 30
0
        public void Type()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Equal("System.Int32", testObject.Type.AsFullName);
        }
Ejemplo n.º 31
0
        public void CanOverride_True()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodB");

            Assert.True(testObject.CanOverride);
        }
Ejemplo n.º 32
0
        public void Overloads_Count()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodE");

            Assert.Equal(2, testObject.Overloads.Count);
        }
Ejemplo n.º 33
0
        public void CanOverride_False()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.False(testObject.CanOverride);
        }
Ejemplo n.º 34
0
        public void GetEndPoint_AttributesWithDelimiter()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Throws <COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter));
        }
Ejemplo n.º 35
0
        private void CollapseElement(CodeElement element)
        {
            if (element.IsCodeType && (element.Kind != vsCMElement.vsCMElementDelegate))
            {
                System.Diagnostics.Debug.Print("got type but not a delegate, named : {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeType     ct   = element as EnvDTE.CodeType;
                CodeElements mems = ct.Members;
                foreach (CodeElement melt in mems)
                {
                    CollapseElement(melt);
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementNamespace)
            {
                System.Diagnostics.Debug.Print("got a namespace, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeNamespace cns = element as EnvDTE.CodeNamespace;
                System.Diagnostics.Debug.Print("set cns = elt, named: {0}", cns.Name);

                CodeElements mems_ns = cns.Members;
                if (mems_ns.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cns.members");
                    foreach (CodeElement melt in mems_ns)
                    {
                        CollapseElement(melt);
                    }
                    System.Diagnostics.Debug.Print("end of cns.members");
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementFunction)
            {
                System.Diagnostics.Debug.Print("got a function, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeFunction cf = element as EnvDTE.CodeFunction;
                System.Diagnostics.Debug.Print("set cf = elt, named: {0}, fkind: {1}", cf.Name, cf.FunctionKind);

                CodeElements mems_f = cf.Children;
                if (mems_f.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cf.members");
                    foreach (CodeElement melt in mems_f)
                    {
                        CollapseElement(melt);
                    }
                    System.Diagnostics.Debug.Print("end of cf.members");
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementProperty)
            {
                System.Diagnostics.Debug.Print("got a property, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeProperty cp = element as EnvDTE.CodeProperty;
                System.Diagnostics.Debug.Print("set cp = elt, named: {0}", cp.Name);

                CodeElements mems_p = cp.Children;
                if (mems_p.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cp.members");
                    foreach (CodeElement melt in mems_p)
                    {
                        CollapseElement(melt);
                    }
                    System.Diagnostics.Debug.Print("end of cp.members");
                }
            }
            else if (element.Kind == vsCMElement.vsCMElementVariable)
            {
                System.Diagnostics.Debug.Print("got a variable, named: {0} in line {1} to {2}", element.Name, element.StartPoint.Line, element.EndPoint.Line);
                CodeVariable cv = element as EnvDTE.CodeVariable;
                System.Diagnostics.Debug.Print("set cv = elt, named: {0}", cv.Name);

                CodeElements mems_v = cv.Children;
                if (mems_v.Count > 0)
                {
                    System.Diagnostics.Debug.Print("got cv.members");
                    foreach (CodeElement melt in mems_v)
                    {
                        CollapseElement(melt);
                    }
                    System.Diagnostics.Debug.Print("end of cv.members");
                }
            }
            else
            {
                System.Diagnostics.Debug.Print("kind = {0} in line {1} to {2}", element.Kind, element.StartPoint.Line, element.EndPoint.Line);
            }
        }
Ejemplo n.º 36
0
        public void GetEndPoint_BodyWithDelimiter()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Throws <NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Writes comments for function parameters.
        /// </summary>
        /// <param name="sb">String builder to write comments into.</param>
        /// <param name="spaces">Indentation spaces.</param>
        /// <param name="codeElement">Function code element.</param>
        /// <param name="parsedComment">Parsed existing comment, if any.</param>
        private void WriteParamComments(StringBuilder sb, string spaces, CodeFunction function, ParsedComment parsedComment)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            int maxTypeDirectionLength = 0;
            int maxParamNameLength     = 0;

            foreach (CodeElement child in function.Children)
            {
                CodeParameter param = child as CodeParameter;

                if (param != null)
                {
                    // Check if the existing comment contained this parameter.
                    ParsedParam parsedParam = null;

                    if (parsedComment.Parameters.ContainsKey(param.Name))
                    {
                        parsedParam = parsedComment.Parameters[param.Name];
                    }

                    string typeDirName = DirectionToString(GetParamDirection(function, param, parsedParam));
                    maxTypeDirectionLength = Math.Max(maxTypeDirectionLength, typeDirName.Length);
                    maxParamNameLength     = Math.Max(maxParamNameLength, param.Name.Length);
                }
            }

            // Create doxygen lines for each parameter.
            if (function.Children.Count > 0)
            {
                sb.Append("\r\n" + spaces + " *");

                foreach (CodeElement child in function.Children)
                {
                    CodeParameter param = child as CodeParameter;

                    if (param != null)
                    {
                        // Check if the existing comment contained this parameter.
                        ParsedParam parsedParam = null;

                        if (parsedComment.Parameters.ContainsKey(param.Name))
                        {
                            parsedParam = parsedComment.Parameters[param.Name];
                        }

                        // Determine type of parameter (in, out or inout).
                        string typeDirName      = DirectionToString(GetParamDirection(function, param, parsedParam));
                        string paramAlignSpaces = new string(' ', maxParamNameLength - param.Name.Length + 1);
                        string typeAlignSpaces  = new string(' ', maxTypeDirectionLength - typeDirName.Length + 1);
                        string tagLine          = m_indentString + Config.TagChar + "param " + typeDirName + typeAlignSpaces + param.Name + paramAlignSpaces;
                        sb.Append("\r\n" + spaces + " *  " + tagLine);

                        // Add existing comments.
                        if (parsedParam != null)
                        {
                            AppendComments(sb, parsedParam.Comments, spaces, tagLine.Length);
                        }
                        else if (Config.SmartComments && function.Children.Count == 1)
                        {
                            sb.Append(TryGenerateParamDesc(function, param));
                        }
                    }
                }
            }
        }
Ejemplo n.º 38
0
        public void GetEndPoint_HeaderWithAttributes()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Throws <NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
        }
        private StepBindingNew CreateStepBinding(CodeAttribute2 attr, CodeFunction codeFunction, BindingType bindingType, BindingScopeNew bindingScope)
        {
            try
            {
                IBindingMethod bindingMethod = new VsBindingMethod(codeFunction);

                var regexArg = attr.Arguments.Cast<CodeAttributeArgument>().FirstOrDefault();
                if (regexArg == null)
                    return null;

                var regexString = VsxHelper.ParseCodeStringValue(regexArg.Value, regexArg.Language);
                var regex = new Regex("^" + regexString + "$", RegexOptions.Compiled | RegexOptions.CultureInvariant);

                return new StepBindingNew(bindingMethod, bindingType, regex, bindingScope);
            }
            catch(Exception)
            {
                return null;
            }
        }
Ejemplo n.º 40
0
        public void GetEndPoint_Whole()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodA");

            Assert.Throws <NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
        }
Ejemplo n.º 41
0
        public static void DoRemoveInvocationWithFilter(this CodeFunction codeFunction, string[] classNames, List <FluentAPIEntityNode> filter)
        {
            if (classNames == null)
            {
                return;
            }
            if (codeFunction == null)
            {
                return;
            }
            EditPoint editPoint = codeFunction.StartPoint.CreateEditPoint();

            editPoint.SmartFormat(codeFunction.EndPoint);
            editPoint = codeFunction.StartPoint.CreateEditPoint();
            string     buff = editPoint.GetText(codeFunction.EndPoint);
            SyntaxTree tree = CSharpSyntaxTree.ParseText(buff);
            SyntaxNode root = tree.GetRoot();

            if (root == null)
            {
                return;
            }
            MethodDeclarationSyntax methodDeclaration =
                root.GetOnModelCreatingParameterName("DbModelBuilder", "ModelBuilder", out string parameterName);

            if ((methodDeclaration == null) || string.IsNullOrEmpty(parameterName))
            {
                return;
            }
            if (methodDeclaration.Body == null)
            {
                return;
            }
            List <TextSpan> spans = new List <TextSpan>();

            foreach (StatementSyntax ss in methodDeclaration.Body.Statements)
            {
                if (ss.Kind() != SyntaxKind.ExpressionStatement)
                {
                    continue;
                }
                ExpressionStatementSyntax expressionStatementSyntax = ss as ExpressionStatementSyntax;
                if (expressionStatementSyntax.Expression == null)
                {
                    continue;
                }
                if (expressionStatementSyntax.Expression.Kind() != SyntaxKind.InvocationExpression)
                {
                    continue;
                }
                InvocationExpressionSyntax invocationExpressionSyntax = expressionStatementSyntax.Expression as InvocationExpressionSyntax;
                if (!parameterName.Equals(invocationExpressionSyntax.InvocationExpressionRootName(classNames)))
                {
                    continue;
                }
                FluentAPIEntityNode faen = expressionStatementSyntax.Expression.InvocationExpressionMethods(null);
                if (faen == null)
                {
                    continue;
                }
                if (faen.Methods == null)
                {
                    continue;
                }
                if (faen.IsSatisfiedTheFilter(filter))
                {
                    spans.Insert(0, expressionStatementSyntax.Span);
                }
            }

            foreach (TextSpan ts in spans)
            {
                buff = buff.Remove(ts.Start, ts.Length);
                //
                // the commented code does not work : ts.Start does not correctly point to begining of the operator
                //editPoint.CharRight(ts.Start);
                //editPoint.Delete(ts.Length);
                //editPoint.CharLeft(ts.Start);
                //if (codeFunction.ProjectItem != null)
                //{
                //   codeFunction.ProjectItem.Save();
                //}
            }
            buff      = buff.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
            editPoint = codeFunction.StartPoint.CreateEditPoint();
            editPoint.Delete(codeFunction.EndPoint);
            editPoint.Insert(buff);
            if (codeFunction.ProjectItem != null)
            {
                codeFunction.ProjectItem.Save();
            }
        }
Ejemplo n.º 42
0
        public void Operator()
        {
            CodeFunction functionObject = GetCodeFunction("A", 3);

            Assert.Equal("operator +", functionObject.Name);
        }
Ejemplo n.º 43
0
        public static List <FluentAPIEntityNode> DoAnalyzeWithFilter(this CodeFunction codeFunction, string[] classNames, List <FluentAPIEntityNode> filter)
        {
            if (classNames == null)
            {
                return(null);
            }
            if (codeFunction == null)
            {
                return(null);
            }
            string     buff = codeFunction.StartPoint.CreateEditPoint().GetText(codeFunction.EndPoint);
            SyntaxTree tree = CSharpSyntaxTree.ParseText(buff);
            SyntaxNode root = tree.GetRoot();

            if (root == null)
            {
                return(null);
            }
            MethodDeclarationSyntax methodDeclaration =
                root.GetOnModelCreatingParameterName("DbModelBuilder", "ModelBuilder", out string parameterName);

            if ((methodDeclaration == null) || string.IsNullOrEmpty(parameterName))
            {
                return(null);
            }
            if (methodDeclaration.Body == null)
            {
                return(null);
            }
            List <FluentAPIEntityNode> entityNodes = null;

            foreach (StatementSyntax ss in methodDeclaration.Body.Statements)
            {
                if (ss.Kind() != SyntaxKind.ExpressionStatement)
                {
                    continue;
                }
                ExpressionStatementSyntax expressionStatementSyntax = ss as ExpressionStatementSyntax;
                if (expressionStatementSyntax.Expression == null)
                {
                    continue;
                }
                if (expressionStatementSyntax.Expression.Kind() != SyntaxKind.InvocationExpression)
                {
                    continue;
                }
                InvocationExpressionSyntax invocationExpressionSyntax = expressionStatementSyntax.Expression as InvocationExpressionSyntax;
                if (!parameterName.Equals(invocationExpressionSyntax.InvocationExpressionRootName(classNames)))
                {
                    continue;
                }
                string methodBodyStr     = expressionStatementSyntax.ToString().Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "");
                FluentAPIEntityNode faen = expressionStatementSyntax.Expression.InvocationExpressionMethods(null);
                if (faen == null)
                {
                    continue;
                }
                if (faen.Methods == null)
                {
                    continue;
                }
                if (faen.IsSatisfiedTheFilter(filter))
                {
                    if (entityNodes == null)
                    {
                        entityNodes = new List <FluentAPIEntityNode>();
                    }
                    faen.MethodBodyString = methodBodyStr;
                    entityNodes.Add(faen);
                }
            }
            return(entityNodes);
        }
Ejemplo n.º 44
0
 private string GetFuncCommen(CodeFunction func)
 {
     StringBuilder str = new StringBuilder();
     str.Append(@"///<summary>" + GetDescriptionFromCamelcase(func.Name) + @"</summary>" + Environment.NewLine);
     foreach (Tuple<string, string> param in GetParamNamesAndTypes(func))
     {
         str.Append(@"///<param name='" + param.Item1 + "'>" + GetDescriptionFromCamelcase(param.Item2) + @"</param>" + Environment.NewLine);
     }
     return str.ToString(); ;
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Spreads the specified single line method onto multiple lines.
        /// </summary>
        /// <param name="method">The method to update.</param>
        private void SpreadSingleLineMethodOntoMultipleLines(CodeFunction method)
        {
            try
            {
                var start = method.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                var end = method.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

                // Insert a new-line before and after the opening brace.
                start.CharLeft();
                start.Insert(Environment.NewLine);
                start.CharRight();
                start.Insert(Environment.NewLine);

                // Insert a new-line before the closing brace, unless the method is empty.
                end.DeleteWhitespace();
                if (end.DisplayColumn > 1)
                {
                    end.Insert(Environment.NewLine);
                }

                // Update the formatting of the method.
                method.StartPoint.CreateEditPoint().SmartFormat(method.EndPoint);
            }
            catch (Exception)
            {
                // Methods may not have a body (ex: partial).
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Gets the declaration of the specified code method as a string.
        /// </summary>
        /// <param name="codeFunction">The code method.</param>
        /// <returns>The string declaration.</returns>
        internal static string GetMethodDeclaration(CodeFunction codeFunction)
        {
            // Get the start point after the attributes.
            var startPoint = codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader);

            return TextDocumentHelper.GetTextToFirstMatch(startPoint, @"[\{;]");
        }
 public ModelMetadataViewModel(CodeFunction codeElements) : base(codeElements)
 {
 }
Ejemplo n.º 48
0
      internal static void OnCodeClassSelection(AbstractTestFramework testFramework, CodeFunction ce, DTE2 applicationObject, UnitTestCodeType codeType)
      {
         Project parentProject = ProjectExaminar.GetCodeClassParentProject((CodeClass)ce.Parent);

         Project unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix);

         if (unitTestProject == null) {

            OnCodeClassSelection(testFramework, (CodeClass)ce.Parent, (CodeElement)ce, applicationObject, codeType);
            return;
         }

         //In cases where we can not simply generate automatically (definition already exists) we will
         //ask the user for input, wait on input, then async back to the function actual useful handler
         //HandelCodeClassSelection
         if (!CanGenerateHandleCodeFunction(testFramework.TestClassFixturePostFix, (CodeClass)ce.Parent, ce, unitTestProject))
         {
            //UTGHelper.ErrorHandler.HandleMessage(CommonUserMessages.MSG_TEST_ALREADY_EXISTS);

            UTGHelper.UserAlertActionRequired tvUserAlertActionRequired = new UserAlertActionRequired(
               "Function definition already exits! What would you like to do?",
               typeof(CodeFunction),
               (CodeElement)ce,
               ref applicationObject,
               codeType,
               testFramework);

            if (!tvUserAlertActionRequired.IsDisposed)
            {
               tvUserAlertActionRequired.FormClosed += new System.Windows.Forms.FormClosedEventHandler(tvUserAlertActionRequired_FormClosed);

               tvUserAlertActionRequired.Show();
            }
            else
            {
               HandelCodeClassSelection(testFramework, ce, applicationObject, codeType);
            }

            return;
         }

         //otherwise simply call HandelCodeClassSelection
         HandelCodeClassSelection(testFramework, ce, applicationObject, codeType);
      }
        /// <summary>
        /// Implements the interface.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="constructor">The constructor.</param>
        /// <param name="variable">The variable.</param>
        public static void ImplementInterface(
            this CodeClass instance, 
            CodeFunction constructor, 
            string variable)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementInterface file=" + variable);

            //// now add in the interfaces!

            //// split the variable string
            string[] parts = variable.Split(' ');

            constructor.AddParameter(parts[1], parts[0]);

            //// we need to add the variable.
            //// variable could already exist!
            try
            {
                instance.ImplementVariable(parts[1], parts[0], true);
            }
            catch (Exception)
            {
                TraceService.WriteError("variable already exists " + parts[1]);
            }

            //// now do the wiring up of the interface and variable!
            EditPoint editPoint = constructor.GetEndPoint(vsCMPart.vsCMPartBody).CreateEditPoint();

            string code = string.Format("this.{0} = {1};", parts[1], parts[1]);
            editPoint.InsertCodeLine(code);

            //// now update the constructor document comments.
            string paramComment = string.Format("<param name=\"{0}\">The {0}.</param>{1}", parts[1], Environment.NewLine);
            string currentComment = constructor.DocComment;

            int index = currentComment.LastIndexOf("</summary>", StringComparison.Ordinal);

            StringBuilder sb = new StringBuilder();

            if (index != -1)
            {
                sb.Append(currentComment.Substring(0, index + 10));
                sb.Append(paramComment);
                sb.Append(currentComment.Substring(index + 10));

                TraceService.WriteLine("comment added=" + paramComment);
            }

            constructor.DocComment = sb.ToString();
        }
Ejemplo n.º 50
0
      internal static void HandelCodeClassSelection(AbstractTestFramework testFramework, CodeFunction function, DTE2 applicationObject, UnitTestCodeType codeType)
      {
         Project parentProject = ProjectExaminar.GetCodeClassParentProject((CodeClass)function.Parent);

         Project unitTestProject = ProjectExaminar.GetUnitTestProject(parentProject.Name, applicationObject, testFramework.TestProjectPostFix);

         //We might or might not use this factory, we don't know at this point
         AbstractTestClassFactory testClassFactory = new NUnitTestClassFactory();

         foreach (ProjectItem projectItem in unitTestProject.ProjectItems)
         {
            System.Collections.Generic.List<CodeClass> lstCodeClasses =
                 ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel);

            foreach (CodeClass codeClass in lstCodeClasses)
            {
               CodeClass parentClass = (CodeClass)function.Parent;

               string className = codeClass.Name;
               string testClassName = ((CodeClass)function.Parent).Name + testFramework.TestClassFixturePostFix;
               
               //find the parent for function passed in
               //if (codeClass.Name.Equals(((CodeClass)function.Parent).Name + CommonStrings.DEFAULT_STRING_SEPERATOR + UTGHelper.CommonStrings.DEFAULT_UNIT_TEST_CLASS_POSTFIX))
               if (className.Equals(testClassName) == true)
               {
                  //if found 
                  AbstractTestClass nunitClass = null;

                  if (codeType == UnitTestCodeType.CSharp)
                  {
                     nunitClass = testClassFactory.CreateCSharpTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract);
                  }
                  else if (codeType == UnitTestCodeType.VB)
                  {
                     nunitClass = testClassFactory.CreateVBTestClass(codeClass.Namespace.FullName, codeClass.Name, codeClass.IsAbstract);
                  }

                  nunitClass.GenerateTest(codeClass, function);

                  //we sure expect just one class, the first class we find matching
                  return;
               }
            }
         }

         //if we have reached this point then it means that we have not been able to locate a parent class in our
         //unit test project, then we simply create a class unit test

         OnCodeClassSelection(testFramework, (CodeClass)function.Parent, (CodeElement)function, applicationObject, unitTestProject, codeType);
      }
		private static bool CheckIfCodeClassInheritsFunction(CodeClass codeClass, CodeFunction codeFunction)
		{
			List<CodeInterface> implementedInterfaces = codeClass.GetImplementedInterfaces();
			if (
				SearchService.SearchInCodeElements<CodeFunction>(implementedInterfaces.OfType<CodeElement>())
					.Any(
						p =>
						p.Name == codeFunction.Name && p.Kind == codeFunction.Kind && p.Type.AsFullName == codeFunction.Type.AsFullName
						&& p.Access == codeClass.Access))
			{
				return true;
			}
			return false;
		}
Ejemplo n.º 52
0
        public void FullName()
        {
            CodeFunction testObject = GetCodeFunction("A", "MethodD");

            Assert.Equal("A.MethodD", testObject.FullName);
        }
Ejemplo n.º 53
0
        internal static void GenerateSerializaCode(CodeClass2 classElement, CodeFunction serializeMethod, CodeFunction deserializeMethod, Dictionary<string, CodeClass2> dic, TyrantVSPackage package/*, string serializeMethodParameterName, string deserializeMethodParameterName*/)
        {
            var memberList = new List<SerializeMember>();
            foreach (CodeElement2 member in classElement.Members)
            {
                var field = member as CodeVariable2;
                if (field != null)
                {
                    memberList.Add(new SerializeMember() { Name = field.Name, TypeRef = field.Type, Attributes = field.Attributes });
                    continue;
                }
                var property = member as CodeProperty2;
                if (property != null && property.Getter != null && property.Setter != null)
                    memberList.Add(new SerializeMember() { Name = property.Name, TypeRef = property.Type, Attributes = property.Attributes });
            }
            int iii = serializeMethod.Parameters.Count;
            string serializeMethodParameterName = serializeMethod.Parameters.Item(1).Name;
            string deserializeMethodParameterName = deserializeMethod.Parameters.Item(1).Name;
            var serializeStatementList = new List<string>();
            var deserializeStatementList = new List<string>();
            string deserializeMethodCode = string.Format("int num;{0}while ((num = source.ReadFieldHeader()) > 0){0}{1}{0}switch (num){0}{1}{0}", Environment.NewLine, "{");
            for (int i = 0; i < memberList.Count; ++i)
            {
                var mem = memberList[i];
                bool needContinue = false;
                foreach (CodeAttribute2 codeArrtibute in mem.Attributes)
                {
                    if (codeArrtibute.FullName == "Tyrant.GameCore.DoNotSerializeAttribute")
                    {
                        needContinue = true;
                        break;
                    }
                }
                if (needContinue)
                    continue;

                string serializeMethodName = "";
                string deserializeMethodName = "";
                if (mem.TypeRef.TypeKind == vsCMTypeRef.vsCMTypeRefArray)
                    GetSerializeMethodAndDeserializeMethodName(mem.TypeRef.ElementType, null, ref serializeMethodName, ref deserializeMethodName, "Array", dic, package);
                else
                {
                    if (mem.TypeRef.AsFullName.StartsWith("System.Collections.Generic.List<"))
                    {
                        string fullName = mem.TypeRef.AsFullName;
                        int first = fullName.IndexOf('<');
                        var elementName = fullName.Substring(first + 1, fullName.Length - 2 - first);
                        GetSerializeMethodAndDeserializeMethodName(null, elementName, ref serializeMethodName, ref deserializeMethodName, "List", dic, package);
                    }
                    else
                        GetSerializeMethodAndDeserializeMethodName(mem.TypeRef, null, ref serializeMethodName, ref deserializeMethodName);
                }

                serializeStatementList.Add($"Tyrant.GameCore.CommunicatorHelper.{serializeMethodName}({i + 1}, {mem.Name}, {serializeMethodParameterName});");
                deserializeStatementList.Add($"case {i + 1}:{Environment.NewLine}{mem.Name} = Tyrant.GameCore.CommunicatorHelper.{deserializeMethodName}({deserializeMethodParameterName});{Environment.NewLine}break;");
            }

            if (serializeStatementList.Count > 0)
            {
                var point = serializeMethod.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                point.ReplaceText(serializeMethod.GetEndPoint(vsCMPart.vsCMPartBody), string.Join(Environment.NewLine, serializeStatementList), (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
            }

            if (deserializeStatementList.Count > 0)
            {
                var point = deserializeMethod.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                point.ReplaceText(deserializeMethod.GetEndPoint(vsCMPart.vsCMPartBody), deserializeMethodCode + string.Join(Environment.NewLine, deserializeStatementList) + Environment.NewLine + "}" + Environment.NewLine + "}", (int)vsEPReplaceTextOptions.vsEPReplaceTextAutoformat);
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Removes the comments.
        /// </summary>
        /// <param name="instance">The instance.</param>
        public static void RemoveComments(this CodeFunction instance)
        {
            TraceService.WriteLine("CodeFunctionExtensions::RemoveComments Name=" + instance.Name);

            instance.DocComment = ScorchioConstants.BlankDocComment;
        }
Ejemplo n.º 55
0
        public override CodeFunction GenerateTest(CodeClass unitTestCodeClass, CodeProperty originalClassCodeProperty)
        {
            vsCMFunction functionKind = vsCMFunction.vsCMFunctionFunction;
            object       functionType = null;

            functionKind = vsCMFunction.vsCMFunctionSub;
            functionType = vsCMTypeRef.vsCMTypeRefVoid;

            string nextAvailableName = originalClassCodeProperty.Name;

            if (!CodeSelectionHandler.CanGenerateHandleCodeFunction(unitTestCodeClass,
                                                                    nextAvailableName))
            {
                nextAvailableName = GetNextAvailableCopyName(unitTestCodeClass, ref nextAvailableName, unitTestCodeClass.ProjectItem.ContainingProject);
            }

            CodeFunction unitTestCodeFunction = unitTestCodeClass.AddFunction(
                nextAvailableName,
                functionKind,
                functionType,
                -1,
                originalClassCodeProperty.Access,
                -1);

            unitTestCodeFunction.AddAttribute("NUnit.Framework.Test", "", -1);

            try
            {
                unitTestCodeFunction.Comment    = originalClassCodeProperty.Comment;
                unitTestCodeFunction.DocComment = originalClassCodeProperty.DocComment;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                //ignore
            }

            TextPoint bodyStartingPoint =
                unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            EditPoint boydEditPoint = bodyStartingPoint.CreateEditPoint();

            //Stop here if not read-write type property now...

            if (originalClassCodeProperty.Setter == null)
            {
                boydEditPoint = bodyStartingPoint.CreateEditPoint();

                boydEditPoint.Insert(StringHelper.GetTabString() + "' Property is not read-write please add your own code here." + Environment.NewLine);

                return(unitTestCodeFunction);
            }

            string tvFunctionCallTemplate = string.Empty; // "iv{0}Type.{1} = default({2});";

            tvFunctionCallTemplate = "iv{0}Type.{1} = New {2}()" + Environment.NewLine;

            string tvFunctionCall = tvFunctionCallTemplate;

            CodeTypeRef tvPropertyType = originalClassCodeProperty.Type;

            string tvPropertyTypeAsString = tvPropertyType.AsString;

            tvFunctionCall = string.Format(tvFunctionCall, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString);

            bodyStartingPoint = unitTestCodeFunction.GetStartPoint(vsCMPart.vsCMPartBody);

            boydEditPoint = bodyStartingPoint.CreateEditPoint();

            //FIX ME (tabing)
            boydEditPoint.Insert(StringHelper.GetTabString() + tvFunctionCall + Environment.NewLine);

            //FIX ME (tabbing)
            string tvTempString = string.Empty; // "iv{0}Type.{1}, default({2})";

            tvTempString = "iv{0}Type.{1}, New {2}()";

            tvTempString = string.Format(tvTempString, ((CodeClass)originalClassCodeProperty.Parent).Name, originalClassCodeProperty.Name, tvPropertyTypeAsString);

            boydEditPoint.Insert(Environment.NewLine);
            boydEditPoint.Insert("\t\t\t'TODO: Update Assert to meet test needs" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t'Assert.AreEqual(" + tvTempString + ")" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\t" + Environment.NewLine);
            boydEditPoint.Insert("\t\t\tThrow New Exception 'Not Implemented'" + Environment.NewLine);

            return(unitTestCodeFunction);
        }
Ejemplo n.º 56
0
        //解析接口或类
        void parse_body(EnvDTE.CodeClass codeClass)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            var children = codeClass.Members;

            foreach (CodeElement codeElement in children)
            {
                //解析方法定义,只解析公有方法
                if (codeElement.Kind == vsCMElement.vsCMElementFunction)
                {
                    CodeFunction codeFunction = codeElement as CodeFunction;
                    if (codeFunction.Access == vsCMAccess.vsCMAccessPublic)
                    {
                        CodeFunctionInfo func_info = new CodeFunctionInfo();
                        //解析返回值
                        var returnType = codeFunction.Type.AsFullName;
                        func_info.ReturnTypeName = returnType;
                        func_info.IsStatic       = codeFunction.IsShared;

                        //解析参数
                        //string parms = "";
                        string parms_for_invoke = "";

                        foreach (CodeParameter param in codeFunction.Parameters)
                        {
                            //TextPoint start = param.GetStartPoint();
                            //TextPoint finish = param.GetEndPoint();
                            //parms += start.CreateEditPoint().GetText(finish) + ",";
                            func_info.ParamList.Add(new CodeParamInfo()
                            {
                                Name = param.Name, TypeName = param.Type.AsFullName
                            });
                            parms_for_invoke += param.Name + ",";
                        }
                        //if (parms.Length > 0) parms = parms.Remove(parms.Length - 1, 1);
                        if (parms_for_invoke.Length > 0)
                        {
                            parms_for_invoke = parms_for_invoke.Remove(parms_for_invoke.Length - 1, 1);
                        }
                        //func_info.ParamString = parms;
                        func_info.InvokeParamString = parms_for_invoke;
                        func_info.ShortName         = codeFunction.Name;
                        var tmps = codeFunction.FullName.Split('.');
                        func_info.Name = tmps[tmps.Length - 1];
                        if (func_info.Name.IndexOf("<") != -1)
                        {
                            var s = func_info.Name.IndexOf("<") + 1;
                            var l = func_info.Name.Length - s - 1;
                            func_info.GenericTypeArguments = func_info.Name.Substring(s, l).Split(',').Select(it => it.Trim()).ToList();
                        }
                        if (func_info.ShortName == this.ShortClassName)
                        {
                            CodeConstructorList.Add(func_info);
                        }
                        else if (func_info.ShortName != codeClass.Name)
                        {
                            CodeFunctionList.Add(func_info);
                        }
                    }
                }
                ////解析属性定义,只解析公有属性
                else if (codeElement.Kind == vsCMElement.vsCMElementProperty)
                {
                    CodeProperty codeProperty = codeElement as CodeProperty;
                    if (codeProperty.Access == vsCMAccess.vsCMAccessPublic)
                    {
                        CodePropertyInfo property_info = new CodePropertyInfo();
                        property_info.Name     = codeProperty.Name;
                        property_info.TypeName = codeProperty.Type.AsFullName;
                        try
                        {
                            var getter = codeProperty.Getter;
                            property_info.HasGet   = getter != null && getter.Access == vsCMAccess.vsCMAccessPublic;
                            property_info.IsStatic = codeProperty.Getter.IsShared;
                        }
                        catch
                        {
                            property_info.HasGet = false;
                        }
                        try
                        {
                            var setter = codeProperty.Setter;
                            property_info.HasSet   = setter != null && setter.Access == vsCMAccess.vsCMAccessPublic;
                            property_info.IsStatic = codeProperty.Setter.IsShared;
                            foreach (CodeParameter param in setter.Parameters)
                            {
                                //TextPoint start = param.GetStartPoint();
                                //TextPoint finish = param.GetEndPoint();
                                //parms += start.CreateEditPoint().GetText(finish) + ",";
                                property_info.ParamList.Add(new CodeParamInfo()
                                {
                                    Name = param.Name, TypeName = param.Type.AsFullName
                                });
                            }
                        }
                        catch
                        {
                            property_info.HasSet = false;
                        }
                        CodePropertyList.Add(property_info);
                    }
                }
                else if (codeElement.Kind == vsCMElement.vsCMElementEvent)
                {
                    CodeEvent codeEvent = codeElement as CodeEvent;
                    if (codeEvent.Access == vsCMAccess.vsCMAccessPublic)
                    {
                        CodeEventInfo codeEventInfo = new CodeEventInfo();
                        codeEventInfo.Name     = codeEvent.Name;
                        codeEventInfo.TypeName = codeEvent.Type.AsFullName;
                        codeEventInfo.IsStatic = codeEvent.IsShared;
                        CodeEventList.Add(codeEventInfo);
                    }
                }
            }
            foreach (CodeClass baseClass in codeClass.Bases)
            {
                if (baseClass.Kind == vsCMElement.vsCMElementClass)
                {
                    parse_body(baseClass);
                    break;
                }
            }
        }
Ejemplo n.º 57
0
 private static bool IsFuncSelected(DTE dte, CodeFunction func)
 {
     int selLine = ((TextSelection)dte.ActiveDocument.Selection).AnchorPoint.Line;
     return func.StartPoint.Line <= selLine
                         && selLine <= func.EndPoint.Line;
 }
Ejemplo n.º 58
0
        //获得单一变量
        private CodeObject GetOneObject()
        {
            CodeObject ret      = null;
            Token      token    = ReadToken();
            bool       not      = false;
            bool       negative = false;
            CALC       calc     = CALC.NONE;

            if (token.Type == TokenType.Not)
            {
                not   = true;
                token = ReadToken();
            }
            else if (token.Type == TokenType.Minus)
            {
                negative = true;
                token    = ReadToken();
            }
            else if (token.Type == TokenType.Increment)
            {
                calc  = CALC.PRE_INCREMENT;
                token = ReadToken();
            }
            else if (token.Type == TokenType.Decrement)
            {
                calc  = CALC.PRE_DECREMENT;
                token = ReadToken();
            }
            switch (token.Type)
            {
            case TokenType.Identifier:
                ret = new CodeMember((string)token.Lexeme);
                break;

            case TokenType.Function:
                UndoToken();
                ret = new CodeFunction(ParseFunctionDeclaration(false));
                break;

            case TokenType.LeftPar:
                ret = GetObject();
                ReadRightParenthesis();
                break;

            case TokenType.LeftBracket:
                UndoToken();
                ret = GetArray();
                break;

            case TokenType.LeftBrace:
                UndoToken();
                ret = GetTable();
                break;

            case TokenType.Eval:
                ret = GetEval();
                break;

            case TokenType.Null:
            case TokenType.Boolean:
            case TokenType.Number:
            case TokenType.String:
                ret = new CodeScriptObject(m_script, token.Lexeme);
                break;

            default:
                throw new ParserException("Object起始关键字错误 ", token);
            }
            ret.StackInfo = new StackInfo(m_strBreviary, token.SourceLine);
            ret           = GetVariable(ret);
            ret.Not       = not;
            ret           = GetTernary(ret);
            ret.Negative  = negative;
            if (ret is CodeMember)
            {
                if (calc != CALC.NONE)
                {
                    ((CodeMember)ret).Calc = calc;
                }
                else
                {
                    Token peek = ReadToken();
                    if (peek.Type == TokenType.Increment)
                    {
                        calc = CALC.POST_INCREMENT;
                    }
                    else if (peek.Type == TokenType.Decrement)
                    {
                        calc = CALC.POST_DECREMENT;
                    }
                    else
                    {
                        UndoToken();
                    }
                    if (calc != CALC.NONE)
                    {
                        ((CodeMember)ret).Calc = calc;
                    }
                }
            }
            else if (calc != CALC.NONE)
            {
                throw new ParserException("++ 或者 -- 只支持变量的操作", token);
            }
            return(ret);
        }
Ejemplo n.º 59
0
 private IEnumerable<Tuple<string, string>> GetParamNamesAndTypes(CodeFunction func)
 {
     foreach (CodeParameter param in func.Parameters)
     {
         yield return new Tuple<string, string>(param.FullName, param.Type.AsString);
     }
 }
Ejemplo n.º 60
0
 private OverloadsCollection(
     CodeModelState state,
     CodeFunction parent)
     : base(state, parent)
 {
 }