コード例 #1
0
 public static glsl.TypeSyntax Translate(this cs.TypeSyntax node)
 {
     return(new glsl.TypeSyntax()
     {
         Name = node.ToString()
     });
 }
コード例 #2
0
        public static SyntaxNode ArrayCreationExpression(this SyntaxGenerator generator, SyntaxNode type, IEnumerable <SyntaxNode> sizeExpression)
        {
            if (generator.NullLiteralExpression() is CS.ExpressionSyntax)
            {
                CS.TypeSyntax typeSyntax = type as CS.TypeSyntax;
                if (typeSyntax == null)
                {
                    throw new ArgumentException($"Invalid syntax node type; Expected {typeof(CS.TypeSyntax).FullName}.", "type");
                }

                IEnumerable <CS.ExpressionSyntax> csSizeExpressions = sizeExpression.Select(exp => exp as CS.ExpressionSyntax);
                if (csSizeExpressions.Any(exp => exp == null))
                {
                    throw new ArgumentException($"Invalid syntax node type; Expected {typeof(CS.ExpressionSyntax).FullName}.", "sizeExpression");
                }

                return(CSSF.ArrayCreationExpression(
                           CSSF.ArrayType(
                               typeSyntax,
                               CSSF.SingletonList(
                                   CSSF.ArrayRankSpecifier(
                                       CSSF.SeparatedList(csSizeExpressions)
                                       )
                                   )
                               )
                           ));
            }
            else
            {
                throw new ArgumentException("Not a CSharp ExpressionSyntax");
            }
        }
コード例 #3
0
 public static MethodDeclarationSyntax MethodDeclaration(
     SyntaxList<AttributeListSyntax> attributeLists,
     SyntaxTokenList modifiers,
     TypeSyntax returnType,
     ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
     SyntaxToken identifier,
     TypeParameterListSyntax typeParameterList,
     ParameterListSyntax parameterList,
     SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses,
     BlockSyntax body,
     SyntaxToken semicolonToken)
 {
     return SyntaxFactory.MethodDeclaration(
         attributeLists,
         modifiers,
         default(SyntaxToken),
         returnType,
         explicitInterfaceSpecifier,
         identifier,
         typeParameterList,
         parameterList,
         constraintClauses,
         body,
         default(ArrowExpressionClauseSyntax),
         semicolonToken);
 }
コード例 #4
0
        protected override bool TryAnalyzeVariableDeclaration(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken, out TextSpan issueSpan)
        {
            issueSpan = default(TextSpan);

            // If it is currently not var, explicit typing exists, return. 
            // this also takes care of cases where var is mapped to a named type via an alias or a class declaration.
            if (!typeName.IsTypeInferred(semanticModel))
            {
                return false;
            }

            if (typeName.Parent.IsKind(SyntaxKind.VariableDeclaration) &&
                typeName.Parent.Parent.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement))
            {
                // check assignment for variable declarations.
                var variable = ((VariableDeclarationSyntax)typeName.Parent).Variables.First();
                if (!AssignmentSupportsStylePreference(variable.Identifier, typeName, variable.Initializer, semanticModel, optionSet, cancellationToken))
                {
                    return false;
                }
            }

            issueSpan = typeName.Span;
            return true;
        }
        private static void HandleDeclaration(SyntaxNodeAnalysisContext context, TypeSyntax returnType)
        {
            var predefinedType = returnType as PredefinedTypeSyntax;

            if (predefinedType != null && predefinedType.Keyword.IsKind(SyntaxKind.VoidKeyword))
            {
                // There is no return value
                return;
            }

            var documentationStructure = context.Node.GetDocumentationCommentTriviaSyntax();

            if (documentationStructure == null)
            {
                return;
            }

            if (documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.InheritdocXmlTag) != null)
            {
                // Don't report if the documentation is inherited.
                return;
            }

            if (documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.ReturnsXmlTag) == null)
            {
                context.ReportDiagnostic(Diagnostic.Create(Descriptor, returnType.GetLocation()));
            }
        }
