コード例 #1
0
 private static SyntaxNode CreateNewLiteral(LiteralExpressionSyntax literal, SyntaxNode root)
 {
     SyntaxNode newRoot;
     if (literal.Token.ValueText != literal.Token.Text)
     {
         var newTokenText = literal.Token.ValueText;
         var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
         newRoot = root.ReplaceNode(literal, newLiteral);
     }
     else
     {
         var value = (dynamic)literal.Token.Value;
         if (literal.Parent != null && literal.Parent.IsKind(SyntaxKind.UnaryMinusExpression))
         {
             var newTokenText = (string)("0x" + (value * -1).ToString("X"));
             var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText))
                 .WithLeadingTrivia(literal.Parent.GetLeadingTrivia())
                 .WithTrailingTrivia(literal.Parent.GetTrailingTrivia());
             newRoot = root.ReplaceNode(literal.Parent, newLiteral);
         }
         else
         {
             var newTokenText = (string)("0x" + value.ToString("X"));
             var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
             newRoot = root.ReplaceNode(literal, newLiteral);
         }
     }
     return newRoot;
 }
		private async Task<Document> FormatXmlAsync(Document document, LiteralExpressionSyntax sleSyntax, CancellationToken cancellationToken)
		{
			var root = await document.GetSyntaxRootAsync(cancellationToken);
			var tree = root.SyntaxTree;

			//Get the character position of the LiteralExpressionSyntax
			FileLinePositionSpan position = tree.GetLineSpan(sleSyntax.Span);
			int cSpace = position.StartLinePosition.Character;

			//Figure out the preceeding trivia since we can't get the column position from GetLineSpan
			var parentTrivia = sleSyntax.GetLeadingTrivia().ToFullString();

			var xml = sleSyntax.GetFirstToken().ValueText;
			var newXmlText = FormatXml(xml);

			//Process each line of the formatted XML and prepend the parent trivia & spaces
			string[] xmlLines = newXmlText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
			for (int i = 1; i < xmlLines.Length; i++)
			{
				xmlLines[i] = parentTrivia + new String(' ', (cSpace + 2)) + xmlLines[i];
			}

			newXmlText = String.Join("\r\n", xmlLines);
			var newXmlValue = "@\"" + newXmlText + "\"";

			var newNode = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
				SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.StringLiteralToken, newXmlValue, newXmlText, SyntaxTriviaList.Empty));
			var newRoot = root.ReplaceNode(sleSyntax, newNode);
			return document.WithSyntaxRoot(newRoot);
		}
コード例 #3
0
 private static string GetParameterNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral)
 {
     var ancestorThatMightHaveParameters = stringLiteral.FirstAncestorOfType(typeof(AttributeListSyntax), typeof(MethodDeclarationSyntax), typeof(ConstructorDeclarationSyntax), typeof(IndexerDeclarationSyntax));
     var parameterName = string.Empty;
     if (ancestorThatMightHaveParameters != null)
     {
         var parameters = new SeparatedSyntaxList<ParameterSyntax>();
         switch (ancestorThatMightHaveParameters.Kind())
         {
             case SyntaxKind.MethodDeclaration:
             case SyntaxKind.ConstructorDeclaration:
                 var method = (BaseMethodDeclarationSyntax)ancestorThatMightHaveParameters;
                 parameters = method.ParameterList.Parameters;
                 break;
             case SyntaxKind.IndexerDeclaration:
                 var indexer = (IndexerDeclarationSyntax)ancestorThatMightHaveParameters;
                 parameters = indexer.ParameterList.Parameters;
                 break;
             case SyntaxKind.AttributeList:
                 break;
         }
         parameterName = GetParameterWithIdentifierEqualToStringLiteral(stringLiteral, parameters)?.Identifier.Text;
     }
     return parameterName;
 }
コード例 #4
0
ファイル: StringInterpolation.cs プロジェクト: jthelin/Nake
        public StringInterpolation(SemanticModel model, LiteralExpressionSyntax node, bool constant)
        {
            this.model = model;
            this.node = node;
            this.constant = constant;

            literal  = node.Token.ValueText;
        }
        private static Task<Solution> UseStringDotEmptyAsync(Document document, SyntaxNode root, LiteralExpressionSyntax literalDeclaration)
        {
            var stringDotEmptyInvocation = SyntaxFactory.ParseExpression("string.Empty");
            var newRoot = root.ReplaceNode(literalDeclaration, stringDotEmptyInvocation);

            var newDocument = document.WithSyntaxRoot(newRoot);
            return Task.FromResult(newDocument.Project.Solution);
        }
コード例 #6
0
 private static async Task<string> GetIdentifierAsync(Document document, LiteralExpressionSyntax stringLiteral, SyntaxNode root, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var diagnosticSpan = diagnostic.Location.SourceSpan;
     var parameter = FindParameterThatStringLiteralRefers(root, diagnosticSpan.Start, stringLiteral);
     if (parameter != null)
         return parameter.Identifier.Text;
     var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
     var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, stringLiteral.Token.ValueText).First();
     return symbol.ToDisplayParts().Last(NameOfAnalyzer.IncludeOnlyPartsThatAreName).ToString();
 }
コード例 #7
0
 private static ExpressionSyntax ToVerbatimStringLiteral(LiteralExpressionSyntax expression)
 {
     var str = (string)expression.Token.Value;
     return LiteralExpression(SyntaxKind.StringLiteralExpression,
         Literal(
             TriviaList(),
             StringToVerbatimText(str),
             str,
             TriviaList()));
 }
 static bool IsBoolean(LiteralExpressionSyntax expr, out bool value)
 {
     value = false;
     if (expr != null && (expr.Token.Value is bool))
     {
         value = (bool)expr.Token.Value;
         return true;
     }
     return false;
 }
コード例 #9
0
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            if (node.IsKind(SyntaxKind.StringLiteralExpression)
                && node.ToString().IndexOf('\n') >= 0)
            {
                node = node.WithAdditionalAnnotations(LayoutAnnotations.MultiLineConstructAnnotation);
            }

            return base.VisitLiteralExpression(node);
        }
            public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                switch (node.Kind())
                {
                    case SyntaxKind.StringLiteralExpression:
                        return RewriteStringLiteralExpression(node);
                    case SyntaxKind.CharacterLiteralExpression:
                        return RewriteCharacterLiteralExpression(node);
                }

                return node;
            }
コード例 #11
0
ファイル: Rewriter.cs プロジェクト: jthelin/Nake
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            var interpolation = result.Find(node);
            if (interpolation == null)
                return base.VisitLiteralExpression(node);

            var interpolated = interpolation.Interpolate();
            foreach (var variable in interpolation.Captured)
                Captured.Add(variable);

            return interpolated;
        }
