Example #1
0
        internal void UpdateFunctionDescriptor(FunctionDescriptor funcDesc)
        {
            Function = funcDesc;

            // Setting 'summary' to 'null' so its value is retrieved later 
            // when 'Summary' property is invoked. See 'Summary' for details.
            summary = null;
        }
        public void DescriptionTest()
        {
            var assembly = System.Reflection.Assembly.UnsafeLoadFrom("FFITarget.dll");
            var testClass = assembly.GetType("FFITarget.DummyZeroTouchClass");

            MethodInfo methodWithDesc = testClass.GetMethod("FunctionWithDescription");
            MethodInfo methodWithoutDesc = testClass.GetMethod("FunctionWithoutDescription");

            NodeDescriptionAttribute atr = new NodeDescriptionAttribute("");
            IEnumerable<TypedParameter> arguments;
            FunctionDescriptor fucDescriptor;

            // 1 case. Method with description.
            var attributes = methodWithDesc.GetCustomAttributes(typeof(NodeDescriptionAttribute), false);
            Assert.IsNotNull(attributes);
            Assert.Greater(attributes.Length, 0);
            atr = attributes[0] as NodeDescriptionAttribute;
            arguments = methodWithDesc.GetParameters().Select(
                arg =>
                {
                    var type = new ProtoCore.Type();
                    type.Name = arg.ParameterType.ToString();
                    return new TypedParameter(arg.Name, type);
                });

            fucDescriptor = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = methodWithDesc.Name,
                Summary = atr.ElementDescription,
                Parameters = arguments
            });

            NodeModel node = new DSFunction(fucDescriptor);
            Assert.AreEqual(atr.ElementDescription + "\n\n" + fucDescriptor.Signature, node.Description);

            // 2 case. Method without description.
            atr = new NodeDescriptionAttribute("");
            attributes = methodWithoutDesc.GetCustomAttributes(typeof(NodeDescriptionAttribute), false);
            Assert.IsNotNull(attributes);
            Assert.AreEqual(attributes.Length, 0);
            arguments = methodWithoutDesc.GetParameters().Select(
                arg =>
                {
                    var type = new ProtoCore.Type();
                    type.Name = arg.ParameterType.ToString();
                    return new TypedParameter(arg.Name, type);
                });

            fucDescriptor = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = methodWithDesc.Name,
                Summary = atr.ElementDescription,
                Parameters = arguments
            });

            node = new DSFunction(fucDescriptor);
            Assert.AreEqual(fucDescriptor.Signature, node.Description);
        }
        private FunctionDescriptor GetConstructorMethod()
        {
            var funcDesc = new FunctionDescriptor(new FunctionDescriptorParams
            {
                Assembly = "MyAssembly.dll",
                ClassName = "MyNamespace.MyClass",
                FunctionName = "MyClass",
                ReturnType = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.kTypeVar),
                FunctionType = FunctionType.Constructor
            });

            return funcDesc;
        }
