コード例 #1
0
 private static TypeSyntax GenerateTypeSyntax(ITypeSymbol type, OptionSet options)
 {
     return(type.ContainsAnonymousType() ||
            (true /*options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals)*/ && type.TypeKind != TypeKind.Delegate)
                         ? SyntaxFactory.IdentifierName("var")
                                 : type.GenerateTypeSyntax());
 }
コード例 #2
0
        protected override bool TryConvertToLocalDeclaration(ITypeSymbol type, SyntaxToken identifierToken, SemanticModel semanticModel, CancellationToken cancellationToken, out SyntaxNode newRoot)
        {
            var token = identifierToken;
            var node  = identifierToken.Parent as IdentifierNameSyntax;

            if (node.IsLeftSideOfAssignExpression() && node.Parent.IsParentKind(SyntaxKind.ExpressionStatement))
            {
                var assignExpression    = (AssignmentExpressionSyntax)node.Parent;
                var expressionStatement = (StatementSyntax)assignExpression.Parent;

                var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
                    SyntaxFactory.VariableDeclaration(
                        type.GenerateTypeSyntax(),
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.VariableDeclarator(token, null, SyntaxFactory.EqualsValueClause(
                                                                 assignExpression.OperatorToken, assignExpression.Right)))));
                declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);

                var root = token.GetAncestor <CompilationUnitSyntax>();
                newRoot = root.ReplaceNode(expressionStatement, declarationStatement);

                return(true);
            }

            newRoot = null;
            return(false);
        }
コード例 #3
0
        public override SyntaxNode CreateDefaultExpression(ITypeSymbol type)
        {
            // If it's just a reference type, then "null" is the default expression for it.  Note:
            // this counts for actual reference type, or a type parameter with a 'class' constraint.
            // Also, if it's a nullable type, then we can use "null".
            if (type.IsReferenceType ||
                type.IsPointerType() ||
                type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
            {
                return(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
            }

            switch (type.SpecialType)
            {
            case SpecialType.System_Boolean:
                return(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));

            case SpecialType.System_SByte:
            case SpecialType.System_Byte:
            case SpecialType.System_Int16:
            case SpecialType.System_UInt16:
            case SpecialType.System_Int32:
            case SpecialType.System_UInt32:
            case SpecialType.System_Int64:
            case SpecialType.System_UInt64:
            case SpecialType.System_Decimal:
            case SpecialType.System_Single:
            case SpecialType.System_Double:
                return(SyntaxFactory.LiteralExpression(
                           SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)));
            }

            // Default to a "default(<typename>)" expression.
            return(SyntaxFactory.DefaultExpression(type.GenerateTypeSyntax()));
        }
            private StatementSyntax GenerateVariableDeclaration(
                ExpressionSyntax switchExpression,
                ITypeSymbol declaratorToRemoveTypeOpt
                )
            {
                Debug.Assert(_assignmentTargetOpt is IdentifierNameSyntax);

                // There is a probability that we cannot use var if the declaration type is a reference type or nullable type.
                // In these cases, we generate the explicit type for now and decide later whether or not to use var.
                var cannotUseVar =
                    declaratorToRemoveTypeOpt != null &&
                    (
                        declaratorToRemoveTypeOpt.IsReferenceType ||
                        declaratorToRemoveTypeOpt.IsNullable()
                    );
                var type = cannotUseVar
                    ? declaratorToRemoveTypeOpt.GenerateTypeSyntax()
                    : IdentifierName("var");

                return(LocalDeclarationStatement(
                           VariableDeclaration(
                               type,
                               variables: SingletonSeparatedList(
                                   VariableDeclarator(
                                       identifier: ((IdentifierNameSyntax)_assignmentTargetOpt).Identifier,
                                       argumentList: null,
                                       initializer: EqualsValueClause(switchExpression)
                                       )
                                   )
                               )
                           ));
            }