コード例 #12
0
        private static bool OutSideOfDeclarationSideWithSameName(LiteralExpressionSyntax stringLiteral)
        {
            var variableDeclaration = stringLiteral.FirstAncestorOfType<VariableDeclaratorSyntax>();
            if (variableDeclaration != null)
            {
                return !string.Equals(variableDeclaration.Identifier.ValueText, stringLiteral.Token.ValueText, StringComparison.Ordinal);
            }

            var propertyDeclaration = stringLiteral.FirstAncestorOfType<PropertyDeclarationSyntax>();
            var outSideOfAccessors = null == stringLiteral.FirstAncestorOfType<AccessorListSyntax>();
            if (!outSideOfAccessors) return true;
            return !string.Equals(propertyDeclaration?.Identifier.ValueText, stringLiteral.Token.ValueText, StringComparison.Ordinal);
        }
コード例 #13
0
 private static void CheckJsonValue(SyntaxNodeAnalysisContext context, LiteralExpressionSyntax literalParameter,
     string json)
 {
     try
     {
         parseMethodInfo.Value.Invoke(null, new[] { json });
     }
     catch (Exception ex)
     {
         var diag = Diagnostic.Create(Rule, literalParameter.GetLocation(), ex.InnerException.Message);
         context.ReportDiagnostic(diag);
     }
 }
コード例 #14
0
        private async Task<Document> ReplaceWithNameOf(Document document, LiteralExpressionSyntax literalExpression, CancellationToken cancellationToken)
        {
            var stringText = literalExpression.Token.ValueText;

            var nameOfExpression = InvocationExpression(
                expression: IdentifierName("nameof"),
                argumentList: ArgumentList(
                    arguments: SingletonSeparatedList(Argument(IdentifierName(stringText)))));

            var root = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = root.ReplaceNode(literalExpression, nameOfExpression);

            return document.WithSyntaxRoot(newRoot);
        }
コード例 #15
0
        private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel)
        {
            var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral);

            if (!Found(programElementName))
            {
                var literalValueText = stringLiteral.Token.ValueText;
                var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault();

                programElementName = symbol?.ToDisplayParts().LastOrDefault(IncludeOnlyPartsThatAreName).ToString();
            }

            return programElementName;
        }
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     switch (node.Kind())
     {
         case SyntaxKind.TrueLiteralExpression:
             VisitSymbol("true");
             break;
         case SyntaxKind.FalseLiteralExpression:
             VisitSymbol("false");
             break;
         default:
             throw new InvalidPreprocessorExpressionException("Expected true or false literal expression");
     }
 }
コード例 #17
0
            public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                if (node.Kind != SyntaxKind.StringLiteralExpression)
                    return node;

                var variables = InterpolationUtils.EnumerateVariables(node.GetText().ToString()).Distinct().ToArray();
                var arguments = string.Join(", ", variables);
                var formatString = node.GetText().ToString();

                for (int i = 0; i < variables.Length; i++) {
                    formatString = formatString.Replace("$" + variables[0], "{" + i + "}");
                }

                return Syntax.ParseExpression(string.Format("string.Format({0}, {1})", formatString, arguments));
            }
            private static SyntaxNode RewriteCharacterLiteralExpression(LiteralExpressionSyntax node)
            {
                Debug.Assert(node.Kind() == SyntaxKind.CharacterLiteralExpression);

                if (HasNonAsciiCharacters(node.Token.Text))
                {
                    string convertedText = EscapeNonAsciiCharacters(node.Token.Text);

                    SyntaxToken t = SyntaxFactory.Literal(node.Token.LeadingTrivia, convertedText, node.Token.ValueText, node.Token.TrailingTrivia);

                    node = node.WithToken(t);
                }

                return node;
            }
コード例 #19
0
        private static SyntaxToken GetNewLiteral(LiteralExpressionSyntax literal, SemanticModel semanticModel)
        {
            var type = semanticModel.GetTypeInfo(literal).Type;
            var text = literal.Token.Text;
            var reversedText = text.Reverse();
            var reversedTextEnding = new string(reversedText.TakeWhile(char.IsLetter).ToArray());
            var reversedTextBeginning = new string(reversedText.SkipWhile(char.IsLetter).ToArray());
            var newText = new string((reversedTextEnding.ToUpperInvariant() + reversedTextBeginning).Reverse().ToArray());

            switch (type.SpecialType)
            {
                case SpecialType.System_Int32:
                    return SyntaxFactory.Literal(
                        newText,
                        (int)literal.Token.Value);
                case SpecialType.System_Char:
                    return SyntaxFactory.Literal(
                        newText,
                        (char)literal.Token.Value);
                case SpecialType.System_UInt32:
                    return SyntaxFactory.Literal(
                        newText,
                        (uint)literal.Token.Value);
                case SpecialType.System_Int64:
                    return SyntaxFactory.Literal(
                        newText,
                        (long)literal.Token.Value);
                case SpecialType.System_UInt64:
                    return SyntaxFactory.Literal(
                        newText,
                        (ulong)literal.Token.Value);
                case SpecialType.System_Decimal:
                    return SyntaxFactory.Literal(
                        newText,
                        (decimal)literal.Token.Value);
                case SpecialType.System_Single:
                    return SyntaxFactory.Literal(
                        newText,
                        (float)literal.Token.Value);
                case SpecialType.System_Double:
                    return SyntaxFactory.Literal(
                        newText,
                        (double)literal.Token.Value);
                default:
                    return SyntaxFactory.Token(SyntaxKind.None);
            }
        }
コード例 #20
0
ファイル: RoslynTool.cs プロジェクト: GHScan/DailyProjects
        public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            if (node.CSharpKind() != SyntaxKind.StringLiteralExpression) return node;

            var pos = node.GetLocation().GetMappedLineSpan();
            var result = OnRewrite(pos.StartLinePosition.Line + 1, pos.StartLinePosition.Character + 1, Source.Lines[pos.StartLinePosition.Line].ToString(), node.Token.ValueText);
            if (result == null) return node;

            var names = result.Split('.');
            ExpressionSyntax newNode = SyntaxFactory.IdentifierName(names.First());
            foreach (var name in names.Skip(1))
            {
                newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, newNode, SyntaxFactory.IdentifierName(name));
            }

            return newNode.WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia());
        }
            public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                this.IsAttributeArgument = node.Parent.IsKind(SyntaxKind.AttributeArgument);
                if (node.IsKind(SyntaxKind.StringLiteralExpression) &&
                    !IsParameterDefaultArgument(node) &&
                    !this.IsAttributeArgument &&
                    !IsConstVariableDeclaration(node))
                {
                    if (string.IsNullOrEmpty(node.Token.ValueText))
                    {
                        this.addedAnnotations = true;
                        return SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)),
                            SyntaxFactory.IdentifierName("Empty"));
                    }
                }

                return base.VisitLiteralExpression(node);
            }