Example #4
0
        /// <summary>
        ///     Add a function descriptor to the group
        /// </summary>
        /// <param name="function"></param>
        /// <returns></returns>
        internal bool AddFunctionDescriptor(FunctionDescriptor function)
        {
            if (!QualifiedName.Equals(function.QualifiedName) || functions.Contains(function))
                return false;

            functions.Add(function);

            if (functions.Count > 1)
            {
                functions[0].IsOverloaded = true;
                functions[functions.Count - 1].IsOverloaded = true;
            }

            return true;
        }
        private FunctionDescriptor GetMyMethod()
        {
            var parms = new List<TypedParameter>()
            {
                new TypedParameter("a", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.kTypeDouble, 0)),
                new TypedParameter("b", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.kTypeDouble, 0)),
                new TypedParameter("c", TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.kTypeDouble, 0))
            };

            var funcDesc = new FunctionDescriptor(new FunctionDescriptorParams
            {
                Assembly = "MyAssembly.dll",
                ClassName = "MyNamespace.MyClass",
                FunctionName = "MyMethod",
                Parameters = parms,
                ReturnType = TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.kTypeVar),
                FunctionType = FunctionType.InstanceMethod
            });

            parms.ForEach(x => x.UpdateFunctionDescriptor(funcDesc));

            return funcDesc;
        }
        public void TypedParametersToStringTest()
        {
            //1. Foo(x: double, y : double) -> Foo.double-double
            //2. Foo(point : Point) -> Foo.Point
            //3. Foo(a : bool [ ] [ ] , b : var[], c : double[][]) -> Foo.bool2-var1-double2            
            //4. Foo(arr : var[]..[], a : int) -> Foo.varN-int
            //5. Foo(a: Autodesk.DesignScript.Geometry.Circle, b: Xxxx.Yyy.Curve)
            //6. Empty string(a: int)

            // 1 case
            var parameters1 = new List<TypedParameter>();
            parameters1.Add(new TypedParameter("x", new ProtoCore.Type { Name = "double" }));
            parameters1.Add(new TypedParameter("y", new ProtoCore.Type { Name = "double" }));
            var functionItem1 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "Foo", Parameters = parameters1, FunctionType = FunctionType.GenericFunction
            });

            System.Console.WriteLine(functionItem1.Parameters.Count());
            Assert.AreEqual("Foo.double-double", Utils.TypedParametersToString(functionItem1));

            //2 case
            var parameters2 = new List<TypedParameter>();
            parameters2.Add(new TypedParameter("point", new ProtoCore.Type { Name = "Point" }));
            var functionItem2 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "Foo", Parameters = parameters2, FunctionType = FunctionType.GenericFunction
            });

            Assert.AreEqual("Foo.Point", Utils.TypedParametersToString(functionItem2));

            //3 case
            var parameters3 = new List<TypedParameter>();
            parameters3.Add(new TypedParameter("a", new ProtoCore.Type { Name = "bool [ ] [ ] " }));
            parameters3.Add(new TypedParameter("b", new ProtoCore.Type { Name = "var[]" }));
            parameters3.Add(new TypedParameter("c", new ProtoCore.Type { Name = "double[][]" }));
            var functionItem3 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "Foo", Parameters = parameters3, FunctionType = FunctionType.GenericFunction
            });

            Assert.AreEqual("Foo.bool2-var1-double2", Utils.TypedParametersToString(functionItem3));

            //4 case
            var parameters4 = new List<TypedParameter>();
            parameters4.Add(new TypedParameter("arr", new ProtoCore.Type { Name = "var[]..[]" }));
            parameters4.Add(new TypedParameter("a", new ProtoCore.Type { Name = "int" }));
            var functionItem4 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "Foo", Parameters = parameters4, FunctionType = FunctionType.GenericFunction
            });

            Assert.AreEqual("Foo.varN-int", Utils.TypedParametersToString(functionItem4));

            //5 case
            var parameters5 = new List<TypedParameter>();
            parameters5.Add(new TypedParameter("a", new ProtoCore.Type { Name = "Autodesk.DesignScript.Geometry.Circle" }));
            parameters5.Add(new TypedParameter("b", new ProtoCore.Type { Name = "Xxxx.Yyy.Curve" }));
            var functionItem5 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "Foo", Parameters = parameters5, FunctionType = FunctionType.GenericFunction
            });

            Assert.AreEqual("Foo.Circle-Curve", Utils.TypedParametersToString(functionItem5));

            //6 case
            var parameters6 = new List<TypedParameter>();
            parameters6.Add(new TypedParameter("a", new ProtoCore.Type { Name = "int" }));
            var functionItem6 = new FunctionDescriptor(new FunctionDescriptorParams
            {
                FunctionName = "", Parameters = parameters6, FunctionType = FunctionType.GenericFunction
            });

            Assert.AreEqual(".int", Utils.TypedParametersToString(functionItem6));
        }