コード例 #5
0
        private SyntaxNode FixMethod(
            bool keepVoid, IMethodSymbol methodSymbol, MethodDeclarationSyntax method,
            ITypeSymbol taskType, INamedTypeSymbol taskOfTType)
        {
            var newReturnType = method.ReturnType;

            if (methodSymbol.ReturnsVoid)
            {
                if (!keepVoid)
                {
                    newReturnType = taskType.GenerateTypeSyntax();
                }
            }
            else
            {
                if (!IsTaskLike(methodSymbol.ReturnType, taskType, taskOfTType))
                {
                    // If it's not already Task-like, then wrap the existing return type
                    // in Task<>.
                    newReturnType = taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax();
                }
            }

            var newModifiers = method.Modifiers.Add(s_asyncToken);

            return(method.WithReturnType(newReturnType).WithModifiers(newModifiers));
        }
コード例 #6
0
        private SyntaxNode FixMethod(
            bool keepVoid, IMethodSymbol methodSymbol, MethodDeclarationSyntax method,
            ITypeSymbol taskType, INamedTypeSymbol taskOfTType)
        {
            var newReturnType = method.ReturnType;

            if (methodSymbol.ReturnsVoid)
            {
                if (!keepVoid)
                {
                    newReturnType = taskType.GenerateTypeSyntax();
                }
            }
            else
            {
                if (!IsTaskLike(methodSymbol.ReturnType, taskType, taskOfTType))
                {
                    // If it's not already Task-like, then wrap the existing return type
                    // in Task<>.
                    newReturnType = taskOfTType.Construct(methodSymbol.ReturnType).GenerateTypeSyntax();
                }
            }

            var newModifiers = method.Modifiers.Add(s_asyncToken);
            return method.WithReturnType(newReturnType).WithModifiers(newModifiers);
        }
コード例 #7
0
        internal static ExpressionSyntax GenerateNonEnumValueExpression(
            ITypeSymbol type, object value, bool canUseFieldReference)
        {
            if (value is bool)
            {
                return(SyntaxFactory.LiteralExpression((bool)value
                    ? SyntaxKind.TrueLiteralExpression
                    : SyntaxKind.FalseLiteralExpression));
            }

            if (value is string)
            {
                var valueString = CSharp.SymbolDisplay.FormatLiteral((string)value, quote: true);
                return(SyntaxFactory.LiteralExpression(
                           SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(valueString, (string)value)));
            }

            if (value is char)
            {
                var charValue = (char)value;
                var literal   = CSharp.SymbolDisplay.FormatLiteral(charValue, quote: true);
                return(SyntaxFactory.LiteralExpression(
                           SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal(literal, charValue)));
            }

            if (value is sbyte || value is short || value is int || value is long ||
                value is byte || value is ushort || value is uint || value is ulong)
            {
                var suffix = DetermineSuffix(type, value);
                return(GenerateIntegralLiteralExpression(type, value, suffix, canUseFieldReference));
            }

            if (value is float)
            {
                var suffix = DetermineSuffix(type, value);
                return(GenerateSingleLiteralExpression(type, (float)value, suffix, canUseFieldReference));
            }

            if (value is double)
            {
                var suffix = DetermineSuffix(type, value);
                return(GenerateDoubleLiteralExpression(type, (double)value, suffix, canUseFieldReference));
            }

            if (value is decimal)
            {
                var suffix = DetermineSuffix(type, value);
                return(GenerateDecimalLiteralExpression(type, value, suffix, canUseFieldReference));
            }

            if (type == null || type.IsReferenceType || type.IsPointerType())
            {
                return(GenerateNullLiteral());
            }
            else
            {
                return(SyntaxFactory.DefaultExpression(type.GenerateTypeSyntax()));
            }
        }
コード例 #8
0
 public override SyntaxNode CreateLocalDeclarationStatement(bool isConst, ITypeSymbol type, SyntaxNode variableDeclarator)
 {
     return(SyntaxFactory.LocalDeclarationStatement(
                isConst ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList),
                SyntaxFactory.VariableDeclaration(
                    type == null ? SyntaxFactory.IdentifierName("var") : type.GenerateTypeSyntax(),
                    SyntaxFactory.SingletonSeparatedList((VariableDeclaratorSyntax)variableDeclarator))));
 }