コード例 #22
0
        private static bool HasToBeConstant(LiteralExpressionSyntax literalExpression)
        {
            ExpressionSyntax outermostExpression = FindOutermostExpression(literalExpression);

            if (outermostExpression.Parent.IsKind(SyntaxKind.AttributeArgument)
                || outermostExpression.Parent.IsKind(SyntaxKind.CaseSwitchLabel))
            {
                return true;
            }

            EqualsValueClauseSyntax equalsValueClause = outermostExpression.Parent as EqualsValueClauseSyntax;
            if (equalsValueClause != null)
            {
                ParameterSyntax parameterSyntax = equalsValueClause.Parent as ParameterSyntax;
                if (parameterSyntax != null)
                {
                    return true;
                }

                VariableDeclaratorSyntax variableDeclaratorSyntax = equalsValueClause.Parent as VariableDeclaratorSyntax;
                VariableDeclarationSyntax variableDeclarationSyntax = variableDeclaratorSyntax?.Parent as VariableDeclarationSyntax;
                if (variableDeclaratorSyntax == null || variableDeclarationSyntax == null)
                {
                    return false;
                }

                FieldDeclarationSyntax fieldDeclarationSyntax = variableDeclarationSyntax.Parent as FieldDeclarationSyntax;
                if (fieldDeclarationSyntax != null && fieldDeclarationSyntax.Modifiers.Any(SyntaxKind.ConstKeyword))
                {
                    return true;
                }

                LocalDeclarationStatementSyntax localDeclarationStatementSyntax = variableDeclarationSyntax.Parent as LocalDeclarationStatementSyntax;
                if (localDeclarationStatementSyntax != null && localDeclarationStatementSyntax.Modifiers.Any(SyntaxKind.ConstKeyword))
                {
                    return true;
                }
            }

            return false;
        }
コード例 #23
0
 private static BoundExpression ProcessLiteral(LiteralExpressionSyntax node)
 {
     switch (node.Kind)
     {
         case SyntaxKind.TrueLiteralExpression:
         case SyntaxKind.FalseLiteralExpression:
             return new BoundLiteralExpression(node, IntrinsicTypes.Bool);
         case SyntaxKind.NumericLiteralExpression:
             switch (node.Token.Kind)
             {
                 case SyntaxKind.IntegerLiteralToken:
                     return new BoundLiteralExpression(node, IntrinsicTypes.Int);
                 case SyntaxKind.FloatLiteralToken:
                     return new BoundLiteralExpression(node, IntrinsicTypes.Float);
                 default:
                     throw new ArgumentOutOfRangeException();
             }
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
コード例 #24
0
        private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel)
        {
            var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral);

            if (!Found(programElementName))
            {
                var literalValueText = stringLiteral.Token.ValueText;
                var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault();

                if (symbol?.Kind == SymbolKind.Local)
                {
                    var symbolSpan = symbol.Locations.Min(i => i.SourceSpan);
                    if (symbolSpan.CompareTo(stringLiteral.Token.Span) > 0)
                        return string.Empty;
                }

                programElementName = symbol?.ToDisplayParts().LastOrDefault(AnalyzerExtensions.IsName).ToString();
            }

            return programElementName;
        }
            private static SyntaxNode RewriteStringLiteralExpression(LiteralExpressionSyntax node)
            {
                Debug.Assert(node.Kind() == SyntaxKind.StringLiteralExpression);

                if (node.Token.IsVerbatimStringLiteral())
                {
                    // We do not correctly rewrite verbatim string literals yet.  Once Issue 39 is
                    // fixed we can remove this early out.
                    return node;
                }

                if (HasNonAsciiCharacters(node.Token.Text))
                {
                    string convertedText = EscapeNonAsciiCharacters(node.Token.Text);

                    SyntaxToken t = SyntaxFactory.Literal(node.Token.LeadingTrivia, convertedText, node.Token.ValueText, node.Token.TrailingTrivia);

                    node = node.WithToken(t);
                }

                return node;
            }
            private static bool IsConstVariableDeclaration(LiteralExpressionSyntax node)
            {
                if (
                    !(node.Parent.IsKind(SyntaxKind.EqualsValueClause)
                      && node.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator)
                      && node.Parent.Parent.Parent.IsKind(SyntaxKind.VariableDeclaration)
                      && node.Parent.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)))
                {
                    return false;
                }

                foreach (var modifier in ((FieldDeclarationSyntax)node.Parent.Parent.Parent.Parent).Modifiers)
                {
                    switch (modifier.Kind())
                    {
                        case SyntaxKind.ConstKeyword:
                            return true;
                    }
                }

                return false;
            }
コード例 #27
0
        private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel, out bool externalSymbol)
        {
            externalSymbol = false;
            var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral);
            if (!Found(programElementName))
            {
                var literalValueText = stringLiteral.Token.ValueText;
                var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault();
                if (symbol == null) return null;
                externalSymbol = !symbol.Locations.Any(l => l.IsInSource);

                if (symbol.Kind == SymbolKind.Local)
                {
                    var symbolSpan = symbol.Locations.Min(i => i.SourceSpan);
                    if (symbolSpan.CompareTo(stringLiteral.Token.Span) > 0)
                        return null;
                }

                programElementName = symbol.ToDisplayParts(NameOfSymbolDisplayFormat).LastOrDefault(AnalyzerExtensions.IsName).ToString();
            }

            return programElementName;
        }
コード例 #28
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     //base.VisitLiteralExpression(node);
 }
コード例 #29
0
 public override void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
 }