コード例 #6
0
            public override SyntaxList <StatementSyntax> VisitForEachBlock(VBSyntax.ForEachBlockSyntax node)
            {
                var stmt = node.ForEachStatement;

                TypeSyntax  type = null;
                SyntaxToken id;

                if (stmt.ControlVariable is VBSyntax.VariableDeclaratorSyntax)
                {
                    var v           = (VBSyntax.VariableDeclaratorSyntax)stmt.ControlVariable;
                    var declaration = SplitVariableDeclarations(v, nodesVisitor, semanticModel).Values.Single();
                    type = declaration.Type;
                    id   = declaration.Variables[0].Identifier;
                }
                else
                {
                    var v = (IdentifierNameSyntax)stmt.ControlVariable.Accept(nodesVisitor);
                    id   = v.Identifier;
                    type = SyntaxFactory.ParseTypeName("var");
                }

                var block = SyntaxFactory.Block(node.Statements.SelectMany(s => s.Accept(this)));

                return(SingleStatement(SyntaxFactory.ForEachStatement(
                                           type,
                                           id,
                                           (ExpressionSyntax)stmt.Expression.Accept(nodesVisitor),
                                           block.UnpackBlock()
                                           )));
            }
コード例 #7
0
ファイル: Utility.cs プロジェクト: SaladLab/TrackableData
        public static string GetTrackerClassName(TypeSyntax type)
        {
            // NOTE: it's naive approach because we don't know semantic type information here.
            var genericType = type as GenericNameSyntax;
            if (genericType == null)
            {
                if (type.ToString().StartsWith("Trackable"))
                {
                    return $"TrackablePocoTracker<I{type.ToString().Substring(9)}>";
                }
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableDictionary"))
            {
                return $"TrackableDictionaryTracker{genericType.TypeArgumentList}";
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableSet"))
            {
                return $"TrackableSetTracker{genericType.TypeArgumentList}";
            }
            else if (CodeAnalaysisExtensions.CompareTypeName(genericType.Identifier.ToString(),
                                                             "TrackableData.TrackableList"))
            {
                return $"TrackableListTracker{genericType.TypeArgumentList}";
            }

            throw new Exception("Cannot resolve tracker class of " + type);
        }
コード例 #8
0
ファイル: Utility.cs プロジェクト: SaladLab/TrackableData
 public static bool IsTrackableType(TypeSyntax type)
 {
     // NOTE: it's naive approach because we don't know semantic type information here.
     var parts = type.ToString().Split('.');
     var typeName = parts[parts.Length - 1];
     return typeName.StartsWith("Trackable");
 }
コード例 #9
0
		private static IEnumerable<TypeSyntax> GetAllReferencedTypes(TypeSyntax type, SyntaxNodeAnalysisContext context)
		{
			if (type == null)
				throw new ArgumentNullException(nameof(type));

			// The "all referenced types" set will be the current type and any generic type parameters that it has (and any generic type parameters that
			// they might have)..
			yield return type;

			// .. so, if this type doesn't have any type parameters then we're done here..
			// If this isn't 
			var genericTypeIfApplicable = type as GenericNameSyntax;
			if (genericTypeIfApplicable == null)
				yield break;

			// .. alternatively, if the type has the Bridge [IgnoreGeneric] attribute on it then we don't need to worry about the type parameters since
			// there won't be references to them at runtime
			var typeSymbolInfo = context.SemanticModel.GetSymbolInfo(type);
			if ((typeSymbolInfo.Symbol != null) && typeSymbolInfo.Symbol.GetAttributes().Any(attribute => IsBridgeClass(attribute.AttributeClass, "IgnoreGenericAttribute")))
				yield break;

			foreach (var typeParameter in genericTypeIfApplicable.TypeArgumentList.Arguments)
			{
				foreach (var typeRelatedToTypeParameter in GetAllReferencedTypes(typeParameter, context))
					yield return typeRelatedToTypeParameter;
			}
		}
コード例 #10
0
 private void AddTypeParameters(TypeSyntax typeSyntax, MultiDictionary<string, TypeParameterSymbol> map)
 {
     switch (typeSyntax.Kind())
     {
         case SyntaxKind.AliasQualifiedName:
             AddTypeParameters(((AliasQualifiedNameSyntax)typeSyntax).Name, map);
             break;
         case SyntaxKind.QualifiedName:
             // NOTE: Dev11 does not warn about duplication, it just matches parameter types to the
             // *last* type parameter with the same name.  That's why we're iterating backwards.
             QualifiedNameSyntax qualifiedNameSyntax = (QualifiedNameSyntax)typeSyntax;
             AddTypeParameters(qualifiedNameSyntax.Right, map);
             AddTypeParameters(qualifiedNameSyntax.Left, map);
             break;
         case SyntaxKind.GenericName:
             AddTypeParameters((GenericNameSyntax)typeSyntax, map);
             break;
         case SyntaxKind.IdentifierName:
         case SyntaxKind.PredefinedType:
             break;
         default:
             Debug.Assert(false, "Unexpected type syntax kind " + typeSyntax.Kind());
             break;
     }
 }
コード例 #11
0
        public MethodDeclarationSyntax BuildDeclaration(TypeSyntax returnType, string name, IEnumerable<ParameterSyntax> paramsInfo)
        {
            MethodDeclarationSyntax mDecl = SF.MethodDeclaration (returnType, name);
            mDecl = mDecl.AddModifiers (SF.Token (SyntaxKind.PublicKeyword));
            mDecl = mDecl.AddParameterListParameters (paramsInfo.ToArray ());

            return mDecl;
        }
コード例 #12
0
ファイル: SourceLocalSymbol.cs プロジェクト: riversky/roslyn
 public static SourceLocalSymbol MakeForeachLocal(
     MethodSymbol containingMethod,
     ForEachLoopBinder binder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     ExpressionSyntax collection)
 {
     return new SourceLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, null, collection, LocalDeclarationKind.ForEach);
 }
コード例 #13
0
        public FurnaceTypeWriter(string baseClassFullName)
        {
            GuardBaseClass(baseClassFullName);
            var typeIndex = baseClassFullName.LastIndexOf('.') + 1;
            _typeName = baseClassFullName.Substring(typeIndex);
            _typeNamespace = baseClassFullName.Substring(0, typeIndex - 1);

            _baseTypeSyntax = SyntaxFactory.ParseTypeName(baseClassFullName);
        }
 internal static Document PerformAction(Document document, SyntaxNode root, TypeSyntax type)
 {
     var newRoot = root.ReplaceNode((SyntaxNode)
         type,
         SyntaxFactory.IdentifierName("var")
         .WithLeadingTrivia(type.GetLeadingTrivia())
         .WithTrailingTrivia(type.GetTrailingTrivia())
     );
     return document.WithSyntaxRoot(newRoot);
 }
コード例 #15
0
        internal static PropertyDeclarationSyntax CreateAutoProperty(TypeSyntax type, string identifier, SyntaxList<AccessorDeclarationSyntax> accessors, SyntaxKind? accessibility)
        {
            var newProperty = SyntaxFactory.PropertyDeclaration(type, identifier)
                .WithAccessorList(SyntaxFactory.AccessorList(accessors));

            if (accessibility.HasValue)
                newProperty = newProperty.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(accessibility.Value)));

            return newProperty.WithAdditionalAnnotations(Formatter.Annotation);
        }
