private INamespaceOrTypeSymbol GetContainer(TypeInfo typeInfo, SymbolInfo symbolInfo)
        {
            INamespaceOrTypeSymbol container = null;

            if (typeInfo.Type != null)
            {
                container = typeInfo.Type;
            }
            else if (symbolInfo.Symbol is INamespaceSymbol)
            {
                container = (INamespaceSymbol)symbolInfo.Symbol;
            }
            else if (symbolInfo.Symbol is IMethodSymbol)
            {
                ITypeSymbol returnType = ((IMethodSymbol)symbolInfo.Symbol).ReturnType;
                container = returnType;
            }
            else if (symbolInfo.Symbol is INamedTypeSymbol)
            {
                var namedType = ((INamedTypeSymbol)symbolInfo.Symbol);
                container = namedType.OriginalDefinition;
            }

            return(container);
        }
        public string GetCallTipTextAtPosition(string code, int position)
        {
            SyntaxTree syntaxTree  = CSharpSyntaxTree.ParseText(code);
            var        options     = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var        compilation = CSharpCompilation.Create("output", options: options)
                                     .AddSyntaxTrees(syntaxTree)
                                     .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoSharpTextWriter).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(IEnumerable <int>).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(IQueryable).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Bson.BsonDocument).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Driver.MongoCollection).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Driver.MongoClient).Assembly.Location)
                                                    );

            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            SyntaxToken token      = syntaxTree.GetRoot().FindToken(position);
            SyntaxNode  identifier = token.Parent;
            SymbolInfo  symbolInfo = semanticModel.GetSymbolInfo(identifier);
            TypeInfo    typeInfo   = semanticModel.GetTypeInfo(identifier);

            ITypeSymbol typeSymbol = typeInfo.Type;

            if (typeSymbol == null && symbolInfo.Symbol != null && symbolInfo.Symbol is ITypeSymbol)
            {
                typeSymbol = (ITypeSymbol)symbolInfo.Symbol.OriginalDefinition;
            }

            var err = (from e in semanticModel.GetDiagnostics()
                       where (e.Severity == DiagnosticSeverity.Error || e.Severity == DiagnosticSeverity.Info) &&
                       position >= e.Location.SourceSpan.Start && position <= (e.Location.SourceSpan.Start + e.Location.SourceSpan.Length)
                       select e.ToString()).ToList();

            if (err.Any())
            {
                return(err[0]);
            }

            if (typeSymbol != null)
            {
                string xmlComments = new XmlCommentsHelper().GetTypeComments(typeSymbol);

                string symbolName = symbolInfo.Symbol == null ? "" : symbolInfo.Symbol.Name + "   ";
                string callTip    = typeSymbol.ToString() + " " + symbolName + Environment.NewLine + "   " + xmlComments;
                callTip = callTip.TrimEnd(new[] { ' ', '\t', '\n' });
                return(Environment.NewLine + "   " + callTip + "   " + Environment.NewLine);
            }
            else if (symbolInfo.Symbol is IMethodSymbol)
            {
                var    method      = ((IMethodSymbol)symbolInfo.Symbol);
                string xmlComments = new XmlCommentsHelper().GetMethodComments(method);

                string callTip = method.ReturnType.Name + " " + symbolInfo.Symbol.ToDisplayString() + Environment.NewLine + "   " + xmlComments;
                callTip = callTip.TrimEnd(new[] { ' ', '\t', '\n' });
                return(Environment.NewLine + "   " + callTip + "   " + Environment.NewLine);
            }

            return(null);
        }
Example #3
0
        private void AnalyzeInvocation(SyntaxNodeAnalysisContext context)
        {
            InvocationExpressionSyntax expressionSyntax = (InvocationExpressionSyntax)context.Node;

            if (!(expressionSyntax.Expression is MemberAccessExpressionSyntax expression))
            {
                return;
            }

            if (expression.Name.Identifier.ValueText != "ToString")
            {
                return;
            }


            TypeInfo type = context.SemanticModel.GetTypeInfo(expression.Expression);

            if (IsItAlreadyObject(type, context))
            {
                return;
            }

            if (HasToStringOverride(type, context))
            {
                return;
            }

            Location loc = expression.GetLocation();

            context.ReportDiagnostic(Diagnostic.Create(Rule, loc));
        }