コード例 #30
0
        private async Task <Document> ConvertToAsyncPackageAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            Compilation compilation = await context.Document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode root = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            BaseTypeSyntax          baseTypeSyntax         = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf <BaseTypeSyntax>();
            ClassDeclarationSyntax  classDeclarationSyntax = baseTypeSyntax.FirstAncestorOrSelf <ClassDeclarationSyntax>();
            MethodDeclarationSyntax initializeMethodSyntax = classDeclarationSyntax.DescendantNodes()
                                                             .OfType <MethodDeclarationSyntax>()
                                                             .FirstOrDefault(method => method.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.OverrideKeyword)) && method.Identifier.Text == Types.Package.Initialize);
            InvocationExpressionSyntax baseInitializeInvocationSyntax = initializeMethodSyntax?.Body?.DescendantNodes()
                                                                        .OfType <InvocationExpressionSyntax>()
                                                                        .FirstOrDefault(ies => ies.Expression is MemberAccessExpressionSyntax memberAccess && memberAccess.Name?.Identifier.Text == Types.Package.Initialize && memberAccess.Expression is BaseExpressionSyntax);
            var             getServiceInvocationsSyntax = new List <InvocationExpressionSyntax>();
            AttributeSyntax packageRegistrationSyntax   = null;

            {
                INamedTypeSymbol userClassSymbol             = semanticModel.GetDeclaredSymbol(classDeclarationSyntax, context.CancellationToken);
                INamedTypeSymbol packageRegistrationType     = compilation.GetTypeByMetadataName(Types.PackageRegistrationAttribute.FullName);
                AttributeData    packageRegistrationInstance = userClassSymbol?.GetAttributes().FirstOrDefault(a => a.AttributeClass == packageRegistrationType);
                if (packageRegistrationInstance?.ApplicationSyntaxReference != null)
                {
                    packageRegistrationSyntax = (AttributeSyntax)await packageRegistrationInstance.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
                }
            }

            if (initializeMethodSyntax != null)
            {
                getServiceInvocationsSyntax.AddRange(
                    from invocation in initializeMethodSyntax.DescendantNodes().OfType <InvocationExpressionSyntax>()
                    let memberBinding = invocation.Expression as MemberAccessExpressionSyntax
                                        let identifierName = invocation.Expression as IdentifierNameSyntax
                                                             where identifierName?.Identifier.Text == Types.Package.GetService ||
                                                             (memberBinding.Name.Identifier.Text == Types.Package.GetService && memberBinding.Expression.IsKind(SyntaxKind.ThisExpression))
                                                             select invocation);
            }

            // Make it easier to track nodes across changes.
            var nodesToTrack = new List <SyntaxNode>
            {
                baseTypeSyntax,
                initializeMethodSyntax,
                baseInitializeInvocationSyntax,
                packageRegistrationSyntax,
            };

            nodesToTrack.AddRange(getServiceInvocationsSyntax);
            nodesToTrack.RemoveAll(n => n == null);
            SyntaxNode updatedRoot = root.TrackNodes(nodesToTrack);

            // Replace the Package base type with AsyncPackage
            baseTypeSyntax = updatedRoot.GetCurrentNode(baseTypeSyntax);
            SimpleBaseTypeSyntax asyncPackageBaseTypeSyntax = SyntaxFactory.SimpleBaseType(Types.AsyncPackage.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation))
                                                              .WithLeadingTrivia(baseTypeSyntax.GetLeadingTrivia())
                                                              .WithTrailingTrivia(baseTypeSyntax.GetTrailingTrivia());

            updatedRoot = updatedRoot.ReplaceNode(baseTypeSyntax, asyncPackageBaseTypeSyntax);

            // Update the PackageRegistration attribute
            if (packageRegistrationSyntax != null)
            {
                LiteralExpressionSyntax trueExpression = SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression);
                packageRegistrationSyntax = updatedRoot.GetCurrentNode(packageRegistrationSyntax);
                AttributeArgumentSyntax allowsBackgroundLoadingSyntax = packageRegistrationSyntax.ArgumentList.Arguments.FirstOrDefault(a => a.NameEquals?.Name?.Identifier.Text == Types.PackageRegistrationAttribute.AllowsBackgroundLoading);
                if (allowsBackgroundLoadingSyntax != null)
                {
                    updatedRoot = updatedRoot.ReplaceNode(
                        allowsBackgroundLoadingSyntax,
                        allowsBackgroundLoadingSyntax.WithExpression(trueExpression));
                }
                else
                {
                    updatedRoot = updatedRoot.ReplaceNode(
                        packageRegistrationSyntax,
                        packageRegistrationSyntax.AddArgumentListArguments(
                            SyntaxFactory.AttributeArgument(trueExpression).WithNameEquals(SyntaxFactory.NameEquals(Types.PackageRegistrationAttribute.AllowsBackgroundLoading))));
                }
            }

            // Find the Initialize override, if present, and update it to InitializeAsync
            if (initializeMethodSyntax != null)
            {
                IdentifierNameSyntax cancellationTokenLocalVarName = SyntaxFactory.IdentifierName("cancellationToken");
                IdentifierNameSyntax progressLocalVarName          = SyntaxFactory.IdentifierName("progress");
                initializeMethodSyntax = updatedRoot.GetCurrentNode(initializeMethodSyntax);
                BlockSyntax newBody = initializeMethodSyntax.Body;

                SyntaxTriviaList leadingTrivia = SyntaxFactory.TriviaList(
                    SyntaxFactory.Comment(@"// When initialized asynchronously, we *may* be on a background thread at this point."),
                    SyntaxFactory.CarriageReturnLineFeed,
                    SyntaxFactory.Comment(@"// Do any initialization that requires the UI thread after switching to the UI thread."),
                    SyntaxFactory.CarriageReturnLineFeed,
                    SyntaxFactory.Comment(@"// Otherwise, remove the switch to the UI thread if you don't need it."),
                    SyntaxFactory.CarriageReturnLineFeed);

                ExpressionStatementSyntax switchToMainThreadStatement = SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.AwaitExpression(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.ThisExpression(),
                                    SyntaxFactory.IdentifierName(Types.ThreadHelper.JoinableTaskFactory)),
                                SyntaxFactory.IdentifierName(Types.JoinableTaskFactory.SwitchToMainThreadAsync)))
                        .AddArgumentListArguments(SyntaxFactory.Argument(cancellationTokenLocalVarName))))
                                                                        .WithLeadingTrivia(leadingTrivia)
                                                                        .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

                if (baseInitializeInvocationSyntax != null)
                {
                    var baseInitializeAsyncInvocationBookmark = new SyntaxAnnotation();
                    AwaitExpressionSyntax baseInitializeAsyncInvocationSyntax = SyntaxFactory.AwaitExpression(
                        baseInitializeInvocationSyntax
                        .WithLeadingTrivia()
                        .WithExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.BaseExpression(),
                                SyntaxFactory.IdentifierName(Types.AsyncPackage.InitializeAsync)))
                        .AddArgumentListArguments(
                            SyntaxFactory.Argument(cancellationTokenLocalVarName),
                            SyntaxFactory.Argument(progressLocalVarName)))
                                                                                .WithLeadingTrivia(baseInitializeInvocationSyntax.GetLeadingTrivia())
                                                                                .WithAdditionalAnnotations(baseInitializeAsyncInvocationBookmark);
                    newBody = newBody.ReplaceNode(initializeMethodSyntax.GetCurrentNode(baseInitializeInvocationSyntax), baseInitializeAsyncInvocationSyntax);
                    StatementSyntax baseInvocationStatement = newBody.GetAnnotatedNodes(baseInitializeAsyncInvocationBookmark).First().FirstAncestorOrSelf <StatementSyntax>();

                    newBody = newBody.InsertNodesAfter(
                        baseInvocationStatement,
                        new[] { switchToMainThreadStatement.WithLeadingTrivia(switchToMainThreadStatement.GetLeadingTrivia().Insert(0, SyntaxFactory.LineFeed)) });
                }
                else
                {
                    newBody = newBody.WithStatements(
                        newBody.Statements.Insert(0, switchToMainThreadStatement));
                }

                MethodDeclarationSyntax initializeAsyncMethodSyntax = initializeMethodSyntax
                                                                      .WithIdentifier(SyntaxFactory.Identifier(Types.AsyncPackage.InitializeAsync))
                                                                      .WithReturnType(Types.Task.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation))
                                                                      .AddModifiers(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))
                                                                      .AddParameterListParameters(
                    SyntaxFactory.Parameter(cancellationTokenLocalVarName.Identifier).WithType(Types.CancellationToken.TypeSyntax.WithAdditionalAnnotations(Simplifier.Annotation)),
                    SyntaxFactory.Parameter(progressLocalVarName.Identifier).WithType(Types.IProgress.TypeSyntaxOf(Types.ServiceProgressData.TypeSyntax).WithAdditionalAnnotations(Simplifier.Annotation)))
                                                                      .WithBody(newBody);
                updatedRoot = updatedRoot.ReplaceNode(initializeMethodSyntax, initializeAsyncMethodSyntax);

                // Replace GetService calls with GetServiceAsync
                getServiceInvocationsSyntax = updatedRoot.GetCurrentNodes <InvocationExpressionSyntax>(getServiceInvocationsSyntax).ToList();
                updatedRoot = updatedRoot.ReplaceNodes(
                    getServiceInvocationsSyntax,
                    (orig, node) =>
                {
                    InvocationExpressionSyntax invocation = node;
                    if (invocation.Expression is IdentifierNameSyntax methodName)
                    {
                        invocation = invocation.WithExpression(SyntaxFactory.IdentifierName(Types.AsyncPackage.GetServiceAsync));
                    }
                    else if (invocation.Expression is MemberAccessExpressionSyntax memberAccess)
                    {
                        invocation = invocation.WithExpression(
                            memberAccess.WithName(SyntaxFactory.IdentifierName(Types.AsyncPackage.GetServiceAsync)));
                    }

                    return(SyntaxFactory.ParenthesizedExpression(SyntaxFactory.AwaitExpression(invocation))
                           .WithAdditionalAnnotations(Simplifier.Annotation));
                });

                updatedRoot = await Utils.AddUsingTaskEqualsDirectiveAsync(updatedRoot, cancellationToken);
            }

            Document newDocument = context.Document.WithSyntaxRoot(updatedRoot);

            newDocument = await ImportAdder.AddImportsAsync(newDocument, Simplifier.Annotation, cancellationToken : cancellationToken);

            return(newDocument);
        }