コード例 #16
0
ファイル: SourceLocalSymbol.cs プロジェクト: EkardNT/Roslyn
 public static SourceLocalSymbol MakeLocal(
     Symbol containingSymbol,
     Binder binder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     LocalDeclarationKind declarationKind)
 {
     Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
     return new SourceLocalSymbol(containingSymbol, binder, typeSyntax, identifierToken, declarationKind);
 }
 static Document PerformAction(Document document, SemanticModel model, SyntaxNode root, ITypeSymbol type, TypeSyntax typeSyntax)
 {
     var newRoot = root.ReplaceNode((SyntaxNode)
         typeSyntax,
         SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart))
         .WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
         .WithTrailingTrivia(typeSyntax.GetTrailingTrivia())
     );
     return document.WithSyntaxRoot(newRoot);
 }
コード例 #18
0
ファイル: SourceLocalSymbol.cs プロジェクト: EkardNT/Roslyn
 public static SourceLocalSymbol MakePossibleOutVarLocalWithoutInitializer(
     Symbol containingSymbol,
     Binder binder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     CSharpSyntaxNode scopeSegmentRoot,
     LocalDeclarationKind declarationKind)
 {
     Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
     return new PossibleOutVarLocalWithoutInitializer(containingSymbol, binder, typeSyntax, identifierToken, scopeSegmentRoot, declarationKind);
 }
