Exemple #1
0
        private string ParseEnum(EnumDeclarationSyntax syntax)
        {
            var name      = syntax.Identifier.Text;
            var modeKeyof = false;

            if (_enumModes.ContainsKey(name) && _enumModes[name] == "keyof")
            {
                modeKeyof = true;
                name     += "Enum";
            }
            var segment = "";

            segment += ParseTrivia(syntax.GetLeadingTrivia());
            // lead
            segment += $"export enum {name} {{\n";
            foreach (var member in syntax.Members)
            {
                segment += IndentString(ParseTrivia(member.GetLeadingTrivia()), "  ");
                segment += $"  {member.Identifier.Text}{ParseEnumValue(member.EqualsValue)},\n";
            }
            segment += "}\n";
            if (modeKeyof)
            {
                segment += $"export type {syntax.Identifier.Text} = Uncapitalize<keyof typeof {name}>;\n";
            }
            _exports.Add(syntax.Identifier.Text);
            return(segment);
        }
Exemple #2
0
        public override void VisitEnumDeclaration(EnumDeclarationSyntax node)
        {
            var docComment = node.GetLeadingTrivia().Select(i => i.GetStructure()).OfType <DocumentationCommentTriviaSyntax>().FirstOrDefault();

            _parsedBaseTypes.Add(new ParsedType(node, docComment));
            base.VisitEnumDeclaration(node);
        }
        private async Task <Document> AddTodoCommentAsync(Document document, EnumDeclarationSyntax typeDecl, CancellationToken cancellationToken)
        {
            // Compute new uppercase name.
            //var identifierToken = typeDecl.Identifier;
            ////var newName = identifierToken.Text.ToUpperInvariant();

            // Get the symbol representing the type to be renamed.
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            //var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

            var lastWhiteSpaceLeadingTrivia = typeDecl.GetLeadingTrivia().LastOrDefault(x => x.IsKind(SyntaxKind.WhitespaceTrivia));


            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = root.ReplaceTrivia(lastWhiteSpaceLeadingTrivia,
                                             SyntaxFactory.Comment(
                                                 $"//TODO: Remove use of duplicate enum members pointing to same value?{Environment.NewLine}"));

            // Produce a new solution that has all references to that type renamed, including the declaration.
            //var originalSolution = document.Project.Solution;
            //var optionSet = originalSolution.Workspace.Options;
            ////var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

            // Return the new solution with the now-uppercase type name.
            return(document.WithSyntaxRoot(newRoot));
        }
        public static string EnumDeclaration(EnumDeclarationSyntax declaration)
        {
            Builder.Instance.EnumMapToNames.Clear();
            var parsedAttributes = ParseAttributes(declaration.AttributeLists);

            var output = declaration.GetLeadingTrivia().ToFullString();

            output += parsedAttributes.Item1;
            var nameToUse = parsedAttributes.Item2;

            output +=
                Builder.Instance.LanguageConvertEnum()
                + " "
                + (nameToUse ?? SyntaxTokenConvert(declaration.Identifier).TrimEnd());

            //Get the value of the enum
            foreach (var decl in declaration.ChildNodes().OfType <EnumMemberDeclarationSyntax>()
                     .Where(decl => decl.EqualsValue != null).Select(decl => decl.EqualsValue.Value))
            {
                if (decl.IsKind(SyntaxKind.StringLiteralExpression))
                {
                    output += Builder.Instance.LanguageConvertEnumPostfix("String");
                }
                else if (decl.IsKind(SyntaxKind.CharacterLiteralExpression))
                {
                    output += Builder.Instance.LanguageConvertEnumPostfix("Character");
                }
                else if (decl.IsKind(SyntaxKind.NumericLiteralExpression))
                {
                    output += Builder.Instance.LanguageConvertEnumPostfix("Int");
                }
                else
                {
                    continue;
                }

                break;
            }

            var outputMembers = declaration.Members.ConvertSeparatedSyntaxList(
                separatorForced: Builder.Instance.LanguageEnumMemberSeparator()
                ).TrimEnd();
            var outputEnumMapToName = Builder.Instance.LanguageConvertEnumMapToName();

            output +=
                " "
                + SyntaxTokenConvert(declaration.OpenBraceToken).TrimStart()
                + outputMembers
                + NewLine
                + outputEnumMapToName
                + SyntaxTokenConvert(declaration.CloseBraceToken);
            return(output);
        }
        /// <summary>
        /// Adds documentation header async.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="root">The root.</param>
        /// <param name="declarationSyntax">The declaration syntax.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Document.</returns>
        private async Task <Document> AddDocumentationHeaderAsync(Document document, SyntaxNode root, EnumDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
        {
            SyntaxTriviaList leadingTrivia = declarationSyntax.GetLeadingTrivia();

            string comment = CommentHelper.CreateEnumComment(declarationSyntax.Identifier.ValueText);
            DocumentationCommentTriviaSyntax commentTrivia = await Task.Run(() => DocumentationHeaderHelper.CreateOnlySummaryDocumentationCommentTrivia(comment), cancellationToken);

            SyntaxTriviaList      newLeadingTrivia = leadingTrivia.Insert(leadingTrivia.Count - 1, SyntaxFactory.Trivia(commentTrivia));
            EnumDeclarationSyntax newDeclaration   = declarationSyntax.WithLeadingTrivia(newLeadingTrivia);

            SyntaxNode newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
Exemple #6
0
        /// <summary>
        /// Analyzes node.
        /// </summary>
        /// <param name="context">The context.</param>
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            EnumDeclarationSyntax node = context.Node as EnumDeclarationSyntax;

            DocumentationCommentTriviaSyntax commentTriviaSyntax = node
                                                                   .GetLeadingTrivia()
                                                                   .Select(o => o.GetStructure())
                                                                   .OfType <DocumentationCommentTriviaSyntax>()
                                                                   .FirstOrDefault();

            if (commentTriviaSyntax != null && CommentHelper.HasComment(commentTriviaSyntax))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Rule, node.Identifier.GetLocation()));
        }
        public static EnumDeclarationSyntax Apply(EnumDeclarationSyntax node, Func <EnumDeclarationSyntax, SyntaxTrivia, EnumDeclarationSyntax> builder)
        {
            var leadingTrivia  = node.GetLeadingTrivia();
            var trailingTrivia = node.GetTrailingTrivia();

            node = node.WithoutLeadingTrivia();
            node = node.WithoutTrailingTrivia();

            var wp = leadingTrivia.FirstOrDefault(w => w.Kind() == SyntaxKind.WhitespaceTrivia);

            node = builder?.Invoke(node, wp);

            node = node.WithLeadingTrivia(leadingTrivia);

            node = node.WithTrailingTrivia(trailingTrivia);

            return(node);
        }
        private void VisitEnumDelcaration(EnumDeclarationSyntax enumDecl)
        {
            if (IgnoreByModifier(enumDecl.Modifiers))
            {
                return;
            }

            enumDecl.AttributeLists.Consume(VisitAttributeList);
            VisitXmlComment(enumDecl.GetLeadingTrivia());

            var @const = this.MakeEnumConst ? "const" : "";
            var name   = enumDecl.Identifier;

            this.writer.WriteLine($"export {@const} enum {name} {{");
            this.writer.Indent();
            foreach (var enumMember in enumDecl.Members)
            {
                this.writer.BeginLine();
                this.writer.Write(enumMember.Identifier);
                if (enumMember.EqualsValue != null)
                {
                    if (enumMember.EqualsValue.Value is LiteralExpressionSyntax literal &&
                        literal.Kind() == SyntaxKind.NumericLiteralExpression &&
                        long.TryParse(literal.Token.Text, out var constValue))
                    {
                        this.writer.Write(" = ");
                        this.writer.Write(constValue);
                    }
                    else
                    {
                        this.OnUnhandledSyntaxNode?.Invoke(enumMember.EqualsValue.Value);
                        this.writer.Write("/*");
                        this.writer.Write(enumMember.EqualsValue.Value);
                        this.writer.Write("*/");
                    }
                }
                this.writer.Write(",");
                this.writer.EndLine();
            }
Exemple #9
0
        public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node)
        {
            if (node.AttributeLists.Count > 0)
            {
                var newAttributeLists = new SyntaxList <AttributeListSyntax>();
                foreach (var attributeList in node.AttributeLists)
                {
                    var nodesToRemove = attributeList.Attributes.Where(attribute => NodeHelper.AttributeNameMatches(attribute, Constants.Proto.BASE_PROP_NAME)).ToArray();

                    // If the lists are the same length, we are removing all attributes and can just avoid populating newAttributes.
                    if (nodesToRemove.Length != attributeList.Attributes.Count)
                    {
                        var newAttribute = (AttributeListSyntax)VisitAttributeList(attributeList.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia));
                        newAttributeLists = newAttributeLists.Add(newAttribute);
                    }
                }
                var leadTriv = node.GetLeadingTrivia();
                node = node.WithAttributeLists(newAttributeLists);
                node = node.WithLeadingTrivia(leadTriv);
            }
            return(base.VisitEnumDeclaration(node));
        }
        public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node)
        {
            String name        = node.Identifier.ValueText;
            String replaceName = "";

            if (SharedContainer.Instance.nameMap.ContainsKey(name))
            {
                replaceName = SharedContainer.Instance.nameMap[name];
            }
            else
            {
                replaceName = SharedContainer.Instance.RandomString(SharedContainer.Instance.nameMap.Count() + 1);
                SharedContainer.Instance.nameType[name] = Priority.En_Priority.CLASS;
                SharedContainer.Instance.nameMap[name]  = replaceName;
            }

            EnumDeclarationSyntax newSyntax = node.WithIdentifier(Identifier(replaceName)).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());

            return(base.VisitEnumDeclaration(node.ReplaceNode(node, newSyntax)));
        }
        /// <summary>
        /// Still needs work!
        /// </summary>
        /// <returns></returns>
        private Model.Enum TraverseEnums(EnumDeclarationSyntax eds)
        {
            Model.Enum retEnu = new Model.Enum();
            //public List<string> EnumItems { get; set; }
            //public string Name { get; set; }
            //public Type Type { get; set; }

            if (eds.HasLeadingTrivia)
            {
                SetOuterComments(retEnu, eds.GetLeadingTrivia().ToFullString());
            }

            if (eds.HasTrailingTrivia)
            {
                SetInnerComments(retEnu, eds.GetTrailingTrivia().ToFullString());
            }

            var types = from aType in eds.ChildNodes().OfType<TypeDeclarationSyntax>() select aType;
            foreach (TypeDeclarationSyntax tds in types)
            {
                //TODO put breakpoint here
                //to find out how to get types
            }
            foreach (SyntaxToken st in eds.Modifiers)
            {
                string modifier = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(st.ValueText);
                retEnu.Encapsulation.Add((Encapsulation)System.Enum.Parse(typeof(Encapsulation), modifier));
            }

            var enumItems = from aEnumItem in eds.ChildNodes().OfType<EnumMemberDeclarationSyntax>() select aEnumItem;
            foreach (EnumMemberDeclarationSyntax emds in enumItems)
            {
                //TODO put breakpoint here
                //to find out how to get enumitems
            }

            return retEnu;
        }