コード例 #31
0
 public virtual void VisitLiteralExpresion(LiteralExpressionSyntax node)
 {
 }
コード例 #32
0
        private static ExpressionSyntax ToStringLiteral(LiteralExpressionSyntax expression)
        {
            var str = (string)expression.Token.Value;

            return(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(str)));
        }
コード例 #33
0
        public override string VisitLiteralExpression(LiteralExpressionSyntax node)
        {
            string literal = node.ToFullString().Trim();

            return(_backend.CorrectLiteral(literal));
        }
コード例 #34
0
 public LiteralExpressionTranslation(LiteralExpressionSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
 }
コード例 #35
0
        private BoundExpression BindLiteralExpression(LiteralExpressionSyntax syntax)
        {
            var value = syntax.Value ?? 0;

            return(new BoundLiteralExpression(value));
        }
コード例 #36
0
        internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken));
            var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0);

            TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32);
            BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType);
            return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteDiagnostics);
        }
コード例 #37
0
ファイル: FirstPass.cs プロジェクト: renesugar/CSharpToD
 public override void VisitLiteralExpression(LiteralExpressionSyntax literalExpression)
 {
     // I think literals do not contain types...not 100% sure though
 }
コード例 #38
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, LiteralExpressionSyntax literalExpression)
        {
            StringLiteralExpressionInfo info = SyntaxInfo.StringLiteralExpressionInfo(literalExpression);

            Debug.Assert(info.Success);

            if (!info.Success)
            {
                return;
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InsertStringInterpolation) &&
                context.SupportsCSharp6 &&
                context.Span.End < literalExpression.Span.End &&
                !CSharpUtility.IsPartOfExpressionThatMustBeConstant(literalExpression))
            {
                int startIndex = GetStartIndex(info, context.Span);

                if (startIndex != -1)
                {
                    context.RegisterRefactoring(
                        "Insert interpolation",
                        cancellationToken =>
                    {
                        return(ReplaceWithInterpolatedStringAsync(
                                   context.Document,
                                   literalExpression,
                                   startIndex,
                                   context.Span.Length,
                                   addNameOf: false,
                                   cancellationToken: cancellationToken));
                    },
                        RefactoringIdentifiers.InsertStringInterpolation);

                    if (!context.Span.IsEmpty)
                    {
                        SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        string name = StringLiteralParser.Parse(literalExpression.Token.Text, startIndex, context.Span.Length, info.IsVerbatim, isInterpolatedText: false);

                        foreach (ISymbol symbol in semanticModel.LookupSymbols(literalExpression.SpanStart))
                        {
                            if (string.Equals(name, symbol.MetadataName, StringComparison.Ordinal))
                            {
                                context.RegisterRefactoring(
                                    "Insert interpolation with nameof",
                                    cancellationToken =>
                                {
                                    return(ReplaceWithInterpolatedStringAsync(
                                               context.Document,
                                               literalExpression,
                                               startIndex,
                                               context.Span.Length,
                                               addNameOf: true,
                                               cancellationToken: cancellationToken));
                                },
                                    EquivalenceKey.Join(RefactoringIdentifiers.InsertStringInterpolation, "WithNameOf"));

                                break;
                            }
                        }
                    }
                }
            }

            if (context.Span.IsBetweenSpans(literalExpression))
            {
                if (info.IsVerbatim)
                {
                    if (info.ContainsEscapeSequence)
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiteral))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literal",
                                ct => ReplaceWithRegularStringLiteralAsync(context.Document, literalExpression, ct),
                                RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiteral);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiterals) &&
                            info.ContainsLinefeed)
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literals",
                                ct => ReplaceWithRegularStringLiteralsAsync(context.Document, literalExpression, ct),
                                RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiterals);
                        }
                    }
                }
                else if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceRegularStringLiteralWithVerbatimStringLiteral) &&
                         info.ContainsEscapeSequence)
                {
                    context.RegisterRefactoring(
                        "Replace regular string literal with verbatim string literal",
                        ct => ReplaceWithVerbatimStringLiteralAsync(context.Document, literalExpression, ct),
                        RefactoringIdentifiers.ReplaceRegularStringLiteralWithVerbatimStringLiteral);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral) &&
                CanReplaceWithStringEmpty(literalExpression))
            {
                context.RegisterRefactoring(
                    "Replace \"\" with 'string.Empty'",
                    ct => ReplaceWithStringEmptyAsync(context.Document, literalExpression, ct),
                    RefactoringIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral);
            }
        }