コード例 #19
0
 protected SyntaxNode HoistVariable(CSharpSyntaxNode node, ref SyntaxToken identifier, TypeSyntax type)
 {
     if (hoistedVariables.ContainsKey(identifier.ToString()))
     {
         var newName = GenerateNewName(identifier);
         var newIdentifier = SyntaxFactory.Identifier(newName);
         identifier = newIdentifier;
     }
     hoistedVariables[identifier.ToString()] = type;
     return node;
 }
コード例 #20
0
ファイル: SourceLocalSymbol.cs プロジェクト: riversky/roslyn
 public static SourceLocalSymbol MakeLocal(
     MethodSymbol containingMethod,
     Binder binder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     EqualsValueClauseSyntax initializer,
     LocalDeclarationKind declarationKind)
 {
     Debug.Assert(declarationKind != LocalDeclarationKind.ForEach);
     return new SourceLocalSymbol(containingMethod, binder, typeSyntax, identifierToken, initializer, null, declarationKind);
 }
コード例 #21
0
ファイル: SourceLocalSymbol.cs プロジェクト: EkardNT/Roslyn
 public static SourceLocalSymbol MakeLocalWithInitializer(
     Symbol containingSymbol,
     Binder binder,
     TypeSyntax typeSyntax,
     SyntaxToken identifierToken,
     EqualsValueClauseSyntax initializer,
     LocalDeclarationKind declarationKind)
 {
     Debug.Assert(declarationKind != LocalDeclarationKind.ForEachIterationVariable);
     return new LocalWithInitializer(containingSymbol, binder, typeSyntax, identifierToken, initializer, declarationKind);
 }
コード例 #22
0
 public QueryUnboundLambdaState(UnboundLambda unbound, Binder binder, RangeVariableMap rangeVariableMap, ImmutableArray<RangeVariableSymbol> parameters, ExpressionSyntax body, TypeSyntax castTypeSyntax, TypeSymbol castType)
     : this(unbound, binder, rangeVariableMap, parameters, (LambdaSymbol lambdaSymbol, ExecutableCodeBinder lambdaBodyBinder, DiagnosticBag diagnostics) =>
 {
     BoundExpression expression = lambdaBodyBinder.BindValue(body, diagnostics, BindValueKind.RValue);
     Debug.Assert((object)castType != null);
     Debug.Assert(castTypeSyntax != null);
     // We transform the expression from "expr" to "expr.Cast<castTypeOpt>()".
     expression = lambdaBodyBinder.MakeQueryInvocation(body, expression, "Cast", castTypeSyntax, castType, diagnostics);
     return lambdaBodyBinder.WrapExpressionLambdaBody(expression, body, diagnostics);
 })
 { }
