Exemplo n.º 1
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlText(CSSyntax.XmlTextSyntax node)
    {
        var TextTokens = TriviaListSupport.TranslateTokenList(node.TextTokens);
        var XmlText    = VBFactory.XmlText(TextTokens);

        return(XmlText);
    }
Exemplo n.º 2
0
        public SyntaxTree SingleFirstPass(Compilation sourceCompilation, SyntaxTree tree)
        {
            var converted     = CSharpConverter.ConvertCompilationTree((CSharpCompilation)sourceCompilation, (CSharpSyntaxTree)tree);
            var convertedTree = VBSyntaxFactory.SyntaxTree(converted);

            return(convertedTree);
        }
Exemplo n.º 3
0
        private SyntaxNode AddFlagAttributeVisualBasic(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var generator = SyntaxGenerator.GetGenerator(document);

            var flagsAttribute = VisualBasicSyntaxFactory.Attribute(VisualBasicSyntaxFactory.ParseName("Flags"));
            var newStatement   = generator.AddAttributes(statement, flagsAttribute);

            var newRoot = root.ReplaceNode(statement, newStatement).WithAdditionalAnnotations(Formatter.Annotation);

            var compilationUnit = (VisualBasicCompilationUnitSyntax)newRoot;

            var importSystemClause =
                VisualBasicSyntaxFactory.SimpleImportsClause(
                    VisualBasicSyntaxFactory.ParseName("System"))
                .WithTrailingTrivia(
                    VisualBasicSyntaxFactory.SyntaxTrivia(
                        Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.EndOfLineTrivia, Environment.NewLine));
            var importsList = VisualBasicSyntaxFactory.SeparatedList(new List <ImportsClauseSyntax> {
                importSystemClause
            });
            var importStatement = VisualBasicSyntaxFactory.ImportsStatement(importsList);

            var imports =
                compilationUnit.Imports.SelectMany(
                    c => c.ImportsClauses.OfType <SimpleImportsClauseSyntax>().Select(i => i.Name.GetText().ToString()));

            if (imports.All(u => u != importSystemClause.Name.GetText().ToString()))
            {
                newRoot = generator.AddNamespaceImports(compilationUnit, importStatement);
            }

            return(newRoot);
        }
        internal static SyntaxTokenList TranslateTokenList(IEnumerable <SyntaxToken> ChildTokens)
        {
            var NewTokenList = new SyntaxTokenList();

            foreach (SyntaxToken token in ChildTokens)
            {
                var NewLeadingTriviaList  = new SyntaxTriviaList();
                var NewTrailingTriviaList = new SyntaxTriviaList();

                string TokenText = token.Text;
                string ValueText = token.ValueText;
                if (token.HasLeadingTrivia)
                {
                    foreach (SyntaxTrivia t in token.LeadingTrivia)
                    {
                        if (t.IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia))
                        {
                            NewLeadingTriviaList = NewLeadingTriviaList.Add(VBFactory.DocumentationCommentExteriorTrivia(token.LeadingTrivia[0].ToString().Replace("///", "'''")));
                            if (!TokenText.StartsWith(" "))
                            {
                                TokenText = " " + TokenText;
                                ValueText = " " + ValueText;
                            }
                        }
                        else
                        {
                        }
                    }
                }

                var switchExpr = token.RawKind;
                switch (switchExpr)
                {
                case (int)CS.SyntaxKind.XmlTextLiteralToken:
                {
                    NewTokenList = NewTokenList.Add(VBFactory.XmlTextLiteralToken(NewLeadingTriviaList, TokenText, ValueText, NewTrailingTriviaList));
                    break;
                }

                case (int)CS.SyntaxKind.XmlTextLiteralNewLineToken:
                {
                    NewTokenList = NewTokenList.Add(VBFactory.XmlTextNewLine(text: Constants.vbCrLf, value: Constants.vbCrLf, NewLeadingTriviaList, NewTrailingTriviaList));
                    break;
                }

                case (int)CS.SyntaxKind.XmlEntityLiteralToken:
                {
                    NewTokenList = NewTokenList.Add(VBFactory.XmlEntityLiteralToken(NewLeadingTriviaList, TokenText, ValueText, NewTrailingTriviaList));
                    break;
                }

                default:
                {
                    break;
                }
                }
            }
            return(NewTokenList);
        }
Exemplo n.º 5
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlName(CSSyntax.XmlNameSyntax node)
    {
        VBSyntax.XmlPrefixSyntax Prefix;
        Prefix = node.Prefix == null ? null : (VBSyntax.XmlPrefixSyntax)node.Prefix.Accept(this);
        var localName = VBFactory.XmlNameToken(node.LocalName.ValueText, default(VBasic.SyntaxKind));

        return(VBFactory.XmlName(Prefix, localName));
    }
Exemplo n.º 6
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlNameAttribute(CSSyntax.XmlNameAttributeSyntax node)
    {
        var    Name        = ((VBSyntax.XmlNodeSyntax)node.Name.Accept(this));
        string ValueString = node.Identifier.ToString();

        VBSyntax.XmlNodeSyntax Value = VBFactory.XmlString(VisualBasicSyntaxFactory.DoubleQuoteToken, SyntaxTokenList.Create(VBFactory.XmlTextLiteralToken(ValueString, ValueString)), VisualBasicSyntaxFactory.DoubleQuoteToken);
        return(VBFactory.XmlAttribute(Name, Value));
    }
