public MapFunctionProcessor(CSharpSyntaxRewriter collectionRetriever, SelectManyRewriter selectManyRewriter) { _selectManyRewriter = selectManyRewriter; CollectionRetriever = collectionRetriever; _refCollectionsRetriever = new ReferencedCollectionsRetriever(); _compareExchangeReferenceDetector = new CompareExchangeReferenceDetectorRewriter(); }
public static int Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: CodeFormat [Path to File or Folder]"); return(-1); } CSharpSyntaxRewriter[] rewriters = new CSharpSyntaxRewriter[] { new SingleLineIfBracesRule(), new UsingOrderRule(), new CopyrightCommentRule(), }; string path = args[0]; if (Directory.Exists(path)) { Traverse(path, rewriters); } else if (Path.GetExtension(path).ToLowerInvariant().Equals(".cs")) { Transform(path, rewriters); } else { Console.WriteLine($"Error: \"{path}\" was not a directory or a C# class file."); Console.WriteLine("Usage: CodeFormat [Path to File or Folder]"); return(-1); } return(0); }
public void parseCompilationWithProvidedPriorities(Priority.En_Priority[] prioritiesTablo) { Tuple <Compilation, int> compilationTuple; Array.Sort(prioritiesTablo); foreach (Priority.En_Priority priority in prioritiesTablo) { compilationTuple = CreateCompilation(); SyntaxNode finalNode = null; foreach (SyntaxTree sourceTree in compilationTuple.Item1.SyntaxTrees) { CSharpSyntaxRewriter rewriter = Priority.GetInstancePriorityBased(priority, compilationTuple.Item1.GetSemanticModel(sourceTree)); if (rewriter != null) { finalNode = rewriter.Visit(sourceTree.GetRoot()); if (finalNode != null) { File.WriteAllText(sourceTree.FilePath, finalNode.ToFullString()); } } else { continue; } } } }
private static SyntaxTrivia ConvertDocumentationComment(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter) { var structure = trivia.GetStructure(); var updatedStructure = (StructuredTriviaSyntax)rewriter.Visit(structure); return(SyntaxFactory.Trivia(updatedStructure)); }
private string RewriteTypeName(CSharpSyntaxRewriter rewriter, string typeName) { var parsed = SyntaxFactory.ParseTypeName(typeName); var rewritten = (TypeSyntax)rewriter.Visit(parsed); return(rewritten.ToFullString()); }
private static SyntaxTrivia ConvertDocumentationComment(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter) { var structure = trivia.GetStructure(); var rewritten = rewriter.Visit(structure); Contract.ThrowIfNull(rewritten); return(SyntaxFactory.Trivia((StructuredTriviaSyntax)rewritten)); }
private void RewriteTypeNames(CSharpSyntaxRewriter rewriter, ComponentExtensionNode node) { // Rewrite the component type name node.TypeName = RewriteTypeName(rewriter, node.TypeName); foreach (var attribute in node.Attributes) { if (attribute.BoundAttribute?.IsGenericTypedProperty() ?? false && attribute.TypeName != null) { // If we know the type name, then replace any generic type parameter inside it with // the known types. attribute.TypeName = RewriteTypeName(rewriter, attribute.TypeName); } else if (attribute.TypeName == null && (attribute.BoundAttribute?.IsDelegateProperty() ?? false)) { // This is a weakly typed delegate, treat it as Action<object> attribute.TypeName = "System.Action<System.Object>"; } else if (attribute.TypeName == null) { // This is a weakly typed attribute, treat it as System.Object attribute.TypeName = "System.Object"; } } foreach (var capture in node.Captures) { if (capture.IsComponentCapture && capture.ComponentCaptureTypeName != null) { capture.ComponentCaptureTypeName = RewriteTypeName(rewriter, capture.ComponentCaptureTypeName); } else if (capture.IsComponentCapture) { capture.ComponentCaptureTypeName = "System.Object"; } } foreach (var childContent in node.ChildContents) { if (childContent.BoundAttribute?.IsGenericTypedProperty() ?? false && childContent.TypeName != null) { // If we know the type name, then replace any generic type parameter inside it with // the known types. childContent.TypeName = RewriteTypeName(rewriter, childContent.TypeName); } else if (childContent.IsParameterized) { // This is a weakly typed parameterized child content, treat it as RenderFragment<object> childContent.TypeName = BlazorApi.RenderFragment.FullTypeName + "<System.Object>"; } else { // This is a weakly typed child content, treat it as RenderFragment childContent.TypeName = BlazorApi.RenderFragment.FullTypeName; } } }
private static MethodDeclarationSyntax CopyLeadingTrivia( PropertyDeclarationSyntax propertyDeclaration, MethodDeclarationSyntax methodDeclaration, CSharpSyntaxRewriter documentationCommentRewriter) { var leadingTrivia = propertyDeclaration.GetLeadingTrivia(); return(methodDeclaration.WithLeadingTrivia(leadingTrivia.Select(trivia => ConvertTrivia(trivia, documentationCommentRewriter)))); }
private static SyntaxTrivia ConvertTrivia(SyntaxTrivia trivia, CSharpSyntaxRewriter rewriter) { if (trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) { return(ConvertDocumentationComment(trivia, rewriter)); } return(trivia); }
/// <summary> /// Rewrites the source code using the given rewriter. /// </summary> /// <returns>The modified source file.</returns> public SourceFile Rewrite(CSharpSyntaxRewriter rewriter) { var newRoot = rewriter.Visit(_root); // If we didn't find anything to change, that's almost always due to a bug, so fail quickly. if (newRoot == _root) { throw new Exception("Rewriter made no changes"); } return(WithRootNode(newRoot)); }
/// <summary> /// Formats the specified <see cref="CompilationUnitSyntax"/> and returns its file string representation. /// </summary> /// <param name="syntax">The <see cref="CompilationUnitSyntax"/> to format.</param> /// <param name="rewriter">The <see cref="CSharpSyntaxRewriter"/> to use.</param> /// <returns>The formatted file string representation of the <paramref name="syntax"/>.</returns> internal static string ToFileString(this CompilationUnitSyntax syntax, CSharpSyntaxRewriter rewriter = null) { SyntaxTriviaList header = SyntaxFactory.ParseLeadingTrivia(string.Format(Strings.FileHeader, Environment.Version)); if (syntax.Usings.Count > 0 || syntax.Members.Count > 0) { header = header.Add(SyntaxFactory.CarriageReturnLineFeed).Add(SyntaxFactory.CarriageReturnLineFeed); } return(syntax.NormalizeWhitespace().Accept(rewriter ?? new Rewriter()).WithLeadingTrivia(header).WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed).ToFullString()); }
private static Compilation Rewrite(this Compilation compilation, CSharpSyntaxRewriter rewriter) { foreach (var syntaxTree in compilation.SyntaxTrees) { compilation = compilation.ReplaceSyntaxTree( syntaxTree, syntaxTree.WithRootAndOptions( rewriter.Visit(syntaxTree.GetRoot()), syntaxTree.Options)); } return(compilation); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is BlockSyntax) { action = LookAheadAction.SUCCEDED; BlockSyntax code = (BlockSyntax)node; return(dsl_.setCode(ctx_, dctx_, code)); } action = LookAheadAction.FAILED; return(null); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is ClassDeclarationSyntax) { action = LookAheadAction.SUCCEDED; ClassDeclarationSyntax clazz = (ClassDeclarationSyntax)node; DSLContext dctx = new DSLContext { MainNode = node, Surroundings = DSLSurroundings.Global, ExtraMembers = extraMembers_ }; return(dsl_.compile(ctx_, dctx)); } action = LookAheadAction.FAILED; return(null); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is FieldDeclarationSyntax) { FieldDeclarationSyntax fd = (FieldDeclarationSyntax)node; var type = fd.Declaration.Type; string param_name = fd.Declaration.Variables.First().Identifier.ToString().Replace(")", ""); params_.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(param_name)). WithType(type)); switch (fd.Declaration.Variables.Count) { case 1: { action = LookAheadAction.SUCCEDED; extraMembers_.Add(SyntaxFactory.DelegateDeclaration(Compiler.Void, name_). WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(params_))). WithModifiers(modifiers_)); break; } case 2: { action = LookAheadAction.CONTINUE; break; } default: { action = LookAheadAction.FAILED; break; } } return(null); } else { Debug.Assert(false); //td: error } action = LookAheadAction.FAILED; return(null); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is IncompleteMemberSyntax) { var incomplete = (IncompleteMemberSyntax)node; var identifier = incomplete.Type.ToString(); var complete = SyntaxFactory.ParseStatement(incomplete.ToFullString()); var value = null as ExpressionSyntax; if (complete is ExpressionStatementSyntax) { ExpressionStatementSyntax exprStatement = (ExpressionStatementSyntax)complete; switch (exprStatement.Expression.CSharpKind()) { case SyntaxKind.SimpleAssignmentExpression: { BinaryExpressionSyntax bs = (BinaryExpressionSyntax)exprStatement.Expression; value = bs.Right; break; } case SyntaxKind.IdentifierName: { break; } default: { //td: error break; } } } if (value != null) { //td: !!! initializer } action = LookAheadAction.SUCCEDED; return(result_.ReplaceToken(result_.Identifier, SyntaxFactory.ParseToken(identifier))); } action = LookAheadAction.FAILED; return(node); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is IncompleteMemberSyntax) { action = LookAheadAction.SUCCEDED; IncompleteMemberSyntax incomplete = (IncompleteMemberSyntax)node; string typeName = incomplete.Type.ToString(); string typeDef = field_.Declaration.Variables.First().Identifier.ToString(); var typeNode = SyntaxFactory.ParseTypeName(typeDef); ClassDeclarationSyntax parent = (ClassDeclarationSyntax)field_.Parent; ctx_.AddTypeInfo(parent.Identifier.ToString(), "typedefs", new Typedef(typeName, (TypeSyntax)ctx_.CompileType(typeNode, parent))); return(null); } action = LookAheadAction.FAILED; return(node); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is EmptyStatementSyntax) { var arguments = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(args_)); ctx_.AddLinkData(node_, arguments); action = LookAheadAction.SUCCEDED; return(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.SemicolonToken))); } if (node is VariableDeclaratorSyntax) { //found another array var vard = (VariableDeclaratorSyntax)node; if (vard.ArgumentList != null) { var values = vard.ArgumentList.Arguments.Select <ArgumentSyntax, ExpressionSyntax>(arg => arg.Expression); var array = SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName("object[]")), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(values))); //td: link args_.Add(SyntaxFactory.Argument(array)); } action = LookAheadAction.CONTINUE; return(null); } if (node is ExpressionStatementSyntax) { var expr = (ExpressionStatementSyntax)transform.Visit(node); args_.Add(SyntaxFactory.Argument(expr.Expression)); action = LookAheadAction.CONTINUE; return(null); } action = LookAheadAction.FAILED; return(node); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is EmptyStatementSyntax) { var arguments = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(args_)); ctx_.AddLinkData(node_, arguments); action = LookAheadAction.SUCCEDED; return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } if (node is VariableDeclaratorSyntax) { //found another array var vard = (VariableDeclaratorSyntax)node; if (vard.ArgumentList != null) { var values = vard.ArgumentList.Arguments.Select<ArgumentSyntax, ExpressionSyntax>(arg => arg.Expression); var array = SyntaxFactory.ArrayCreationExpression(SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName("object[]")), SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, SyntaxFactory.SeparatedList(values))); //td: link args_.Add(SyntaxFactory.Argument(array)); } action = LookAheadAction.CONTINUE; return null; } if (node is ExpressionStatementSyntax) { var expr = (ExpressionStatementSyntax)transform.Visit(node); args_.Add(SyntaxFactory.Argument(expr.Expression)); action = LookAheadAction.CONTINUE; return null; } action = LookAheadAction.FAILED; return node; }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is MethodDeclarationSyntax) { action = LookAheadAction.SUCCEDED; MethodDeclarationSyntax method = (MethodDeclarationSyntax)node; TypeSyntax type = field_.Declaration.Type; SyntaxToken identifier = method.Identifier; SyntaxTokenList modifiers = field_.Modifiers.Any() ? field_.Modifiers : SyntaxFactory.TokenList(asPublic_ ? Compiler.Public : Compiler.Private); return(SyntaxFactory.MethodDeclaration(type, identifier) .WithLeadingTrivia(SyntaxFactory.Space) .WithModifiers(modifiers) .WithParameterList((ParameterListSyntax)(new ExcessParamListRewriter(ctx_)).Visit(method.ParameterList)) .WithBody((BlockSyntax)transform.Visit(method.Body))); } action = LookAheadAction.FAILED; return(null); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is FieldDeclarationSyntax) { FieldDeclarationSyntax fd = (FieldDeclarationSyntax)node; var type = fd.Declaration.Type; string param_name = fd.Declaration.Variables.First().Identifier.ToString().Replace(")", ""); params_.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier(param_name)). WithType(type)); switch (fd.Declaration.Variables.Count) { case 1: { action = LookAheadAction.SUCCEDED; extraMembers_.Add(SyntaxFactory.DelegateDeclaration(Compiler.Void, name_). WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(params_))). WithModifiers(modifiers_)); break; } case 2: { action = LookAheadAction.CONTINUE; break; } default: { action = LookAheadAction.FAILED; break; } } return null; } else { Debug.Assert(false); //td: error } action = LookAheadAction.FAILED; return null; }
static SyntaxTree RunRewriter(SyntaxTree syntaxTree, CSharpSyntaxRewriter rewriter) { var newRoot = rewriter.Visit(syntaxTree.GetRoot()); return(SyntaxFactory.SyntaxTree(newRoot)); }
public ClientExtractor(CSharpSyntaxRewriter rewriter) { this.rewriter = rewriter; }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is BlockSyntax) { action = LookAheadAction.SUCCEDED; BlockSyntax code = (BlockSyntax)node; return dsl_.setCode(ctx_, dctx_, code); } action = LookAheadAction.FAILED; return null; }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is IncompleteMemberSyntax) { var incomplete = (IncompleteMemberSyntax)node; var identifier = incomplete.Type.ToString(); var complete = SyntaxFactory.ParseStatement(incomplete.ToFullString()); var value = null as ExpressionSyntax; if (complete is ExpressionStatementSyntax) { ExpressionStatementSyntax exprStatement = (ExpressionStatementSyntax)complete; switch (exprStatement.Expression.CSharpKind()) { case SyntaxKind.SimpleAssignmentExpression: { BinaryExpressionSyntax bs = (BinaryExpressionSyntax)exprStatement.Expression; value = bs.Right; break; } case SyntaxKind.IdentifierName: { break; } default: { //td: error break; } } } if (value != null) { //td: !!! initializer } action = LookAheadAction.SUCCEDED; return result_.ReplaceToken(result_.Identifier, SyntaxFactory.ParseToken(identifier)); } action = LookAheadAction.FAILED; return node; }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is IncompleteMemberSyntax) { action = LookAheadAction.SUCCEDED; IncompleteMemberSyntax incomplete = (IncompleteMemberSyntax)node; string typeName = incomplete.Type.ToString(); string typeDef = field_.Declaration.Variables.First().Identifier.ToString(); var typeNode = SyntaxFactory.ParseTypeName(typeDef); ClassDeclarationSyntax parent = (ClassDeclarationSyntax)field_.Parent; ctx_.AddTypeInfo(parent.Identifier.ToString(), "typedefs", new Typedef(typeName, (TypeSyntax)ctx_.CompileType(typeNode, parent))); return null; } action = LookAheadAction.FAILED; return node; }
public TestFixtureDocumentConverter() { _attributeRewriter = new TestFixtureLifecycleAttributeRewriter( new TestFixtureSetupAttributeRenamer(), new TestFixtureTeardownAttributeRenamer()); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is MethodDeclarationSyntax) { action = LookAheadAction.SUCCEDED; MethodDeclarationSyntax method = (MethodDeclarationSyntax)node; TypeSyntax type = field_.Declaration.Type; SyntaxToken identifier = method.Identifier; SyntaxTokenList modifiers = field_.Modifiers.Any() ? field_.Modifiers : SyntaxFactory.TokenList(asPublic_ ? Compiler.Public : Compiler.Private); return SyntaxFactory.MethodDeclaration(type, identifier) .WithLeadingTrivia(SyntaxFactory.Space) .WithModifiers(modifiers) .WithParameterList((ParameterListSyntax)(new ExcessParamListRewriter(ctx_)).Visit(method.ParameterList)) .WithBody((BlockSyntax)transform.Visit(method.Body)); } action = LookAheadAction.FAILED; return null; }
public static string GenerateExternalSources(IReadOnlyList <string> externalPaths, ICollection <string> sourcePaths, Type attributeType = null, ICodeGenerateContainerValidation validation = null, Compilation compilation = null, SyntaxGenerator generator = null) { if (externalPaths == null) { throw new ArgumentNullException(nameof(externalPaths)); } if (sourcePaths == null) { throw new ArgumentNullException(nameof(sourcePaths)); } if (validation == null) { validation = CodeGenerateContainerAssetEditorUtility.DefaultValidation; } if (compilation == null) { compilation = CodeAnalysisEditorUtility.ProjectCompilation; } if (generator == null) { generator = CodeAnalysisEditorUtility.Generator; } string externalsTempPath = FileUtil.GetUniqueTempPathInProject(); var types = new HashSet <Type>(); CSharpSyntaxRewriter rewriterAddAttribute = null; if (attributeType != null && compilation.TryConstructTypeSymbol(attributeType, out ITypeSymbol typeSymbol)) { rewriterAddAttribute = GetAttributeRewriter(compilation, generator, typeSymbol); } Directory.CreateDirectory(externalsTempPath); for (int i = 0; i < externalPaths.Count; i++) { string externalPath = externalPaths[i]; var info = AssetInfoEditorUtility.LoadInfo <CodeGenerateContainerInfo>(externalPath); if (info.TryGetTargetType(out Type type)) { if (types.Add(type)) { SyntaxNode unit = CodeGenerateContainerInfoEditorUtility.CreateUnit(info, validation, compilation, generator); if (rewriterAddAttribute != null) { unit = rewriterAddAttribute.Visit(unit); } string sourcePath = $"{externalsTempPath}/{Guid.NewGuid():N}.cs"; string source = unit.NormalizeWhitespace().ToFullString(); File.WriteAllText(sourcePath, source); sourcePaths.Add(sourcePath); } else { Debug.LogWarning($"The specified type already generated: '{type}'."); } } } return(externalsTempPath); }
public SyntaxNode rewrite(CSharpSyntaxRewriter transform, SyntaxNode node, out LookAheadAction action) { if (node is ClassDeclarationSyntax) { action = LookAheadAction.SUCCEDED; ClassDeclarationSyntax clazz = (ClassDeclarationSyntax)node; DSLContext dctx = new DSLContext { MainNode = node, Surroundings = DSLSurroundings.Global, ExtraMembers = extraMembers_ }; return dsl_.compile(ctx_, dctx); } action = LookAheadAction.FAILED; return null; }