コード例 #23
0
 internal GlobalExpressionVariable(
     SourceMemberContainerTypeSymbol containingType,
     DeclarationModifiers modifiers,
     TypeSyntax typeSyntax,
     string name,
     SyntaxReference syntax,
     Location location)
     : base(containingType, modifiers, name, syntax, location)
 {
     Debug.Assert(DeclaredAccessibility == Accessibility.Private);
     _typeSyntax = typeSyntax.GetReference();
 }
コード例 #24
0
        /// <summary>
        /// Semantic model merges the symbols, but the compiled form retains multiple namespaces, which (when referenced from C#) need to keep the correct casing.
        /// <seealso cref="DeclarationNodeVisitor.WithDeclarationCasingAsync(VBSyntax.NamespaceBlockSyntax, ISymbol)"/>
        /// <seealso cref="CommonConversions.WithDeclarationCasing(SyntaxToken, ISymbol, string)"/>
        /// </summary>
        private static TypeSyntax WithDeclarationCasing(TypeSyntax syntax, ITypeSymbol typeSymbol)
        {
            var vbType        = SyntaxFactory.ParseTypeName(typeSymbol.ToDisplayString());
            var originalNames = vbType.DescendantNodes().OfType <CSSyntax.IdentifierNameSyntax>()
                                .Select(i => i.ToString()).ToList();

            return(syntax.ReplaceNodes(syntax.DescendantNodes().OfType <CSSyntax.IdentifierNameSyntax>(), (oldNode, n) =>
            {
                var originalName = originalNames.FirstOrDefault(on => string.Equals(@on, oldNode.ToString(), StringComparison.OrdinalIgnoreCase));
                return originalName != null ? SyntaxFactory.IdentifierName(originalName) : oldNode;
            }));
        }
コード例 #25
0
		protected void FilterType(TypeSyntax syntax)
		{
			if (syntax.IsKind(SyntaxKind.PredefinedType))
			{
				var symbolInfo = SemanticModel.GetSymbolInfo(syntax);
				if ((symbolInfo.Symbol != null) && (symbolInfo.Symbol.Kind == SymbolKind.NamedType))
				{
					var symbol = (ITypeSymbol)symbolInfo.Symbol;
					FilterTypeSymbol(symbol);
				}
			}
		}