コード例 #39
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, LiteralExpressionSyntax literalExpression)
        {
            switch (literalExpression.Kind())
            {
            case SyntaxKind.TrueLiteralExpression:
            case SyntaxKind.FalseLiteralExpression:
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.InvertBooleanLiteral) &&
                    literalExpression.Span.Contains(context.Span))
                {
                    context.RegisterRefactoring(
                        "Invert boolean literal",
                        cancellationToken => InvertBooleanLiteralRefactoring.RefactorAsync(context.Document, literalExpression, cancellationToken),
                        RefactoringIdentifiers.InvertBooleanLiteral);
                }

                break;
            }

            case SyntaxKind.StringLiteralExpression:
            {
                if (context.Span.IsContainedInSpanOrBetweenSpans(literalExpression))
                {
                    await StringLiteralExpressionRefactoring.ComputeRefactoringsAsync(context, literalExpression).ConfigureAwait(false);
                }

                break;
            }

            case SyntaxKind.NumericLiteralExpression:
            {
                if (context.IsRefactoringEnabled(RefactoringIdentifiers.ConvertHexadecimalLiteralToDecimalLiteral) &&
                    context.Span.IsBetweenSpans(literalExpression))
                {
                    ConvertHexadecimalLiteralToDecimalLiteralRefactoring.ComputeRefactoring(context, literalExpression);
                }

                break;
            }
            }
        }
コード例 #40
0
 public static bool CanConvertStringLiteralToStringEmpty(LiteralExpressionSyntax literalExpression)
 {
     return(literalExpression.IsKind(SyntaxKind.StringLiteralExpression) &&
            literalExpression.Token.ValueText.Length == 0);
 }
コード例 #41
0
        private static void CreateField(CodeRefactoringContext context, Document document, TextSpan span, SemanticModel model, SyntaxNode root, LiteralExpressionSyntax constantLiteral, SyntaxNode parentBlock, MemberDeclarationSyntax parentTypeMember)
        {
            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("Create constant field"),
                    t2 =>
            {
                TypeInfo constType  = model.GetTypeInfo(constantLiteral);
                string newConstName = CreateName(context, root, parentBlock, constType.ConvertedType.Name);

                var newConstDecl = SyntaxFactory.FieldDeclaration(SyntaxFactory.List <AttributeListSyntax>(),
                                                                  CreateConst(),
                                                                  CreateVariableDecl(constantLiteral.Token, model, constType, newConstName)
                                                                  ).WithAdditionalAnnotations(Formatter.Annotation);

                var trackedRoot = root.TrackNodes(constantLiteral, parentTypeMember);
                var newRoot     = trackedRoot.InsertNodesBefore(trackedRoot.GetCurrentNode(parentTypeMember), new[] { newConstDecl });
                newRoot         = ReplaceWithConst(newRoot.GetCurrentNode(constantLiteral), newConstName, newRoot);
                return(Task.FromResult(document.WithSyntaxRoot(newRoot)));
            })
                );
        }
コード例 #42
0
        private static void RegisterBinaryExpressionRemoval(CodeFixContext context, SyntaxNode root, LiteralExpressionSyntax literal, BinaryExpressionSyntax binaryParent)
        {
            var otherNode = binaryParent.Left.RemoveParentheses().Equals(literal)
                ? binaryParent.Right
                : binaryParent.Left;

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
            {
                var newExpression = GetNegatedExpression(otherNode);
                var newRoot       = root.ReplaceNode(binaryParent, newExpression
                                                     .WithAdditionalAnnotations(Formatter.Annotation));

                return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot)));
            }),
                context.Diagnostics);
        }
コード例 #43
0
        public AnnotatedExpression AnnotateLiteralExpression(LiteralExpressionSyntax syntax)
        {
            var value = syntax.Value ?? 0;

            return(new AnnotatedLiteralExpression(value));
        }
コード例 #44
0
 private static void RegisterConditionalExpressionRewrite(CodeFixContext context, SyntaxNode root, LiteralExpressionSyntax literal, ConditionalExpressionSyntax conditionalParent)
 {
     context.RegisterCodeFix(
         CodeAction.Create(
             Title,
             c => Task.FromResult(RewriteConditional(context.Document, root, literal, conditionalParent))),
         context.Diagnostics);
 }
コード例 #45
0
 private static bool IsMatchingMethodParameterName(LiteralExpressionSyntax literalExpression) =>
 literalExpression.FirstAncestorOrSelf <BaseMethodDeclarationSyntax>()
 ?.ParameterList
 ?.Parameters
 .Any(p => p.Identifier.ValueText == literalExpression.Token.ValueText)
 ?? false;
コード例 #46
0
 public virtual void VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     DefaultVisit(node);
 }
コード例 #47
0
 internal static HexNumericLiteralExpressionInfo HexNumericLiteralExpressionInfo(LiteralExpressionSyntax literalExpression)
 {
     return(Syntax.HexNumericLiteralExpressionInfo.Create(literalExpression));
 }