Exemplo n.º 7
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlTextAttribute(CSSyntax.XmlTextAttributeSyntax node)
    {
        VBSyntax.XmlNodeSyntax Name = (VBSyntax.XmlNodeSyntax)node.Name.Accept(this);
        var TextTokens = TriviaListSupport.TranslateTokenList(node.TextTokens);
        var XmlText    = VBFactory.XmlText(TextTokens);

        VBSyntax.XmlNodeSyntax Value = VBFactory.XmlString(VisualBasicSyntaxFactory.DoubleQuoteToken, SyntaxTokenList.Create(VBFactory.XmlTextLiteralToken(XmlText.ToString(), XmlText.ToString())), VisualBasicSyntaxFactory.DoubleQuoteToken);
        return(VBFactory.XmlAttribute(Name, Value));
    }
Exemplo n.º 8
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlCrefAttribute(CSSyntax.XmlCrefAttributeSyntax node)
    {
        VBSyntax.XmlNameSyntax Name = (VBSyntax.XmlNameSyntax)node.Name.Accept(this);

        var cref         = node.Cref.Accept(this);
        var SyntaxTokens = new SyntaxTokenList();

        SyntaxTokens = SyntaxTokens.AddRange(cref.DescendantTokens());
        VBSyntax.XmlNodeSyntax Value = VBFactory.XmlString(VisualBasicSyntaxFactory.DoubleQuoteToken, SyntaxTokens, VisualBasicSyntaxFactory.DoubleQuoteToken);
        return(VBFactory.XmlAttribute(Name, Value));
    }
Exemplo n.º 9
0
    public override VBasic.VisualBasicSyntaxNode VisitGenericName(CSSyntax.GenericNameSyntax node)
    {
        var Identifier = VBFactory.Identifier(node.Identifier.ToString());
        var TypeList   = new List <VBSyntax.TypeSyntax>();

        foreach (CSSyntax.TypeSyntax a in node.TypeArgumentList.Arguments)
        {
            VBSyntax.TypeSyntax TypeIdentifier = (VBSyntax.TypeSyntax)a.Accept(this);
            TypeList.Add(TypeIdentifier);
        }
        return(VBFactory.GenericName(Identifier, VBFactory.TypeArgumentList(TypeList.ToArray())));
    }
Exemplo n.º 10
0
    public override VBasic.VisualBasicSyntaxNode VisitQualifiedCref(CSSyntax.QualifiedCrefSyntax QualifiedCref)
    {
        var IdentifierOrTypeName = QualifiedCref.Container.Accept(this);

        VBSyntax.CrefReferenceSyntax Value = (VBSyntax.CrefReferenceSyntax)QualifiedCref.Member.Accept(this);
        VBSyntax.NameSyntax          Identifier;
        Identifier = IdentifierOrTypeName is VBSyntax.NameSyntax ? (VBSyntax.NameSyntax)IdentifierOrTypeName : VBFactory.IdentifierName(IdentifierOrTypeName.ToString());
        var QualifiedNameSyntax = VBFactory.QualifiedName(left: Identifier, VisualBasicSyntaxFactory.DotToken, right: (VBSyntax.SimpleNameSyntax)Value.Name);

        if (Value.Signature == null)
        {
            return(QualifiedNameSyntax);
        }
        return(VBFactory.CrefReference(QualifiedNameSyntax, Value.Signature, null));
    }
Exemplo n.º 11
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlElement(CSSyntax.XmlElementSyntax node)
    {
        var Content = new SyntaxList <VBSyntax.XmlNodeSyntax>();

        VBSyntax.XmlElementStartTagSyntax StartTag = (VBSyntax.XmlElementStartTagSyntax)node.StartTag.Accept(this);

        bool NoEndTag = string.IsNullOrWhiteSpace(node.EndTag.Name.LocalName.ValueText);
        var  EndTag   = NoEndTag ? VBFactory.XmlElementEndTag(((VBSyntax.XmlNameSyntax)StartTag.Name)) : VBFactory.XmlElementEndTag((VBSyntax.XmlNameSyntax)node.EndTag.Name.Accept(this));

        try
        {
            for (int i = 0, loopTo = node.Content.Count - 1; i <= loopTo; i++)
            {
                var C = node.Content[i];
                VBSyntax.XmlNodeSyntax Node1 = (VBSyntax.XmlNodeSyntax)C.Accept(this);
                if (NoEndTag)
                {
                    var LastToken = Node1.GetLastToken();
                    if (LastToken.ValueText.IsNewLine())
                    {
                        Node1 = Node1.ReplaceToken(LastToken, default(SyntaxToken));
                    }
                }
                Content = Content.Add(Node1);
            }

            if (node.EndTag?.HasLeadingTrivia == true && node.EndTag.GetLeadingTrivia()[0].IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia) == true)
            {
                var NewLeadingTriviaList = new SyntaxTriviaList();
                NewLeadingTriviaList = NewLeadingTriviaList.Add(VBFactory.DocumentationCommentExteriorTrivia(node.EndTag.GetLeadingTrivia()[0].ToString().Replace("///", "'''")));
                var NewTokenList = new SyntaxTokenList();
                NewTokenList = NewTokenList.Add(VBFactory.XmlTextLiteralToken(NewLeadingTriviaList, " ", " ", new SyntaxTriviaList()));
                Content      = Content.Add(VBFactory.XmlText(NewTokenList));
                EndTag       = EndTag.WithoutLeadingTrivia();
            }
        }
        catch (OperationCanceledException)
        {
            throw;
        }
        catch (Exception)
        {
        }
        var XmlElement = VBFactory.XmlElement(StartTag, Content, EndTag);

        return(XmlElement);
    }