コード例 #9
0
        public static TypeSyntax GenerateTypeSyntaxOrVar(
            this ITypeSymbol symbol, OptionSet options, bool typeIsApparent)
        {
            var useVar = IsVarDesired(symbol, options, typeIsApparent);

            return(useVar
                ? SyntaxFactory.IdentifierName("var")
                : symbol.GenerateTypeSyntax());
        }
コード例 #10
0
 public static CastExpressionSyntax Cast(
     this ExpressionSyntax expression,
     ITypeSymbol targetType)
 {
     return(SyntaxFactory.CastExpression(
                type: targetType.GenerateTypeSyntax(),
                expression: expression.Parenthesize())
            .WithAdditionalAnnotations(Simplifier.Annotation));
 }
コード例 #11
0
 public static CastExpressionSyntax Cast(
     this ExpressionSyntax expression,
     ITypeSymbol targetType)
 {
     return SyntaxFactory.CastExpression(
         type: targetType.GenerateTypeSyntax(),
         expression: expression.Parenthesize())
         .WithAdditionalAnnotations(Simplifier.Annotation);
 }
コード例 #12
0
            public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                ITypeSymbol underlyingType = symbol;

                while (underlyingType is IArrayTypeSymbol innerArray)
                {
                    underlyingType = innerArray.ElementType;

#if !CODE_STYLE // TODO: Remove the #if once NullableAnnotation is available.
                    // https://github.com/dotnet/roslyn/issues/41462 tracks adding this support
                    if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated)
                    {
                        // If the inner array we just moved to is also nullable, then
                        // we must terminate the digging now so we produce the syntax for that,
                        // and then append the ranks we passed through at the end. This is because
                        // nullability annotations acts as a "barrier" where we won't reorder array
                        // through. So whereas:
                        //
                        //     string[][,]
                        //
                        // is really an array of rank 1 that has an element of rank 2,
                        //
                        //     string[]?[,]
                        //
                        // is really an array of rank 2 that has nullable elements of rank 1.

                        break;
                    }
#endif
                }

                var elementTypeSyntax = underlyingType.GenerateTypeSyntax();
                var ranks             = new List <ArrayRankSpecifierSyntax>();

                var arrayType = symbol;
                while (arrayType != null && !arrayType.Equals(underlyingType))
                {
                    ranks.Add(SyntaxFactory.ArrayRankSpecifier(
                                  SyntaxFactory.SeparatedList(Enumerable.Repeat <ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank))));

                    arrayType = arrayType.ElementType as IArrayTypeSymbol;
                }

                TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList());

#if !CODE_STYLE // TODO: Remove the #if once NullableAnnotation is available.
                // https://github.com/dotnet/roslyn/issues/41462 tracks adding this support
                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax);
                }
#endif

                return(AddInformationTo(arrayTypeSyntax, symbol));
            }
コード例 #13
0
        public static CastExpressionSyntax Cast(
            this ExpressionSyntax expression,
            ITypeSymbol targetType)
        {
            var parenthesized  = expression.Parenthesize();
            var castExpression = SyntaxFactory.CastExpression(
                targetType.GenerateTypeSyntax(), parenthesized.WithoutTrivia()).WithTriviaFrom(parenthesized);

            return(castExpression.WithAdditionalAnnotations(Simplifier.Annotation));
        }
コード例 #14
0
        private static async Task <Document> FixAsync(
            Document document, TextSpan span, ITypeSymbol type, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var variableDeclaration = (VariableDeclarationSyntax)root.FindNode(span);

            var newRoot = root.ReplaceNode(variableDeclaration.Type, type.GenerateTypeSyntax(allowVar: false));

            return(document.WithSyntaxRoot(newRoot));
        }