コード例 #26
0
        //		internal static readonly AstNode wherePatternCase1 =
        //			new InvocationExpression(
        //				new MemberReferenceExpression(
        //					new InvocationExpression(
        //						new MemberReferenceExpression(new AnyNode("target"), "Where"),
        //						new LambdaExpression {
        //							Parameters = { PatternHelper.NamedParameter ("param1", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
        //							Body = PatternHelper.OptionalParentheses (new IsExpression(new AnyNode("expr1"), new AnyNode("type")))
        //						}
        //					), "Select"),
        //				new LambdaExpression {
        //					Parameters = { PatternHelper.NamedParameter ("param2", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
        //					Body = PatternHelper.OptionalParentheses (new AsExpression(PatternHelper.OptionalParentheses (new AnyNode("expr2")), new Backreference("type")))
        //				}
        //		);
        //
        //		internal static readonly AstNode wherePatternCase2 =
        //			new InvocationExpression(
        //				new MemberReferenceExpression(
        //					new InvocationExpression(
        //						new MemberReferenceExpression(new AnyNode("target"), "Where"),
        //						new LambdaExpression {
        //							Parameters = { PatternHelper.NamedParameter ("param1", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
        //							Body = PatternHelper.OptionalParentheses (new IsExpression(PatternHelper.OptionalParentheses (new AnyNode("expr1")), new AnyNode("type")))
        //						}
        //					), "Select"),
        //				new LambdaExpression {
        //					Parameters = { PatternHelper.NamedParameter ("param2", PatternHelper.AnyType ("paramType", true), Pattern.AnyString) },
        //					Body = PatternHelper.OptionalParentheses (new CastExpression(new Backreference("type"), PatternHelper.OptionalParentheses (new AnyNode("expr2"))))
        //				}
        //		);
        static bool MatchWhereSelect(InvocationExpressionSyntax selectInvoke, out ExpressionSyntax target, out TypeSyntax type)
        {
            target = null;
            type = null;

            if (selectInvoke.ArgumentList.Arguments.Count != 1)
                return false;
            var anyInvokeBase = selectInvoke.Expression as MemberAccessExpressionSyntax;
            if (anyInvokeBase == null || anyInvokeBase.Name.Identifier.Text != "Select")
                return false;
            var whereInvoke = anyInvokeBase.Expression as InvocationExpressionSyntax;
            if (whereInvoke == null || whereInvoke.ArgumentList.Arguments.Count != 1)
                return false;
            var baseMember = whereInvoke.Expression as MemberAccessExpressionSyntax;
            if (baseMember == null || baseMember.Name.Identifier.Text != "Where")
                return false;
            target = baseMember.Expression;

            ParameterSyntax param1, param2;
            ExpressionSyntax expr1, expr2;
            if (!ExtractLambda(whereInvoke.ArgumentList.Arguments[0], out param1, out expr1))
                return false;
            if (!ExtractLambda(selectInvoke.ArgumentList.Arguments[0], out param2, out expr2))
                return false;
            if (!expr1.IsKind(SyntaxKind.IsExpression))
                return false;
            type = (expr1 as BinaryExpressionSyntax)?.Right as TypeSyntax;
            if (type == null)
                return false;
            if (expr2.IsKind(SyntaxKind.AsExpression))
            {
                if (!CompareNames(param2, (expr2 as BinaryExpressionSyntax).Left as IdentifierNameSyntax))
                    return false;
                if (!type.IsEquivalentTo((expr2 as BinaryExpressionSyntax)?.Right))
                    return false;
            }
            else if (expr2.IsKind(SyntaxKind.CastExpression))
            {
                if (!CompareNames(param2, (expr2 as CastExpressionSyntax)?.Expression.SkipParens() as IdentifierNameSyntax))
                    return false;
                if (!type.IsEquivalentTo((expr2 as CastExpressionSyntax)?.Type))
                    return false;
            }
            else
                return false;

            if (!CompareNames(param1, (expr1 as BinaryExpressionSyntax)?.Left as IdentifierNameSyntax))
                return false;


            return target != null;
        }