Example #7
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DSFunction"/> class.
 /// </summary>
 /// <param name="description">Function descritor.</param>
 public DSFunction(FunctionDescriptor functionDescription) 
     : base(new ZeroTouchNodeController<FunctionDescriptor>(functionDescription)) 
 {
 }
Example #8
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DSFunction"/> class.
 /// </summary>
 /// <param name="descriptor">Function descritor.</param>
 public DSFunction(FunctionDescriptor descriptor) 
     : base(new ZeroTouchNodeController<FunctionDescriptor>(descriptor)) 
 { }
Example #9
0
        private void ImportProcedure(string library, ProcedureNode proc)
        {
            string procName = proc.Name;

            if (proc.IsAutoGeneratedThisProc ||
                CoreUtils.IsSetter(procName) ||
                CoreUtils.IsDisposeMethod(procName) ||
                CoreUtils.StartsWithDoubleUnderscores(procName))
            {
                return;
            }

            string           obsoleteMessage = "";
            int              classScope      = proc.ClassID;
            string           className       = string.Empty;
            MethodAttributes methodAttribute = proc.MethodAttribute;
            ClassAttributes  classAttribute  = null;

            if (classScope != Constants.kGlobalScope)
            {
                var classNode = LibraryManagementCore.ClassTable.ClassNodes[classScope];

                classAttribute = classNode.ClassAttributes;
                className      = classNode.Name;
            }

            // MethodAttribute's HiddenInLibrary has higher priority than
            // ClassAttribute's HiddenInLibrary
            var isVisible             = true;
            var canUpdatePeriodically = false;

            if (methodAttribute != null)
            {
                isVisible             = !methodAttribute.HiddenInLibrary;
                canUpdatePeriodically = methodAttribute.CanUpdatePeriodically;
            }
            else
            {
                if (classAttribute != null)
                {
                    isVisible = !classAttribute.HiddenInLibrary;
                }
            }

            FunctionType type;

            if (classScope == Constants.kGlobalScope)
            {
                type = FunctionType.GenericFunction;
            }
            else
            {
                if (CoreUtils.IsGetter(procName))
                {
                    type = proc.IsStatic
                        ? FunctionType.StaticProperty
                        : FunctionType.InstanceProperty;

                    string property;
                    if (CoreUtils.TryGetPropertyName(procName, out property))
                    {
                        procName = property;
                    }
                }
                else
                {
                    if (proc.IsConstructor)
                    {
                        type = FunctionType.Constructor;
                    }
                    else if (proc.IsStatic)
                    {
                        type = FunctionType.StaticMethod;
                    }
                    else
                    {
                        type = FunctionType.InstanceMethod;
                    }
                }
            }

            List <TypedParameter> arguments = proc.ArgumentInfos.Zip(
                proc.ArgumentTypes,
                (arg, argType) =>
            {
                AssociativeNode defaultArgumentNode;
                // Default argument specified by DefaultArgumentAttribute
                // takes higher priority
                if (!TryGetDefaultArgumentFromAttribute(arg, out defaultArgumentNode) &&
                    arg.IsDefault)
                {
                    var binaryExpr = arg.DefaultExpression as BinaryExpressionNode;
                    if (binaryExpr != null)
                    {
                        defaultArgumentNode = binaryExpr.RightNode;
                    }
                }
                string shortName = null;
                if (defaultArgumentNode != null)
                {
                    shortName           = defaultArgumentNode.ToString();
                    var rewriter        = new ElementRewriter(LibraryManagementCore.ClassTable, LibraryManagementCore.BuildStatus.LogSymbolConflictWarning);
                    defaultArgumentNode = defaultArgumentNode.Accept(rewriter);
                }
                return(new TypedParameter(arg.Name, argType, defaultArgumentNode, shortName));
            }).ToList();

            IEnumerable <string> returnKeys = null;

            if (proc.MethodAttribute != null)
            {
                if (proc.MethodAttribute.ReturnKeys != null)
                {
                    returnKeys = proc.MethodAttribute.ReturnKeys;
                }
                if (proc.MethodAttribute.IsObsolete)
                {
                    obsoleteMessage = proc.MethodAttribute.ObsoleteMessage;
                }
            }

            var function = new FunctionDescriptor(new FunctionDescriptorParams
            {
                Assembly              = library,
                ClassName             = className,
                FunctionName          = procName,
                Parameters            = arguments,
                ReturnType            = proc.ReturnType,
                FunctionType          = type,
                IsVisibleInLibrary    = isVisible,
                ReturnKeys            = returnKeys,
                PathManager           = pathManager,
                IsVarArg              = proc.IsVarArg,
                ObsoleteMsg           = obsoleteMessage,
                CanUpdatePeriodically = canUpdatePeriodically,
                IsBuiltIn             = pathManager.PreloadedLibraries.Contains(library),
                IsPackageMember       = packagedLibraries.Contains(library)
            });

            AddImportedFunctions(library, new[] { function });
        }
        private static MemberDocumentNode GetMemberDocumentNode(
            FunctionDescriptor function,
            XmlReader xml )
        {
            //customNodeDefinitions typedParameters don't have functionDescriptors
            if (function == null)
            {
                return null;
            }
            var assemblyName = function.Assembly;

            if (string.IsNullOrEmpty(assemblyName))
                return null;

            var fullyQualifiedName = MemberDocumentNode.MakeFullyQualifiedName
                (assemblyName, GetMemberElementName(function));

            if (!documentNodes.ContainsKey(fullyQualifiedName))
            {
                if (xml == null)
                    xml = DocumentationServices.GetForAssembly(function.Assembly, function.PathManager);
                LoadDataFromXml(xml, assemblyName);
            }

            MemberDocumentNode documentNode = null;
            if (documentNodes.ContainsKey(fullyQualifiedName))
                documentNode = documentNodes[fullyQualifiedName];
            else
            {
                var overloadedName = documentNodes.Keys.
                        Where(key => key.Contains(function.ClassName + "." + function.FunctionName)).FirstOrDefault();

                if (overloadedName == null)
                    return null;
                if (documentNodes.ContainsKey(overloadedName))
                    documentNode = documentNodes[overloadedName];
            }

            return documentNode;
        }
        private static string GetMemberElementName(FunctionDescriptor member)
        {
            char prefixCode;

            string memberName = member.FunctionName;

            if (!string.IsNullOrEmpty(member.ClassName))
            {
                memberName = member.ClassName + "." + member.FunctionName;
            }

            switch (member.Type)
            {
            case FunctionType.Constructor:
                // XML documentation uses slightly different constructor names
                int lastPoint = member.ClassName.LastIndexOf(".");
                if (lastPoint == -1)
                {
                    goto case FunctionType.InstanceMethod;
                }

                string classNameWithoutNamespace = member.ClassName.Substring(lastPoint + 1);
                // If classname is the same as function name, then it's usual constructor.
                // Otherwise it's static method which return type is the same as class.
                if (classNameWithoutNamespace == member.FunctionName)
                {
                    memberName = member.ClassName + ".#ctor";
                }

                goto case FunctionType.InstanceMethod;

            case FunctionType.InstanceMethod:
                prefixCode = 'M';

                // parameters are listed according to their type, not their name
                string paramTypesList = String.Join(
                    ",",
                    member.Parameters.Select(x => x.Type.ToString()).Select(PrimitiveMap).ToArray()
                    );

                if (!String.IsNullOrEmpty(paramTypesList))
                {
                    memberName += "(" + paramTypesList + ")";
                }
                break;

            case FunctionType.StaticMethod:
                goto case FunctionType.InstanceMethod;
                break;

            case FunctionType.InstanceProperty:
                prefixCode = 'P';
                break;

            case FunctionType.StaticProperty:
                goto case FunctionType.InstanceProperty;
                break;

            case FunctionType.GenericFunction:
                return(member.FunctionName);

                break;

            default:
                throw new ArgumentException("Unknown member type", "member");
            }

            // elements are of the form "M:Namespace.Class.Method"
            return(String.Format("{0}:{1}", prefixCode, memberName));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ZeroTouchSearchElement"/> class 
        /// with the DesignScript function description
        /// </summary>
        /// <param name="functionDescriptor"><see cref="FunctionDescriptor"/> object
        /// describing DesignScript function.</param>
        public ZeroTouchSearchElement(FunctionDescriptor functionDescriptor)
        {
            this.functionDescriptor = functionDescriptor;

            Name = functionDescriptor.UserFriendlyName;
            
            if (functionDescriptor.IsOverloaded)
            {
                var parameters = new StringBuilder();
                parameters.Append("(");
                parameters.Append(String.Join(", ", functionDescriptor.Parameters.Select(x => x.Name)));
                parameters.Append(")");

                Parameters = parameters.ToString();
            }
            
            FullCategoryName = functionDescriptor.Category;
            Description = functionDescriptor.Description;
            Assembly = functionDescriptor.Assembly;

            ElementType = ElementTypes.ZeroTouch;

            if (functionDescriptor.IsBuiltIn)
                ElementType |= ElementTypes.BuiltIn;

            if (functionDescriptor.IsPackageMember)
                ElementType |= ElementTypes.Packaged;

            inputParameters = new List<Tuple<string, string>>(functionDescriptor.InputParameters);
            outputParameters = new List<string>() { functionDescriptor.ReturnType.ToShortString() };

            foreach (var tag in functionDescriptor.GetSearchTags())
                SearchKeywords.Add(tag);

            var weights = functionDescriptor.GetSearchTagWeights();
            foreach (var weight in weights)
            {
                // Search tag weight can't be more then 1.
                if (weight <= 1)
                    keywordWeights.Add(weight);
            }

            int weightsCount = weights.Count();
            // If there weren't added weights for search tags, then add default value - 0.5
            if (weightsCount != SearchKeywords.Count)
            {
                int numberOfLackingWeights = SearchKeywords.Count - weightsCount;

                // Number of lacking weights should be more than 0.
                // It can be less then 0 only if there was some mistake in xml file.
                if (numberOfLackingWeights > 0)
                {
                    for (int i = 0; i < numberOfLackingWeights; i++)
                    {
                        keywordWeights.Add(0.5);
                    }
                }

            }

            iconName = GetIconName();
        }
        private static string GetMemberElementName(FunctionDescriptor member)
        {
            char prefixCode;

            string memberName = member.FunctionName;
            if (!string.IsNullOrEmpty(member.ClassName))
                memberName = member.ClassName + "." + member.FunctionName;

            switch (member.Type)
            {
                case FunctionType.Constructor:
                    // XML documentation uses slightly different constructor names
                    int lastPoint = member.ClassName.LastIndexOf(".");
                    if (lastPoint == -1)
                        goto case FunctionType.InstanceMethod;

                    string classNameWithoutNamespace = member.ClassName.Substring(lastPoint + 1);
                    // If classname is the same as function name, then it's usual constructor.
                    // Otherwise it's static method which return type is the same as class.
                    if (classNameWithoutNamespace == member.FunctionName)
                        memberName = member.ClassName + ".#ctor";

                    goto case FunctionType.InstanceMethod;

                case FunctionType.InstanceMethod: 
                     prefixCode = 'M';

                    // parameters are listed according to their type, not their name
                    string paramTypesList = String.Join(
                        ",",
                        member.Parameters.Select(x => x.Type.ToString()).Select(PrimitiveMap).ToArray()
                        );
                    
                    if (!String.IsNullOrEmpty(paramTypesList)) memberName += "(" + paramTypesList + ")";
                    break;

                case FunctionType.StaticMethod:
                    goto case FunctionType.InstanceMethod;
                    break;

                case FunctionType.InstanceProperty:
                    prefixCode = 'P';
                    break;

                case FunctionType.StaticProperty:
                    goto case FunctionType.InstanceProperty;
                    break;
                case FunctionType.GenericFunction:
                    return member.FunctionName;
                    break;

                default:
                    throw new ArgumentException("Unknown member type", "member");
            }

            // elements are of the form "M:Namespace.Class.Method"
            return String.Format("{0}:{1}", prefixCode, memberName);
        }
        private static string GetMemberElement(
            FunctionDescriptor function,
            XmlReader xml,
            DocumentElementType property,
            string paramName = "")
        {
            var documentNode = GetMemberDocumentNode(function, xml);

            if (documentNode == null)
                return String.Empty;

            if (property.Equals(DocumentElementType.Description) && !documentNode.Parameters.ContainsKey(paramName))
                return String.Empty;

            switch (property)
            {
                case DocumentElementType.Summary:
                    return documentNode.Summary;

                case DocumentElementType.Description:
                    return documentNode.Parameters[paramName];

                case DocumentElementType.SearchTags:
                    return documentNode.SearchTags;

                case DocumentElementType.SearchTagWeights:
                    return documentNode.SearchTagWeights;

                default:
                    throw new ArgumentException("property");
            }
        }
Example #15
0
        /// <summary>
        /// This method returns a name for the icon based on name of the node.
        /// </summary>
        /// <param name="descriptor">Function descriptor, that contains all info about node.</param>
        /// <param name="overridePrefix">
        /// overridePrefix is used as default value for generating node icon name.
        /// If overridePrefix is empty, it uses QualifiedName property.
        /// e.g. Autodesk.DesignScript.Geometry.CoordinateSystem.ByOrigin
        /// </param>
        internal static string TypedParametersToString(FunctionDescriptor descriptor, string overridePrefix = "")
        {
            var builder = new StringBuilder();

            foreach (TypedParameter tp in descriptor.Parameters)
            {
                string typeOfParameter = tp.Type.ToString();

                // Check to see if there is array indexer symbols '[]', if so turn their 
                // dimensionality into a number (e.g. 'bool[][]' turned into 'bool2').
                int squareBrackets = typeOfParameter.Count(x => x == '[');
                if (squareBrackets > 0)
                {
                    if (typeOfParameter.Contains("[]..[]"))
                    {
                        // Remove square brackets.
                        typeOfParameter = typeOfParameter.Replace("[]..[]", "");
                        // Add number of them.
                        typeOfParameter = String.Concat(typeOfParameter, "N");
                    }
                    else
                    {
                        // Remove square brackets.
                        int index = typeOfParameter.IndexOf('[');
                        typeOfParameter = typeOfParameter.Substring(0, index).TrimEnd();

                        // Add number of them.
                        typeOfParameter = String.Concat(typeOfParameter, squareBrackets.ToString());
                    }
                }

                if (builder.Length > 0)
                    builder.Append("-");

                typeOfParameter = typeOfParameter.Split('.').Last();
                builder.Append(typeOfParameter);
            }

            // If the caller does not supply a prefix, use default logic to generate one.
            if (string.IsNullOrEmpty(overridePrefix))
                overridePrefix = NormalizeAsResourceName(descriptor.QualifiedName);

            return overridePrefix + "." + builder.ToString();
        }
Example #16
0
 private void AddZeroTouchNodeToSearch(FunctionDescriptor functionDescriptor)
 {
     if (functionDescriptor.IsVisibleInLibrary)
     {
         SearchModel.Add(new ZeroTouchSearchElement(functionDescriptor));
     }
 }
 /// <summary>
 /// Get a summary of a method from its documentation xml,
 /// using the corresponding FunctionDescriptor object.
 /// </summary>
 /// <param name="member">The FunctionDescriptor object corresponding to the method.</param>
 /// <param name="xml"></param>
 /// <returns>The contents of the documentation summary tag.</returns>
 internal static string GetSummary(this FunctionDescriptor member, XmlReader xml = null)
 {
     return(GetMemberElement(member, xml, DocumentElementType.Summary));
 }