コード例 #15
0
            public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol)
            {
                ThrowIfNameOnly();

                ITypeSymbol underlyingType = symbol;

                while (underlyingType is IArrayTypeSymbol innerArray)
                {
                    underlyingType = innerArray.ElementType;

                    if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated)
                    {
                        // If the inner array we just moved to is also nullable, then
                        // we must terminate the digging now so we produce the syntax for that,
                        // and then append the ranks we passed through at the end. This is because
                        // nullability annotations acts as a "barrier" where we won't reorder array
                        // through. So whereas:
                        //
                        //     string[][,]
                        //
                        // is really an array of rank 1 that has an element of rank 2,
                        //
                        //     string[]?[,]
                        //
                        // is really an array of rank 2 that has nullable elements of rank 1.

                        break;
                    }
                }

                var elementTypeSyntax = underlyingType.GenerateTypeSyntax();

                using var _ = ArrayBuilder <ArrayRankSpecifierSyntax> .GetInstance(out var ranks);

                var arrayType = symbol;

                while (arrayType != null && !arrayType.Equals(underlyingType))
                {
                    ranks.Add(SyntaxFactory.ArrayRankSpecifier(
                                  SyntaxFactory.SeparatedList(Enumerable.Repeat <ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank))));

                    arrayType = arrayType.ElementType as IArrayTypeSymbol;
                }

                TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList());

                if (symbol.NullableAnnotation == NullableAnnotation.Annotated)
                {
                    arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax);
                }

                return(AddInformationTo(arrayTypeSyntax, symbol));
            }
コード例 #16
0
        /// <summary>
        /// Adds to <paramref name="targetType"/> if it does not contain an anonymous
        /// type and binds to the same type at the given <paramref name="position"/>.
        /// </summary>
        public static ExpressionSyntax CastIfPossible(
            this ExpressionSyntax expression,
            ITypeSymbol targetType,
            int position,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            if (targetType.ContainsAnonymousType())
            {
                return(expression);
            }

            if (targetType.IsSystemVoid())
            {
                return(expression);
            }

            if (targetType.Kind == SymbolKind.DynamicType)
            {
                targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
            }

            var typeSyntax = targetType.GenerateTypeSyntax();
            var type       = semanticModel.GetSpeculativeTypeInfo(
                position,
                typeSyntax,
                SpeculativeBindingOption.BindAsTypeOrNamespace).Type;

            if (!targetType.Equals(type))
            {
                return(expression);
            }

            var castExpression = expression.Cast(targetType);

            // Ensure that inserting the cast doesn't change the semantics.
            var specAnalyzer             = new SpeculationAnalyzer(expression, castExpression, semanticModel, cancellationToken);
            var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;

            if (speculativeSemanticModel == null)
            {
                return(expression);
            }

            var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;

            if (!CastSimplifier.IsUnnecessaryCast(speculatedCastExpression, speculativeSemanticModel, cancellationToken))
            {
                return(expression);
            }

            return(castExpression);
        }
コード例 #17
0
        public static TypeSyntax GenerateTypeSyntaxOrVar(
            ITypeSymbol symbol, OptionSet options)
        {
            var useVar = IsVarDesired(symbol, options);

            // Note: we cannot use ".GenerateTypeSyntax()" only here.  that's because we're
            // actually creating a DeclarationExpression and currently the Simplifier cannot
            // analyze those due to limitations between how it uses Speculative SemanticModels
            // and how those don't handle new declarations well.
            return(useVar
                ? SyntaxFactory.IdentifierName("var")
                : symbol.GenerateTypeSyntax());
        }
コード例 #18
0
        /// <summary>
        /// Return type syntax following code style options for the given type
        /// </summary>
        public static TypeSyntax GetTypeExpression(
            this SyntaxGenerator generator, OptionSet options, ITypeSymbol type)
        {
            // types are not apparent in foreach statements.
            var isBuiltInTypeContext = IsBuiltInType(type);

            if (IsImplicitStylePreferred(options, isBuiltInTypeContext, isTypeApparentContext: false))
            {
                return(SyntaxFactory.IdentifierName("var"));
            }
            else
            {
                return(type.GenerateTypeSyntax(allowVar: false));
            }
        }
