Пример #1
0
        /// <summary>
        /// This method will format the label of the SignatureInformation with procedure's name and all the expected arguments
        /// </summary>
        /// <param name="procedure">The selected procedure</param>
        /// <returns></returns>
        public static SignatureInformation SignatureHelperSignatureFormatter(FunctionDeclaration procedure)
        {
            var parametersInfo = new ParameterInformation[procedure.Profile.Parameters.Count];
            int i = 0; bool firstPass = true;

            foreach (var parameter in procedure.Profile.InputParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "INPUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null); //Replace null with commented documentation linked to parameter

                i++; firstPass = false;
            }
            firstPass = true;
            foreach (var parameter in procedure.Profile.InoutParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "IN-OUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null);

                i++; firstPass = false;
            }
            firstPass = true;
            foreach (var parameter in procedure.Profile.OutputParameters)
            {
                var label = string.Format("{0}{1}({2})", firstPass ? "OUTPUT " : null, parameter.DataName, parameter.DataType.Name);
                parametersInfo[i] = new ParameterInformation(label, null);

                i++; firstPass = false;
            }

            return(new SignatureInformation(procedure.Name, null, parametersInfo)); //Replace null with commented documentation linked to procedure declaration
        }
        public SignatureHelp OnTextDocumentSignaureHelp(JToken arg)
        {
            Log("textDocument/signatureHelp", arg);

            var signatures = new List <SignatureInformation>();

            for (int i = 0; i < 2; ++i)
            {
                var signature = new SignatureInformation
                {
                    Documentation = "Signature documentation " + i,
                    Label         = "Signature " + i
                };

                var parameters = new List <ParameterInformation>();

                for (int j = 0; j < 3; ++j)
                {
                    var parameter = new ParameterInformation
                    {
                        Documentation = "Parameter documentation " + i,
                        Label         = "Parameter " + i
                    };
                }

                signature.Parameters = parameters.ToArray();

                signatures.Add(signature);
            }

            return(new SignatureHelp
            {
                Signatures = signatures.ToArray()
            });
        }
        public void SimpleTest(string expected)
        {
            var model = new ParameterInformation {
                Documentation = "docs",
                Label         = "label"
            };
            var result = Fixture.SerializeObject(model);

            result.Should().Be(expected);

            var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject <ParameterInformation>(expected);

            deresult.Should().BeEquivalentTo(model);
        }
        public async Task <SignatureHelp> Handle(SignatureHelpParams request, CancellationToken cancellationToken)
        {
            ScriptFile scriptFile =
                _workspaceService.GetFile(
                    request.TextDocument.Uri.ToString());

            ParameterSetSignatures parameterSets =
                await _symbolsService.FindParameterSetsInFileAsync(
                    scriptFile,
                    (int)request.Position.Line + 1,
                    (int)request.Position.Character + 1,
                    _powerShellContextService);

            SignatureInformation[] signatures = s_emptySignatureResult;

            if (parameterSets != null)
            {
                signatures = new SignatureInformation[parameterSets.Signatures.Length];
                for (int i = 0; i < signatures.Length; i++)
                {
                    var parameters = new ParameterInformation[parameterSets.Signatures[i].Parameters.Count()];
                    int j          = 0;
                    foreach (ParameterInfo param in parameterSets.Signatures[i].Parameters)
                    {
                        parameters[j] = CreateParameterInfo(param);
                        j++;
                    }

                    signatures[i] = new SignatureInformation
                    {
                        Label         = parameterSets.CommandName + " " + parameterSets.Signatures[i].SignatureText,
                        Documentation = null,
                        Parameters    = parameters,
                    };
                }
            }

            return(new SignatureHelp
            {
                Signatures = signatures,
                ActiveParameter = null,
                ActiveSignature = 0
            });
        }
        public SignatureHelp OnTextDocumentSignaureHelp(JToken arg)
        {
            Log(Methods.TextDocumentSignatureHelpName, arg);

            var signatures = new List <SignatureInformation>();

            for (int i = 0; i < 2; ++i)
            {
                var signature = new SignatureInformation
                {
                    Documentation = CreateMarkupContent("Signature documentation " + i),
                    Label         = "Signature " + i,
                };

                var parameters = new List <ParameterInformation>();

                for (int j = 0; j < 3; ++j)
                {
                    var parameter = new ParameterInformation
                    {
                        Documentation = CreateMarkupContent("Parameter documentation " + i),
                        Label         = "Parameter " + i
                    };
                    parameters.Add(parameter);
                }

                signature.Parameters = parameters.ToArray();

                signatures.Add(signature);
            }

            return(new SignatureHelp
            {
                Signatures = signatures.ToArray()
            });
        }
