private void LookForAggregates(ClassDeclarationSyntax classNode) { if (classNode.Modifiers.Any(SyntaxKind.AbstractKeyword) || classNode.BaseList == null || !classNode.BaseList.Types.Any()) return; // Dong Xie: Need review: if (classNode.BaseList.Types.Any<TypeSyntax>(x => AggregateRootPlainIfx.Contains(x.ToString()))) AggregateRoots.Add(classNode); }
private Task<Document> AddStaticKeyword(Document document, SyntaxNode root, ClassDeclarationSyntax classDeclaration) { var staticKeyword = SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithAdditionalAnnotations(Formatter.Annotation); var newDeclaration = classDeclaration.AddModifiers(staticKeyword); var newRoot = root.ReplaceNode(classDeclaration, newDeclaration); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }
/// <summary> /// Returns true if the given class declaration is a P# machine. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="classDecl">Class declaration</param> /// <returns>Boolean</returns> internal static bool IsMachine(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl) { var result = false; if (classDecl.BaseList == null) { return result; } var model = compilation.GetSemanticModel(classDecl.SyntaxTree); var symbol = model.GetDeclaredSymbol(classDecl); while (true) { if (symbol.ToString() == typeof(Machine).FullName) { result = true; break; } else if (symbol.BaseType != null) { symbol = symbol.BaseType; continue; } break; } return result; }
public static Boolean checkAttribute(IEnumerable<MethodDeclarationSyntax> methods, String attr, ClassDeclarationSyntax c) { Boolean isSet = false; //Check at class level, digging two levels deep for class-level attributes in ClassDeclarationSyntax Type foreach (var attribute in c.AttributeLists) { foreach (var name in attribute.Attributes) { if (name.Name.ToString().Equals(attr)) { isSet = true; } } } /* If not found at Class level, check the methods * Unfortunately MethodDeclarationSyntax is of Type IEnumerable, so we dig three levels for the Atttribute Lists */ foreach (var methodList in methods) { foreach (var methodLevelAttirbutes in methodList.AttributeLists) { foreach (var methodAttr in methodLevelAttirbutes.Attributes) { if (methodAttr.ToString().Equals(attr)) { isSet = true; } } } } return isSet; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); Classes.Add(node); return node; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { if (node.Modifiers.Any(m => m.Kind() == SyntaxKind.PartialKeyword)) return base.VisitClassDeclaration(node); _notPartialClass = true; return ((ClassDeclarationSyntax)base.VisitClassDeclaration(node)).WithModifiers(SyntaxFactory.TokenList(node.Modifiers.Union(new[] { SyntaxFactory.Token(SyntaxKind.PartialKeyword) }))); }
public static IEnumerable<string> GetUsingNamespaces(ClassDeclarationSyntax classes) { var syntaxTree = classes.SyntaxTree; var root = (CompilationUnitSyntax)syntaxTree.GetRoot(); return root.Usings.Select(x => x.Name.ToString()); }
private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic, ClassDeclarationSyntax classNode) { // Generated from http://roslynquoter.azurewebsites.net/ var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .WithParameterList(SyntaxFactory.ParameterList() .WithOpenParenToken( SyntaxFactory.Token(SyntaxKind.OpenParenToken)) .WithCloseParenToken( SyntaxFactory.Token( SyntaxKind.CloseParenToken))) .WithBody(SyntaxFactory.Block() .WithOpenBraceToken( SyntaxFactory.Token( SyntaxKind.OpenBraceToken)) .WithCloseBraceToken( SyntaxFactory.Token( SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation); var newClassNode = classNode.AddMembers(constructor); var newRoot = root.ReplaceNode(classNode, newClassNode); context.RegisterCodeFix( CodeAction.Create( CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription, _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)), CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic); }
private static void AddCodeFix(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic, ClassDeclarationSyntax classNode) { var newRoot = IsBusinessObjectSerializableMakeSerializableCodeFix.AddAttribute( root, classNode, IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SerializableName); if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace)) { newRoot = (newRoot as CompilationUnitSyntax).AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.SystemNamespace))); } if (!root.HasUsing(IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace)) { newRoot = (newRoot as CompilationUnitSyntax).AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.CslaSerializationNamespace))); } context.RegisterCodeFix( CodeAction.Create( IsBusinessObjectSerializableMakeSerializableCodeFixConstants.AddSerializableAndUsingDescription, _ => Task.FromResult<Document>(context.Document.WithSyntaxRoot(newRoot))), diagnostic); }
private static void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context, INamedTypeSymbol symbol) { if (symbol.BaseType is ITypeSymbol baseSymbol && IsInternal(context, baseSymbol)) { foreach (var declaringSyntax in symbol.DeclaringSyntaxReferences) { var location = declaringSyntax.GetSyntax() switch { CSharpSyntax.ClassDeclarationSyntax s when s.BaseList?.Types.Count > 0 => s.BaseList.Types[0].GetLocation(), { } otherSyntax => otherSyntax.GetLocation() }; context.ReportDiagnostic(Diagnostic.Create(_descriptor, location, baseSymbol)); } } foreach (var iface in symbol.Interfaces.Where(i => IsInternal(context, i))) { foreach (var declaringSyntax in symbol.DeclaringSyntaxReferences) { var location = declaringSyntax.GetSyntax() switch { CSharpSyntax.ClassDeclarationSyntax s => s.Identifier.GetLocation(), { } otherSyntax => otherSyntax.GetLocation() }; context.ReportDiagnostic(Diagnostic.Create(_descriptor, location, iface)); } } }
public TestFixtureDetails GetTestFixtureDetails(ClassDeclarationSyntax fixtureNode, ISemanticModel semanticModel) { var fixture = ExtractTests(fixtureNode, semanticModel); fixture.AssemblyName = PathHelper.GetCoverageDllName(semanticModel.GetAssemblyName()); return fixture; }
private static ObjectCreationExpressionSyntax CallConstuctor(ClassDeclarationSyntax @class) { var typeName = F.ParseName(@class.Identifier.Text); var args = F.ArgumentList(); var ctor = @class.DescendantNodes().OfType<ConstructorDeclarationSyntax>().FirstOrDefault(); if(ctor != null) { var parameters = ctor.ParameterList.DescendantNodes().OfType<ParameterSyntax>().ToList(); foreach (var parameter in parameters) { var ident = parameter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(); var parameterType = ident.Identifier.Text; var invocation = F.InvocationExpression(F.MemberAccessExpression( K.SimpleMemberAccessExpression, F.IdentifierName(parameterType), F.IdentifierName("Factory"))); args = args.AddArguments(F.Argument(invocation)); } } return F.ObjectCreationExpression(typeName) .WithNewKeyword(F.Token(F.TriviaList(), K.NewKeyword, F.TriviaList(F.Space))) .WithArgumentList(args); }
private static MethodDeclarationSyntax GetFactoryMethodDeclaration(ClassDeclarationSyntax @class) { return F.MethodDeclaration( F.ParseName(@class.Identifier.Text), F.Identifier(F.TriviaList(F.Space), @"Factory", F.TriviaList())) .WithModifiers(F.TokenList( F.Token(F.TriviaList(), K.PublicKeyword, F.TriviaList(F.Space)), F.Token(F.TriviaList(), K.StaticKeyword, F.TriviaList(F.Space)))) .WithBody( F.Block(F.SingletonList<StatementSyntax>( F.ReturnStatement(CallConstuctor(@class)) .WithReturnKeyword( F.Token( F.TriviaList( F.Whitespace( " ")), K.ReturnKeyword, F.TriviaList( F.Space))) .WithSemicolonToken( F.Token( F.TriviaList(), K.SemicolonToken, F.TriviaList() )) ))); }
private async Task<Document> RebuildClassAsync(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken) { var newImplementation = @" private bool _isEnabled; private readonly Action _handler; public RelayCommand(Action handler) { _handler = handler; } public event EventHandler CanExecuteChanged; public bool IsEnabled { get { return _isEnabled; } set { if ((value != _isEnabled)) { _isEnabled = value; if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } } public bool CanExecute(object parameter) { return IsEnabled; } public void Execute(object parameter) { _handler(); } "; var newClassTree = SyntaxFactory.ParseSyntaxTree(newImplementation). GetRoot().DescendantNodes(). Where(n => n.IsKind(SyntaxKind.FieldDeclaration) || n.IsKind(SyntaxKind.MethodDeclaration) || n.IsKind(SyntaxKind.PropertyDeclaration) || n.IsKind(SyntaxKind.ConstructorDeclaration) || n.IsKind(SyntaxKind.EventDeclaration) || n.IsKind(SyntaxKind.EventFieldDeclaration)). Cast<MemberDeclarationSyntax>(). Select(decl => decl.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)). ToArray(); ClassDeclarationSyntax newClassBlock = SyntaxFactory.ClassDeclaration("RelayCommand").AddTypeParameterListParameters(SyntaxFactory.TypeParameter("T")).WithOpenBraceToken(SyntaxFactory.ParseToken("{")). WithCloseBraceToken(SyntaxFactory.ParseToken("}").WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)); newClassBlock = newClassBlock.AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ICommand"))); var newClassNode = newClassBlock.AddMembers(newClassTree); var root = await document.GetSyntaxRootAsync(); var newRoot = root.ReplaceNode(classDeclaration, newClassNode); var newDocument = document.WithSyntaxRoot(newRoot); return newDocument; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var value = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); if (_first) { var statements = new[] { string.Format(" unityContainer.RegisterType<I{0}Service, {0}ServiceClient>(new InjectionConstructor());\r\n", _edmxName), string.Format(" unityContainer.RegisterType<I{0}ClientContext, {0}ClientContext>();\r\n", _edmxName), string.Format(" ClientContextFactory<I{0}ClientContext>.Factory = () => unityContainer.Resolve<I{0}ClientContext>();\r\n", _edmxName) }; if (_addApplicationStart) value = value.AddMembers( SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "OnStartup") .WithModifiers(SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.ProtectedKeyword), SyntaxFactory.Token(SyntaxKind.OverrideKeyword))) .AddParameterListParameters( SyntaxFactory.Parameter(SyntaxFactory.Identifier("e")).WithType(SyntaxFactory.ParseTypeName("StartupEventArgs"))) .WithBody(SyntaxFactory.Block().AddStatements( SyntaxFactory.ParseStatement("IUnityContainer unityContainer = new UnityContainer();"), SyntaxFactory.ParseStatement("unityContainer.RegisterType<IMessageBoxService, MessageBoxService>();"), SyntaxFactory.ParseStatement("DispatcherUnhandledException += (sender, ex) => { unityContainer.Resolve<IMessageBoxService>().ShowError(ex.Exception.Message);ex.Handled = true; };"), SyntaxFactory.ParseStatement("TaskScheduler.UnobservedTaskException += (sender, ex) => { unityContainer.Resolve<IMessageBoxService>().ShowError(ex.Exception.InnerException.Message);ex.SetObserved(); };"), SyntaxFactory.ParseStatement("InitWAQSModules(unityContainer);"), SyntaxFactory.ParseStatement("UIThread.Dispatcher = Application.Current.Dispatcher;"), SyntaxFactory.ParseStatement("UIThread.TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();"), SyntaxFactory.ParseStatement(string.Format("unityContainer.Resolve<{0}>().Show();", _pageTypeName))))); if (_addInitWAQSModules) return value.AddMembers( SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "InitWAQSModules") .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))) .AddParameterListParameters( SyntaxFactory.Parameter(SyntaxFactory.Identifier("unityContainer")).WithType(SyntaxFactory.ParseTypeName("IUnityContainer"))) .WithBody(SyntaxFactory.Block().AddStatements( statements.Select(s => SyntaxFactory.ParseStatement(s)).ToArray()))); } return value; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var namedTypeSymbol = _semanticModel.GetDeclaredSymbol(node, _cancellationToken); var classAssumptions = _classAssumptions.Where(ca => ca.Class == namedTypeSymbol).ToList(); if (classAssumptions.Count == 0) { return base.VisitClassDeclaration(node); } var newClass = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); foreach (var classAssumption in classAssumptions) { foreach (string attributeToDelete in classAssumption.GetAttributesToDelete(_objectTheoremResult)) { newClass = RemoveAttribute(newClass, attributeToDelete); } foreach (string attributeToAdd in classAssumption.GetAttributesToAdd(_objectTheoremResult)) { newClass = EnsureAttribute(newClass, attributeToAdd); } } return newClass; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { TypeName = node.Identifier.ValueText; TypeSyntax clientContextInterface = SyntaxFactory.ParseTypeName(string.Format("I{0}ClientContext", _edmxName)); var value = node.AddMembers( SyntaxFactory.FieldDeclaration( attributeLists: default(SyntaxList<AttributeListSyntax>), modifiers: SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PrivateKeyword)), declaration: SyntaxFactory.VariableDeclaration( clientContextInterface, SyntaxFactory.SeparatedList( new[] { SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier("_context")) }))), SyntaxFactory.ConstructorDeclaration(SyntaxFactory.Identifier(node.Identifier.ValueText)) .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword))) .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("context")).WithType(clientContextInterface)) .WithInitializer(SyntaxFactory.ConstructorInitializer( kind: SyntaxKind.BaseConstructorInitializer, argumentList: SyntaxFactory.ArgumentList( arguments: SyntaxFactory.SeparatedList( new[] { SyntaxFactory.Argument( expression: SyntaxFactory.IdentifierName("context")) }))) .WithThisOrBaseKeyword(SyntaxFactory.Token(SyntaxKind.BaseKeyword))) .WithBody(SyntaxFactory.Block(SyntaxFactory.ParseStatement("_context = context;")))) .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("ViewModelBase"))); if (!value.Modifiers.Any(m => m.Kind() == SyntaxKind.PublicKeyword || m.Kind() == SyntaxKind.InternalKeyword)) value = value.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); return value; }
public static ClassDeclarationSyntax AddField(ClassDeclarationSyntax classDeclaration, string type, string name) { return classDeclaration.AddMembers( SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(type), SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier(name)) }))) .AddModifiers(SF.Token(SyntaxKind.PrivateKeyword))); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var typesList = new List<TypeSyntax> { _baseTypeSyntax }; if (node.BaseList != null) typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList<TypeSyntax>(); types = types.AddRange(typesList); var identifier = SyntaxFactory.Identifier(FurnaceTypeIdentifier + _typeName); var newNode = node.Update( node.AttributeLists, node.Modifiers, node.Keyword, identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return base.VisitClassDeclaration(newNode); }
public override void VisitClassDeclaration(ClassDeclarationSyntax node) { if (node.ShouldBeHidden()) return; ++ClassDepth; if (ClassDepth == 1) { base.VisitClassDeclaration(node); } else if (node.ChildNodes().All(childNode => childNode is PropertyDeclarationSyntax || childNode is AttributeListSyntax)) { // simple nested POCO var line = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line; var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line); walker.Visit(node); this.Blocks.AddRange(walker.Blocks); } else { var methods = node.ChildNodes().OfType<MethodDeclarationSyntax>(); if (!methods.Any(m => m.AttributeLists.SelectMany(a => a.Attributes).Any())) { // nested class with methods that are not unit or integration tests e.g. example PropertyVisitor in Automap.doc.cs var line = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line; var walker = new CodeWithDocumentationWalker(ClassDepth - 2, line); walker.Visit(node); this.Blocks.AddRange(walker.Blocks); } } --ClassDepth; }
/// <summary> /// creates a new class declaration where members are delegated to the mixin /// reference /// </summary> /// <param name="classDeclaration"></param> /// <returns></returns> public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax classDeclaration) { var mixinName = _mixin.Name; // currently, only three types of member forwardings are possible, // there is a strategy for every forwarding implementation var implementationStrategies = CreateStrategies(_mixin, _semantic, _settings); // needed to evaluate whether type names can be reduced (depends on the using statements in the file) var positionOfClassInSourceFile = classDeclaration.GetLocation().SourceSpan.Start; // generate the members that should be implemented var membersToAdd = _members .Select(x => implementationStrategies[x.GetType()].ImplementMember(x, positionOfClassInSourceFile)) .Where(x => x != null).ToArray(); // add regions if there is something to generate if (_settings.CreateRegions) { var regionCaption = $" mixin {mixinName}"; // if there is already a region, add members to this one, // otherwise create a new one if (classDeclaration.HasRegion(regionCaption)) return classDeclaration.AddMembersIntoRegion(regionCaption, membersToAdd); else membersToAdd.AddRegionAround(regionCaption); } // return a new class node with the additional members // problem with AddMembers is that it adds the new code // after the last syntax node, so when a region exists in the class // the code will be added before the region end, this leads to the bug // https://github.com/pgenfer/mixinSharp/issues/9 // where the newly created region is nested into the old one. // a solution is to ensure that the members are added after any endregion directive // check if there is an end region in the file var lastEndRegion = classDeclaration.GetLastElementInClass<EndRegionDirectiveTriviaSyntax>(); // only interesting if there is an end region directive at all if(lastEndRegion != null) { var lastSyntaxNode = classDeclaration.GetLastElementInClass<SyntaxNode>(false); if (lastSyntaxNode != lastEndRegion && lastSyntaxNode.SpanStart < lastEndRegion.Span.End) { // special case here: there is an end region directive at the end of the class // so we must add our members AFTER this endregion (by removing it and adding it before the first member) if (membersToAdd.Length > 0) { var newClassDeclaration = classDeclaration.RemoveNode(lastEndRegion, SyntaxRemoveOptions.AddElasticMarker); membersToAdd[0] = membersToAdd[0].WithLeadingTrivia( new SyntaxTriviaList() .Add(Trivia(EndRegionDirectiveTrivia(true))) .Add(EndOfLine(NewLine)) .AddRange(membersToAdd[0].GetLeadingTrivia())); return newClassDeclaration.AddMembers(membersToAdd); } } } return classDeclaration.AddMembers(membersToAdd); }
public override void VisitClassDeclaration(ClassDeclarationSyntax node) { TypeWalker typeWalker = this.CreateSyntaxWalker<TypeWalker>(node); typeWalker.Visit(node); Classes.Add(typeWalker); base.VisitClassDeclaration(node); }
private static NamespaceDeclarationSyntax AddParameterClassToNamespaceAndUpdateClassToUseNamespace(NamespaceDeclarationSyntax oldNamespace, ClassDeclarationSyntax oldClass, MethodDeclarationSyntax oldMethod) { var className = $"NewClass{oldMethod.Identifier.Text}"; var newParameterClass = CreateParameterClass(className, oldMethod); var newNamespace = oldNamespace.ReplaceNode(oldClass, UpdateClassToUseNewParameterClass(className, oldClass, oldMethod)) .AddMembers(newParameterClass); return newNamespace; }
public static ClassDeclarationSyntax AddBase(ClassDeclarationSyntax type, string baseName) { if (type.BaseList == null) { type = type.WithBaseList(SF.BaseList()); } return type.WithBaseList(AddBase(type.BaseList, baseName)); }
public YieldClassGenerator(Compilation compilation, ClassDeclarationSyntax classDeclarationSyntax, MemberDeclarationSyntax node) { this.compilation = compilation; this.classDeclarationSyntax = classDeclarationSyntax; this.node = node; method = ModelExtensions.GetDeclaredSymbol(compilation.GetSemanticModel(node.SyntaxTree), node); }
/// <summary> /// /// </summary> /// <param name="node"></param> /// <remarks> /// This will cause an AST walker to be created, thus we don't need to go further deeper in the /// tree by visiting the node. /// </remarks> public override void VisitClassDeclaration(ClassDeclarationSyntax node) { var classDefinitionWalker = ClassDefinitionASTWalker.Create(node, this.CreateWalkingContext(), this.semanticModel); var translationUnit = classDefinitionWalker.Walk(); this.program.AddContent(translationUnit); this.InvokeClassDeclarationVisited(this, new WalkerEventArgs()); }
private static SyntaxNode AddAttribute(SyntaxNode root, ClassDeclarationSyntax classNode, string name) { var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(name)); var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList<AttributeSyntax>().Add(attribute)); var newClassNode = classNode.AddAttributeLists(attributeList); return root.ReplaceNode(classNode, newClassNode); }
public ClassDeclarationTranslation(ClassDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { var constructor = Members.GetEnumerable<ConstructorDeclarationTranslation>().FirstOrDefault(); if (constructor == null) { return; } }
private bool IsInClassDeclarationHeader(ClassDeclarationSyntax node, SyntaxToken token) { var start = node.SpanStart; var end = node.BaseList != null ? node.BaseList.Span.End : node.Identifier.Span.End; return TextSpan.FromBounds(start, end).Contains(token.Span); }
/// <summary> /// Checks the given machine for using non-P# related asynchrony. /// </summary> /// <param name="machine"></param> private static void CheckForExternalAsynchronyUseInMachine(ClassDeclarationSyntax machine) { if (machine.SyntaxTree.GetRoot().DescendantNodesAndSelf().Any(v => v.ToString().Contains("System.Threading"))) { Log log = new Log(null, machine, null, null); AnalysisErrorReporter.ReportExternalAsynchronyUsage(log); } }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var typeList = node.ChildNodes().OfType<TypeParameterListSyntax>(); if (typeList.Any()) return node.RemoveNodes(typeList, SyntaxRemoveOptions.KeepEndOfLine); return node; }
public static glsl.ClassDeclarationSyntax Translate(this cs.ClassDeclarationSyntax node) { return(new glsl.ClassDeclarationSyntax() { Identifier = node.Identifier, Members = node.Members.Select(m => Translate(m)).Where(m => m != null).ToList(), OpenBraceToken = node.OpenBraceToken, CloseBraceToken = node.CloseBraceToken, }); }
public override void VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) { var type = semanticModel.GetDeclaredSymbol(node) as INamedTypeSymbol; var oldTypeParameters = availableTypeParameters; if (type != null) { availableTypeParameters = Concat(availableTypeParameters, type.TypeParameters); } base.VisitClassDeclaration(node); availableTypeParameters = oldTypeParameters; }
public override void VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) { ctx.CancellationToken.ThrowIfCancellationRequested(); var type = semanticModel.GetDeclaredSymbol(node) as INamedTypeSymbol; var oldTypeParameters = availableTypeParameters; if (type != null) { availableTypeParameters = availableTypeParameters.AddRange(type.TypeParameters); } base.VisitClassDeclaration(node); availableTypeParameters = oldTypeParameters; }
public override void VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) { var symbol = semanticModel.GetDeclaredSymbol(node); if (symbol != null && IsInactiveConditional(symbol)) { Colorize(node, inactiveCodeColor); } else { base.VisitClassDeclaration(node); Colorize(node.Identifier, referenceTypeColor); } }
public override VisualBasicSyntaxNode VisitClassDeclaration(CSS.ClassDeclarationSyntax node) { var members = node.Members.Select(m => (StatementSyntax)m.Accept(this)).ToList(); var id = SyntaxFactory.Identifier(node.Identifier.ValueText, SyntaxFacts.IsKeywordKind(node.Identifier.Kind()), node.Identifier.GetIdentifierText(), TypeCharacter.None); List <InheritsStatementSyntax> inherits = new List <InheritsStatementSyntax>(); List <ImplementsStatementSyntax> implements = new List <ImplementsStatementSyntax>(); ConvertBaseList(node, inherits, implements); members.AddRange(PatchInlineHelpers(node)); return(SyntaxFactory.ClassBlock( SyntaxFactory.ClassStatement( SyntaxFactory.List(node.AttributeLists.Select(a => (AttributeListSyntax)a.Accept(this))), ConvertModifiers(node.Modifiers), id, (TypeParameterListSyntax)node.TypeParameterList?.Accept(this) ), SyntaxFactory.List(inherits), SyntaxFactory.List(implements), SyntaxFactory.List(members) )); }
public override void VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) { AddFolding(node.OpenBraceToken, node.CloseBraceToken, FoldType.Type); base.VisitClassDeclaration(node); }
private void VisitMethodsCSharp(SyntaxNodeAnalysisContext ctx) { CSharpSyntax.ClassDeclarationSyntax node = ctx.Node as CSharpSyntax.ClassDeclarationSyntax; if (node == null) { return; } // Ensures that the analyzed class has a dependency to Controller if (node .DescendantNodesAndSelf() .OfType <CSharpSyntax.BaseListSyntax>() .Count(childrenNode => childrenNode.ToString().Contains("Controller")) .Equals(0)) { return; } IEnumerable <CSharpSyntax.MethodDeclarationSyntax> methodsWithParameters = node.DescendantNodesAndSelf() .OfType <CSharpSyntax.MethodDeclarationSyntax>() .Where(method => !method.ParameterList.Parameters.Count.Equals(0)) .Where(method => method.Modifiers.ToString().Equals("public")) .Where(method => method.ReturnType.ToString().Equals("string")); foreach (CSharpSyntax.MethodDeclarationSyntax method in methodsWithParameters) { SyntaxList <CSharpSyntax.StatementSyntax> methodStatements = method.Body.Statements; IEnumerable <CSharpSyntax.InvocationExpressionSyntax> methodInvocations = method.DescendantNodes().OfType <CSharpSyntax.InvocationExpressionSyntax>(); if (!methodStatements.Count.Equals(0)) { DataFlowAnalysis flow = ctx.SemanticModel.AnalyzeDataFlow(methodStatements.First(), methodStatements.Last()); // Returns from the Data Flow Analysis of sensible data // Sensible data is: Data passed as a parameter that is also returned as is by the method IEnumerable <ISymbol> sensibleVariables = flow.DataFlowsIn.Union(flow.VariablesDeclared.Except(flow.AlwaysAssigned)) .Union(flow.WrittenInside) .Intersect(flow.WrittenOutside); if (!sensibleVariables.Count().Equals(0)) { foreach (ISymbol sensibleVariable in sensibleVariables) { bool sensibleVariableIsEncoded = false; foreach (CSharpSyntax.InvocationExpressionSyntax methodInvocation in methodInvocations) { SeparatedSyntaxList <CSharpSyntax.ArgumentSyntax> arguments = methodInvocation.ArgumentList.Arguments; if (!arguments.Count.Equals(0)) { if (arguments.First().ToString().Contains(sensibleVariable.Name)) { sensibleVariableIsEncoded = true; } } } if (!sensibleVariableIsEncoded) { ctx.ReportDiagnostic(Diagnostic.Create(Rule, method.GetLocation())); } } } } } }
// Returns the name of the declared API if the node is the type of node that should have an XML doc comment // otherwise returns null; public string GetAPIForNode(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: { ConstructorDeclarationSyntax syntax = (ConstructorDeclarationSyntax)node; // assume only one field/identifier string text = syntax.Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.ConversionOperatorDeclaration: { ConversionOperatorDeclarationSyntax syntax = (ConversionOperatorDeclarationSyntax)node; // assume only one field/identifier string text = syntax.OperatorKeyword.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.DelegateDeclaration: { DelegateDeclarationSyntax syntax = (DelegateDeclarationSyntax)node; // assume only one field/identifier string text = syntax.Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.EnumDeclaration: { EnumDeclarationSyntax syntax = (EnumDeclarationSyntax)node; // assume only one field/identifier string text = syntax.Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.EventDeclaration: { /* EventDeclarationSyntax syntax = (EventDeclarationSyntax)node; * * string text = syntax.Identifier.Text; * // for now assume only one match * if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) * { * var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); * // but which one is the right one? * var symbol = symbols.Single(); * return symbol.GetDocumentationCommentId(); * }*/ return(null); } case SyntaxKind.FieldDeclaration: { FieldDeclarationSyntax syntax = (FieldDeclarationSyntax)node; // assume only one field/identifier string text = syntax.Declaration.Variables.First().Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.IndexerDeclaration: { IndexerDeclarationSyntax syntax = (IndexerDeclarationSyntax)node; string text = syntax.ThisKeyword.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.InterfaceDeclaration: { InterfaceDeclarationSyntax syntax = (InterfaceDeclarationSyntax)node; string text = syntax.Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.MethodDeclaration: { MethodDeclarationSyntax methodDeclarationSyntax = (MethodDeclarationSyntax)node; string text = methodDeclarationSyntax.Identifier.Text; var parameters = methodDeclarationSyntax.ParameterList.Parameters; if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // select the symbol whose declaring syntax reference matches the node's syntax reference. //var symbol = symbols.Where(s => s.DeclaringSyntaxReferences.Contains(node.GetReference())).Single(); foreach (var symbol in symbols) { var references = symbol.DeclaringSyntaxReferences; foreach (var reference in references) { SyntaxNode testNode = reference.GetSyntax(); if (testNode.Equals(node)) { Console.WriteLine("Matched nodes."); } } } // find the one that corresponds to this syntax node. //foreach (var symbol in symbols) //{ // IMethodSymbol methodsymbol = (IMethodSymbol)symbol; // symbol.DeclaringSyntaxReferences.Select(syntaxReference => syntaxReference == node.GetReference()); // //} return(symbols.First().GetDocumentationCommentId()); } return(null); } case SyntaxKind.NamespaceDeclaration: // doesn't work { NamespaceDeclarationSyntax syntax = (NamespaceDeclarationSyntax)node; NameSyntax nameSyntax = syntax.Name; string text = nameSyntax.ToFullString(); // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.OperatorDeclaration: { OperatorDeclarationSyntax syntax = (OperatorDeclarationSyntax)node; // this won't work, it needs to be figured out. string text = syntax.OperatorKeyword.Text + syntax.OperatorToken.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.PropertyDeclaration: { PropertyDeclarationSyntax syntax = (PropertyDeclarationSyntax)node; string text = syntax.Identifier.Text; // for now assume only one match if (m_compilation.ContainsSymbolsWithName(symbolName => symbolName == text)) { var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } return(null); } case SyntaxKind.ClassDeclaration: { Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax classSyntax = (ClassDeclarationSyntax)node; string text = classSyntax.Identifier.Text; string valueText = classSyntax.Identifier.ValueText; // for now assume only one match var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } case SyntaxKind.StructDeclaration: { Microsoft.CodeAnalysis.CSharp.Syntax.StructDeclarationSyntax structSyntax = (StructDeclarationSyntax)node; string text = structSyntax.Identifier.Text; string valueText = structSyntax.Identifier.ValueText; // for now assume only one match var symbols = m_compilation.GetSymbolsWithName(symbolName => symbolName == text); // but which one is the right one? var symbol = symbols.Single(); return(symbol.GetDocumentationCommentId()); } default: return(null); } //var types = m_compilation.GlobalNamespace.GetTypeMembers(name); //m_compilation.GetTypeByMetadataName() //string docCommentId = classSymbol.GetDocumentationCommentId(); return(""); }
public override void VisitClassDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax node) { cancellationToken.ThrowIfCancellationRequested(); AddFolding(node.OpenBraceToken, node.CloseBraceToken, FoldType.Type); base.VisitClassDeclaration(node); }
public override VisualBasicSyntaxNode VisitClassDeclaration(CsSyntax.ClassDeclarationSyntax node) { return(WithMappedBlockEnd(node)); }