コード例 #19
0
        protected override SyntaxNode ConvertForNode(
            ForStatementSyntax forStatement, TypeSyntax typeNode,
            SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression,
            ITypeSymbol iterationVariableType, OptionSet optionSet)
        {
            typeNode ??= iterationVariableType.GenerateTypeSyntax();

            return(SyntaxFactory.ForEachStatement(
                       SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword),
                       forStatement.OpenParenToken,
                       typeNode,
                       foreachIdentifier,
                       SyntaxFactory.Token(SyntaxKind.InKeyword),
                       collectionExpression,
                       forStatement.CloseParenToken,
                       forStatement.Statement));
        }
コード例 #20
0
        private static TypeSyntax GenerateTypeSyntax(ITypeSymbol type, OptionSet options, ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            // if there isn't a semantic model, we cannot perform further analysis.
            if (semanticModel != null)
            {
                if (type.ContainsAnonymousType())
                {
                    return(SyntaxFactory.IdentifierName("var"));
                }

                if (type.TypeKind != TypeKind.Delegate &&
                    TypeStyleHelper.IsImplicitTypePreferred(expression, semanticModel, options, cancellationToken))
                {
                    return(SyntaxFactory.IdentifierName("var"));
                }
            }

            return(type.GenerateTypeSyntax());
        }
コード例 #21
0
        internal static ExpressionSyntax GenerateNonEnumValueExpression(
            ITypeSymbol type, object value, bool canUseFieldReference)
        {
            switch (value)
            {
            case bool val: return(GenerateBooleanLiteralExpression(val));

            case string val: return(GenerateStringLiteralExpression(val));

            case char val: return(GenerateCharLiteralExpression(val));

            case sbyte val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.SByteSpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)));

            case short val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.Int16SpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)));

            case int val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.Int32SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));

            case long val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.Int64SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));

            case byte val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.ByteSpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)));

            case ushort val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.UInt16SpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, (uint)v)));

            case uint val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.UInt32SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));

            case ulong val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.UInt64SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));

            case float val: return(GenerateSingleLiteralExpression(type, val, canUseFieldReference));

            case double val: return(GenerateDoubleLiteralExpression(type, val, canUseFieldReference));

            case decimal val: return(GenerateLiteralExpression(type, val, LiteralSpecialValues.DecimalSpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
            }

            return(type == null || type.IsReferenceType || type.IsPointerType() || type.IsNullable()
                ? GenerateNullLiteral()
                : SyntaxFactory.DefaultExpression(type.GenerateTypeSyntax()));
        }
コード例 #22
0
ファイル: CSharpSyntaxFactory.cs プロジェクト: nagyist/roslyn
 public override SyntaxNode CreateObjectCreationExpression(ITypeSymbol typeName, IList<SyntaxNode> arguments)
 {
     return SyntaxFactory.ObjectCreationExpression(typeName.GenerateTypeSyntax(), CreateArgumentList(arguments), null);
 }
コード例 #23
0
        /// <summary>
        /// Adds to <paramref name="targetType"/> if it does not contain an anonymous
        /// type and binds to the same type at the given <paramref name="position"/>.
        /// </summary>
        public static ExpressionSyntax CastIfPossible(
            this ExpressionSyntax expression,
            ITypeSymbol targetType,
            int position,
            SemanticModel semanticModel,
            out bool wasCastAdded)
        {
            wasCastAdded = false;

            if (targetType.ContainsAnonymousType())
            {
                return expression;
            }

            if (targetType.Kind == SymbolKind.DynamicType)
            {
                targetType = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
            }

            var typeSyntax = targetType.GenerateTypeSyntax();
            var type = semanticModel.GetSpeculativeTypeInfo(
                position,
                typeSyntax,
                SpeculativeBindingOption.BindAsTypeOrNamespace).Type;

            if (!targetType.Equals(type))
            {
                return expression;
            }

            var castExpression = expression.Cast(targetType);

            // Ensure that inserting the cast doesn't change the semantics.
            var specAnalyzer = new SpeculationAnalyzer(expression, castExpression, semanticModel, CancellationToken.None);
            var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel;
            if (speculativeSemanticModel == null)
            {
                return expression;
            }

            var speculatedCastExpression = (CastExpressionSyntax)specAnalyzer.ReplacedExpression;
            if (!speculatedCastExpression.IsUnnecessaryCast(speculativeSemanticModel, CancellationToken.None))
            {
                return expression;
            }

            wasCastAdded = true;
            return castExpression;
        }