コード例 #48
0
ファイル: CSharpUtility.cs プロジェクト: mphome/Roslynator
        public static bool IsPartOfExpressionThatMustBeConstant(LiteralExpressionSyntax literalExpression)
        {
            for (SyntaxNode parent = literalExpression.Parent; parent != null; parent = parent.Parent)
            {
                switch (parent.Kind())
                {
                case SyntaxKind.AttributeArgument:
                case SyntaxKind.Parameter:
                case SyntaxKind.CaseSwitchLabel:
                    return(true);

                case SyntaxKind.FieldDeclaration:
                    return(((FieldDeclarationSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword));

                case SyntaxKind.LocalDeclarationStatement:
                    return(((LocalDeclarationStatementSyntax)parent).Modifiers.Contains(SyntaxKind.ConstKeyword));

                case SyntaxKind.Block:
                case SyntaxKind.ExpressionStatement:
                case SyntaxKind.EmptyStatement:
                case SyntaxKind.LabeledStatement:
                case SyntaxKind.GotoStatement:
                case SyntaxKind.GotoCaseStatement:
                case SyntaxKind.GotoDefaultStatement:
                case SyntaxKind.BreakStatement:
                case SyntaxKind.ContinueStatement:
                case SyntaxKind.ReturnStatement:
                case SyntaxKind.YieldReturnStatement:
                case SyntaxKind.YieldBreakStatement:
                case SyntaxKind.ThrowStatement:
                case SyntaxKind.WhileStatement:
                case SyntaxKind.DoStatement:
                case SyntaxKind.ForStatement:
                case SyntaxKind.ForEachStatement:
                case SyntaxKind.ForEachVariableStatement:
                case SyntaxKind.UsingStatement:
                case SyntaxKind.FixedStatement:
                case SyntaxKind.CheckedStatement:
                case SyntaxKind.UncheckedStatement:
                case SyntaxKind.UnsafeStatement:
                case SyntaxKind.LockStatement:
                case SyntaxKind.IfStatement:
                case SyntaxKind.SwitchStatement:
                case SyntaxKind.TryStatement:
                case SyntaxKind.LocalFunctionStatement:
                case SyntaxKind.GlobalStatement:
                case SyntaxKind.NamespaceDeclaration:
                case SyntaxKind.ClassDeclaration:
                case SyntaxKind.StructDeclaration:
                case SyntaxKind.InterfaceDeclaration:
                case SyntaxKind.EnumDeclaration:
                case SyntaxKind.DelegateDeclaration:
                case SyntaxKind.EnumMemberDeclaration:
                case SyntaxKind.EventFieldDeclaration:
                case SyntaxKind.MethodDeclaration:
                case SyntaxKind.OperatorDeclaration:
                case SyntaxKind.ConversionOperatorDeclaration:
                case SyntaxKind.ConstructorDeclaration:
                case SyntaxKind.DestructorDeclaration:
                case SyntaxKind.PropertyDeclaration:
                case SyntaxKind.EventDeclaration:
                case SyntaxKind.IndexerDeclaration:
                case SyntaxKind.GetAccessorDeclaration:
                case SyntaxKind.SetAccessorDeclaration:
                case SyntaxKind.AddAccessorDeclaration:
                case SyntaxKind.RemoveAccessorDeclaration:
                case SyntaxKind.UnknownAccessorDeclaration:
                case SyntaxKind.IncompleteMember:
                    return(false);
                }
            }

            return(false);
        }
コード例 #49
0
        private ExpressionSyntax ParseTerm()
        {
            ExpressionSyntax expr;

            var tk = Current.Kind;

            switch (tk)
            {
            case SyntaxKind.IdentifierToken:
                expr = ParseIdentifierOrFunctionInvocationExpression();
                break;

            case SyntaxKind.FalseKeyword:
            case SyntaxKind.TrueKeyword:
            case SyntaxKind.IntegerLiteralToken:
            case SyntaxKind.FloatLiteralToken:
                expr = new LiteralExpressionSyntax(SyntaxFacts.GetLiteralExpression(Current.Kind), NextToken());
                break;

            case SyntaxKind.StringLiteralToken:
            {
                var stringTokens = new List <SyntaxToken> {
                    NextToken()
                };
                while (Current.Kind == SyntaxKind.StringLiteralToken)
                {
                    stringTokens.Add(NextToken());
                }
                expr = new StringLiteralExpressionSyntax(stringTokens);
                break;
            }

            case SyntaxKind.OpenParenToken:
                expr = ParseCastOrParenthesizedExpression();
                break;

            default:
                if (_allowLinearAndPointAsIdentifiers && (tk == SyntaxKind.LinearKeyword || tk == SyntaxKind.PointKeyword))
                {
                    goto case SyntaxKind.IdentifierToken;
                }

                if ((SyntaxFacts.IsPredefinedScalarType(tk) && tk != SyntaxKind.UnsignedKeyword && tk != SyntaxKind.VoidKeyword) || SyntaxFacts.IsPredefinedVectorType(tk) || SyntaxFacts.IsPredefinedMatrixType(tk))
                {
                    if (Lookahead.Kind == SyntaxKind.OpenParenToken)
                    {
                        expr = ParseNumericConstructorInvocationExpression();
                        break;
                    }
                }

                expr = CreateMissingIdentifierName();

                if (tk == SyntaxKind.EndOfFileToken)
                {
                    expr = WithDiagnostic(expr, DiagnosticId.ExpressionExpected);
                }
                else
                {
                    expr = WithDiagnostic(expr, DiagnosticId.InvalidExprTerm, tk.GetText());
                }

                break;
            }

            return(ParsePostFixExpression(expr));
        }
コード例 #50
0
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, LiteralExpressionSyntax literalExpression)
        {
            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InsertStringInterpolation) &&
                context.SupportsCSharp6 &&
                context.Span.End < literalExpression.Span.End)
            {
                int startIndex = GetStartIndex(context, literalExpression);

                if (startIndex != -1)
                {
                    context.RegisterRefactoring(
                        "Insert interpolation",
                        cancellationToken =>
                    {
                        return(ReplaceWithInterpolatedStringAsync(
                                   context.Document,
                                   literalExpression,
                                   startIndex,
                                   context.Span.Length,
                                   cancellationToken));
                    });
                }
            }

            if (context.Span.IsBetweenSpans(literalExpression))
            {
                string text = literalExpression.GetStringLiteralInnerText();

                if (literalExpression.IsVerbatimStringLiteral())
                {
                    if (text.Contains("\"\""))
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiteral))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literal",
                                cancellationToken =>
                            {
                                return(ReplaceWithRegularStringLiteralAsync(
                                           context.Document,
                                           literalExpression,
                                           cancellationToken));
                            });
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceVerbatimStringLiteralWithRegularStringLiterals) &&
                            text.Contains("\n"))
                        {
                            context.RegisterRefactoring(
                                "Replace verbatim string literal with regular string literals",
                                cancellationToken =>
                            {
                                return(ReplaceWithRegularStringLiteralsAsync(
                                           context.Document,
                                           literalExpression,
                                           cancellationToken));
                            });
                        }
                    }
                }
                else if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceRegularStringLiteralWithVerbatimStringLiteral) &&
                         text.Contains(@"\"))
                {
                    context.RegisterRefactoring(
                        "Replace regular string literal with verbatim string literal",
                        cancellationToken =>
                    {
                        return(ReplaceWithVerbatimStringLiteralAsync(
                                   context.Document,
                                   literalExpression,
                                   cancellationToken));
                    });
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseStringEmptyInsteadOfEmptyStringLiteral) &&
                CanReplaceWithStringEmpty(literalExpression))
            {
                context.RegisterRefactoring(
                    "Replace \"\" with 'string.Empty'",
                    cancellationToken =>
                {
                    return(ReplaceWithStringEmptyAsync(
                               context.Document,
                               literalExpression,
                               cancellationToken));
                });
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStringLiteralWithCharacterLiteral))
            {
                await ReplaceStringLiteralWithCharacterLiteralRefactoring.ComputeRefactoringAsync(context, literalExpression).ConfigureAwait(false);
            }
        }