コード例 #27
0
        public MethodDeclarationSyntax BuildExtensionMethod(TypeSyntax returnType, string name, IEnumerable<ParameterSyntax> paramsInfo)
        {
            MethodDeclarationSyntax mDecl = SF.MethodDeclaration (returnType, name);
            mDecl = mDecl.AddModifiers (SF.Token (SyntaxKind.PublicKeyword), SF.Token (SyntaxKind.StaticKeyword));

            ParameterSyntax[] parameterSyntax = paramsInfo.ToArray ();
            ParameterSyntax thisParam = parameterSyntax [0];
            parameterSyntax [0] = thisParam.WithModifiers (SF.TokenList ((SF.Token (SyntaxKind.ThisKeyword))));

            mDecl = mDecl.AddParameterListParameters (parameterSyntax);

            return mDecl;
        }
        private static void HandleDeclaration(SyntaxNodeAnalysisContext context, TypeSyntax returnType)
        {
            var predefinedType = returnType as PredefinedTypeSyntax;

            if (predefinedType != null && predefinedType.Keyword.IsKind(SyntaxKind.VoidKeyword))
            {
                // There is no return value
                return;
            }

            var documentationStructure = context.Node.GetDocumentationCommentTriviaSyntax();

            if (documentationStructure == null)
            {
                return;
            }

            if (documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.InheritdocXmlTag) != null)
            {
                // Don't report if the documentation is inherited.
                return;
            }

            var relevantXmlElement = documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.ReturnsXmlTag);
            if (relevantXmlElement != null)
            {
                // A <returns> element was located.
                return;
            }

            relevantXmlElement = documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.IncludeXmlTag);
            if (relevantXmlElement != null)
            {
                var declaration = context.SemanticModel.GetDeclaredSymbol(context.Node, context.CancellationToken);
                var rawDocumentation = declaration?.GetDocumentationCommentXml(expandIncludes: true, cancellationToken: context.CancellationToken);
                XElement completeDocumentation = XElement.Parse(rawDocumentation, LoadOptions.None);
                if (completeDocumentation.Nodes().OfType<XElement>().Any(element => element.Name == XmlCommentHelper.InheritdocXmlTag))
                {
                    // Ignore nodes with an <inheritdoc/> tag in the included XML.
                    return;
                }

                if (completeDocumentation.Nodes().OfType<XElement>().Any(element => element.Name == XmlCommentHelper.ReturnsXmlTag))
                {
                    // A <returns> element was located.
                    return;
                }
            }

            context.ReportDiagnostic(Diagnostic.Create(Descriptor, returnType.GetLocation()));
        }
		private async Task<Document> ReplaceUsage(
			Document document, TypeSyntax type,
			string interfaceName, string interfaceNamespace,
			CancellationToken cancellationToken) {
			var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken) as CompilationUnitSyntax;
			var newRoot = syntaxRoot
				.ReplaceNode(type, IdentifierName(interfaceName))
				.AddUsings(
					UsingDirective(
						IdentifierName(interfaceNamespace))
							.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation));

			return document.WithSyntaxRoot(newRoot);
		}
コード例 #30
0
        protected override bool TryAnalyzeVariableDeclaration(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken, out TextSpan issueSpan)
        {
            // If it is already var, return.
            if (typeName.IsTypeInferred(semanticModel))
            {
                issueSpan = default(TextSpan);
                return false;
            }

            var candidateReplacementNode = SyntaxFactory.IdentifierName("var");
            var candidateIssueSpan = typeName.Span;

            // If there exists a type named var, return.
            var conflict = semanticModel.GetSpeculativeSymbolInfo(typeName.SpanStart, candidateReplacementNode, SpeculativeBindingOption.BindAsTypeOrNamespace).Symbol;
            if (conflict?.IsKind(SymbolKind.NamedType) == true)
            {
                issueSpan = default(TextSpan);
                return false;
            }

            if (typeName.Parent.IsKind(SyntaxKind.VariableDeclaration) &&
                typeName.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.UsingStatement))
            {
                var variableDeclaration = (VariableDeclarationSyntax)typeName.Parent;

                // implicitly typed variables cannot be constants.
                if ((variableDeclaration.Parent as LocalDeclarationStatementSyntax)?.IsConst == true)
                {
                    issueSpan = default(TextSpan);
                    return false;
                }

                var variable = variableDeclaration.Variables.Single();
                if (AssignmentSupportsStylePreference(
                        variable.Identifier, typeName, variable.Initializer.Value,
                        semanticModel, optionSet, cancellationToken))
                {
                    issueSpan = candidateIssueSpan;
                    return true;
                }
            }
            else if (typeName.IsParentKind(SyntaxKind.ForEachStatement))
            {
                issueSpan = candidateIssueSpan;
                return true;
            }

            issueSpan = default(TextSpan);
            return false;
        }