Пример #6
0
 public override ParameterInformation CustomizeParameterInformation(ParameterInformation p)
 {
     p.TargetDatabaseType = ConvertGenericTypeToCustomType(p.Type);
     return p;
 }
        public IEnumerable <TypeInformation> GetTypeInformation(byte[] rawAssembly)
        {
            if (rawAssembly == null || rawAssembly.Length == 0)
            {
                return(Enumerable.Empty <TypeInformation>());
            }

            List <TypeInformation> results = new List <TypeInformation>();

            Assembly assembly = Assembly.Load(rawAssembly);

            foreach (TypeInfo typeInfo in assembly.DefinedTypes)
            {
                if (typeInfo != null)
                {
                    if (typeInfo.IsNotPublic)
                    {
                        continue;
                    }

                    TypeInformation typeInformationModel = new TypeInformation()
                    {
                        Name        = typeInfo.Name,
                        Description = GetAttributeProperty(typeInfo.CustomAttributes, "Description", "Description"),
                        Type        = ConvertTypeName(typeInfo.FullName),
                    };

                    List <string> filteredMethodNames = new List <string>()
                    {
                        "MainCalc",
                        "ToString",
                        "GetHashCode",
                        "Equals",
                        "GetType"
                    };


                    List <MethodInformation> methods = new List <MethodInformation>();
                    foreach (MethodInfo methodInfo in typeInfo.GetMethods())
                    {
                        if (IsAggregateFunction(methodInfo.Name))
                        {
                            methods.Add(ConfigureAggregateFunctionMetadata(methodInfo));
                        }
                        else if (filteredMethodNames.Any(f => string.Equals(methodInfo.Name, f, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            continue;
                        }
                        else
                        {
                            if (!methodInfo.IsSpecialName)
                            {
                                List <ParameterInformation> parameters = new List <ParameterInformation>();

                                foreach (ParameterInfo parameter in methodInfo.GetParameters())
                                {
                                    ParameterInformation parameterInformation = new ParameterInformation()
                                    {
                                        Name        = parameter.Name,
                                        Description = parameter.Name,
                                        Type        = ConvertTypeName(parameter.ParameterType),
                                    };

                                    parameters.Add(parameterInformation);
                                }

                                string entityId = null;

                                bool isCustom = false;

                                var calculationAttribute = methodInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CalculationAttribute").FirstOrDefault();

                                if (calculationAttribute != null)
                                {
                                    entityId = calculationAttribute.NamedArguments.Where(a => a.MemberName == "Id").FirstOrDefault().TypedValue.Value?.ToString();
                                    isCustom = true;
                                }

                                MethodInformation methodInformation = new MethodInformation()
                                {
                                    Name       = methodInfo.Name,
                                    ReturnType = ConvertTypeName(methodInfo.ReturnType),
                                    Parameters = parameters,
                                    EntityId   = entityId,
                                    IsCustom   = isCustom
                                };

                                if (string.IsNullOrWhiteSpace(methodInformation.FriendlyName))
                                {
                                    methodInformation.FriendlyName = GetAttributeProperty(methodInfo.CustomAttributes, "Calculation", "Name");
                                }

                                if (string.IsNullOrWhiteSpace(methodInformation.Description))
                                {
                                    methodInformation.Description = GetAttributeProperty(methodInfo.CustomAttributes, "Description", "Description");
                                }

                                methods.Add(methodInformation);
                            }
                        }
                    }

                    List <MethodInformation> fields = new List <MethodInformation>();

                    FieldInfo[] fieldInfos = typeInfo.DeclaredFields.ToArray();

                    foreach (FieldInfo fieldInfo in fieldInfos.Where(m => m.FieldType == typeof(Func <decimal?>)).ToList())
                    {
                        if (!fieldInfo.IsSpecialName)
                        {
                            string entityId = null;

                            bool isCustom = false;

                            var calculationAttribute = fieldInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CalculationAttribute").FirstOrDefault();

                            if (calculationAttribute != null)
                            {
                                entityId = calculationAttribute.NamedArguments.Where(a => a.MemberName == "Id").FirstOrDefault().TypedValue.Value?.ToString();
                                isCustom = true;
                            }

                            MethodInformation methodInformation = new MethodInformation()
                            {
                                Name       = fieldInfo.Name,
                                ReturnType = ConvertTypeName(fieldInfo.ReflectedType),
                                EntityId   = entityId,
                                IsCustom   = isCustom
                            };

                            if (string.IsNullOrWhiteSpace(methodInformation.FriendlyName))
                            {
                                methodInformation.FriendlyName = GetAttributeProperty(fieldInfo.CustomAttributes, "Calculation", "Name");
                            }

                            if (string.IsNullOrWhiteSpace(methodInformation.Description))
                            {
                                methodInformation.Description = GetAttributeProperty(fieldInfo.CustomAttributes, "Description", "Description");
                            }

                            methods.Add(methodInformation);
                        }
                    }

                    List <PropertyInformation> properties = new List <PropertyInformation>();

                    foreach (PropertyInfo property in typeInfo.GetProperties())
                    {
                        if (!property.IsSpecialName && property.MemberType == MemberTypes.Property)
                        {
                            PropertyInformation propertyInformation = new PropertyInformation()
                            {
                                Name = property.Name,
                                Type = ConvertTypeName(property.PropertyType),
                            };

                            if (string.IsNullOrWhiteSpace(propertyInformation.FriendlyName))
                            {
                                propertyInformation.FriendlyName = GetAttributeProperty(property.CustomAttributes, "DatasetRelationship", "Name");
                            }

                            if (string.IsNullOrWhiteSpace(propertyInformation.FriendlyName))
                            {
                                propertyInformation.FriendlyName = GetAttributeProperty(property.CustomAttributes, "Field", "Name");
                            }

                            if (string.IsNullOrWhiteSpace(propertyInformation.FriendlyName))
                            {
                                propertyInformation.FriendlyName = GetAttributeProperty(property.CustomAttributes, "Calculation", "Name");
                            }

                            if (string.IsNullOrWhiteSpace(propertyInformation.Description))
                            {
                                propertyInformation.Description = GetAttributeProperty(property.CustomAttributes, "Description", "Description");
                            }

                            if (string.IsNullOrWhiteSpace(propertyInformation.IsAggregable))
                            {
                                propertyInformation.IsAggregable = GetAttributeProperty(property.CustomAttributes, "IsAggregable", "IsAggregable");
                            }

                            properties.Add(propertyInformation);
                        }
                    }

                    typeInformationModel.Methods    = methods;
                    typeInformationModel.Properties = properties;

                    results.Add(typeInformationModel);
                }
            }
            IEnumerable <TypeInformation> dataTypes = GetDefaultTypes();

            foreach (TypeInformation typeInformation in dataTypes)
            {
                results.Add(typeInformation);
            }

            IEnumerable <TypeInformation> keywords = GetKeywords();

            foreach (TypeInformation typeInformation in keywords)
            {
                results.Add(typeInformation);
            }

            return(results);
        }
Пример #8
0
        public override Task <SignatureHelp> Handle(SignatureHelpParams request, CancellationToken cancellationToken)
        {
            var currentHash = Hash.StringHash(request.TextDocument.Uri.GetFileSystemPath());

            var pos = request.Position;

            TreeSitter.GetSignature(currentHash, pos.Line, pos.Character, out var signatureArrayPtr, out var parameterCount, out var activeParameter, out var errorCount, out var errorRanges);

            if (signatureArrayPtr.ToInt64() == 0)
            {
                return(Task.FromResult(new SignatureHelp()));
            }

            var signaturePtr = System.Runtime.InteropServices.Marshal.ReadIntPtr(signatureArrayPtr);
            var signature    = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(signaturePtr);


            SignatureInformation info = new SignatureInformation();

            info.Label = signature;


            var paramList = new List <ParameterInformation>();

            if (parameterCount > 0)
            {
                for (int i = 0; i < parameterCount; i++)
                {
                    var paramInfo = new ParameterInformation();
                    var paramPtr  = System.Runtime.InteropServices.Marshal.ReadIntPtr(signatureArrayPtr + 8 * (i + 1));;
                    paramInfo.Label = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(paramPtr);
                    paramList.Add(paramInfo);
                }
            }

            info.Parameters = new Container <ParameterInformation>(paramList);


            SignatureHelp help = new SignatureHelp();

            help.Signatures      = new Container <SignatureInformation>(info);
            help.ActiveParameter = activeParameter;
            help.ActiveSignature = 0;


            if (errorCount > 0)
            {
                List <Diagnostic>        diagnostics       = new List <Diagnostic>();
                PublishDiagnosticsParams diagnosticsParams = new PublishDiagnosticsParams();
                diagnosticsParams.Uri = request.TextDocument.Uri;
                unsafe
                {
                    for (int i = 0; i < errorCount; i++)
                    {
                        Range *    errors     = (Range *)errorRanges;
                        var        error      = errors[i];
                        Diagnostic diagnostic = new Diagnostic();
                        diagnostic.Message = "Extra argument";
                        diagnostic.Range   = new OmniSharp.Extensions.LanguageServer.Protocol.Models.Range(
                            new Position(error.startLine, error.startCol),
                            new Position(error.endLine, error.endCol));
                        diagnostics.Add(diagnostic);
                    }
                }

                diagnoser.Add(request.TextDocument.Uri, 1, diagnostics);
            }
            else
            {
                diagnoser.Add(request.TextDocument.Uri, 1, new List <Diagnostic>());
            }

            return(Task.FromResult(help));
        }
        public SignatureHelp GetSignature(IDocumentAnalysis analysis, SourceLocation location)
        {
            if (analysis is EmptyAnalysis)
            {
                return(null);
            }

            ExpressionLocator.FindExpression(analysis.Ast, location,
                                             FindExpressionOptions.Hover, out var node, out var statement, out var scope);

            IMember     value    = null;
            IPythonType selfType = null;
            string      name     = null;
            var         call     = node as CallExpression;

            if (call != null)
            {
                using (analysis.ExpressionEvaluator.OpenScope(analysis.Document, scope)) {
                    switch (call.Target)
                    {
                    case MemberExpression mex:
                        var v = analysis.ExpressionEvaluator.GetValueFromExpression(mex.Target);
                        selfType = v?.GetPythonType();
                        name     = mex.Name;
                        break;

                    case NameExpression ne:
                        name = ne.Name;
                        break;
                    }

                    value = analysis.ExpressionEvaluator.GetValueFromExpression(call.Target);
                }
            }

            var ft = value.TryGetFunctionType();

            if (ft == null)
            {
                return(null);
            }

            var signatures = new SignatureInformation[ft.Overloads.Count];

            for (var i = 0; i < ft.Overloads.Count; i++)
            {
                var o = ft.Overloads[i];

                var signatureLabel = _docSource.GetSignatureString(ft, selfType, out var parameterSpans, i, name);

                var parameterInfo = new ParameterInformation[parameterSpans.Length];
                for (var j = 0; j < parameterSpans.Length; j++)
                {
                    var(ps, p) = parameterSpans[j];

                    parameterInfo[j] = new ParameterInformation {
                        label         = _labelOffsetSupport ? new[] { ps.Start, ps.End } : (object)p.Name,
                        documentation = _docSource.FormatParameterDocumentation(p)
                    };
                }

                signatures[i] = new SignatureInformation {
                    label         = signatureLabel,
                    documentation = _docSource.FormatDocumentation(ft.Documentation),
                    parameters    = parameterInfo
                };
            }

            var index = location.ToIndex(analysis.Ast);

            if (call.GetArgumentAtIndex(analysis.Ast, index, out var activeParameter) && activeParameter < 0)
            {
                // Returned 'true' and activeParameter == -1 means that we are after
                // the trailing comma, so assume partially typed expression such as 'pow(x, y, |)
                activeParameter = call.Args.Count;
            }

            var activeSignature = -1;

            if (activeParameter >= 0)
            {
                // TODO: Better selection of active signature by argument set
                activeSignature = signatures
                                  .Select((s, i) => Tuple.Create(s, i))
                                  .OrderBy(t => t.Item1.parameters.Length)
                                  .FirstOrDefault(t => t.Item1.parameters.Length > activeParameter)
                                  ?.Item2 ?? -1;
            }

            activeSignature = activeSignature >= 0
                ? activeSignature
                : (signatures.Length > 0 ? 0 : -1);

            return(new SignatureHelp {
                signatures = signatures.ToArray(),
                activeSignature = activeSignature,
                activeParameter = activeParameter
            });
        }
        public IEnumerable <TypeInformation> GetTypeInformation(byte[] rawAssembly)
        {
            if (rawAssembly == null || rawAssembly.Length == 0)
            {
                return(Enumerable.Empty <TypeInformation>());
            }

            List <TypeInformation> results = new List <TypeInformation>();

            Assembly      assembly = Assembly.Load(rawAssembly);
            List <string> propertyNamesToFilterFromCalculationContexts = GeneratePropertyNameToFilterForCalculationContexts(assembly);

            TypeInfo[] assemblyDefinedTypes = assembly.DefinedTypes.ToArray();

            foreach (TypeInfo typeInfo in assemblyDefinedTypes)
            {
                if (typeInfo != null)
                {
                    if (typeInfo.IsNotPublic)
                    {
                        continue;
                    }

                    TypeInformation typeInformationModel = new TypeInformation()
                    {
                        Name        = typeInfo.Name,
                        Description = GetAttributeProperty(typeInfo.CustomAttributes, "Description", "Description"),
                        Type        = ConvertTypeName(typeInfo.FullName),
                    };

                    if (typeInfo.Name.EndsWith("Exception", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    if (typeInfo.Name.StartsWith("_Closure$", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    if (typeInfo.Name.Equals("ProjectData", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    bool isTemplateCalculationContainerClass = IsTemplateCalculationContextClass(typeInfo);

                    List <MethodInformation> methods = new List <MethodInformation>();
                    foreach (MethodInfo methodInfo in typeInfo.GetMethods())
                    {
                        if (isTemplateCalculationContainerClass && filteredTemplateCalcMethods.Contains(methodInfo.Name))
                        {
                            continue;
                        }

                        if (IsAggregateFunction(methodInfo.Name))
                        {
                            methods.Add(ConfigureAggregateFunctionMetadata(methodInfo));
                        }
                        else if (filteredMethodNames.Any(f => string.Equals(methodInfo.Name, f, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            continue;
                        }
                        else
                        {
                            if (!methodInfo.IsSpecialName)
                            {
                                List <ParameterInformation> parameters = new List <ParameterInformation>();

                                foreach (ParameterInfo parameter in methodInfo.GetParameters())
                                {
                                    var parameterReturnDetails = ConvertTypeName(parameter.ParameterType);

                                    ParameterInformation parameterInformation = new ParameterInformation()
                                    {
                                        Name        = parameter.Name,
                                        Description = parameter.Name,
                                        Type        = parameterReturnDetails.fullReturnType,
                                        TypeClass   = parameterReturnDetails.directType,
                                    };

                                    parameters.Add(parameterInformation);
                                }

                                string entityId = null;

                                bool isCustom = false;

                                var calculationAttribute = methodInfo.CustomAttributes.Where(c => c.AttributeType.Name == "CalculationAttribute").FirstOrDefault();

                                if (calculationAttribute != null)
                                {
                                    entityId = calculationAttribute.NamedArguments.Where(a => a.MemberName == "Id").FirstOrDefault().TypedValue.Value?.ToString();
                                    isCustom = true;
                                }

                                var(fullReturnType, directType, isNullable) = ConvertTypeName(methodInfo.ReturnType);

                                MethodInformation methodInformation = new MethodInformation()
                                {
                                    Name                 = methodInfo.Name,
                                    ReturnType           = fullReturnType,
                                    ReturnTypeClass      = directType,
                                    ReturnTypeIsNullable = isNullable,
                                    Parameters           = parameters,
                                    EntityId             = entityId,
                                    IsCustom             = isCustom
                                };

                                if (string.IsNullOrWhiteSpace(methodInformation.FriendlyName))
                                {
                                    methodInformation.FriendlyName = GetAttributeProperty(methodInfo.CustomAttributes, "Calculation", "Name");
                                }

                                if (string.IsNullOrWhiteSpace(methodInformation.Description))
                                {
                                    methodInformation.Description = GetAttributeProperty(methodInfo.CustomAttributes, "Description", "Description");
                                }

                                if (methodInfo.GetCustomAttribute <System.ComponentModel.EditorBrowsableAttribute>()?.State != System.ComponentModel.EditorBrowsableState.Never)
                                {
                                    methods.Add(methodInformation);
                                }
                            }
                        }
                    }

                    FieldInfo[] fieldInfos = typeInfo.DeclaredFields.ToArray();

                    List <string> enumValues = new List <string>();
                    AddMethodsForClass(methods, fieldInfos, enumValues);

                    List <PropertyInformation> properties = new List <PropertyInformation>();

                    AddClassProperties(propertyNamesToFilterFromCalculationContexts, typeInfo, isTemplateCalculationContainerClass, properties);

                    typeInformationModel.Methods    = methods;
                    typeInformationModel.Properties = properties;
                    typeInformationModel.EnumValues = enumValues;

                    results.Add(typeInformationModel);
                }
            }
            IEnumerable <TypeInformation> dataTypes = GetDefaultTypes();

            foreach (TypeInformation typeInformation in dataTypes)
            {
                results.Add(typeInformation);
            }

            IEnumerable <TypeInformation> keywords = GetKeywords();

            foreach (TypeInformation typeInformation in keywords)
            {
                results.Add(typeInformation);
            }

            return(results);
        }