private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, NamespaceDeclarationSyntax namespaceDeclaration) { if (namespaceDeclaration != null) { var usings = namespaceDeclaration.Usings; var start = usings.First().SpanStart; var end = usings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var rootUsings = root.Usings; if (rootUsings.Any()) { var start = rootUsings.First().SpanStart; var end = rootUsings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var start = 0; var end = root.Members.Any() ? root.Members.First().GetFirstToken().Span.End : root.Span.End; return TextSpan.FromBounds(start, end); } } }
private static SyntaxElement[] ParseFileContent(CompilationUnitSyntax root, SemanticCache semanticCache) { var walker = new FileSyntaxWalker(semanticCache); walker.Visit(root); return walker.ResultsAccumulator.GetResults(); }
public static glsl.CompilationUnitSyntax Translate(this cs.CompilationUnitSyntax node) { return(new glsl.CompilationUnitSyntax() { Members = node.Members.Select(m => Translate(m)).Where(m => m != null).ToList() }); }
static CompilationUnitSyntax RemovePrivateMethods(CompilationUnitSyntax root) { List<SyntaxNode> removes = new List<SyntaxNode>(); var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>(); foreach (var @class in classes) { var methods = @class.Members.OfType<MethodDeclarationSyntax>(); foreach (var method in methods) { SyntaxTokenList modifiers = method.Modifiers; bool result = false; foreach (SyntaxToken m in modifiers) { if (m.Text.Equals("private")) { result = true; removes.Add(method); break; } } } } root = root.RemoveNodes(removes,SyntaxRemoveOptions.KeepDirectives); return root; }
private async Task<Document> ImplementNotifyPropertyChangedAsync(Document document, CompilationUnitSyntax root, SemanticModel model, IEnumerable<ExpandablePropertyInfo> properties, CancellationToken cancellationToken) { document = document.WithSyntaxRoot(CodeGeneration.ImplementINotifyPropertyChanged(root, model, properties, document.Project.Solution.Workspace)); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); return document; }
public TranslationUnitPorter(CXCursor translationUnit, string ns, IBindingLocator bindingLocator) { if (translationUnit.kind != CXCursorKind.CXCursor_TranslationUnit) throw new ArgumentException (); if (string.IsNullOrWhiteSpace (ns)) throw new ArgumentException (); if (bindingLocator == null) throw new ArgumentNullException (); this.translationUnit = translationUnit; this.bindingLocator = bindingLocator; cu = SyntaxFactory.CompilationUnit (); IEnumerable<UsingDirectiveSyntax> usings = CreateUsings (); foreach (var u in usings) cu = cu.AddUsings (u); var nsDecl = CreateNamespace (ns); foreach (var c in PortClasses ()) nsDecl = nsDecl.AddMembers (c); cu = cu.AddMembers (nsDecl); }
public ModuleDeclaration Import(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax compilationUnit) { var module = new ModuleDeclaration(); convertComputationUnit(compilationUnit, module); return(module); }
static CompilationUnitSyntax AddRequiredUsings(CompilationUnitSyntax root) { NameSyntax name = SyntaxFactory.IdentifierName(" System"); if (root.Usings.Contains(SyntaxFactory.UsingDirective(name)) == false) return root.AddUsings(SyntaxFactory.UsingDirective(name)); return root; }
public override void VisitCompilationUnit (CompilationUnitSyntax node) { var startNode = node.DescendantNodesAndSelf (n => region.Start <= n.SpanStart).FirstOrDefault (); if (startNode == node || startNode == null) { base.VisitCompilationUnit (node); } else { this.Visit (startNode); } }
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { if (node.Usings.Any() || node.Externs.Any()) { node = node.WithAdditionalAnnotations(LayoutAnnotations.MultiLineConstructAnnotation); } return base.VisitCompilationUnit(node); }
public override VisualBasicSyntaxNode VisitCompilationUnit(CsSyntax.CompilationUnitSyntax node) { var convertedNode = (VbSyntax.CompilationUnitSyntax)DefaultVisitInner(node); // Special case where we need to map manually because it's a special zero-width token that just has leading trivia that isn't at the start of the line necessarily return(convertedNode.WithEndOfFileToken( convertedNode.EndOfFileToken.WithSourceMappingFrom(node.EndOfFileToken) )); }
internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration(method, CodeGenerationDestination.CompilationUnit, options); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); }
public override void VisitCompilationUnit(CompilationUnitSyntax node) { foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind() == SyntaxKind.GlobalStatement) { Visit(member); } } }
private IList<INamespaceSymbol> GetExistingNamespaces( SemanticModel semanticModel, CompilationUnitSyntax compilationUnit, CancellationToken cancellationToken) { var q = from u in compilationUnit.Usings let symbol = semanticModel.GetSymbolInfo(u.Name, cancellationToken).Symbol as INamespaceSymbol where symbol != null && !symbol.IsGlobalNamespace select symbol; return q.ToList(); }
private IEnumerable<string> GetImport(CompilationUnitSyntax root) { List<string> result = new List<string>(); foreach (var import in root.Usings) { result.Add(import.Name.ToFullString()); } return result; }
public static CompilationUnitSyntax AddNamedTypeTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options); var members = Insert(destination.Members, declaration, options, availableIndices); return destination.WithMembers(members); }
private IEnumerable<Microsoft.CodeAnalysis.CodeActions.CodeIssue> GetIssuesInternal(IEnumerable<ClousotOutput> results, CompilationUnitSyntax compilationUnitDeclaration) { IEnumerator<ClousotOutput> enumerator; try { enumerator = results.GetEnumerator(); } catch { yield break; } bool hasNext; try { hasNext = enumerator.MoveNext(); } catch { yield break; } while (hasNext) { var result = enumerator.Current; //foreach (var result in results ) { var msg = result.Message; var span = result.Span; var action = result.action; if (span.IsEmpty) { msg = "Unknown location: " + msg; span = compilationUnitDeclaration.GetFirstToken().Span; } if (action == null) yield return new Microsoft.CodeAnalysis.CodeActions.CodeIssue(Microsoft.CodeAnalysis.CodeActions.CodeIssueKind.Warning, span, msg); else yield return new Microsoft.CodeAnalysis.CodeActions.CodeIssue(Microsoft.CodeAnalysis.CodeActions.CodeIssueKind.Warning, span, msg, action); } try { hasNext = enumerator.MoveNext(); } catch { yield break; } } }
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter( IEnumerable<IFormattingRule> formattingRules, CompilationUnitSyntax root, TextLine line, OptionSet optionSet, CancellationToken cancellationToken) { Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(root); if (!optionSet.GetOption(FeatureOnOffOptions.AutoFormattingOnReturn, LanguageNames.CSharp)) { return false; } if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart) { return false; } var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition(); if (!firstNonWhitespacePosition.HasValue) { return false; } var token = root.FindToken(firstNonWhitespacePosition.Value); if (token.IsKind(SyntaxKind.None) || token.SpanStart != firstNonWhitespacePosition) { return false; } // first see whether there is a line operation for current token var previousToken = token.GetPreviousToken(includeZeroWidth: true); // only use smart token formatter when we have two visible tokens. if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing) { return false; } var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet); if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine) { // no indentation operation, nothing to do for smart token formatter return false; } // We're pressing enter between two tokens, have the formatter figure out hte appropriate // indentation. return true; }
internal static CompilationUnitSyntax AddPropertyTo( CompilationUnitSyntax destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GeneratePropertyOrIndexer(property, CodeGenerationDestination.CompilationUnit, options); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastPropertyOrField, before: FirstMember); return destination.WithMembers(members); }
private void AddFormattingSpans( CompilationUnitSyntax compilationUnit, List<TextSpan> spans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); spans.Add(TextSpan.FromBounds(0, GetEndPosition(compilationUnit, compilationUnit.Members))); foreach (var @namespace in compilationUnit.Members.OfType<NamespaceDeclarationSyntax>()) { AddFormattingSpans(@namespace, spans, cancellationToken); } }
public Model.ParsingResults ParseSource(string filename) { try { mTree = CSharpSyntaxTree.ParseFile(filename); mRoot = (CompilationUnitSyntax)mTree.GetRoot(); } catch { throw; } return Model.ParsingResults.Success; }
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { var value = (CompilationUnitSyntax)base.VisitCompilationUnit(node); if (_notPartialClass) { var usings = _globalModelCompilationUnit.Usings.Where(u => !value.Usings.Any(u2 => u2.Name.ToString() == u.Name.ToString())).ToList(); if (usings.Count != 0) { value = value.WithUsings(SyntaxFactory.List<UsingDirectiveSyntax>(value.Usings.Union(usings).OrderBy(u => u.Name.ToString()))); } } return value; }
private static Task<Document> FixGuidExportMetadata(Document document, CompilationUnitSyntax root, ClassDeclarationSyntax classDeclaration, string guid) { var newSyntax = classDeclaration; newSyntax = newSyntax.ReplaceNode( newSyntax.GetAttributes("ExportMetadata").First(x => x.ArgumentList.Arguments[0].ToString() == "\"Guid\""), SyntaxFactory.Attribute(SyntaxFactory.ParseName("ExportMetadata"), SyntaxFactory.ParseAttributeArgumentList($"(\"Guid\", \"{guid}\")"))); var newRoot = root.ReplaceNode(classDeclaration, newSyntax); var newDocument = document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); }
private static ImmutableArray<LabelSymbol> GetLabels(SynthesizedInteractiveInitializerMethod scriptInitializer, CompilationUnitSyntax syntax) { var builder = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var member in syntax.Members) { if (member.Kind() != SyntaxKind.GlobalStatement) { continue; } LocalScopeBinder.BuildLabels(scriptInitializer, ((GlobalStatementSyntax)member).Statement, ref builder); } return builder.ToImmutableAndFree(); }
public override VisualBasicSyntaxNode VisitCompilationUnit(CSS.CompilationUnitSyntax node) { var imports = node.Usings.Select(u => (ImportsStatementSyntax)u.Accept(this)) .Concat(node.Externs.Select(e => (ImportsStatementSyntax)e.Accept(this))); var attributes = node.AttributeLists.Select(a => SyntaxFactory.AttributesStatement(SyntaxFactory.SingletonList((AttributeListSyntax)a.Accept(this)))); var members = node.Members.Select(m => (StatementSyntax)m.Accept(this)); return(SyntaxFactory.CompilationUnit( SyntaxFactory.List <OptionStatementSyntax>(), SyntaxFactory.List(imports), SyntaxFactory.List(attributes), SyntaxFactory.List(members) )); }
private CompilationUnitSyntax UpdateUsings(CompilationUnitSyntax compilationUnit) { var namespaces = compilationUnit.Members.OfType<NamespaceDeclarationSyntax>().ToList(); var usings = compilationUnit.Usings; usings = usings .AddRange(extraUsingDirectives) .AddRange(namespaces.SelectMany(c => GetNamespacesAndParents(c.Name.ToString()).Select(d => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(d))))) .Sort(); usings = usings.Replace(usings[0], usings[0].WithLeadingTrivia(SyntaxFactory.Trivia(SyntaxFactory.PragmaWarningDirectiveTrivia(SyntaxFactory.Token(SyntaxKind.DisableKeyword), true)))); return compilationUnit.WithUsings(usings); }
internal static CompilationUnitSyntax AddFieldTo( CompilationUnitSyntax destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateFieldDeclaration(field, CodeGenerationDestination.CompilationUnit, options); // Place the field after the last field or const, or at the start of the type // declaration. var members = Insert(destination.Members, declaration, options, availableIndices, after: m => LastField(m, declaration), before: FirstMember); return destination.WithMembers(members.ToSyntaxList()); }
public void InitializeExecutableCompilationUnit(string @namespace, string mainClassName) { CompilationUnitSyntax = SyntaxFactory.CompilationUnit().AddMembers( SyntaxFactory.NamespaceDeclaration( SyntaxFactory.IdentifierName(@namespace)).AddMembers( SyntaxFactory.ClassDeclaration(mainClassName).AddMembers( SyntaxFactory.MethodDeclaration( SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "Main") .AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithBody(SyntaxFactory.Block()).AddBodyStatements(SyntaxFactory.ReturnStatement()) ) )); }
internal static CompilationUnitSyntax ImplementINotifyPropertyChanged(CompilationUnitSyntax root, SemanticModel model, IEnumerable<ExpandablePropertyInfo> properties, Workspace workspace) { var typeDeclaration = properties.First().PropertyDeclaration.FirstAncestorOrSelf<TypeDeclarationSyntax>(); var backingFieldLookup = Enumerable.ToDictionary(properties, info => info.PropertyDeclaration, info => info.BackingFieldName); root = root.ReplaceNodes(properties.Select(p => p.PropertyDeclaration as SyntaxNode).Concat(new[] { typeDeclaration }), (original, updated) => original.IsKind(SyntaxKind.PropertyDeclaration) ? ExpandProperty((PropertyDeclarationSyntax)original, backingFieldLookup[(PropertyDeclarationSyntax)original]) as SyntaxNode : ExpandType((TypeDeclarationSyntax)original, (TypeDeclarationSyntax)updated, properties.Where(p => p.NeedsBackingField), model, workspace)); return root .WithUsing("System.Collections.Generic") .WithUsing("System.ComponentModel"); }
public SmartTokenFormatter( OptionSet optionSet, IEnumerable<IFormattingRule> formattingRules, CompilationUnitSyntax root) { Contract.ThrowIfNull(optionSet); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(root); _optionSet = optionSet; _formattingRules = formattingRules; _root = root; }
internal static CompilationUnitSyntax AddEventTo( CompilationUnitSyntax destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateEventDeclaration(@event, CodeGenerationDestination.CompilationUnit, options); // Place the event depending on its shape. Field style events go with fields, property // style events go with properties. If there var members = Insert(destination.Members, declaration, options, availableIndices, after: list => AfterMember(list, declaration), before: list => BeforeMember(list, declaration)); return destination.WithMembers(members.ToSyntaxList()); }
private static Task<Document> AddInterface(Document document, CompilationUnitSyntax root, ClassDeclarationSyntax classDeclaration, string[] interfaceNames) { var newSyntax = classDeclaration; foreach (var interfaceName in interfaceNames) { var baseType = SyntaxFactory.SimpleBaseType(SyntaxFactory.IdentifierName(interfaceName)); newSyntax = newSyntax .AddBaseListTypes(baseType); newSyntax = newSyntax.ReplaceToken(newSyntax.Identifier, newSyntax.Identifier.WithTrailingTrivia(SyntaxFactory.Whitespace(" "))); } var newRoot = root.ReplaceNode(classDeclaration, newSyntax); var newDocument = document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); }
private static Task<Document> AddExport(Document document, CompilationUnitSyntax root, ClassDeclarationSyntax classDeclaration, string[] interfaceNames) { var newSyntax = classDeclaration; foreach (var interfaceName in interfaceNames) { var attributeList = SyntaxFactory.AttributeList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Attribute(SyntaxFactory.ParseName("Export"), SyntaxFactory.ParseAttributeArgumentList($"(typeof({interfaceName}))")))); newSyntax = newSyntax.AddAttributeLists(attributeList); } var newRoot = root.ReplaceNode(classDeclaration, newSyntax); var newDocument = document.WithSyntaxRoot(newRoot); return Task.FromResult(newDocument); }
private IEnumerable<ClassModel> GetClass(IEnumerable<ClassDeclarationSyntax> classes, CompilationUnitSyntax root) { List<ClassModel> result = new List<ClassModel>(); foreach (ClassDeclarationSyntax cs in classes) { ClassModel classModel = new ClassModel(); classModel.Name = cs.Identifier.ToFullString().Trim(); classModel.Properties = GetProperty(cs, root); result.Add(classModel); } return result; }
public override void VisitCompilationUnit(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax node) { AddUsings(node); base.VisitCompilationUnit(node); }
/// <summary> /// Applies merge sort on Span.Start to obtain ordered stream of namespace decls and documentation /// syntax nodes. /// </summary> /// <param name="root">root of the syntax tree</param> /// <returns>stream ordered by span.start</returns> private static IEnumerable <SyntaxNode> NamespaceDeclsAndDocumentations(CompilationUnitSyntax root) { using var namespaceDecls = root .DescendantNodes() .OfType <Syntax.NamespaceDeclarationSyntax>() .GetEnumerator(); using var documentations = root .DescendantNodes(descendIntoTrivia: true) .OfType <Syntax.DocumentationCommentTriviaSyntax>() .GetEnumerator(); bool doneWithNamespaceDecls = !namespaceDecls.MoveNext(); bool doneWithDocumentations = !documentations.MoveNext(); SyntaxNode?prevWhat = null; // previous yield return while (!doneWithNamespaceDecls || !doneWithDocumentations) { SyntaxNode?what; // what to yield return if (doneWithNamespaceDecls && !doneWithDocumentations) { what = documentations.Current; doneWithDocumentations = !documentations.MoveNext(); } else if (!doneWithNamespaceDecls && doneWithDocumentations) { what = namespaceDecls.Current; doneWithNamespaceDecls = !namespaceDecls.MoveNext(); } else { if (namespaceDecls.Current.SpanStart < documentations.Current.SpanStart) { what = namespaceDecls.Current; doneWithNamespaceDecls = !namespaceDecls.MoveNext(); } else { what = documentations.Current; doneWithDocumentations = !documentations.MoveNext(); } } // Loop invariant if (what == null) { throw new InvalidOperationException("Unexpected null what"); } if (prevWhat != null && what.SpanStart <= prevWhat.SpanStart) { throw new InvalidOperationException( $"Unexpected {nameof(what)}.SpanStart (== {what.SpanStart}) " + $"before {nameof(prevWhat)}.SpanStart (== {prevWhat.SpanStart})"); } yield return(what); } }
public override void VisitCompilationUnit(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax node) { cancellationToken.ThrowIfCancellationRequested(); AddUsings(node); base.VisitCompilationUnit(node); }
public override SyntaxNode VisitCompilationUnit(Microsoft.CodeAnalysis.CSharp.Syntax.CompilationUnitSyntax node) => base.VisitCompilationUnit(node.WithUsings( Microsoft.CodeAnalysis.CSharp.SyntaxFactory.List <UsingDirectiveSyntax>()));