Example #4
0
        public async Task <(IReadOnlyCollection <(VariableDeclarationSyntax Decl, ITypeSymbol Type)> Variables, IReadOnlyCollection <CSharpSyntaxNode> Methods)> SplitVariableDeclarationsAsync(
            VariableDeclaratorSyntax declarator, HashSet <ILocalSymbol> symbolsToSkip = null, bool preferExplicitType = false)
        {
            var vbInitValue             = GetInitializerToConvert(declarator);
            var initializerOrMethodDecl = await vbInitValue.AcceptAsync(TriviaConvertingExpressionVisitor);

            var vbInitializerTypeInfo = vbInitValue != null?_semanticModel.GetTypeInfo(vbInitValue) : default(TypeInfo?);

            var vbInitializerType = vbInitValue != null ? vbInitializerTypeInfo.Value.Type : default(ITypeSymbol);

            bool          requireExplicitTypeForAll = declarator.Names.Count > 1;
            IMethodSymbol initSymbol = null;

            if (vbInitValue != null)
            {
                TypeInfo expType = vbInitializerTypeInfo.Value;
                preferExplicitType |= ShouldPreferExplicitType(vbInitValue, expType.ConvertedType, out bool vbInitIsNothingLiteral);
                initSymbol          = _semanticModel.GetSymbolInfo(vbInitValue).Symbol as IMethodSymbol;
                bool isAnonymousFunction = initSymbol?.IsAnonymousFunction() == true;
                requireExplicitTypeForAll |= vbInitIsNothingLiteral || isAnonymousFunction;
            }

            var csVars    = new Dictionary <string, (VariableDeclarationSyntax Decl, ITypeSymbol Type)>();
            var csMethods = new List <CSharpSyntaxNode>();

            foreach (var name in declarator.Names)
            {
                var declaredSymbol = _semanticModel.GetDeclaredSymbol(name);
                if (symbolsToSkip?.Contains(declaredSymbol) == true)
                {
                    continue;
                }
                var declaredSymbolType      = declaredSymbol.GetSymbolType();
                var equalsValueClauseSyntax = await ConvertEqualsValueClauseSyntaxAsync(declarator, name, vbInitValue, declaredSymbolType, declaredSymbol, initializerOrMethodDecl);

                var    v = SyntaxFactory.VariableDeclarator(ConvertIdentifier(name.Identifier), null, equalsValueClauseSyntax);
                string k = declaredSymbolType?.GetFullMetadataName() ?? name.ToString();//Use likely unique key if the type symbol isn't available

                if (csVars.TryGetValue(k, out var decl))
                {
                    csVars[k] = (decl.Decl.AddVariables(v), decl.Type);
                    continue;
                }

                if (initializerOrMethodDecl == null || initializerOrMethodDecl is ExpressionSyntax)
                {
                    var variableDeclaration = CreateVariableDeclaration(declarator, preferExplicitType,
                                                                        requireExplicitTypeForAll, vbInitializerType, declaredSymbolType, equalsValueClauseSyntax,
                                                                        initSymbol, v);
                    csVars[k] = (variableDeclaration, declaredSymbolType);
                }
                else
                {
                    csMethods.Add(initializerOrMethodDecl);
                }
            }

            return(csVars.Values, csMethods);
        }
Example #5
0
        private Boolean IsItAlreadyObject(TypeInfo type, SyntaxNodeAnalysisContext context)
        {
            if (type.Type.Equals(context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Object).FullName)))
            {
                return(true);
            }

            return(false);
        }
Example #6
0
 private List <IMethodSymbol> GetTypeToStringMethods(TypeInfo type)
 {
     return(type
            .Type
            .GetMembers("ToString")
            .Where(k => k is IMethodSymbol)
            .OfType <IMethodSymbol>()
            .Where(k => k.IsOverride && k.Kind == SymbolKind.Method)
            .ToList());
 }