コード例 #24
0
		public string GetTypeReferenceString (ITypeSymbol type, bool highlight = true)
		{
			if (type == null)
				throw new ArgumentNullException (nameof (type));
			if (type.TypeKind == TypeKind.Error) {
				var typeSyntax = type.GenerateTypeSyntax ();
				string generatedTypeSyntaxString;
				try {
					var oldDoc = ctx.AnalysisDocument;
					var newDoc = oldDoc.WithSyntaxRoot (SyntaxFactory.ParseCompilationUnit (typeSyntax.ToString ()).WithAdditionalAnnotations (Simplifier.Annotation));
					var reducedDoc = Simplifier.ReduceAsync (newDoc, options);
					generatedTypeSyntaxString = Ambience.EscapeText (reducedDoc.Result.GetSyntaxRootAsync ().Result.ToString ());
				} catch {
					generatedTypeSyntaxString = typeSyntax != null ? Ambience.EscapeText (typeSyntax.ToString ()) : "?";
				}
				return highlight ? HighlightSemantically (generatedTypeSyntaxString, colorStyle.UserTypes) : generatedTypeSyntaxString;
			}
			if (type.TypeKind == TypeKind.Array) {
				var arrayType = (IArrayTypeSymbol)type;
				return GetTypeReferenceString (arrayType.ElementType, highlight) + "[" + new string (',', arrayType.Rank - 1) + "]";
			}
			if (type.TypeKind == TypeKind.Pointer)
				return GetTypeReferenceString (((IPointerTypeSymbol)type).PointedAtType, highlight) + "*";
			string displayString;
			if (ctx != null) {
				SemanticModel model = SemanticModel;
				if (model == null) {
					var parsedDocument = ctx.ParsedDocument;
					if (parsedDocument != null) {
						model = parsedDocument.GetAst<SemanticModel> () ?? ctx.AnalysisDocument?.GetSemanticModelAsync ().Result;
					}
				}
				//Math.Min (model.SyntaxTree.Length, offset)) is needed in case parsedDocument.GetAst<SemanticModel> () is outdated
				//this is tradeoff between performance and consistency between editor text(offset) and model, since
				//ToMinimalDisplayString can use little outdated model this is fine
				//but in case of Sketches where user usually is at end of document when typing text this can throw exception
				//because offset can be >= Length
				displayString = model != null ? RoslynCompletionData.SafeMinimalDisplayString (type, model, Math.Min (model.SyntaxTree.Length - 1, offset), MonoDevelop.Ide.TypeSystem.Ambience.LabelFormat) : type.Name;
			} else {
				displayString = type.ToDisplayString (MonoDevelop.Ide.TypeSystem.Ambience.LabelFormat);
			}
			var text = MonoDevelop.Ide.TypeSystem.Ambience.EscapeText (displayString);
			return highlight ? HighlightSemantically (text, colorStyle.UserTypes) : text;
		}