コード例 #51
0
 /// <summary>
 /// Is syntax node used to index array
 /// </summary>
 public static bool IsArrayIndexArgument(this LiteralExpressionSyntax literal)
 {
     return(literal.Parent is ArgumentSyntax && literal.Parent.Parent is BracketedArgumentListSyntax);
 }
コード例 #52
0
        private static SyntaxNode ReplaceWithConst(LiteralExpressionSyntax expression, string newConstName, SyntaxNode root)
        {
            var newRoot = root.ReplaceNode(expression, SyntaxFactory.IdentifierName(newConstName));

            return(newRoot);
        }
コード例 #53
0
            //private void UpdateOffsets(int replaceLength, TextSpan span)
            //{
            //    Offsets[span.Start - ShiftSize] = span.Start;
            //    ShiftSize += span.Length - replaceLength;
            //    Offsets[span.Start + span.Length - ShiftSize] = span.Start + span.Length;
            //}

            public override SyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node)
            {
                //UpdateOffsets(2, node.Span);
                Offsets?.StoreOffset(node.Span.Start, node.Span.Length, 2);
                return(_literalExpression);
            }
コード例 #54
0
 private static LiteralExpressionSyntax[] GetEquivalentLiterals(LiteralExpressionSyntax sourceLiteralExpression, SyntaxNode searchRootSyntax)
 {
     return(searchRootSyntax.DescendantNodes().Where(node => node.IsEquivalentTo(sourceLiteralExpression)).OfType <LiteralExpressionSyntax>().ToArray());
 }
コード例 #55
0
 public virtual TResult VisitLiteralExpression(LiteralExpressionSyntax node)
 {
     return(DefaultVisit(node));
 }
コード例 #56
0
 public BoundLiteralExpression(LiteralExpressionSyntax syntax, TypeSymbol type)
     : base(BoundNodeKind.LiteralExpression)
 {
     Type  = type;
     Value = syntax.Token.Value;
 }
コード例 #57
0
        private ExpressionSyntax ParseTerm()
        {
            ExpressionSyntax expr;

            var tk = Current.Kind;
            switch (tk)
            {
                case SyntaxKind.IdentifierToken:
                    expr = ParseIdentifier();
                    break;
                case SyntaxKind.FalseKeyword:
                case SyntaxKind.TrueKeyword:
                case SyntaxKind.IntegerLiteralToken:
                case SyntaxKind.FloatLiteralToken:
                    expr = new LiteralExpressionSyntax(SyntaxFacts.GetLiteralExpression(Current.Kind), NextToken());
                    break;
                case SyntaxKind.StringLiteralToken:
                {
                    var stringTokens = new List<SyntaxToken> { NextToken() };
                    while (Current.Kind == SyntaxKind.StringLiteralToken)
                        stringTokens.Add(NextToken());
                    expr = new StringLiteralExpressionSyntax(stringTokens);
                    break;
                }
                case SyntaxKind.OpenParenToken:
                    expr = ParseCastOrParenthesizedExpression();
                    break;
                default:
                    if ((SyntaxFacts.IsPredefinedScalarType(tk) && tk != SyntaxKind.UnsignedKeyword && tk != SyntaxKind.VoidKeyword)
                        || SyntaxFacts.IsPredefinedVectorType(tk)
                        || SyntaxFacts.IsPredefinedMatrixType(tk))
                    {
                        if (Lookahead.Kind == SyntaxKind.OpenParenToken)
                        {
                            expr = ParseNumericConstructorInvocationExpression();
                            break;
                        }
                    }

                    expr = CreateMissingIdentifierName();

                    if (tk == SyntaxKind.EndOfFileToken)
                        expr = WithDiagnostic(expr, DiagnosticId.ExpressionExpected);
                    else
                        expr = WithDiagnostic(expr, DiagnosticId.InvalidExprTerm, tk.GetText());

                    break;
            }

            return ParsePostFixExpression(expr);
        }
コード例 #58
0
 private static void RegisterBooleanInversion(CodeFixContext context, SyntaxNode root, LiteralExpressionSyntax literal)
 {
     context.RegisterCodeFix(
         CodeAction.Create(
             Title,
             c => Task.FromResult(RemovePrefixUnary(context.Document, root, literal))),
         context.Diagnostics);
 }
コード例 #59
0
        private ExpressionSyntax ParseDirectiveTerm()
        {
            ExpressionSyntax expr;

            var tk = Current.Kind;
            switch (tk)
            {
                case SyntaxKind.IdentifierToken:
                    expr = ParseIdentifier();
                    break;
                case SyntaxKind.FalseKeyword:
                case SyntaxKind.TrueKeyword:
                case SyntaxKind.IntegerLiteralToken:
                case SyntaxKind.FloatLiteralToken:
                    expr = new LiteralExpressionSyntax(SyntaxFacts.GetLiteralExpression(Current.Kind), NextToken());
                    break;
                case SyntaxKind.OpenParenToken:
                    expr = ParseDirectiveParenthesizedExpression();
                    break;
                default:
                    expr = CreateMissingIdentifierName();

                    if (tk == SyntaxKind.EndOfFileToken)
                        expr = WithDiagnostic(expr, DiagnosticId.ExpressionExpected);
                    else
                        expr = WithDiagnostic(expr, DiagnosticId.InvalidExprTerm, tk.GetText());

                    break;
            }

            // Might be function invocation. We only have one function in the preprocessor - "defined".
            if (Current.Kind == SyntaxKind.OpenParenToken && expr.Kind == SyntaxKind.IdentifierName
                && ((IdentifierNameSyntax) expr).Name.ContextualKind == SyntaxKind.DefinedKeyword)
            {
                _lexer.ExpandMacros = false;

                var openParen = Match(SyntaxKind.OpenParenToken);
                var name = new IdentifierNameSyntax(NextToken());

                _lexer.ExpandMacros = true;

                var closeParen = Match(SyntaxKind.CloseParenToken);
                expr = new InvocationExpressionSyntax(expr, new ArgumentListSyntax(
                    openParen,
                    new SeparatedSyntaxList<ExpressionSyntax>(new List<SyntaxNode> { name }),
                    closeParen));
            }

            return expr;
        }
コード例 #60
0
 private UrlTemplate(LiteralExpressionSyntax literal, ImmutableArray <Component> path)
 {
     this.Literal = literal;
     this.Path    = path;
 }