コード例 #31
0
 public static PropertyDeclarationSyntax PropertyDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList, ArrowExpressionClauseSyntax expressionBody, EqualsValueClauseSyntax initializer, SyntaxToken semicolonToken)
 {
     return PropertyDeclaration(
         attributeLists,
         modifiers,
         refKeyword: default(SyntaxToken),
         type: type,
         explicitInterfaceSpecifier: explicitInterfaceSpecifier, 
         identifier: identifier, 
         accessorList: accessorList, 
         expressionBody: expressionBody, 
         initializer: initializer, 
         semicolonToken: semicolonToken);
 }
        private static async Task<Location[]> FindTypeLocationsInSourceCodeAsync(Document document, TypeSyntax type, CancellationToken cancellationToken)
        {
            var result = new Location[] { };

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var typeSymbol = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol;

            if(typeSymbol != null)
            {
                result = typeSymbol.Locations.Where(location => location.IsInSource).ToArray();
            }

            return result;
        }
コード例 #33
0
 public static DelegateDeclarationSyntax DelegateDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken semicolonToken)
 {
     return DelegateDeclaration(
         attributeLists,
         modifiers, 
         delegateKeyword, 
         refKeyword: default(SyntaxToken), 
         returnType: returnType, 
         identifier: identifier, 
         typeParameterList: typeParameterList, 
         parameterList: parameterList, 
         constraintClauses: constraintClauses, 
         semicolonToken: semicolonToken);
 }
コード例 #34
0
            private static void AppendTypeName(StringBuilder builder, TypeSyntax type)
            {
                if (type is NameSyntax)
                {
                    AppendName(builder, (NameSyntax)type);
                }
                else
                {
                    switch (type.Kind())
                    {
                        case SyntaxKind.PredefinedType:
                            builder.Append(((PredefinedTypeSyntax)type).Keyword.ValueText);
                            break;

                        case SyntaxKind.ArrayType:
                            var arrayType = (ArrayTypeSyntax)type;
                            AppendTypeName(builder, arrayType.ElementType);

                            var specifiers = arrayType.RankSpecifiers;
                            for (int i = 0; i < specifiers.Count; i++)
                            {
                                builder.Append('[');

                                var specifier = specifiers[i];
                                if (specifier.Rank > 1)
                                {
                                    builder.Append(',', specifier.Rank - 1);
                                }

                                builder.Append(']');
                            }

                            break;

                        case SyntaxKind.PointerType:
                            AppendTypeName(builder, ((PointerTypeSyntax)type).ElementType);
                            builder.Append('*');
                            break;

                        case SyntaxKind.NullableType:
                            AppendTypeName(builder, ((NullableTypeSyntax)type).ElementType);
                            builder.Append('?');
                            break;
                    }
                }
            }
コード例 #35
0
        private (TypeSyntax, ExpressionSyntax) AdjustFromName(TypeSyntax rawType,
                                                              ModifiedIdentifierSyntax name, ExpressionSyntax initializer)
        {
            var type = rawType;

            if (!SyntaxTokenExtensions.IsKind(name.Nullable, SyntaxKind.None))
            {
                if (type is ArrayTypeSyntax)
                {
                    type = ((ArrayTypeSyntax)type).WithElementType(
                        SyntaxFactory.NullableType(((ArrayTypeSyntax)type).ElementType));
                    initializer = null;
                }
                else
                {
                    type = SyntaxFactory.NullableType(type);
                }
            }

            var rankSpecifiers = ConvertArrayRankSpecifierSyntaxes(name.ArrayRankSpecifiers, name.ArrayBounds, false);

            if (rankSpecifiers.Count > 0)
            {
                var rankSpecifiersWithSizes = ConvertArrayRankSpecifierSyntaxes(name.ArrayRankSpecifiers,
                                                                                name.ArrayBounds);
                if (!rankSpecifiersWithSizes.SelectMany(ars => ars.Sizes).OfType <OmittedArraySizeExpressionSyntax>().Any())
                {
                    initializer =
                        SyntaxFactory.ArrayCreationExpression(
                            SyntaxFactory.ArrayType(type, rankSpecifiersWithSizes));
                }

                type = SyntaxFactory.ArrayType(type, rankSpecifiers);
            }

            return(type, initializer);
        }