Exemplo n.º 12
0
 public override VBasic.VisualBasicSyntaxNode VisitXmlEmptyElement(CSSyntax.XmlEmptyElementSyntax node)
 {
     try
     {
         VBSyntax.XmlNodeSyntax Name = (VBSyntax.XmlNodeSyntax)node.Name.Accept(this);
         var ListOfAttributes        = GatherAttributes(node.Attributes);
         return(VBFactory.XmlEmptyElement(Name, ListOfAttributes));
     }
     catch (OperationCanceledException)
     {
         throw;
     }
     catch (Exception)
     {
         return(VBFactory.XmlText(node.GetText().ToString()));
     }
 }
Exemplo n.º 13
0
    public override VBasic.VisualBasicSyntaxNode VisitNameMemberCref(CSSyntax.NameMemberCrefSyntax node)
    {
        var Name           = node.Name.Accept(this);
        var CrefParameters = new List <VBSyntax.CrefSignaturePartSyntax>();

        VBSyntax.CrefSignatureSyntax Signature = null;
        if (node.Parameters != null)
        {
            foreach (CSSyntax.CrefParameterSyntax p in node.Parameters.Parameters)
            {
                VBSyntax.TypeSyntax TypeSyntax1 = (VBSyntax.TypeSyntax)p.Accept(this);
                CrefParameters.Add(VBFactory.CrefSignaturePart(modifier: default(SyntaxToken), TypeSyntax1));
            }
            Signature = VBFactory.CrefSignature(CrefParameters.ToArray());
        }
        return(VBFactory.CrefReference((VBSyntax.TypeSyntax)Name, signature: Signature, asClause: null));
    }
Exemplo n.º 14
0
    public override VBasic.VisualBasicSyntaxNode VisitPredefinedType(CSSyntax.PredefinedTypeSyntax node)
    {
        var Token      = VBUtil.ConvertTypesTokenToKind(CS.CSharpExtensions.Kind(node.Keyword), true);
        var switchExpr = Token.RawKind;

        switch (switchExpr)
        {
        case (int)VBasic.SyntaxKind.EmptyToken:
        {
            return(VBFactory.ParseTypeName(node.ToString()));
        }

        case (int)VBasic.SyntaxKind.NothingKeyword:
        {
            return(VisualBasicSyntaxFactory.NothingExpression);
        }

        default:
        {
            return(VBFactory.PredefinedType(Token));
        }
        }
    }
Exemplo n.º 15
0
    internal IEnumerable <SyntaxTrivia> ConvertTrivia(IReadOnlyCollection <SyntaxTrivia> TriviaToConvert)
    {
        var TriviaList = new List <SyntaxTrivia>();

        if (TriviaToConvert == null)
        {
            return(TriviaList);
        }
        int TriviaCount = TriviaToConvert.Count - 1;

        for (int i = 0, loopTo = TriviaCount; i <= loopTo; i++)
        {
            var Trivia     = TriviaToConvert.ElementAtOrDefault(i);
            var NextTrivia = i < TriviaCount?TriviaToConvert.ElementAtOrDefault(i + 1) : default(SyntaxTrivia);

            var switchExpr = Trivia.RawKind;
            switch (switchExpr)
            {
            case (int)CS.SyntaxKind.MultiLineCommentTrivia: {
                var Lines = Trivia.ToFullString().Substring(2).Split(new[] { "\r\n" }, StringSplitOptions.None);
                foreach (string line in Lines)
                {
                    if (line.EndsWith("*/", StringComparison.InvariantCulture))
                    {
                        TriviaList.Add(VBFactory.CommentTrivia($"' {RemoveLeadingSpacesStar(line.Substring(0, line.Length - 2))}"));
                        if (Trivia.ToFullString().EndsWith(Constants.vbLf, StringComparison.InvariantCulture))
                        {
                            TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                        }
                    }
                    else
                    {
                        TriviaList.Add(VBFactory.CommentTrivia($"' {RemoveLeadingSpacesStar(line)}"));
                        TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                    }
                    if (Lines.Length == 1 && (i == TriviaCount || !TriviaToConvert.ElementAtOrDefault(i + 1).IsEndOfLine()))
                    {
                        TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                    }
                }

                break;
            }

            case (int)CS.SyntaxKind.MultiLineDocumentationCommentTrivia: {
                CSSyntax.StructuredTriviaSyntax sld = (CSSyntax.StructuredTriviaSyntax)Trivia.GetStructure();
                foreach (SyntaxNode t1 in sld.ChildNodes())
                {
                    var Lines = t1.ToFullString().ConsistentNewlines().Split(new[] { "\r\n" }, StringSplitOptions.None);
                    foreach (string line in Lines)
                    {
                        if (line.StartsWith("/*", StringComparison.InvariantCulture))
                        {
                            TriviaList.Add(VBFactory.CommentTrivia($"' {RemoveLeadingSpacesStar(line.Substring(1, line.Length - 1))}"));
                            TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                        }
                        else
                        {
                            TriviaList.Add(VBFactory.CommentTrivia($"' {RemoveLeadingSpacesStar(line)}"));
                            TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                        }
                    }
                }

                break;
            }

            default: {
                var convertedTrivia = ConvertTrivia(Trivia);
                TriviaList.Add(convertedTrivia);
                if (Trivia.IsKind(CS.SyntaxKind.SingleLineCommentTrivia))
                {
                    if (!NextTrivia.IsKind(CS.SyntaxKind.EndOfLineTrivia))
                    {
                        TriviaList.Add(VisualBasicSyntaxFactory.VBEOLTrivia);
                    }
                }

                break;
            }
            }
        }
        return(TriviaList);
    }
