/// <summary> /// Rewrites a syntax tree using the specified rewriter. /// </summary> private static CSharpSyntaxTree RewriteSyntaxTree(CSharpSyntaxTree tree, SemanticModel semanticModel, Func <SemanticModel, CSharpSyntaxRewriter> rewriter) { var rewrittenRoot = rewriter(semanticModel).Visit(tree.GetRoot()); if (rewrittenRoot != tree.GetRoot()) { return((CSharpSyntaxTree)CSharpSyntaxTree.Create((CSharpSyntaxNode)rewrittenRoot, tree.Options, tree.FilePath, tree.Encoding)); } return(tree); }
public CSharpClass(CSharpSyntaxTree syntaxTree) { Name = Path.GetFileNameWithoutExtension(syntaxTree.FilePath); SyntaxTree = syntaxTree; IEnumerable <ConstructorDeclarationSyntax> constructors = SyntaxTree.GetRoot() .DescendantNodes(). OfType <ConstructorDeclarationSyntax>().ToList(); Constructors = new List <ConstructorDeclarationSyntax>(constructors); IEnumerable <MethodDeclarationSyntax> methods = SyntaxTree.GetRoot() .DescendantNodes() .OfType <MethodDeclarationSyntax>().ToList(); Methods = new List <MethodDeclarationSyntax>(methods); }
private void CheckClassNameAndFileName(CSharpSyntaxTree syntaxTree, SyntaxTreeAnalysisContext compilationContext) { if (syntaxTree.IsGeneratedCode()) { return; } var fileNameWithExtensions = Path.GetFileName(syntaxTree.FilePath); var fileName = fileNameWithExtensions.Split('.').First(); var typeDecls = GetTopLevelType(syntaxTree.GetRoot()); if (typeDecls.Count() == 1) { TypeDeclarationSyntax typeDecl = typeDecls.First(); //skip partial class if (typeDecl is ClassDeclarationSyntax && ((ClassDeclarationSyntax)typeDecl).Modifiers.Any(SyntaxKind.PartialKeyword)) { return; } if (typeDecl.Identifier.ValueText != fileName) { compilationContext.ReportDiagnostic( Diagnostic.Create( Descriptor, typeDecl.Identifier.GetLocation(), fileNameWithExtensions)); } } }
private static CSharpSyntaxTree EditSyntaxTree(CSharpSyntaxTree syntaxTree, CSharpCompilation compilation, CancellationToken cancellationToken) { Rewriter rewriter = new Rewriter(compilation, syntaxTree, cancellationToken); CSharpSyntaxNode root = syntaxTree.GetRoot(cancellationToken); return(syntaxTree.WithRoot(rewriter.Visit(root)) as CSharpSyntaxTree); }
/// <summary> /// Compile routine. Used to compile the CSharp code /// </summary> /// <param name="projectDir"></param> public static void Compile(string projectDir, CompilerFlags flags) { // Obtain the source code from the project Program file. string sourceCodeText = ReadSourceFile(projectDir + "\\Program.cs"); // Parse the source code into a syntax tree. CSharpSyntaxTree syntaxTree = Parse(sourceCodeText); // Get the root node of the syntax tree CSharpSyntaxNode rootNode = syntaxTree.GetRoot(); // Generate output or serialize compile unit // if (flags.GenerateOutput) { StringBuilder sourceCode = CPPCodeGenerator.GenerateCode(rootNode); if (flags.ArduinoSketch) { System.IO.Directory.CreateDirectory(projectDir + "\\arduino\\program"); AddSketch(sourceCode, "BlinkSample", "Program", "Main"); System.IO.File.WriteAllText(projectDir + "\\arduino\\program\\program.ino", sourceCode.ToString()); } else { System.IO.Directory.CreateDirectory(projectDir + "\\src"); AddMainEntry(sourceCode, "BlinkSample", "Program", "Main"); System.IO.File.WriteAllText(projectDir + "\\src\\program.cpp", sourceCode.ToString()); } } else { rootNode.SerializeTo(System.IO.File.OpenWrite(projectDir + "\\out\\out.cu")); } }
static public SingleItemResult <ClassDeclarationSyntax> FindClass(CSharpSyntaxTree syntaxTree, string className) { var results = syntaxTree .GetRoot() .DescendantNodes() .OfType <ClassDeclarationSyntax>() .Where(x => (x.Identifier.ToString() == className)) .Take(2) .ToList() ; switch (results) { case var noRes when(results.Count == 0): { return(SingleItemResult <ClassDeclarationSyntax> .NoneElementsMatching); } case var singleton when(results.Count == 1): { return(singleton.Single()); } case var twoItems when(results.Count >= 2): { return(SingleItemResult <ClassDeclarationSyntax> .MoreThanTwoElementsMatching(twoItems[0], twoItems[1])); } default: throw NotPreparedForThatCase.CannotHappenException; } }
public string ConvertToTypescript(string text, ConvertSettings settingStore) { try { CSharpSyntaxTree text1 = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, null, "", null, new CancellationToken()); if (text1.GetDiagnostics(new CancellationToken()).Any(f => f.Severity == (DiagnosticSeverity)3)) { return(null); } CSharpSyntaxNode syntaxNode = text1.GetRoot(new CancellationToken()); if (this.IsEmptyRoot(syntaxNode)) { return(null); } if (settingStore.IsConvertToInterface) { syntaxNode = ClassToInterfaceReplacement.ReplaceClass(syntaxNode); } if (settingStore.IsConvertMemberToCamelCase) { syntaxNode = MakeMemberCamelCase.Make(syntaxNode); } if (settingStore.IsConvertListToArray) { syntaxNode = ListToArrayReplacement.ReplaceList(syntaxNode); } if (settingStore.ReplacedTypeNameArray.Length != 0) { syntaxNode = TypeNameReplacement.Replace(settingStore.ReplacedTypeNameArray, syntaxNode); } if (settingStore.AddIPrefixInterfaceDeclaration) { syntaxNode = AddIPrefixInterfaceDeclaration.AddIPrefix(syntaxNode); } if (settingStore.IsInterfaceOptionalProperties) { syntaxNode = OptionalInterfaceProperties.AddOptional(syntaxNode); } CSharpSyntaxTree syntaxTree = (CSharpSyntaxTree)syntaxNode.SyntaxTree; SyntaxTranslation syntaxTranslation = TF.Get(syntaxNode, null); CSharpCompilation csharpCompilation = CSharpCompilation.Create("TemporaryCompilation", new[] { syntaxTree }); SemanticModel semanticModel = ((Compilation)csharpCompilation).GetSemanticModel(syntaxTree, false); syntaxTranslation.Compilation = csharpCompilation; syntaxTranslation.SemanticModel = semanticModel; syntaxTranslation.ApplyPatch(); return(syntaxTranslation.Translate()); } catch (Exception ex) { } return((string)null); }
public CSharpSyntaxNode Fix() { var syntaxNode = _syntaxTree.GetRoot(); return(syntaxNode.ReplaceNodes(syntaxNode.DescendantNodes(), ComputeReplacementNode) .TypeSwitch( (CompilationUnitSyntax x) => TidyUsings(x), node => node )); }
public static IEnumerable <(object element, ElementType type, int nestedLevel)> GetElements(CSharpSyntaxTree target) { var root = target.GetRoot(); yield return(root, ElementType.SyntaxNode, 1); foreach (var element in GetChildElements(root.ChildNodesAndTokens(), 2)) { yield return(element); } }
private CSharpSyntaxTree EditSyntaxTree(CSharpSyntaxTree tree, CSharpCompilation compilation, CancellationToken token) { // The whole compilation is edited at once instead of going through each node independently, // because syntax trees cannot change if we want to use their semantic model. SemanticModel semanticModel = compilation.GetSemanticModel(tree, true); SyntaxNode root = tree.GetRoot(token); Rewriter rewriter = new Rewriter(semanticModel, startAtSyntax); return((CSharpSyntaxTree)tree.WithRoot(rewriter.Visit(root))); }
public static GlslSyntaxTree Translate(this CSharpSyntaxTree tree) { var supportCode = File.ReadAllText("Shader.cs"); supportCode += File.ReadAllText("Shader.Vectors.cs"); supportCode += File.ReadAllText("Shader.Matrices.cs"); var supportTree = CSharpSyntaxTree.ParseText(supportCode); var compilation = CSharpCompilation.Create("Shader").AddSyntaxTrees(tree, supportTree); model = compilation.GetSemanticModel(tree); return(new GlslSyntaxTree(tree.GetRoot().Translate())); }
static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Usage: <program> <csharp-file>"); } else { CSharpTreeDumper dumper = new CSharpTreeDumper(Microsoft.CodeAnalysis.SyntaxWalkerDepth.Trivia); CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(System.IO.File.ReadAllText(args[0])); dumper.Visit(tree.GetRoot()); } }
public CSharpCodeAnalyzer(string filepath) { SyntaxTree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(File.ReadAllText(filepath)); IEnumerable <ClassDeclarationSyntax> classes = SyntaxTree.GetRoot() .DescendantNodes() .OfType <ClassDeclarationSyntax>().ToList(); List <ClassDeclarationSyntax> classSyntax = new List <ClassDeclarationSyntax>(classes); foreach (var cls in classSyntax) { SubClasses.Add(new CSharpClass((CSharpSyntaxTree)cls.SyntaxTree)); } }
public static void ConvertRoslynToCCI( IMetadataHost host, CSharpSyntaxTree tree, SemanticModel semanticModel, out IModule module, out ISourceLocationProvider sourceLocationProvider) { sourceLocationProvider = new SourceLocationProvider(); var transformer = new NodeVisitor(host, semanticModel, sourceLocationProvider); var assembly = (Module)transformer.Visit(tree.GetRoot()); assembly.Location = Path.GetFullPath(tree.FilePath); module = assembly; }
public static void GenerateServers(JObject jobj, string projdir) { CSharpSyntaxTree cst = CSharpSyntaxTree.ParseText(content, CSharpParseOptions.Default, "HelloWorld.cs") as CSharpSyntaxTree; var root = cst.GetRoot(); //root. IEnumerable <MethodDeclarationSyntax> methodsDeclarations = root.DescendantNodes().OfType <MethodDeclarationSyntax>(); var metaRefSystem = MetadataReference.CreateFromFile(typeof(String).Assembly.Location); var metaRefs = ImmutableArray.Create <MetadataReference>(metaRefSystem); //CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(); //var compilation = CSharpCompilation.Create("GenerateScriptAssembly", , metaRefs); }
private static void RewriteCode(string input) { // Inspiration: // https://github.com/dotnet/roslyn/wiki/Getting-Started-C%23-Syntax-Transformation CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(input); var mscorlib = MetadataReference.CreateFromFile(typeof(Attribute).Assembly.Location); var contractsLibrary = MetadataReference.CreateFromFile(typeof(Contracts.Contract).Assembly.Location); var systemCore = MetadataReference.CreateFromFile(typeof(ParallelQuery).Assembly.Location); CSharpCompilation compilation = CSharpCompilation.Create("translated_assembly", new[] { tree }, new[] { mscorlib, contractsLibrary, systemCore }); SemanticModel semanticModel = compilation.GetSemanticModel(tree, true); ContractsRemover remover = new ContractsRemover(semanticModel); SyntaxNode newSource = remover.Visit(tree.GetRoot()); Console.Write(newSource.ToFullString()); }
public override void Open() { base.Open(); tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(Source, CSharpParseOptions.Default); CompilationUnitSyntax root = (CompilationUnitSyntax)tree.GetRoot(); MemberDeclarationSyntax firstMember = root.Members [0]; Console.WriteLine(firstMember.GetType().FullName); SyntaxToken tok = root.GetFirstToken(); while (tok.Value != null) { Console.Write(tok.Text); tok = tok.GetNextToken(true, true); } Console.Out.Flush(); }
/// <summary> /// Registers a new <paramref name="edit"/> that is to be applied to any <see cref="SyntaxNode"/> /// found on the <see cref="CSharpCompilation"/>. /// </summary> /// <param name="editor"></param> /// <param name="edit"></param> public static void EditSyntax(this CompilationEditor editor, SyntaxEdit edit) { IList <SyntaxEdit> GetDefaultValue() { editor.CompilationPipeline += EditCompilation; return(new LightList <SyntaxEdit>()); } CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken) { IList <SyntaxEdit> edits = editor.Storage.Get <IList <SyntaxEdit> >(SyntaxKey); SyntaxTreeRewriter syntaxRewriter = new SyntaxTreeRewriter(compilation, edits, cancellationToken); for (int i = 0; i < compilation.SyntaxTrees.Length; i++) { CSharpSyntaxTree tree = compilation.SyntaxTrees[i] as CSharpSyntaxTree; if (tree == null) { continue; } CSharpSyntaxNode root = tree.GetRoot(cancellationToken); SyntaxNode newRoot = syntaxRewriter.Visit(root); if (root != newRoot) { compilation = compilation.ReplaceSyntaxTree(tree, tree.WithRootAndOptions(newRoot, tree.Options)); } } return(compilation); } editor.Storage.GetOrAdd(SyntaxKey, GetDefaultValue).Add(edit); }
public string ConvertToTypescript(string text, ISettingStore settingStore) { try { CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text); // detect to see if it's actually C# sourcode by checking whether it has any error if (tree.GetDiagnostics().Any(f => f.Severity == DiagnosticSeverity.Error)) { return(null); } CSharpSyntaxNode root = tree.GetRoot(); // if it only contains comments, just return the original texts if (IsEmptyRoot(root)) { return(null); } if (settingStore.IsConvertToInterface) { root = ClassToInterfaceReplacement.ReplaceClass(root); } if (settingStore.IsConvertMemberToCamelCase) { root = MakeMemberCamelCase.Make(root); } if (settingStore.IsConvertListToArray) { root = ListToArrayReplacement.ReplaceList(root); } if (settingStore.ReplacedTypeNameArray.Length > 0) { root = TypeNameReplacement.Replace(settingStore.ReplacedTypeNameArray, root); } if (settingStore.AddIPrefixInterfaceDeclaration) { root = AddIPrefixInterfaceDeclaration.AddIPrefix(root); } if (settingStore.IsInterfaceOptionalProperties) { root = OptionalInterfaceProperties.AddOptional(root); } tree = (CSharpSyntaxTree)root.SyntaxTree; var translationNode = TF.Get(root, null); var compilation = CSharpCompilation.Create( "TemporaryCompilation", syntaxTrees: new[] { tree }, references: new[] { Mscorlib } ); var model = compilation.GetSemanticModel(tree); translationNode.Compilation = compilation; translationNode.SemanticModel = model; translationNode.ApplyPatch(); return(translationNode.Translate()); } catch (Exception ex) { // TODO // swallow exception .!!!!!!!!!!!!!!!!!!!!!!! Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } return(null); }
public CSharpSyntaxNode Fix() { var syntaxNode = _syntaxTree.GetRoot(); return(TidyUsings(syntaxNode)); }
public void Visit(CSharpSyntaxTree tree) { walker.Visit(tree.GetRoot()); }
public CSharpCompilation Rewrite() { var newRoot = tree.GetRoot().Accept(this); return(compilation.ReplaceSyntaxTree(tree, CreateTree(newRoot))); }
public AnalyzerResult Analyze() { result = new AnalyzerResult(); tree.GetRoot().Accept(this); return(result); }
public CSharpSyntaxNode Fix() { var syntaxNode = syntaxTree.GetRoot(); return(syntaxNode.ReplaceNodes(syntaxNode.DescendantNodes(), ComputeReplacementNode)); }