Example #7
0
        private Boolean HasToStringOverride(TypeInfo type, SyntaxNodeAnalysisContext context)
        {
            var toStringMethod = GetTypeToStringMethods(type);

            if (toStringMethod.Any())
            {
                if (!IsToStringIsShadow(toStringMethod, context))
                {
                    return(true);
                }
            }

            return(false);
        }
        public string GetCallTipTextAtPosition(string code, int position)
        {
            var syntaxTree    = CSharpSyntaxTree.ParseText(code);
            var semanticModel = GenerateSemanticModel(syntaxTree);

            SyntaxToken token      = syntaxTree.GetRoot().FindToken(position);
            SyntaxNode  identifier = token.Parent;
            SymbolInfo  symbolInfo = semanticModel.GetSymbolInfo(identifier);
            TypeInfo    typeInfo   = semanticModel.GetTypeInfo(identifier);

            ITypeSymbol typeSymbol = typeInfo.Type;

            if (typeSymbol == null && symbolInfo.Symbol != null && symbolInfo.Symbol is ITypeSymbol)
            {
                typeSymbol = (ITypeSymbol)symbolInfo.Symbol.OriginalDefinition;
            }

            var err = (from e in semanticModel.GetDiagnostics()
                       where (e.Severity == DiagnosticSeverity.Error || e.Severity == DiagnosticSeverity.Info) &&
                       position >= e.Location.SourceSpan.Start && position <= (e.Location.SourceSpan.Start + e.Location.SourceSpan.Length)
                       select e.ToString()).ToList();

            if (err.Any())
            {
                return(err[0]);
            }

            if (typeSymbol != null)
            {
                string xmlComments = new XmlCommentsHelper().GetTypeComments(typeSymbol);

                string symbolName = symbolInfo.Symbol == null ? "" : symbolInfo.Symbol.Name + "   ";
                string callTip    = typeSymbol.ToString() + " " + symbolName + Environment.NewLine + "   " + xmlComments;
                callTip = callTip.TrimEnd(new[] { ' ', '\t', '\n' });
                return(Environment.NewLine + "   " + callTip + "   " + Environment.NewLine);
            }
            else if (symbolInfo.Symbol is IMethodSymbol)
            {
                var    method      = ((IMethodSymbol)symbolInfo.Symbol);
                string xmlComments = new XmlCommentsHelper().GetMethodComments(method);

                string callTip = method.ReturnType.Name + " " + symbolInfo.Symbol.ToDisplayString() + Environment.NewLine + "   " + xmlComments;
                callTip = callTip.TrimEnd(new[] { ' ', '\t', '\n' });
                return(Environment.NewLine + "   " + callTip + "   " + Environment.NewLine);
            }

            return(null);
        }
        public List <string> GetCompletionListAtPosition(string source, int position)
        {
            SyntaxTree syntaxTree  = CSharpSyntaxTree.ParseText(source);
            var        options     = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var        compilation = CSharpCompilation.Create("output", options: options)
                                     .AddSyntaxTrees(syntaxTree)
                                     .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoSharpTextWriter).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(IEnumerable <int>).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(IQueryable).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Bson.BsonDocument).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Driver.MongoCollection).Assembly.Location),
                                                    MetadataReference.CreateFromFile(typeof(MongoDB.Driver.MongoClient).Assembly.Location)
                                                    );

            var semanticModel = compilation.GetSemanticModel(syntaxTree);
            //position += 2;
            SyntaxToken token      = syntaxTree.GetRoot().FindToken(position);
            SyntaxNode  identifier = token.Parent;

            if (identifier is ArgumentListSyntax)
            {
                identifier = identifier.Parent;
            }

            TypeInfo   typeInfo   = semanticModel.GetTypeInfo(identifier);
            SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(identifier);

            INamespaceOrTypeSymbol   container = GetContainer(typeInfo, symbolInfo);
            ImmutableArray <ISymbol> symbols   = semanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: container is ITypeSymbol);

            var results = new List <string>();
            var sb      = new StringBuilder();

            foreach (ISymbol symbol in symbols.Where(x => (x.DeclaredAccessibility == Accessibility.Public || x.DeclaredAccessibility == Accessibility.NotApplicable)
                                                     /*&& !x.IsStatic*/))
            {
                sb.AppendLine(symbol.DeclaredAccessibility + " " + symbol.Kind + ": " + symbol.ToDisplayString());

                string symbolName = symbol.Name.Replace('\r', ' ').Replace('\n', ' ').Replace(" ", "");
                if (symbol is IMethodSymbol)
                {
                    if (((IMethodSymbol)symbol).IsGenericMethod)
                    {
                        symbolName += "<>";
                    }
                    if (((IMethodSymbol)symbol).IsExtensionMethod)
                    {
                        symbolName += "?0";
                    }
                    else
                    {
                        symbolName += "?1";
                    }
                }
                else if (symbol is IPropertySymbol)
                {
                    symbolName += "?2";
                }

                results.Add(symbolName);
            }

            results = results.Distinct().OrderBy(x => x).ToList();
            return(results);
        }
        public List<T> Parse<T>(string codeFilePath, string methodName, int paramsCount)
        {
            string sCodeLocation = codeFilePath;
            string sCodeText = File.ReadAllText(sCodeLocation, Encoding.UTF8);

            FileInfo CSProjFile = null;

            #region Find project file.
            FileInfo codeFileInfo = new FileInfo(sCodeLocation);
            FileInfo[] projFileInfos = codeFileInfo.Directory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly);
            projFileInfos = projFileInfos.Where((projFileInfo) => { if (Regex.IsMatch(projFileInfo.FullName, ".*[.]csproj$")) { return true; } return false; }).ToArray();

            DirectoryInfo parentFolder = null;
            int iDeepth = 0;
            while (!projFileInfos.Any())
            {
                iDeepth++;
                parentFolder = codeFileInfo.Directory.Parent;

                projFileInfos = codeFileInfo.Directory.GetFiles("*.csproj", SearchOption.TopDirectoryOnly);
                projFileInfos = projFileInfos.Where((projFileInfo) => { if (Regex.IsMatch(projFileInfo.FullName, ".*[.]csproj$")) { return true; } return false; }).ToArray();

                if (iDeepth > 3 && codeFileInfo.Directory.GetFiles("*.sln", SearchOption.TopDirectoryOnly).Any())
                {
                    break;
                }
            }

            if (projFileInfos.Any())
            {
                CSProjFile = projFileInfos[0];
            }
            else
            {
                throw new FileNotFoundException(string.Format("Can't found the project configuration file. Code file {0}.", codeFilePath));
            }
            #endregion

            #region Get all references
            references = new List<ReferenceInfo>();

            XDocument xdocCSProj = XDocument.Load(CSProjFile.FullName);
            string sXmlns = xdocCSProj.Root.Attribute(XName.Get("xmlns")).Value;
            List<XElement> refNodes = xdocCSProj.Root.Descendants().Where((xe) => { if (xe.Name.LocalName == "Reference") { return true; } return false; }).ToList();

            ReferenceInfo refInfo = null;
            foreach (XElement refNode in refNodes)
            {
                refInfo = new ReferenceInfo();
                refInfo.IsProjectReference = false;
                refInfo.IsTeamCode = true;
                refInfo.Name = refNode.Attribute(XName.Get("Include")).Value;
                if (refNode.HasElements)
                {
                    refInfo.AssemblyLocationForDebug = refNode.Element(XName.Get("HintPath", sXmlns)).Value;
                    refInfo.AssemblyLocationForDebug = Path.Combine(CSProjFile.Directory.FullName, refInfo.AssemblyLocationForDebug);

                    refInfo.AssemblyLocationForRelease = refNode.Element(XName.Get("HintPath", sXmlns)).Value;
                    refInfo.AssemblyLocationForRelease = Path.Combine(CSProjFile.Directory.FullName, refInfo.AssemblyLocationForDebug);
                }
                if (refInfo.AssemblyLocationForDebug == null)
                {
                    refInfo.AssemblyName = refInfo.Name;

                    refInfo.AssemblyLocationForDebug = refInfo.Name;
                    refInfo.AssemblyLocationForRelease = refInfo.Name;
                }
                if (!File.Exists(refInfo.Name))
                {
                    refInfo.IsTeamCode = false;
                }
                else
                {
                    refInfo.LoadedAssembly = Assembly.LoadFile(refInfo.AssemblyLocationForRelease);
                }
                references.Add(refInfo);
            }

            refNodes = xdocCSProj.Root.Descendants().Where((xe) => { if (xe.Name.LocalName == "ProjectReference") { return true; } return false; }).ToList();
            FileInfo refProjFileInfo = null;
            XDocument xdocRefProjFile = null;
            string sRefCSProjXmlns = string.Empty;
            XElement CSProjInfoNode = null;
            foreach (XElement refNode in refNodes)
            {
                refInfo = new ReferenceInfo();
                refInfo.IsProjectReference = true;
                refInfo.IsTeamCode = true;
                refInfo.Name = refNode.Attribute(XName.Get("Include")).Value;

                refProjFileInfo = new FileInfo(Path.Combine(CSProjFile.Directory.FullName, refInfo.Name));
                xdocRefProjFile = XDocument.Load(refProjFileInfo.FullName);

                sRefCSProjXmlns = xdocRefProjFile.Root.Attribute(XName.Get("xmlns")).Value;
                CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("AssemblyName", sRefCSProjXmlns)).FirstOrDefault();
                if (CSProjInfoNode != null)
                {
                    refInfo.AssemblyName = CSProjInfoNode.Value;
                }

                CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("Configuration", sRefCSProjXmlns)).FirstOrDefault();
                if (CSProjInfoNode.Value == "Debug")
                {
                    #region For Debug
                    CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("PropertyGroup", sRefCSProjXmlns))
                    .Where(xe =>
                    {
                        try
                        {
                            if (xe.Attribute(XName.Get("Condition")).Value.Contains("Debug"))
                            {
                                return true;
                            }
                        }
                        catch
                        {
                        }
                        return false;
                    })
                    .FirstOrDefault();
                    CSProjInfoNode = CSProjInfoNode != null ? CSProjInfoNode.Descendants(XName.Get("OutputPath", sRefCSProjXmlns)).FirstOrDefault() : null;
                    if (CSProjInfoNode != null)
                    {
                        refInfo.AssemblyLocationForDebug = CSProjInfoNode.Value;
                        refInfo.AssemblyLocationForDebug = Path.Combine(refProjFileInfo.Directory.FullName, refInfo.AssemblyLocationForDebug);
                        if (!refInfo.AssemblyLocationForDebug.EndsWith(refInfo.AssemblyName + ".dll"))
                        {
                            refInfo.AssemblyLocationForDebug = Path.Combine(refInfo.AssemblyLocationForDebug, refInfo.AssemblyName + ".dll");
                        }
                    }
                    #endregion
                }
                else
                {
                    #region For Release
                    CSProjInfoNode = xdocRefProjFile.Root.Descendants(XName.Get("PropertyGroup", sRefCSProjXmlns))
                        .Where(xe =>
                    {
                        try
                        {
                            if (xe.Attribute(XName.Get("Condition")).Value.Contains("Release"))
                            {
                                return true;
                            }
                        }
                        catch
                        {
                        }
                        return false;
                    })
                        .FirstOrDefault();
                    CSProjInfoNode = CSProjInfoNode != null ? CSProjInfoNode.Descendants(XName.Get("OutputPath", sRefCSProjXmlns)).FirstOrDefault() : null;
                    if (CSProjInfoNode != null)
                    {
                        refInfo.AssemblyLocationForRelease = CSProjInfoNode.Value;
                        refInfo.AssemblyLocationForRelease = Path.Combine(refProjFileInfo.Directory.FullName, refInfo.AssemblyLocationForRelease);
                        if (!refInfo.AssemblyLocationForRelease.EndsWith(refInfo.AssemblyName + ".dll"))
                        {
                            refInfo.AssemblyLocationForRelease = Path.Combine(refInfo.AssemblyLocationForRelease, refInfo.AssemblyName + ".dll");
                        }
                    }
                    #endregion
                }

                refInfo.Name = refNode.Element(XName.Get("Name", sXmlns)).Value;

                if (File.Exists(refInfo.Name))
                {
                    refInfo.IsTeamCode = false;
                }
                else
                {
                    refInfo.LoadedAssembly = Assembly.LoadFile((refInfo.AssemblyLocationForDebug != null) ? refInfo.AssemblyLocationForDebug : refInfo.AssemblyLocationForRelease);
                }
                references.Add(refInfo);
            }
            #endregion

            CSharpCompilationOptions co = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            List<SyntaxTree> trees = new List<SyntaxTree>();
            trees.Add(CSharpSyntaxTree.ParseText(sCodeText)); 

            
             CSharpCompilation compilation = CSharpCompilation.Create(@"Roslyn_Output.dll"
                , options: co
                , syntaxTrees: trees);

            #region Add reference metadata to compiler.
            MetadataReference mr = null;
            foreach (ReferenceInfo RI in references)
            {
                if (File.Exists(RI.AssemblyLocationForDebug))
                {
                    if (string.IsNullOrEmpty(RI.AssemblyLocationForRelease))
                    {
                        mr = MetadataReference.CreateFromFile(RI.AssemblyLocationForDebug, properties: MetadataReferenceProperties.Assembly);
                    }
                    else
                    {
                        mr = MetadataReference.CreateFromFile(RI.AssemblyLocationForDebug, properties: MetadataReferenceProperties.Assembly);
                    }
                }
                RI.CurrentReferenceMetadata = mr;
                compilation = compilation.AddReferences(RI.CurrentReferenceMetadata);
            }
            #endregion

            #region create compilation unit and 

            SemanticModel semanticModel = compilation.GetSemanticModel(trees[0]);

            
            CompilationUnitSyntax compilationUnit = trees[0].GetCompilationUnitRoot();

            this.usings = compilationUnit.Usings;

            NamespaceDeclarationSyntax namespaceDeclaration = compilationUnit.Members
                .OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
            ClassDeclarationSyntax classDeclaration = namespaceDeclaration.Members
                .OfType<ClassDeclarationSyntax>().FirstOrDefault();

            MethodDeclarationSyntax methodDeclaration = classDeclaration.Members
                .OfType<MethodDeclarationSyntax>()
                .Where(mds
                    => string.Equals(mds.Identifier.ValueText, methodName) && mds.ParameterList.Parameters.Count >= paramsCount)
                .FirstOrDefault();

            ParameterSyntax parameter = methodDeclaration.ParameterList.Parameters[0];
            #endregion

            //(methodDeclaration.Body.Statements[1] as StatementSyntax);

            //MethodSymbol members = semanticModel.GetDeclaredSymbol(methodDeclaration);
            //// (line - column) information - start at 0.
            //string lcInfo = members.Locations[0].GetLineSpan(true).ToString();

            //Symbol symbolAt44 = semanticModel.LookupSymbols(compilationUnit.DescendantTokens().ToArray()[44].FullSpan.End).FirstOrDefault();

            List<InvocationExpressionSyntax> methodCalls = methodDeclaration.Body.DescendantNodes()
                .OfType<InvocationExpressionSyntax>().ToList();

            

            string sMethodName = (methodCalls[3].Expression as MemberAccessExpressionSyntax).GetLastToken().ValueText;
            ExpressionSyntax es0 = methodDeclaration
                .FindToken((methodCalls[3] as InvocationExpressionSyntax).Expression.FullSpan.Start)
                .Parent as ExpressionSyntax;
            string varType0 = es0.Kind().ToString();// IdentifierName

            if (es0.Kind() == SyntaxKind.IdentifierName)
            {
                SyntaxToken[] callSeq = (methodCalls[3].Expression as MemberAccessExpressionSyntax).DescendantTokens()
                    .Where(st => { if (st.Kind() == SyntaxKind.IdentifierToken) { return true; } return false; }).ToArray();

                SymbolInfo symbolInfo0 = semanticModel.GetSymbolInfo(es0);
                Microsoft.CodeAnalysis.TypeInfo ti = semanticModel.GetTypeInfo(es0);
                string sVariableTypeName = ti.Type.Name; // first token type name. cpb1

                Type tCPB = SearchTypeInAllAssemblies(sVariableTypeName);
                
                MemberInfo memberInfo = null;
                Type sNextType = null;
                int iSearchStart = 1;
                for (; iSearchStart < callSeq.Length; iSearchStart++)
                {
                    memberInfo = tCPB.GetMembers()
                        .Where(mi =>
                        {
                            if (string.Equals(mi.Name, callSeq[iSearchStart].ValueText))
                            {
                                return true;
                            }
                            return false;
                        })
                        .FirstOrDefault();

                    if (memberInfo != null)
                    {
                        switch (memberInfo.MemberType)
                        {
                            case MemberTypes.Field:
                                sNextType = (memberInfo as FieldInfo).FieldType;
                                break;
                            case MemberTypes.Property:
                                sNextType = (memberInfo as PropertyInfo).PropertyType;
                                break;
                            case MemberTypes.Method:
                                sNextType = (memberInfo as MethodInfo).ReturnType;
                                break;
                        }
                        tCPB = sNextType;
                        sNextType = null;
                    }
                    else
                    {
                        break;
                    }
                }

                // Most possibility is extension method. 
                if (memberInfo == null)
                {
                }

                MethodInfo target = memberInfo as MethodInfo;
            }

            foreach (ReferenceInfo RI in references.Where(e => e.LoadedAssembly != null))
            {
                RI.LoadedAssembly = null;
            }

            return null;
        }
        public SymbolResult LookupSymbols(string source, int pos, char c)
        {
            var result = new SymbolResult();

            SyntaxTree syntaxTree  = CSharpSyntaxTree.ParseText(source);
            var        options     = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var        compilation = CSharpCompilation.Create("output", options: options)
                                     .AddSyntaxTrees(syntaxTree)
                                     .AddReferences(new MetadataFileReference(typeof(object).Assembly.Location),
                                                    new MetadataFileReference(typeof(MongoSharpTextWriter).Assembly.Location),
                                                    new MetadataFileReference(typeof(IEnumerable <int>).Assembly.Location),
                                                    new MetadataFileReference(typeof(IQueryable).Assembly.Location),
                                                    new MetadataFileReference(typeof(MongoDB.Bson.BsonDocument).Assembly.Location),
                                                    new MetadataFileReference(typeof(MongoDB.Driver.MongoCollection).Assembly.Location));

            SemanticModel semanticModel = compilation.GetSemanticModel(syntaxTree);

            if (c == '.')
            {
                SyntaxToken syntaxToken = syntaxTree.GetRoot().FindToken(pos - 2);
                SyntaxNode  syntaxNode  = syntaxToken.Parent;
                if (syntaxNode is ArgumentListSyntax)
                {
                    syntaxNode = syntaxNode.Parent;
                }

                TypeInfo   typeInfo   = semanticModel.GetTypeInfo(syntaxNode);
                SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(syntaxNode);

                INamespaceOrTypeSymbol   container = GetContainer(typeInfo, symbolInfo);
                ImmutableArray <ISymbol> symbols   = semanticModel.LookupSymbols(pos - 2, container, includeReducedExtensionMethods: container is ITypeSymbol);
                result.Symbols.AddRange(symbols.ToList());
            }
            else if (c == '(')
            {
                SyntaxToken        token      = syntaxTree.GetRoot().FindToken(pos - 2);
                SyntaxNode         identifier = token.Parent;
                ArgumentListSyntax arglist    = null;
                if (identifier is ArgumentListSyntax)
                {
                    arglist    = identifier as ArgumentListSyntax;
                    identifier = identifier.Parent;
                }

                var symbolInfo = semanticModel.GetSymbolInfo(identifier);
                if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure &&
                    symbolInfo.CandidateSymbols.Length > 0 && symbolInfo.CandidateSymbols[0].Kind == SymbolKind.Method)
                {
                    if (arglist != null)
                    {
                        List <ArgumentSyntax> args = arglist.Arguments.ToList();
                        var ex = args[0].Expression;
                    }

                    var methodSymbol = ((IMethodSymbol)symbolInfo.CandidateSymbols[0]);
                    result.MethodInfos.AddRange(GetMethodInfos(methodSymbol).ConvertAll(x => new MethodResult {
                        MethodInfo = x
                    }));
                }
                else if (symbolInfo.Symbol is IMethodSymbol)
                {
                    var methodSymbol = ((IMethodSymbol)symbolInfo.Symbol);
                    result.MethodInfos.AddRange(GetMethodInfos(methodSymbol).ConvertAll(x => new MethodResult {
                        MethodInfo = x
                    }));
                }
                else if (symbolInfo.Symbol is ITypeSymbol)
                {
                    var typeSymbol = symbolInfo.Symbol as ITypeSymbol;
                    result.ConstructorInfos.AddRange(GetConstructorInfos(typeSymbol).ConvertAll(x => new ConstructorResult {
                        ConstructorInfo = x
                    }));
                }
            }
            else
            {
            }


            return(result);
        }
        public SymbolResult LookupSymbols(string source, int pos, char c)
        {
            var result = new SymbolResult();

            var syntaxTree    = CSharpSyntaxTree.ParseText(source);
            var semanticModel = GenerateSemanticModel(syntaxTree);

            if (c == '.')
            {
                SyntaxToken syntaxToken = syntaxTree.GetRoot().FindToken(pos - 2);
                SyntaxNode  syntaxNode  = syntaxToken.Parent;
                if (syntaxNode is ArgumentListSyntax)
                {
                    syntaxNode = syntaxNode.Parent;
                }

                TypeInfo   typeInfo   = semanticModel.GetTypeInfo(syntaxNode);
                SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(syntaxNode);

                INamespaceOrTypeSymbol   container = GetContainer(typeInfo, symbolInfo);
                ImmutableArray <ISymbol> symbols   = semanticModel.LookupSymbols(pos - 2, container, includeReducedExtensionMethods: container is ITypeSymbol);
                result.Symbols.AddRange(symbols.ToList());
            }
            else if (c == '(')
            {
                SyntaxToken        token      = syntaxTree.GetRoot().FindToken(pos - 2);
                SyntaxNode         identifier = token.Parent;
                ArgumentListSyntax arglist    = null;
                if (identifier is ArgumentListSyntax)
                {
                    arglist    = identifier as ArgumentListSyntax;
                    identifier = identifier.Parent;
                }

                var symbolInfo = semanticModel.GetSymbolInfo(identifier);
                if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure &&
                    symbolInfo.CandidateSymbols.Length > 0 && symbolInfo.CandidateSymbols[0].Kind == SymbolKind.Method)
                {
                    if (arglist != null)
                    {
                        List <ArgumentSyntax> args = arglist.Arguments.ToList();
                        var ex = args[0].Expression;
                    }

                    var methodSymbol = ((IMethodSymbol)symbolInfo.CandidateSymbols[0]);
                    result.MethodInfos.AddRange(GetMethodInfos(methodSymbol).ConvertAll(x => new MethodResult {
                        MethodInfo = x
                    }));
                }
                else if (symbolInfo.Symbol is IMethodSymbol)
                {
                    var methodSymbol = ((IMethodSymbol)symbolInfo.Symbol);
                    result.MethodInfos.AddRange(GetMethodInfos(methodSymbol).ConvertAll(x => new MethodResult {
                        MethodInfo = x
                    }));
                }
                else if (symbolInfo.Symbol is ITypeSymbol)
                {
                    var typeSymbol = symbolInfo.Symbol as ITypeSymbol;
                    result.ConstructorInfos.AddRange(GetConstructorInfos(typeSymbol).ConvertAll(x => new ConstructorResult {
                        ConstructorInfo = x
                    }));
                }
            }
            else
            {
            }


            return(result);
        }
 public static AnnotatedType GetAnnotatedTypeForConverted(this TypeInfo typeInfo) => new AnnotatedType(typeInfo.ConvertedType);
 public static AnnotatedType GetAnnotatedType(this TypeInfo typeInfo) => new AnnotatedType(typeInfo.Type);