Exemplo n.º 16
0
    internal SyntaxTrivia ConvertTrivia(SyntaxTrivia t)
    {
        var switchExpr = t.RawKind;

        /* TODO ERROR: Skipped RegionDirectiveTrivia */
        switch (switchExpr)
        {
        case (int)CS.SyntaxKind.WhitespaceTrivia: {
            return(VBFactory.WhitespaceTrivia(t.ToString()));
        }

        case (int)CS.SyntaxKind.EndOfLineTrivia: {
            return(VisualBasicSyntaxFactory.VBEOLTrivia);
        }

        case (int)CS.SyntaxKind.SingleLineCommentTrivia: {
            if (t.ToFullString().EndsWith("*/", StringComparison.InvariantCulture))
            {
                return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2, t.ToFullString().Length - 4))}"));
            }
            return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2))}"));
        }

        case (int)CS.SyntaxKind.MultiLineCommentTrivia: {
            if (t.ToFullString().EndsWith("*/", StringComparison.InvariantCulture))
            {
                return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2, t.ToFullString().Length - 4)).Replace(Constants.vbLf, "").Replace(Constants.vbCr, "")}"));
            }
            return(VBFactory.CommentTrivia($"'{ReplaceLeadingSlashes(t.ToFullString().Substring(2)).Replace(Constants.vbLf, "").Replace(Constants.vbCr, "")}"));
        }

        case (int)CS.SyntaxKind.DocumentationCommentExteriorTrivia: {
            return(VBFactory.SyntaxTrivia(VBasic.SyntaxKind.CommentTrivia, "'''"));
        }

        case (int)CS.SyntaxKind.DisabledTextTrivia: {
            if (TriviaDepth > 0)
            {
                return(VBFactory.DisabledTextTrivia(t.ToString().WithoutNewLines(' ')));
            }
            return(VBFactory.DisabledTextTrivia(t.ToString().ConsistentNewlines()));
        }

        case (int)CS.SyntaxKind.PreprocessingMessageTrivia: {
            return(VBFactory.CommentTrivia($" ' {t}"));
        }

        case (int)CS.SyntaxKind.None: {
            return(default(SyntaxTrivia));
        }
        }

        /* TODO ERROR: Skipped EndRegionDirectiveTrivia */
        /* TODO ERROR: Skipped RegionDirectiveTrivia */
        CSSyntax.StructuredTriviaSyntax StructuredTrivia = (CSSyntax.StructuredTriviaSyntax)t.GetStructure();
        Debug.Assert(StructuredTrivia != null, $"Found new type of non structured trivia {t.RawKind}");
        var switchExpr1 = t.RawKind;

        switch (switchExpr1)
        {
        case (int)CS.SyntaxKind.DefineDirectiveTrivia: {
            CSSyntax.DefineDirectiveTriviaSyntax DefineDirective = (CSSyntax.DefineDirectiveTriviaSyntax)StructuredTrivia;
            var Name = VBFactory.Identifier(DefineDirective.Name.ValueText);
            VBSyntax.ExpressionSyntax value = VBFactory.TrueLiteralExpression(VisualBasicSyntaxFactory.TrueKeyword);
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(WithConvertedTriviaFrom(VBFactory.ConstDirectiveTrivia(Name, value), DefineDirective), DefineDirective.EndOfDirectiveToken)
                                    ));
        }

        case (int)CS.SyntaxKind.UndefDirectiveTrivia: {
            CSSyntax.UndefDirectiveTriviaSyntax UndefineDirective = (CSSyntax.UndefDirectiveTriviaSyntax)StructuredTrivia;
            var Name = VBFactory.Identifier(UndefineDirective.Name.ValueText);
            VBSyntax.ExpressionSyntax value = VisualBasicSyntaxFactory.NothingExpression;
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(WithConvertedTriviaFrom(VBFactory.ConstDirectiveTrivia(Name, value), UndefineDirective), UndefineDirective.EndOfDirectiveToken)
                                    ));
        }

        case (int)CS.SyntaxKind.EndIfDirectiveTrivia: {
            if (TriviaDepth > 0)
            {
                TriviaDepth -= 1;
                return(VBFactory.CommentTrivia($"' TODO VB does not allow directives here, original statement {t.ToFullString().WithoutNewLines(' ')}"));
            }
            CSSyntax.EndIfDirectiveTriviaSyntax EndIfDirective = (CSSyntax.EndIfDirectiveTriviaSyntax)StructuredTrivia;
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.EndIfDirectiveTrivia().WithConvertedTrailingTriviaFrom(EndIfDirective.EndIfKeyword), EndIfDirective.EndOfDirectiveToken)
                                    ));
        }

        case (int)CS.SyntaxKind.ErrorDirectiveTrivia: {
            CSSyntax.ErrorDirectiveTriviaSyntax ErrorDirective = (CSSyntax.ErrorDirectiveTriviaSyntax)StructuredTrivia;
            return(VBFactory.CommentTrivia($"' TODO: Check VB does not support Error Directive Trivia, Original Directive {ErrorDirective.ToFullString()}"));
        }

        case (int)CS.SyntaxKind.IfDirectiveTrivia: {
            if (t.Token.Parent?.AncestorsAndSelf().OfType <CSSyntax.InitializerExpressionSyntax>().Any() == true)
            {
                TriviaDepth += 1;
            }
            CSSyntax.IfDirectiveTriviaSyntax IfDirective = (CSSyntax.IfDirectiveTriviaSyntax)StructuredTrivia;
            string Expression1 = StringReplaceCondition(IfDirective.Condition.ToString());

            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.IfDirectiveTrivia(VisualBasicSyntaxFactory.IfKeyword, VBFactory.ParseExpression(Expression1)).With(IfDirective.GetLeadingTrivia().ConvertTrivia(), IfDirective.Condition.GetTrailingTrivia().ConvertTrivia()), IfDirective.EndOfDirectiveToken)));
        }

        case (int)CS.SyntaxKind.ElifDirectiveTrivia: {
            if (t.Token.Parent.AncestorsAndSelf().OfType <CSSyntax.InitializerExpressionSyntax>().Any())
            {
                TriviaDepth += 1;
            }
            CSSyntax.ElifDirectiveTriviaSyntax ELIfDirective = (CSSyntax.ElifDirectiveTriviaSyntax)StructuredTrivia;
            string Expression1 = StringReplaceCondition(ELIfDirective.Condition.ToString());

            SyntaxToken IfOrElseIfKeyword;
            if (t.IsKind(CS.SyntaxKind.ElifDirectiveTrivia))
            {
                IfOrElseIfKeyword = VisualBasicSyntaxFactory.ElseIfKeyword;
            }
            else
            {
                IfOrElseIfKeyword = VisualBasicSyntaxFactory.IfKeyword;
            }
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.ElseIfDirectiveTrivia(IfOrElseIfKeyword, VBFactory.ParseExpression(Expression1))
                                                                              .With(ELIfDirective.GetLeadingTrivia().ConvertTrivia(), ELIfDirective.Condition.GetTrailingTrivia().ConvertTrivia())
                                                                              , ELIfDirective.EndOfDirectiveToken)));
        }

        case (int)CS.SyntaxKind.LineDirectiveTrivia: {
            return(VBFactory.CommentTrivia($"' TODO: Check VB does not support Line Directive Trivia, Original Directive {t}"));
        }

        case (int)CS.SyntaxKind.ElseDirectiveTrivia: {
            return(VBFactory.Trivia(WithTrailingEOL(VBFactory.ElseDirectiveTrivia().NormalizeWhitespace().WithConvertedTrailingTriviaFrom(((CSSyntax.ElseDirectiveTriviaSyntax)StructuredTrivia).ElseKeyword))));
        }

        case (int)CS.SyntaxKind.EndRegionDirectiveTrivia: {
            CSSyntax.EndRegionDirectiveTriviaSyntax EndRegionDirective = (CSSyntax.EndRegionDirectiveTriviaSyntax)StructuredTrivia;
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(VBFactory.EndRegionDirectiveTrivia(VisualBasicSyntaxFactory.HashToken, VisualBasicSyntaxFactory.EndKeyword, VisualBasicSyntaxFactory.RegionKeyword), EndRegionDirective.EndOfDirectiveToken)));
        }

        case (int)CS.SyntaxKind.PragmaWarningDirectiveTrivia: {
            // Dim PragmaWarningDirectiveTrivia As CSSyntax.PragmaWarningDirectiveTriviaSyntax = DirectCast(StructuredTrivia, CSSyntax.PragmaWarningDirectiveTriviaSyntax)
            // Dim ErrorList As New List(Of VBS.IdentifierNameSyntax)
            // Dim TrailingTriviaStringBuilder As New StringBuilder
            // For Each i As CSSyntax.ExpressionSyntax In PragmaWarningDirectiveTrivia.ErrorCodes
            // Dim ErrorCode As String = i.ToString
            // If ErrorCode.IsInteger Then
            // ErrorCode = $"CS_{ErrorCode}"
            // End If
            // ErrorList.Add(VBFactory.IdentifierName(ErrorCode))
            // For Each Trivial As SyntaxTrivia In i.GetTrailingTrivia
            // TrailingTriviaStringBuilder.Append(Trivial.ToString)
            // Next
            // Next
            // Dim WarningDirectiveTrivia As VBS.DirectiveTriviaSyntax
            // If PragmaWarningDirectiveTrivia.DisableOrRestoreKeyword.IsKind(CS.SyntaxKind.DisableKeyword) Then
            // WarningDirectiveTrivia = VBFactory.DisableWarningDirectiveTrivia(ErrorList.ToArray)
            // Else
            // WarningDirectiveTrivia = VBFactory.EnableWarningDirectiveTrivia(ErrorList.ToArray)
            // End If
            // Return VBFactory.CommentTrivia($" ' TODO {WarningDirectiveTrivia.NormalizeWhitespace}{TrailingTriviaStringBuilder.ToString}")
            return(default(SyntaxTrivia));
        }

        case (int)CS.SyntaxKind.RegionDirectiveTrivia: {
            CSSyntax.RegionDirectiveTriviaSyntax RegionDirective = (CSSyntax.RegionDirectiveTriviaSyntax)StructuredTrivia;
            var    EndOfDirectiveToken       = RegionDirective.EndOfDirectiveToken;
            string NameString                = $"\"{EndOfDirectiveToken.LeadingTrivia.ToString().Replace("\"", "")}\"";
            var    RegionDirectiveTriviaNode = VBFactory.RegionDirectiveTrivia(VisualBasicSyntaxFactory.HashToken, VisualBasicSyntaxFactory.RegionKeyword, VBFactory.StringLiteralToken(NameString, NameString)
                                                                               ).WithConvertedTrailingTriviaFrom(EndOfDirectiveToken);
            return(VBFactory.Trivia(WithTrailingEOL(RegionDirectiveTriviaNode)));
        }

        case (int)CS.SyntaxKind.SingleLineDocumentationCommentTrivia: {
            CSSyntax.DocumentationCommentTriviaSyntax SingleLineDocumentationComment = (CSSyntax.DocumentationCommentTriviaSyntax)StructuredTrivia;
            var walker = new XMLVisitor();
            walker.Visit(SingleLineDocumentationComment);

            var xmlNodes = new List <VBSyntax.XmlNodeSyntax>();
            for (int i = 0, loopTo = SingleLineDocumentationComment.Content.Count - 1; i <= loopTo; i++)
            {
                var node = SingleLineDocumentationComment.Content[i];
                if (!node.IsKind(CS.SyntaxKind.XmlText) && node.GetLeadingTrivia().Count > 0 && node.GetLeadingTrivia().First().IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia))
                {
                    if (i < SingleLineDocumentationComment.Content.Count - 1)
                    {
                        var NextNode = SingleLineDocumentationComment.Content[i + 1];
                        if (!NextNode.IsKind(CS.SyntaxKind.XmlText) || NextNode.GetLeadingTrivia().Count == 0 || !NextNode.GetLeadingTrivia().First().IsKind(CS.SyntaxKind.DocumentationCommentExteriorTrivia))
                        {
                            xmlNodes.Add(VBFactory.XmlText(" ").WithLeadingTrivia(VBFactory.DocumentationCommentExteriorTrivia("'''")));
                        }
                    }
                    node = node.WithoutLeadingTrivia();
                }
                VBSyntax.XmlNodeSyntax Item = (VBSyntax.XmlNodeSyntax)node.Accept(walker);
                xmlNodes.Add(Item);
            }
            var DocumentationCommentTrivia = VBFactory.DocumentationCommentTrivia(VBFactory.List(xmlNodes.ToArray()));
            if (!DocumentationCommentTrivia.HasLeadingTrivia || !DocumentationCommentTrivia.GetLeadingTrivia()[0].IsKind(VBasic.SyntaxKind.DocumentationCommentExteriorTrivia))
            {
                DocumentationCommentTrivia = DocumentationCommentTrivia.WithLeadingTrivia(VBFactory.DocumentationCommentExteriorTrivia("''' "));
            }
            var _DocumentationComment = VBFactory.Trivia(DocumentationCommentTrivia.WithTrailingTrivia(VBFactory.EndOfLine("")));
            return(_DocumentationComment);
        }

        case (int)CS.SyntaxKind.PragmaChecksumDirectiveTrivia: {
            CSSyntax.PragmaChecksumDirectiveTriviaSyntax PragmaChecksumDirective = (CSSyntax.PragmaChecksumDirectiveTriviaSyntax)StructuredTrivia;
            var Guid1          = VBFactory.ParseToken(PragmaChecksumDirective.Guid.Text.ToUpperInvariant());
            var Bytes          = VBFactory.ParseToken(PragmaChecksumDirective.Bytes.Text);
            var ExternalSource = VBFactory.ParseToken(PragmaChecksumDirective.File.Text);
            return(VBFactory.Trivia(WithAppendedTriviaFromEndOfDirectiveToken(
                                        VBFactory.ExternalChecksumDirectiveTrivia(VisualBasicSyntaxFactory.HashToken, VisualBasicSyntaxFactory.ExternalChecksumKeyword, VisualBasicSyntaxFactory.OpenParenToken, ExternalSource, VisualBasicSyntaxFactory.CommaToken, Guid1, VisualBasicSyntaxFactory.CommaToken, Bytes, VisualBasicSyntaxFactory.CloseParenToken), PragmaChecksumDirective.EndOfDirectiveToken)));
        }

        case (int)CS.SyntaxKind.SkippedTokensTrivia: {
            var Builder = new StringBuilder();
            foreach (SyntaxToken tok in ((CSSyntax.SkippedTokensTriviaSyntax)StructuredTrivia).Tokens)
            {
                Builder.Append(tok.ToString());
            }
            return(VBFactory.CommentTrivia($"' TODO: Error SkippedTokensTrivia '{Builder}'"));
        }

        case (int)CS.SyntaxKind.BadDirectiveTrivia: {
            return(VBFactory.CommentTrivia($"' TODO: Skipped BadDirectiveTrivia"));
        }

        case (int)CS.SyntaxKind.ConflictMarkerTrivia: {
            break;
        }

        case (int)CS.SyntaxKind.LoadDirectiveTrivia: {
            break;
        }

        default: {
            Debug.WriteLine(((VBasic.SyntaxKind)Conversions.ToUShort(t.RawKind)).ToString());

            break;
        }
        }
        throw new NotImplementedException($"t.Kind({(VBasic.SyntaxKind)Conversions.ToUShort(t.RawKind)}) Is unknown");
    }
