public FieldMover(SemanticModel semanticModel, Symbol symbol, FieldDeclarationSyntax fds, PropertyDeclarationSyntax prop, ClassDeclarationSyntax parent) { this.semanticModel = semanticModel; this.parent = parent; this.fieldSymbol = symbol; this.fds = fds; this.prop = prop; }
public CodeAction(IDocument document, PropertyDeclarationSyntax property) { this.document = document; this.property = property; this.Description = "Convert to auto property"; this.Icon = null; }
protected override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax propertyDeclaration) { //this will remove the property from the child class if (propertyDeclaration == prop) { return null; } return base.VisitPropertyDeclaration(propertyDeclaration); }
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax property) { if (span.IntersectsWith(property.Span) && CodeGeneration.IsExpandableProperty(property, document)) { var annotation = new SyntaxAnnotation(); annotations.Add(annotation); return property.WithAdditionalAnnotations(annotation); } return base.VisitPropertyDeclaration(property); }
internal static IDocument ExpandProperty(this IDocument document, PropertyDeclarationSyntax property) { // Annotate the property declaration so we can find it later. var propertyAnnotation = new SyntaxAnnotation(); var newRoot = document.GetSyntaxRoot().ReplaceNode( property, property.WithAdditionalAnnotations(propertyAnnotation)); IFieldSymbol backingField; return document .UpdateSyntaxRoot(newRoot) .GetOrCreateBackingField(propertyAnnotation, out backingField) .ExpandProperty(propertyAnnotation, backingField); }
public static async Task <Document> RefactorAsync( Document document, PropertyDeclarationSyntax propertyDeclaration, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); SyntaxToken propertyIdentifier = propertyDeclaration.Identifier.WithoutTrivia(); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); ISymbol fieldSymbol = GetFieldSymbol(propertyDeclaration, semanticModel, cancellationToken); var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent; var fieldDeclaration = (FieldDeclarationSyntax)variableDeclaration.Parent; bool isSingleDeclarator = variableDeclaration.Variables.Count == 1; ImmutableArray <SyntaxNode> nodes = await SyntaxFinder.FindReferencesAsync(fieldSymbol, document, allowCandidate : false, cancellationToken : cancellationToken).ConfigureAwait(false); nodes = nodes.Add(propertyDeclaration); if (isSingleDeclarator) { nodes = nodes.Add(fieldDeclaration); } else { nodes = nodes.Add(variableDeclarator); } SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxNode newRoot = root.ReplaceNodes(nodes, (node, _) => { switch (node.Kind()) { case SyntaxKind.IdentifierName: { SyntaxNode newNode = null; if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && ((MemberAccessExpressionSyntax)node.Parent).Name == node) { newNode = IdentifierName(propertyIdentifier); } else if (node.IsParentKind(SyntaxKind.NameMemberCref)) { newNode = IdentifierName(propertyIdentifier); } else if (propertySymbol.IsStatic) { newNode = SimpleMemberAccessExpression( propertySymbol.ContainingType.ToTypeSyntax(), (SimpleNameSyntax)ParseName(propertySymbol.ToDisplayString(SymbolDisplayFormats.Default))).WithSimplifierAnnotation(); } else { newNode = IdentifierName(propertyIdentifier).QualifyWithThis(); } return(newNode.WithTriviaFrom(node)); } case SyntaxKind.PropertyDeclaration: { return(CreateAutoProperty(propertyDeclaration, variableDeclarator.Initializer)); } case SyntaxKind.VariableDeclarator: case SyntaxKind.FieldDeclaration: { return(node.WithAdditionalAnnotations(_removeAnnotation)); } default: { Debug.Fail(node.ToString()); return(node); } } }); SyntaxNode nodeToRemove = newRoot.GetAnnotatedNodes(_removeAnnotation).FirstOrDefault(); if (nodeToRemove != null) { newRoot = newRoot.RemoveNode(nodeToRemove, SyntaxRemoveOptions.KeepUnbalancedDirectives); } return(document.WithSyntaxRoot(newRoot)); }
static PropertyDeclarationSyntax GetPropertyImpl(PropertyDeclarationSyntax syntax, IdentifierNameSyntax dataInterfaceName) { var canBeResolvedAccess = MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizedExpression(CastExpression(dataInterfaceName, ThisExpression())), IdentifierName("Data") ); return(syntax.WithAccessorList( AccessorList( List( new[] { AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithExpressionBody( ArrowExpressionClause( PostfixUnaryExpression( SyntaxKind.SuppressNullableWarningExpression, ConditionalAccessExpression( canBeResolvedAccess, InvocationExpression( MemberBindingExpression( GenericName(Identifier("ToObject")) .WithTypeArgumentList( TypeArgumentList( SingletonSeparatedList <TypeSyntax>(IdentifierName("T")) ) ) ) ) ) ) ) ).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)), AccessorDeclaration( SyntaxKind.SetAccessorDeclaration ) .WithExpressionBody( ArrowExpressionClause( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, canBeResolvedAccess, InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("JToken"), IdentifierName("FromObject") ) ) .WithArgumentList( ArgumentList( SingletonSeparatedList( Argument( IdentifierName("value") ) ) ) ) ) ) ).WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) } ) ) )); }
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { Symbols.Add(node); return(base.VisitPropertyDeclaration(node)); }
public static bool ContainsSetter(this PropertyDeclarationSyntax propertyDeclaration) => Setter(propertyDeclaration) != null;
/// <summary> /// Add the backing field and figure out placement. /// StyleCop ordering is the default but it also checks for if field adjacent to property is used. /// The property is unchanged by this call. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/>.</param> /// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/>.</param> /// <returns>A <see cref="FieldDeclarationSyntax"/>.</returns> public static FieldDeclarationSyntax AddBackingField(this DocumentEditor editor, PropertyDeclarationSyntax propertyDeclaration) { if (editor is null) { throw new System.ArgumentNullException(nameof(editor)); } if (propertyDeclaration is null) { throw new System.ArgumentNullException(nameof(propertyDeclaration)); } var property = editor.SemanticModel.GetDeclaredSymbol(propertyDeclaration); var type = (TypeDeclarationSyntax)propertyDeclaration.Parent; var backingField = CreateBackingField(editor, propertyDeclaration); editor.ReplaceNode( type, (node, generator) => AddBackingField(editor, (TypeDeclarationSyntax)node, backingField, property.Name)); return(backingField); }
/// <summary> /// Retrieves the get and set accessor declarations of the specified property. /// Returns true if both get and set accessors exist; otherwise false. /// </summary> internal static bool TryGetAccessors( PropertyDeclarationSyntax property, out AccessorDeclarationSyntax getter, out AccessorDeclarationSyntax setter) { var accessors = property.AccessorList.Accessors; getter = accessors.FirstOrDefault(ad => ad.Kind == SyntaxKind.GetAccessorDeclaration); setter = accessors.FirstOrDefault(ad => ad.Kind == SyntaxKind.SetAccessorDeclaration); return accessors.Count == 2 && getter != null && setter != null; }
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { base.VisitPropertyDeclaration(node); return VisitMemberDeclaration(node); }
public static void GenerateTypescriptDefinition(string directory) { if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } var js = new StringBuilder(); js.AppendLine("declare module 'rhino3dm' {"); var keys = BindingClass.AllJavascriptEnums.Keys.ToList(); keys.Sort(); foreach (var key in keys) { js.AppendLine(); JavascriptEnum jsenum = BindingClass.AllJavascriptEnums[key]; js.AppendLine($"\tenum {jsenum.Name} {{"); for (int i = 0; i < jsenum.Elements.Count; i++) { if (i < (jsenum.Elements.Count - 1)) { js.AppendLine($"\t\t{jsenum.Elements[i]},"); } else { js.AppendLine($"\t\t{jsenum.Elements[i]}"); } } js.AppendLine("\t}"); } keys = BindingClass.AllJavascriptClasses.Keys.ToList(); keys.Sort(); foreach (var key in keys) { js.AppendLine(); var jsclass = GetJS(key); var rhcommon = RhinoCommonClass.Get(key); js.Append($"\tclass {jsclass.ClassName}"); if (!string.IsNullOrWhiteSpace(jsclass.BaseClass)) { js.Append($" extends {jsclass.BaseClass}"); } js.AppendLine(" {"); foreach (var prop in jsclass.Properties) { PropertyDeclarationSyntax propDecl = null; DocumentationCommentTriviaSyntax doccomment = null; for (int i = 0; i < rhcommon.Properties.Count; i++) { if (prop.Equals(rhcommon.Properties[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { propDecl = rhcommon.Properties[i].Item1; doccomment = rhcommon.Properties[i].Item2; break; } } js.AppendLine("\t\t/**"); if (doccomment != null) { string[] comments = DocCommentToTypeScript(doccomment, propDecl); foreach (var comment in comments) { if (!string.IsNullOrWhiteSpace(comment)) { js.AppendLine($"\t\t * {comment}"); } } } string proptype = "any"; if (propDecl != null) { proptype = ToTypeScriptType(propDecl.Type.ToString()); } js.AppendLine("\t\t */"); js.AppendLine($"\t\t{prop}: {proptype};"); } foreach (var(isStatic, method, args) in jsclass.Methods) { MethodDeclarationSyntax methodDecl = null; DocumentationCommentTriviaSyntax doccomment = null; for (int i = 0; i < rhcommon.Methods.Count; i++) { if (method.Equals(rhcommon.Methods[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { methodDecl = rhcommon.Methods[i].Item1; doccomment = rhcommon.Methods[i].Item2; break; } } List <string> paramNames = new List <string>(); List <string> paramTypes = new List <string>(); if (doccomment == null) { js.AppendLine("\t\t/** ... */"); } else { js.AppendLine("\t\t/**"); string s = DocCommentToTypeScript(doccomment, methodDecl, methodDecl.ParameterList, out paramNames, out paramTypes); string[] lines = s.Split(new char[] { '\n' }); for (int i = 0; i < lines.Length; i++) { string line = lines[i].Trim(); if (string.IsNullOrWhiteSpace(line)) { continue; } if (line.StartsWith("*")) { line = " " + line; } js.AppendLine($"\t\t{line}"); } js.AppendLine("\t\t */"); } string parameters = ""; for (int i = 0; i < paramNames.Count; i++) { parameters += $"{paramNames[i]}:{paramTypes[i]},"; } if (!string.IsNullOrEmpty(parameters)) { parameters = parameters.Substring(0, parameters.Length - 1); } string returnType = "void"; if (methodDecl != null) { returnType = ToTypeScriptType(methodDecl.ReturnType.ToString()); } if (isStatic) { js.AppendLine($"\t\tstatic {method}({parameters}): {returnType};"); } else { js.AppendLine($"\t\t{method}({parameters}): {returnType};"); } } js.AppendLine("\t}"); } js.AppendLine("}"); string path = System.IO.Path.Combine(directory, "rhino3dm.d.ts"); System.IO.File.WriteAllText(path, js.ToString()); }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { ConditionalStore(GetDeclaredSymbol(node), IsRemovableMember); base.VisitPropertyDeclaration(node); }
private static string GetMethodIdentifier(PropertyDeclarationSyntax syntax) { return(syntax.Identifier.ValueText); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyDeclaration"/> class. /// </summary> /// <param name="propertyDeclarationNode"></param> /// <param name="semanticModel"></param> public PropertyDeclaration(PropertyDeclarationSyntax propertyDeclarationNode, SemanticModel semanticModel) : base(propertyDeclarationNode, semanticModel) { this.hasGet = null; this.hasSet = null; }
/// <summary> /// Initializes a new instance of the <see cref="PropertyDeclaration"/> class. /// </summary> /// <param name="propertyDeclarationNode"></param> public PropertyDeclaration(PropertyDeclarationSyntax propertyDeclarationNode) : this(propertyDeclarationNode, null) { }
private static string GetPropertyName(PropertyDeclarationSyntax node) { return(node.Identifier.ToString()); }
public static string GetName(this PropertyDeclarationSyntax propertyDeclaration) { return(propertyDeclaration.Identifier.ValueText); }
public void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); WriteLeadingTrivia(node); BasePropertyDeclarationProlog(node); _writer.WriteIdentifier(node.Identifier); node.AccessorList.Accept(this); WriteTrailingTrivia(node); }
private static string GenerateFieldName(PropertyDeclarationSyntax property, ISemanticModel semanticModel) { var baseName = property.Identifier.ValueText; baseName = char.ToLower(baseName[0]) + baseName.Substring(1); var propertySymbol = semanticModel.GetDeclaredSymbol(property); if (propertySymbol == null || propertySymbol.ContainingType == null) { return baseName; } var index = 0; var name = baseName; while (propertySymbol.ContainingType.MemberNames.Contains(name)) { name = baseName + ++index; } return name; }
/// <summary> /// Create API documentation file(s). Currently javascript help is created /// by first creating a fake javascript file that mocks rhino3dm wasm and /// then runing jsdoc on this file. /// TODO: My plan is to switch this over to the RST+sphinx technique that /// I would like to use for all languages /// </summary> /// <param name="directory">Where to write the API help</param> public static void GenerateApiHelp(string directory) { if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } StringBuilder js = new StringBuilder(); var keys = BindingClass.AllJavascriptClasses.Keys.ToList(); keys.Sort(); foreach (var key in keys) { var jsclass = GetJS(key); var rhcommon = RhinoCommonClass.Get(key); var doccomment = rhcommon.DocComment; js.AppendLine("/**"); if (doccomment == null) { js.AppendLine($" * {jsclass.ClassName}"); } else { string comment = doccomment.ToString(); comment = comment.Replace("///", ""); js.Append(comment); } if (!string.IsNullOrEmpty(jsclass.BaseClass)) { js.AppendLine($" * @extends {jsclass.BaseClass}"); } if (jsclass.Constructors.Count == 0) { js.AppendLine(" * @hideconstructor"); } js.AppendLine(" */"); js.AppendLine($"class {jsclass.ClassName} {{"); foreach (var constructor in jsclass.Constructors) { var c = rhcommon.GetConstructor(constructor); if (c == null) { continue; } ConstructorDeclarationSyntax constructorDecl = c.Item1; doccomment = c.Item2; if (constructorDecl != null) { List <string> paramNames = null; js.AppendLine(" /**"); if (doccomment != null) { string s = DocCommentToJsDoc(doccomment, null, constructorDecl.ParameterList, out paramNames); js.Append(s); } js.AppendLine(" */"); js.Append(" constructor("); if (paramNames != null) { string parameters = ""; foreach (var p in paramNames) { parameters += p + ","; } if (!string.IsNullOrWhiteSpace(parameters)) { parameters = parameters.Substring(0, parameters.Length - 1); js.Append(parameters); } } js.AppendLine("){}"); } } foreach (var(isStatic, method, args) in jsclass.Methods) { MethodDeclarationSyntax methodDecl = null; doccomment = null; for (int i = 0; i < rhcommon.Methods.Count; i++) { if (method.Equals(rhcommon.Methods[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { methodDecl = rhcommon.Methods[i].Item1; doccomment = rhcommon.Methods[i].Item2; break; } } List <string> paramNames = new List <string>(); if (doccomment == null) { js.AppendLine(" /** ... */"); } else { js.AppendLine(" /**"); string s = DocCommentToJsDoc(doccomment, methodDecl, methodDecl.ParameterList, out paramNames); js.Append(s); js.AppendLine(" */"); } string parameters = ""; foreach (var p in paramNames) { parameters += p + ","; } if (!string.IsNullOrEmpty(parameters)) { parameters = parameters.Substring(0, parameters.Length - 1); } if (isStatic) { js.Append($" static {method}({parameters}) {{"); } else { js.Append($" {method}({parameters}) {{"); } js.AppendLine(" }"); } foreach (var prop in jsclass.Properties) { PropertyDeclarationSyntax propDecl = null; doccomment = null; for (int i = 0; i < rhcommon.Properties.Count; i++) { if (prop.Equals(rhcommon.Properties[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { propDecl = rhcommon.Properties[i].Item1; doccomment = rhcommon.Properties[i].Item2; break; } } js.AppendLine(" /**"); if (doccomment != null) { string comment = DocCommentToJsDoc(doccomment, propDecl); js.Append(comment); } if (propDecl != null) { js.AppendLine($" * @type {{{ToJavascriptType(propDecl.Type.ToString())}}}"); } js.AppendLine(" */"); js.AppendLine($" get {prop}() {{ return null;}}"); } js.AppendLine("}"); } string path = System.IO.Path.Combine(directory, "rh3dm_temp.js"); System.IO.File.WriteAllText(path, js.ToString()); }
public void Add(PropertyDeclarationSyntax node) { Symbol s = Chunk.Model.GetDeclaredSymbol(node); Function fGet = null; Function fSet = null; foreach (AccessorDeclarationSyntax ads in node.AccessorList.Accessors) { switch (ads.Keyword.Kind) { case SyntaxKind.GetKeyword: { MethodSymbol ms = Chunk.Model.GetDeclaredSymbol(ads); if (!Chunk.Functions.TryGetValue(ms, out fGet)) { throw new NotImplementedException("Method not found " + ms.ToString()); } } break; case SyntaxKind.SetKeyword: { MethodSymbol ms = Chunk.Model.GetDeclaredSymbol(ads); if (!Chunk.Functions.TryGetValue(ms, out fSet)) { throw new NotImplementedException("Method not found " + ms.ToString()); } } break; default: throw new NotImplementedException("unhandled property accessor: " + ads.Keyword.Kind.ToString()); break; } } FlatArrayBuilder fab = new FlatArrayBuilder(); fab.Add(FlatValue.Int32(s.IsStatic ? (int)ClassMemberType.StaticProperty : (int)ClassMemberType.Property)); //fab.Add(FlatValue.Int32((int)ClassMemberType.Property)); fab.Add(FlatValue.String(node.Identifier.ToString())); if (fGet == null) fab.Add(FlatValue.Null()); else fab.Add(FlatValue.Int32(fGet.NumFunction)); if (fSet == null) fab.Add(FlatValue.Null()); else fab.Add(FlatValue.Int32(fSet.NumFunction)); Members.Add(fab.GetFlatValue()); }
public static bool TryFindContainingPropery(this SyntaxNode node, out PropertyDeclarationSyntax method) { method = node.FindParent <PropertyDeclarationSyntax, ClassDeclarationSyntax>(); return(method != null); }
private static string For(PropertyDeclarationSyntax property) { property = property.WithoutLeadingTrivia(); return($"{property.Modifiers.ToFullString()}{property.Type.ToFullString()}{property.Identifier.ToFullString()}".Trim()); }
/// <summary> /// Creates a new <see cref="Syntax.ModifierListInfo"/> from the specified property declaration. /// </summary> /// <param name="propertyDeclaration"></param> public static ModifierListInfo ModifierListInfo(PropertyDeclarationSyntax propertyDeclaration) { return(Syntax.ModifierListInfo.Create(propertyDeclaration)); }
/// <summary> /// Create a backing <see cref="FieldDeclarationSyntax"/> for the <paramref name="propertyDeclaration"/> /// Handles name collisions and reserved keywords. /// </summary> /// <param name="editor">The <see cref="DocumentEditor"/>.</param> /// <param name="propertyDeclaration">The <see cref="PropertyDeclarationSyntax"/>.</param> /// <returns>A <see cref="FieldDeclarationSyntax"/>.</returns> public static FieldDeclarationSyntax CreateBackingField(this DocumentEditor editor, PropertyDeclarationSyntax propertyDeclaration) { if (editor is null) { throw new System.ArgumentNullException(nameof(editor)); } if (propertyDeclaration is null) { throw new System.ArgumentNullException(nameof(propertyDeclaration)); } var property = editor.SemanticModel.GetDeclaredSymbol(propertyDeclaration); var name = editor.SemanticModel.UnderscoreFields() == CodeStyleResult.Yes ? $"_{property.Name.ToFirstCharLower()}" : property.Name.ToFirstCharLower(); while (property.ContainingType.MemberNames.Any(x => x == name)) { name += "_"; } if (SyntaxFacts.GetKeywordKind(name) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(name) != SyntaxKind.None) { name = "@" + name; } return((FieldDeclarationSyntax)editor.Generator.FieldDeclaration( name, accessibility: Accessibility.Private, modifiers: DeclarationModifiers.None, type: propertyDeclaration.Type, initializer: propertyDeclaration.Initializer?.Value)); }
public static async Task <Document> RefactorAsync( Document document, PropertyDeclarationSyntax propertyDeclaration, bool prefixIdentifierWithUnderscore = true, CancellationToken cancellationToken = default) { string fieldName = StringUtility.ToCamelCase( propertyDeclaration.Identifier.ValueText, prefixWithUnderscore: prefixIdentifierWithUnderscore); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); fieldName = NameGenerator.Default.EnsureUniqueName( fieldName, semanticModel, propertyDeclaration.SpanStart); FieldDeclarationSyntax fieldDeclaration = FieldDeclaration( (propertyDeclaration.Modifiers.Contains(SyntaxKind.StaticKeyword)) ? Modifiers.Private_Static() : Modifiers.Private(), propertyDeclaration.Type, fieldName, propertyDeclaration.Initializer).WithFormatterAnnotation(); IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); PropertyDeclarationSyntax newPropertyDeclaration = ExpandAccessors(document, propertyDeclaration, propertySymbol, fieldName, semanticModel) .WithModifiers(propertyDeclaration.Modifiers.Replace(SyntaxKind.AbstractKeyword, SyntaxKind.VirtualKeyword)) .WithTriviaFrom(propertyDeclaration) .WithFormatterAnnotation(); MemberDeclarationListInfo membersInfo = SyntaxInfo.MemberDeclarationListInfo(propertyDeclaration.Parent); SyntaxList <MemberDeclarationSyntax> members = membersInfo.Members; int propertyIndex = membersInfo.IndexOf(propertyDeclaration); AccessorListSyntax accessorList = propertyDeclaration.AccessorList; if (accessorList?.Getter()?.IsAutoImplemented() == true && accessorList.Setter() == null) { ImmutableArray <SyntaxNode> nodes = await SyntaxFinder.FindReferencesAsync(propertySymbol, document, cancellationToken : cancellationToken).ConfigureAwait(false); IdentifierNameSyntax newNode = IdentifierName(fieldName); SyntaxNode newParent = membersInfo.Parent.ReplaceNodes(nodes, (node, _) => { if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && ((MemberAccessExpressionSyntax)node.Parent).Expression.IsKind(SyntaxKind.BaseExpression)) { return(node); } return(newNode.WithTriviaFrom(node)); }); MemberDeclarationListInfo newMembersInfo = SyntaxInfo.MemberDeclarationListInfo(newParent); members = newMembersInfo.Members; } SyntaxList <MemberDeclarationSyntax> newMembers = members.ReplaceAt(propertyIndex, newPropertyDeclaration); newMembers = MemberDeclarationInserter.Default.Insert(newMembers, fieldDeclaration); return(await document.ReplaceMembersAsync(membersInfo, newMembers, cancellationToken).ConfigureAwait(false)); }
static void HandlePropertyCase(CodeRefactoringContext context, SyntaxNode root, SyntaxToken token, PropertyDeclarationSyntax property) { var getter = property.AccessorList.Accessors.FirstOrDefault(acc => acc.IsKind(SyntaxKind.GetAccessorDeclaration)); ExpressionSyntax expr; if (getter == null || property.AccessorList.Accessors.Count != 1 || !IsSimpleReturn(getter.Body, out expr)) { return; } context.RegisterRefactoring( CodeActionFactory.Create( token.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("To expression body"), t2 => { var newRoot = root.ReplaceNode((SyntaxNode) property, property .WithAccessorList(null) .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(expr)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithTrailingTrivia(expr.Parent.GetTrailingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation) ); return(Task.FromResult(context.Document.WithSyntaxRoot(newRoot))); } ) ); }
private static Property ConvertProperty(PropertyDeclarationSyntax property) => new Property { Identifier = property.Identifier.ToString(), Type = property.Type.ToString(), };
internal static bool IsFixable( PropertyDeclarationSyntax propertyDeclaration, AccessorDeclarationSyntax accessor, SemanticModel semanticModel, CancellationToken cancellationToken) { switch (accessor.Kind()) { case SyntaxKind.GetAccessorDeclaration: { ExpressionSyntax expression = GetGetAccessorExpression(accessor); if (expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) != true) { return(false); } var memberAccess = (MemberAccessExpressionSyntax)expression; if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) { return(false); } SimpleNameSyntax simpleName = memberAccess.Name; IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); if (propertySymbol == null) { return(false); } IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; if (overriddenProperty == null) { return(false); } ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); return(overriddenProperty.Equals(symbol)); } case SyntaxKind.SetAccessorDeclaration: { ExpressionSyntax expression = GetSetAccessorExpression(accessor); SimpleAssignmentExpressionInfo assignment = SyntaxInfo.SimpleAssignmentExpressionInfo(expression); if (!assignment.Success) { return(false); } if (assignment.Left.Kind() != SyntaxKind.SimpleMemberAccessExpression) { return(false); } var memberAccess = (MemberAccessExpressionSyntax)assignment.Left; if (memberAccess.Expression?.IsKind(SyntaxKind.BaseExpression) != true) { return(false); } if (assignment.Right.Kind() != SyntaxKind.IdentifierName) { return(false); } var identifierName = (IdentifierNameSyntax)assignment.Right; if (identifierName.Identifier.ValueText != "value") { return(false); } SimpleNameSyntax simpleName = memberAccess.Name; if (simpleName == null) { return(false); } IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken); if (propertySymbol == null) { return(false); } IPropertySymbol overriddenProperty = propertySymbol.OverriddenProperty; if (overriddenProperty == null) { return(false); } ISymbol symbol = semanticModel.GetSymbol(simpleName, cancellationToken); return(overriddenProperty.Equals(symbol)); } case SyntaxKind.UnknownAccessorDeclaration: { return(false); } default: { Debug.Fail(accessor.Kind().ToString()); return(false); } } }
public static PropertyDeclarationSyntax WithGetter( this PropertyDeclarationSyntax property) => property.AddAccessorListAccessors( AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)));
private static IEnumerable <ObjectCreationExpressionSyntax> GetObjectCreations(SyntaxNodeAnalysisContext context, ClassDeclarationSyntax classDeclaration, PropertyDeclarationSyntax propertyDeclarationSyntax, IPropertySymbol propertySymbol) { var objectCreations = classDeclaration.DescendantNodes() .OfType <AssignmentExpressionSyntax>() .Where(a => context.SemanticModel.GetSymbolInfo(a.Left).Symbol.Equals(propertySymbol) && a.Right is ObjectCreationExpressionSyntax) .Select(a => a.Right as ObjectCreationExpressionSyntax).ToList(); var arrowExpressionClause = propertyDeclarationSyntax.DescendantNodes() .OfType <ArrowExpressionClauseSyntax>() .SingleOrDefault(a => a.Expression is ObjectCreationExpressionSyntax) ?.Expression as ObjectCreationExpressionSyntax; if (arrowExpressionClause != null) { objectCreations.Add(arrowExpressionClause); } var getAcessorDeclararion = propertyDeclarationSyntax.DescendantNodes() .OfType <AccessorDeclarationSyntax>() .SingleOrDefault(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)); if (getAcessorDeclararion != null) { objectCreations.AddRange(getAcessorDeclararion.DescendantNodes() .OfType <ObjectCreationExpressionSyntax>()); } return(objectCreations); }
public PropertyInfo(IPropertySymbol symbol, PropertyDeclarationSyntax declaration) { Symbol = symbol; Declaration = declaration; }
private static async Task RenamePropertyAccodingToTypeName(RefactoringContext context, PropertyDeclarationSyntax propertyDeclaration) { TypeSyntax type = propertyDeclaration.Type; if (type == null) { return; } SyntaxToken identifier = propertyDeclaration.Identifier; if (!context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(identifier)) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); if (typeSymbol?.IsErrorType() != false) { return; } string newName = NameGenerator.CreateName(typeSymbol); if (string.IsNullOrEmpty(newName)) { return; } string oldName = identifier.ValueText; newName = StringUtility.FirstCharToUpper(newName); if (string.Equals(oldName, newName, StringComparison.Ordinal)) { return; } ISymbol symbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); if (!await MemberNameGenerator.IsUniqueMemberNameAsync( newName, symbol, context.Solution, cancellationToken: context.CancellationToken).ConfigureAwait(false)) { return; } context.RegisterRefactoring( $"Rename '{oldName}' to '{newName}'", cancellationToken => Renamer.RenameSymbolAsync(context.Solution, symbol, newName, default(OptionSet), cancellationToken), RefactoringIdentifiers.RenamePropertyAccordingToTypeName); }
protected override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { Boolean isDependencyProperty = node .Attributes .SelectMany(a => a.ChildNodes().OfType<AttributeSyntax>()) .Any(a => a.Name.PlainName == "Dependency"); if (!isDependencyProperty) { return base.VisitPropertyDeclaration(node); } AccessorDeclarationSyntax changeCallback = node .AccessorList .Accessors .FirstOrDefault(a => a.Kind == SyntaxKind.UnknownAccessorDeclaration && a.Keyword.ValueText == "change"); Boolean hasChangeCallback = changeCallback != null; TypeSyntax dpType = Syntax.ParseTypeName("System.Windows.DependencyProperty"); // add a DP field: // DependencyProperty XxxProperty = DependencyProperty.Register("Xxx", typeof(PropType), typeof(OwnerType), // new FrameworkPropertyMetadata(OnXxxChanged); TypeSyntax ownerType = Syntax.ParseTypeName(node .FirstAncestorOrSelf<ClassDeclarationSyntax>() .Identifier .ValueText); String propertyName = node.Identifier.ValueText; ExpressionSyntax propertyNameExpression = Syntax.LiteralExpression(SyntaxKind.StringLiteralExpression, Syntax.Literal(text: '"' + propertyName + '"', value: propertyName)); ExpressionSyntax typeofPropertyType = Syntax.TypeOfExpression(argumentList: Syntax.ArgumentList(arguments: Syntax.SeparatedList(Syntax.Argument(expression: node.Type)))); ExpressionSyntax typeofOwnerType = Syntax.TypeOfExpression(argumentList: Syntax.ArgumentList(arguments: Syntax.SeparatedList(Syntax.Argument(expression: ownerType)))); var registerArgs = new List<ArgumentSyntax> { Syntax.Argument(expression: propertyNameExpression), Syntax.Argument(expression: typeofPropertyType), Syntax.Argument(expression: typeofOwnerType) }; if (hasChangeCallback) { ExpressionSyntax changeMethod = Syntax.ParseName("On" + propertyName + "Changed"); ExpressionSyntax frameworkPropertyMetadata = Syntax.ObjectCreationExpression( type: Syntax.ParseTypeName("System.Windows.FrameworkPropertyMetadata"), argumentListOpt: Syntax.ArgumentList(arguments: Syntax.SeparatedList(Syntax.Argument(expression: changeMethod)))); registerArgs.Add(Syntax.Argument(expression: frameworkPropertyMetadata) ); } IEnumerable<SyntaxToken> argSeparators = Enumerable.Repeat( Syntax.Token(SyntaxKind.CommaToken), registerArgs.Count - 1) .ToList(); ExpressionSyntax dpexpr = Syntax.InvocationExpression( expression: Syntax.ParseName("System.Windows.DependencyProperty.Register"), argumentList: Syntax.ArgumentList(arguments: Syntax.SeparatedList(registerArgs, argSeparators))); String fieldName = propertyName + "Property"; VariableDeclaratorSyntax declarator = Syntax.VariableDeclarator( identifier: Syntax.Identifier(fieldName), initializerOpt: Syntax.EqualsValueClause(value: dpexpr)); FieldDeclarationSyntax newField = Syntax.FieldDeclaration( modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword), Syntax.Token(SyntaxKind.StaticKeyword)), declaration: Syntax.VariableDeclaration( type: dpType, variables: Syntax.SeparatedList(declarator))); _fields.Add(newField); // add a DP CLR wrapper: // public PropType Xxx // { // get { return (PropType)GetValue(XxxProperty); } // set { SetValue(XxxPropety, value); } // } ExpressionSyntax getval = Syntax.ParseExpression("GetValue(" + fieldName + ")"); ExpressionSyntax cast = Syntax.CastExpression(type: node.Type, expression: getval); StatementSyntax getter = Syntax.ReturnStatement(expressionOpt: cast); StatementSyntax setter = Syntax.ParseStatement("SetValue(" + fieldName + ");"); PropertyDeclarationSyntax newProperty = Syntax.PropertyDeclaration( modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword)), type: node.Type, identifier: node.Identifier, accessorList: Syntax.AccessorList( accessors: Syntax.List( Syntax.AccessorDeclaration( kind: SyntaxKind.GetAccessorDeclaration, bodyOpt: Syntax.Block( statements: Syntax.List( getter ) ) ), Syntax.AccessorDeclaration( kind: SyntaxKind.SetAccessorDeclaration, bodyOpt: Syntax.Block( statements: Syntax.List( setter ) ) ) ) )); // add change callback if required // private static void OnXxxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) // { // /* body */ // } if (hasChangeCallback) { List<ParameterSyntax> parameterList = new List<ParameterSyntax> { Syntax.Parameter(identifier: Syntax.Identifier("d"), typeOpt: Syntax.ParseTypeName("System.Windows.DependencyObject")), Syntax.Parameter(identifier: Syntax.Identifier("e"), typeOpt: Syntax.ParseTypeName("System.Windows.DependencyPropertyChangedEventArgs")), }; var paramSeparators = Enumerable.Repeat(Syntax.Token(SyntaxKind.CommaToken), parameterList.Count - 1).ToList(); ParameterListSyntax parameters = Syntax.ParameterList( parameters: Syntax.SeparatedList(parameterList, paramSeparators) ); MethodDeclarationSyntax changeMethod = Syntax.MethodDeclaration( modifiers: Syntax.TokenList(Syntax.Token(SyntaxKind.PrivateKeyword), Syntax.Token(SyntaxKind.StaticKeyword)), identifier: Syntax.Identifier("On" + propertyName + "Changed"), returnType: Syntax.PredefinedType(Syntax.Token(SyntaxKind.VoidKeyword)), parameterList: parameters, bodyOpt: changeCallback.BodyOpt ); _methods.Add(changeMethod); } return newProperty; }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { base.VisitPropertyDeclaration(node); }
public PropertyRewriter(SemanticModel semanticModel, Symbol backingField, PropertyDeclarationSyntax property) { this.semanticModel = semanticModel; this.backingField = backingField; this.property = property; }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { _members.Add(node); }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { VisitIndexerOrPropertyDeclarationSyntax(node); base.VisitPropertyDeclaration(node); }
public static byte[] GetGetterAbiSignature(this PropertyDeclarationSyntax property) { string signature = property.Identifier.Text + "()"; return(HashHelper.Keccak256(signature).GetBytes().Take(4).Reverse().ToArray()); }
public static byte[] GetAbiSignatureSetter(this PropertyDeclarationSyntax method) { throw new NotImplementedException(); }
private PropertyDeclarationSyntax ConvertToAutoProperty(PropertyDeclarationSyntax propertyDeclaration) { // Produce the new property. var newProperty = property .WithAccessorList( Syntax.AccessorList( Syntax.List( Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)), Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken))))); return newProperty; }
private static bool IsAutoPropertyWithNoInitializer(PropertyDeclarationSyntax declaration) { return(declaration.Initializer == null && declaration.AccessorList != null && declaration.AccessorList.Accessors.All(acc => acc.Body == null)); }
public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax propertyDeclaration) { if (propertyDeclaration == property) { // Add an annotation to format the new property. return CodeAnnotations.Formatting.AddAnnotationTo( ConvertToAutoProperty(propertyDeclaration)); } return base.VisitPropertyDeclaration(propertyDeclaration); }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { base.VisitPropertyDeclaration(node); this.members.Add(node); }
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { var modifiers = node.Modifiers; bool bPublic = modifiers.Any(c => c.Kind == SyntaxKind.PublicKeyword); /* bool bGet = false; bool bSet = false; foreach (var acc in node.AccessorList.Accessors) { if (acc.Keyword.Kind == SyntaxKind.GetKeyword) { bGet = true; } if (acc.Keyword.Kind == SyntaxKind.SetKeyword) { bSet = true; } } */ string nodeName = node.Identifier.GetText().ToLowerCamelCase(); string initValue = DefaultValueEmitter.FromType(node.Type.PlainName); if (bPublic) _publicCode.WriteLine(" {0}: {1},", nodeName, initValue); else _writer.WriteLine(" var {0} = {1};", nodeName, initValue); base.VisitPropertyDeclaration(node); }
/// <summary> /// Returns true if the specified <see cref="PropertyDeclarationSyntax"/> can be expanded to include /// support for <see cref="INotifyPropertyChanged"/>. /// </summary> internal static bool IsExpandableProperty(PropertyDeclarationSyntax property, IDocument document) { // Don't expand properties with parse errors. if (property.ContainsDiagnostics) { return false; } // Don't expand static properties (since INotifyPropertyChanged only makes sense for instance properties). if (property.Modifiers.Any(SyntaxKind.StaticKeyword)) { return false; } // Don't expand abstract properties. if (property.Modifiers.Any(SyntaxKind.AbstractKeyword)) { return false; } // Only expand properties with both a getter and a setter. AccessorDeclarationSyntax getter, setter; if (!TryGetAccessors(property, out getter, out setter)) { return false; } // Easy case: neither the getter or setter have a body. if (getter.Body == null && setter.Body == null) { return true; } var semanticModel = document.GetSemanticModel(); IFieldSymbol backingField; return IsExpandableGetter(getter, semanticModel, out backingField) && IsExpandableSetter(setter, semanticModel, backingField); }