コード例 #25
0
 internal static ExpressionSyntax GenerateNonEnumValueExpression(
     ITypeSymbol type, object value, bool canUseFieldReference)
 {
     if (value is bool)
     {
         return(SyntaxFactory.LiteralExpression((bool)value
             ? SyntaxKind.TrueLiteralExpression
             : SyntaxKind.FalseLiteralExpression));
     }
     else if (value is string)
     {
         var valueString = SymbolDisplay.FormatLiteral((string)value, quote: true);
         return(SyntaxFactory.LiteralExpression(
                    SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(valueString, (string)value)));
     }
     else if (value is char)
     {
         var charValue = (char)value;
         var literal   = SymbolDisplay.FormatLiteral(charValue, quote: true);
         return(SyntaxFactory.LiteralExpression(
                    SyntaxKind.CharacterLiteralExpression, SyntaxFactory.Literal(literal, charValue)));
     }
     else if (value is sbyte)
     {
         return(GenerateLiteralExpression(type, (sbyte)value, LiteralSpecialValues.SByteSpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)));
     }
     else if (value is short)
     {
         return(GenerateLiteralExpression(type, (short)value, LiteralSpecialValues.Int16SpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, v)));
     }
     else if (value is int)
     {
         return(GenerateLiteralExpression(type, (int)value, LiteralSpecialValues.Int32SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
     }
     else if (value is long)
     {
         return(GenerateLiteralExpression(type, (long)value, LiteralSpecialValues.Int64SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
     }
     else if (value is byte)
     {
         return(GenerateLiteralExpression(type, (byte)value, LiteralSpecialValues.ByteSpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, (int)v)));
     }
     else if (value is ushort)
     {
         return(GenerateLiteralExpression(type, (ushort)value, LiteralSpecialValues.UInt16SpecialValues, null, canUseFieldReference, (s, v) => SyntaxFactory.Literal(s, (uint)v)));
     }
     else if (value is uint)
     {
         return(GenerateLiteralExpression(type, (uint)value, LiteralSpecialValues.UInt32SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
     }
     else if (value is ulong)
     {
         return(GenerateLiteralExpression(type, (ulong)value, LiteralSpecialValues.UInt64SpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
     }
     else if (value is float)
     {
         return(GenerateSingleLiteralExpression(type, (float)value, canUseFieldReference));
     }
     else if (value is double)
     {
         return(GenerateDoubleLiteralExpression(type, (double)value, canUseFieldReference));
     }
     else if (value is decimal)
     {
         return(GenerateLiteralExpression(type, (decimal)value, LiteralSpecialValues.DecimalSpecialValues, null, canUseFieldReference, SyntaxFactory.Literal));
     }
     else if (type == null || type.IsReferenceType || type.IsPointerType())
     {
         return(GenerateNullLiteral());
     }
     else
     {
         return(SyntaxFactory.DefaultExpression(type.GenerateTypeSyntax()));
     }
 }
コード例 #26
0
 public override SyntaxNode CreateObjectCreationExpression(ITypeSymbol typeName, IList <SyntaxNode> arguments)
 {
     return(SyntaxFactory.ObjectCreationExpression(typeName.GenerateTypeSyntax(), CreateArgumentList(arguments), null));
 }
コード例 #27
0
ファイル: CSharpSyntaxFactory.cs プロジェクト: nagyist/roslyn
 public override SyntaxNode CreateAsExpression(SyntaxNode expression, ITypeSymbol type)
 {
     return SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, Parenthesize(expression), type.GenerateTypeSyntax());
 }
コード例 #28
0
 public override SyntaxNode CreateConvertExpression(ITypeSymbol type, SyntaxNode expression)
 {
     return(SyntaxFactory.CastExpression(type.GenerateTypeSyntax(), Parenthesize(expression)));
 }
コード例 #29
0
 public override SyntaxNode CreateAsExpression(SyntaxNode expression, ITypeSymbol type)
 {
     return(SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, Parenthesize(expression), type.GenerateTypeSyntax()));
 }
コード例 #30
0
ファイル: CSharpSyntaxFactory.cs プロジェクト: nagyist/roslyn
 public override SyntaxNode CreateConvertExpression(ITypeSymbol type, SyntaxNode expression)
 {
     return SyntaxFactory.CastExpression(type.GenerateTypeSyntax(), Parenthesize(expression));
 }
コード例 #31
0
ファイル: CSharpSyntaxFactory.cs プロジェクト: nagyist/roslyn
 public override SyntaxNode CreateLocalDeclarationStatement(bool isConst, ITypeSymbol type, SyntaxNode variableDeclarator)
 {
     return SyntaxFactory.LocalDeclarationStatement(
         isConst ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList),
         SyntaxFactory.VariableDeclaration(
             type == null ? SyntaxFactory.IdentifierName("var") : type.GenerateTypeSyntax(),
             SyntaxFactory.SingletonSeparatedList((VariableDeclaratorSyntax)variableDeclarator)));
 }
コード例 #32
0
        public override TDeclarationNode UpdateDeclarationType <TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken)
        {
            var syntaxNode = declaration as CSharpSyntaxNode;

            if (syntaxNode == null)
            {
                return(declaration);
            }

            TypeSyntax newTypeSyntax;

            switch (syntaxNode.Kind())
            {
            case SyntaxKind.DelegateDeclaration:
                // Handle delegate declarations.
                var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia())
                                .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)));

            case SyntaxKind.MethodDeclaration:
                // Handle method declarations.
                var methodDeclarationSyntax = declaration as MethodDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia())
                                .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)));

            case SyntaxKind.OperatorDeclaration:
                // Handle operator declarations.
                var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia())
                                .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)));

            case SyntaxKind.ConversionOperatorDeclaration:
                // Handle conversion operator declarations.
                var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.PropertyDeclaration:
                // Handle properties.
                var propertyDeclaration = declaration as PropertyDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)));

            case SyntaxKind.EventDeclaration:
                // Handle events.
                var eventDeclarationSyntax = declaration as EventDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.IndexerDeclaration:
                // Handle indexers.
                var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.Parameter:
                // Handle parameters.
                var parameterSyntax = declaration as ParameterSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.IncompleteMember:
                // Handle incomplete members.
                var incompleteMemberSyntax = declaration as IncompleteMemberSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.ArrayType:
                // Handle array type.
                var arrayTypeSyntax = declaration as ArrayTypeSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia())
                                .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)));

            case SyntaxKind.PointerType:
                // Handle pointer type.
                var pointerTypeSyntax = declaration as PointerTypeSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia())
                                .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)));

            case SyntaxKind.VariableDeclaration:
                // Handle variable declarations.
                var variableDeclarationSyntax = declaration as VariableDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)));

            case SyntaxKind.CatchDeclaration:
                // Handle catch declarations.
                var catchDeclarationSyntax = declaration as CatchDeclarationSyntax;
                newTypeSyntax = newType.GenerateTypeSyntax()
                                .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia())
                                .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia());
                return(Cast <TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)));

            default:
                return(declaration);
            }
        }
コード例 #33
0
ファイル: CSharpSyntaxFactory.cs プロジェクト: nagyist/roslyn
        public override SyntaxNode CreateDefaultExpression(ITypeSymbol type)
        {
            // If it's just a reference type, then "null" is the default expression for it.  Note:
            // this counts for actual reference type, or a type parameter with a 'class' constraint.
            // Also, if it's a nullable type, then we can use "null".
            if (type.IsReferenceType ||
                type.IsPointerType() ||
                type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
            {
                return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
            }

            switch (type.SpecialType)
            {
                case SpecialType.System_Boolean:
                    return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression);
                case SpecialType.System_SByte:
                case SpecialType.System_Byte:
                case SpecialType.System_Int16:
                case SpecialType.System_UInt16:
                case SpecialType.System_Int32:
                case SpecialType.System_UInt32:
                case SpecialType.System_Int64:
                case SpecialType.System_UInt64:
                case SpecialType.System_Decimal:
                case SpecialType.System_Single:
                case SpecialType.System_Double:
                    return SyntaxFactory.LiteralExpression(
                        SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0));
            }

            // Default to a "default(<typename>)" expression.
            return SyntaxFactory.DefaultExpression(type.GenerateTypeSyntax());
        }