Exemplo n.º 17
0
    public override VBasic.VisualBasicSyntaxNode VisitIdentifierName(CSSyntax.IdentifierNameSyntax node)
    {
        var Identifier = VBFactory.IdentifierName(node.Identifier.ToString());

        return(Identifier);
    }
Exemplo n.º 18
0
    public override VBasic.VisualBasicSyntaxNode VisitOperatorMemberCref(CSSyntax.OperatorMemberCrefSyntax node)
    {
        var CrefOperator = GetVBOperatorToken(node.OperatorToken.ValueText);

        return(VBFactory.CrefOperatorReference(CrefOperator.WithLeadingTrivia(VisualBasicSyntaxFactory.SpaceTrivia)));
    }
Exemplo n.º 19
0
 public override VBasic.VisualBasicSyntaxNode VisitQualifiedName(CSSyntax.QualifiedNameSyntax node)
 {
     return(VBFactory.QualifiedName((VBSyntax.NameSyntax)node.Left.Accept(this), (VBSyntax.SimpleNameSyntax)node.Right.Accept(this)));
 }
Exemplo n.º 20
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlElementStartTag(CSSyntax.XmlElementStartTagSyntax node)
    {
        var ListOfAttributes = GatherAttributes(node.Attributes);

        return(VBFactory.XmlElementStartTag((VBSyntax.XmlNodeSyntax)node.Name.Accept(this), ListOfAttributes));
    }