Example #15
0
 public static string GetFullName(this TypeInfo typeInfo)
 {
     return(typeInfo.ConvertedType.GetFullName());
 }
Example #16
0
        public static CSharpCompilation RemapDynamicVariables(CSharpCompilation cs)
        {
            var sem  = cs.GetSemanticModel(systree, true);
            var node = systree.GetRoot();

            var vars = node.DescendantNodes()
                       .OfType <LocalDeclarationStatementSyntax>()
                       .ToArray();

            for (int i = 0; i < vars.Count(); i++)
            {
                LocalDeclarationStatementSyntax lds = vars[i];
                VariableDeclaratorSyntax        vds = lds.Declaration.Variables.First();

                Microsoft.CodeAnalysis.TypeInfo initInformation
                    = sem.GetTypeInfo(vds.Initializer.Value);

                var varType     = lds.Declaration.Type;
                var _returnType = SyntaxFactory.IdentifierName
                                      (initInformation.Type.Name + " "); // For the sb.replace
                var returnType = SyntaxFactory.IdentifierName
                                     (initInformation.Type.Name);

                if (initInformation.Type.TypeKind == TypeKind.Array)
                {
                    continue;
                }
                else if (initInformation.Type.Name.Equals("List"))
                {
                    continue;
                }

                var _newDec = lds.ReplaceNode(varType, _returnType); // For the sb.replace

                var newDec = lds.ReplaceNode(varType, returnType);
                var newRt  = node.ReplaceNode(lds, newDec);

                string base1 = lds.ToFullString().Replace("\n", "").Trim();
                string base2 = _newDec.ToFullString().Replace("\n", "").Trim();
                sb = sb.Replace(base1, base2);

                node = newRt;

                SyntaxTree oldTree = cs.SyntaxTrees[0];
                SyntaxTree newTree = node.SyntaxTree;
                cs   = cs.ReplaceSyntaxTree(oldTree, newTree);
                sem  = cs.GetSemanticModel(newTree);
                vars = node.DescendantNodes()
                       .OfType <LocalDeclarationStatementSyntax>()
                       .ToArray();
            }
            var newsys = systree.WithRootAndOptions(node, new CSharpParseOptions());

            systree = newsys;

            Program.WriteCode(sb.ToString());

            return(CSharpCompilation.Create(
                       cs.AssemblyName, new[] { systree },
                       cs.References, cs.Options));
        }