Exemplo n.º 21
0
    public override VBasic.VisualBasicSyntaxNode VisitXmlCDataSection(CSSyntax.XmlCDataSectionSyntax node)
    {
        var TextTokens = TriviaListSupport.TranslateTokenList(node.TextTokens);

        return(VBFactory.XmlCDataSection(VisualBasicSyntaxFactory.BeginCDataToken, TextTokens, VisualBasicSyntaxFactory.EndCDataToken));
    }
Exemplo n.º 22
0
            protected override async Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
            {
                var generator = SyntaxGenerator.GetGenerator(document);
                var root      = await setup.SyntaxTree.GetRootAsync(cancellationToken);

                var node      = FindSetup(root);
                var member    = setup.Ancestors().First(x => generator.GetDeclarationKind(x) == DeclarationKind.Method);
                var @class    = member.Ancestors().First(x => generator.GetDeclarationKind(x) == DeclarationKind.Class);
                var @delegate = generator.GetMembers(@class)
                                // Just check by name for now. Might need to also ensure signature compatibility.
                                .FirstOrDefault(x => generator.GetName(x) == symbol.Name);

                var delegateName = symbol.Name;
                var signature    = generator.DelegateDeclaration(
                    delegateName,
                    parameters: symbol.Parameters.Select(prm => generator.ParameterDeclaration(prm)),
                    returnType: symbol.ReturnsVoid ? null : generator.TypeExpression(symbol.ReturnType));

                if (@delegate == null)
                {
                    root = root.InsertNodesAfter(member, new[] { signature });
                    // Find the updated setup
                    node = FindSetup(root);
                }
                else
                {
                    var tempDoc = document.WithSyntaxRoot(generator.ReplaceNode(root, @delegate, signature));
                    tempDoc = await Simplifier.ReduceAsync(tempDoc);

                    var tempRoot = await tempDoc.GetSyntaxRootAsync(cancellationToken);

                    var className = generator.GetName(@class);
                    var tempClass = tempRoot.DescendantNodes().First(x =>
                                                                     generator.GetDeclarationKind(x) == DeclarationKind.Class &&
                                                                     generator.GetName(x) == className);
                    var tempDelegate = generator.GetMembers(tempClass)
                                       .First(x => generator.GetName(x) == delegateName);

                    if ([email protected](tempDelegate, true))
                    {
                        // Generate the delegate name using full Type+Member name.
                        var semantic = await document.GetSemanticModelAsync(cancellationToken);

                        var mock = semantic.GetSymbolInfo(
                            setup.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.InvocationExpression) ?
                            (SyntaxNode)((setup as CS.InvocationExpressionSyntax)?.Expression as CS.MemberAccessExpressionSyntax)?.Expression :
                            ((setup as VB.InvocationExpressionSyntax)?.Expression as VB.MemberAccessExpressionSyntax)?.Expression);

                        if (mock.Symbol != null &&
                            mock.Symbol.Kind == SymbolKind.Local ||
                            mock.Symbol.Kind == SymbolKind.Field)
                        {
                            var type = mock.Symbol.Kind == SymbolKind.Local ?
                                       ((ILocalSymbol)mock.Symbol).Type :
                                       ((IFieldSymbol)mock.Symbol).Type;

                            delegateName = type.MetadataName + symbol.Name;
                            signature    = generator.WithName(signature, delegateName);
                            root         = root.InsertNodesAfter(member, new[] { signature });
                            // Find the updated setup
                            node = FindSetup(root);
                        }
                    }
                }

                root = generator.ReplaceNode(root, node, generator.WithTypeArguments(node, generator.IdentifierName(delegateName)));
                // Find the updated setup
                node = FindSetup(root);

                // Detect recursive mock access and wrap in a Func<TDelegate>
                if (
                    node.Parent.ChildNodes()
                    .OfType <CS.ArgumentListSyntax>()
                    .Where(list => !list.Arguments.Select(arg => arg.Expression).OfType <CS.LambdaExpressionSyntax>().Any())
                    .SelectMany(list => list.DescendantNodes().OfType <CS.MemberAccessExpressionSyntax>())
                    .Count() > 1 ||
                    node.Parent.ChildNodes()
                    .OfType <VB.ArgumentListSyntax>()
                    .Where(list => !list.Arguments.Select(arg => arg.GetExpression()).OfType <VB.LambdaExpressionSyntax>().Any())
                    .SelectMany(list => list.DescendantNodes().OfType <VB.MemberAccessExpressionSyntax>())
                    .Count() > 1)
                {
                    var expression = node.Parent.ChildNodes().Last()
                                     .DescendantNodes()
                                     .Where(x =>
                                            x.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.SimpleMemberAccessExpression) ||
                                            // For VB, we actually wrap the AddressOf
                                            x.IsKind(Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.AddressOfExpression))
                                     .First();

                    root = generator.ReplaceNode(root, expression,
                                                 generator.ValueReturningLambdaExpression(expression));
                    // Find the updated setup
                    node = FindSetup(root);
                }

                // If there is no Returns, generate one
                if (node.Parent.Parent.IsKind(Microsoft.CodeAnalysis.CSharp.SyntaxKind.ExpressionStatement))
                {
                    var returns = generator.InvocationExpression(
                        generator.MemberAccessExpression(
                            node.Parent.WithTrailingTrivia(
                                node.Parent.Parent.GetLeadingTrivia().Add(CSFactory.Whitespace("\t"))),
                            "Returns"),
                        generator.ValueReturningLambdaExpression(
                            symbol.Parameters.Select(prm => generator.ParameterDeclaration(prm)),
                            generator.ThrowExpression(generator.NullLiteralExpression())));

                    // Replace the parent InvocationExpression with the returning one.
                    root = generator.ReplaceNode(root, node.Parent, returns);
                }
                else if (node.Parent.Parent.IsKind(Microsoft.CodeAnalysis.VisualBasic.SyntaxKind.ExpressionStatement))
                {
                    var lambda = VBFactory.MultiLineFunctionLambdaExpression(
                        VBFactory.FunctionLambdaHeader().WithParameterList(
                            VBFactory.ParameterList(
                                VBFactory.SeparatedList(
                                    symbol.Parameters.Select(prm => (VB.ParameterSyntax)generator.ParameterDeclaration(prm))))),
                        VBFactory.List(new VB.StatementSyntax[]
                    {
                        VBFactory.ThrowStatement(
                            VBFactory.ObjectCreationExpression(
                                VBFactory.ParseTypeName(nameof(NotImplementedException))))
                    }),
                        VBFactory.EndFunctionStatement());

                    var returns = generator.InvocationExpression(
                        generator.MemberAccessExpression(
                            node.Parent.WithTrailingTrivia(
                                node.Parent.Parent.GetLeadingTrivia()
                                .Insert(0, VBFactory.Whitespace(" "))
                                .Insert(1, VBFactory.LineContinuationTrivia(""))
                                .Add(VBFactory.Whitespace("\t"))),
                            "Returns"),
                        lambda);

                    // Replace the parent InvocationExpression with the returning one.
                    root = generator.ReplaceNode(root, node.Parent, returns);
                }

                return(document.WithSyntaxRoot(root));
            }
Exemplo n.º 23
0
 public override VBasic.VisualBasicSyntaxNode VisitXmlElementEndTag(CSSyntax.XmlElementEndTagSyntax node)
 {
     return(VBFactory.XmlElementEndTag((VBSyntax.XmlNameSyntax)node.Name.Accept(this)));
 }