static int Main(string[] args) { try { File.Delete("conversion.log"); List <string> map = new List <string>() { "..\\Controller\\Profiler", "..\\Controller\\Data\\UnmanagedCallTreeNode", "..\\Controller\\structs" }; foreach (string path in map) { CSharpParser parser = new CSharpParser(); #if DEBUG parser.CompilerSettings.ConditionalSymbols.Add("DEBUG"); #endif string filePath = path + ".cs"; if (File.Exists(filePath)) { using (StreamReader reader = new StreamReader(filePath)) { SyntaxTree syntaxTree = parser.Parse(reader, filePath); if (parser.HasErrors) { string message = "Parser errors in file " + filePath + ":\n"; foreach (Error error in parser.Errors) { message += error.Message + "\n"; } Console.WriteLine(message); File.WriteAllText(path + "64.cs", message); return(2); } syntaxTree.AcceptVisitor(new Converter()); using (StreamWriter writer = new StreamWriter(path + "64.cs")) { CSharpOutputVisitor output = new CSharpOutputVisitor(writer, FormattingOptionsFactory.CreateSharpDevelop()); syntaxTree.AcceptVisitor(output); } } } } return(0); } catch (Exception e) { try { File.WriteAllText("conversion.log", e.ToString()); } catch (Exception) { return(-2); } return(-1); } }
void WriteCode(ITextOutput output, DecompilerSettings settings, SyntaxTree syntaxTree, IDecompilerTypeSystem typeSystem) { syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }); TokenWriter tokenWriter = new TextTokenWriter(output, settings, typeSystem) { FoldBraces = settings.FoldBraces, /*ExpandMemberDefinitions = settings.ExpandMemberDefinitions */ }; syntaxTree.AcceptVisitor(new CSharpOutputVisitor(tokenWriter, settings.CSharpFormattingOptions)); }
void WriteCode(ITextOutput output, DecompilerSettings settings, SyntaxTree syntaxTree, IDecompilerTypeSystem typeSystem) { syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }); var outputFormatter = new TextTokenWriter(output, settings, typeSystem) { FoldBraces = settings.FoldBraces }; var formattingPolicy = settings.CSharpFormattingOptions; syntaxTree.AcceptVisitor(new CSharpOutputVisitor(outputFormatter, formattingPolicy)); }
List<NewFolding> CreateNewFoldings(SyntaxTree syntaxTree, IDocument document) { FoldingVisitor v = new FoldingVisitor(); v.document = document; syntaxTree.AcceptVisitor(v); return v.foldings; }
public static ISet <string> Gather(SyntaxTree syntaxTree, IEnumerable <string> predefinedSymbols) { var obj = new DefinedSymbolsGatherer(predefinedSymbols); syntaxTree.AcceptVisitor(obj); return(obj._definedSymbols); }
/// <summary> /// Process the input file using the supplied visitor /// </summary> /// <param name="visitorToUse">visitor to use</param> /// <param name="filePath">path to file</param> private static void ProcessModules(CppVisitorBase visitorToUse, String filePath) { setOutput = false; foreach (IModule module in compiler.TypeSystem.Modules) { if (module.IsMainModule) { foreach (ITypeDefinition typeDefinition in module.TopLevelTypeDefinitions) { if (typeDefinition.Kind == TypeKind.Class || typeDefinition.Kind == TypeKind.Enum || typeDefinition.Kind == TypeKind.Struct) { // Skip modules starting with < or any from CppTranslatorSupport namespace because // those are hand crafted for specific platforms if (!typeDefinition.Name.StartsWith("<", StringComparison.InvariantCulture) && !typeDefinition.Namespace.Contains("CppTranslatorSupport", StringComparison.InvariantCulture)) { if (!setOutput) { formatter.OutputName = filePath; setOutput = true; visitorToUse.AddHeaders(); } List <EntityHandle> entities = new List <EntityHandle>() { typeDefinition.MetadataToken }; SyntaxTree syntaxTree = compiler.Decompile(entities); syntaxTree.AcceptVisitor(visitorToUse); } } } visitorToUse.CreateHeaders(); } } formatter.Close(); }
static public ClassMapper analysecode(string sourceText, string file) { StringBuilder b = new StringBuilder(); ClassMapper mapper = new ClassMapper(); mapper.filename = file; string filename = file; //string sourceText = File.ReadAllText(filename); var parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(sourceText, file); var pc = new CSharpProjectContent(); pc = (CSharpProjectContent)pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()); ICompilation compilation = pc.CreateCompilation(); var resolver = new CSharpAstResolver(compilation, syntaxTree, syntaxTree.ToTypeSystem()); var classVisitor = new ClassVisitor(resolver); classVisitor.filename = filename; classVisitor.b = b; classVisitor.wm = new CacheManager(); classVisitor.mapper = mapper; classVisitor.syntax = syntaxTree; syntaxTree.AcceptVisitor(classVisitor); mapper.syntax = syntaxTree; return(mapper); }
private void Update() { if (this.updating || this.MethodCall == null) { return; } this.updating = true; var identifier = new IdentifyingVisitor(); SyntaxTree tree = SyntaxTree.Parse(Text); tree.AcceptVisitor(identifier); IdCode = tree.GetText(); var layer = AdornerLayer.GetAdornerLayer(this); foreach (Adorner adorner in this.adorners.Values) { layer.Remove(adorner); } this.adorners.Clear(); if (identifier.LineMap.Count > 0) { AdornOperationContainer(this.MethodCall, identifier.LineMap, layer); } this.updating = false; }
private static string CSharpToPowerShell(string csharp) { CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(csharp); CodeDomConvertVisitor visitor = new CodeDomConvertVisitor(); var codeObject = syntaxTree.AcceptVisitor(visitor); var stringWriter = new StringWriter(); var powerShellProvider = new PowerShellCodeDomProvider(); powerShellProvider.GenerateCodeFromCompileUnit(codeObject as CodeCompileUnit, stringWriter, new CodeGeneratorOptions()); return(stringWriter.ToString()); }
IEnumerable<(string itemType, string fileName)> WriteAssemblyInfo(DecompilerTypeSystem ts, CancellationToken cancellationToken) { var decompiler = CreateDecompiler(ts); decompiler.CancellationToken = cancellationToken; decompiler.AstTransforms.Add(new RemoveCompilerGeneratedAssemblyAttributes()); SyntaxTree syntaxTree = decompiler.DecompileModuleAndAssemblyAttributes(); const string prop = "Properties"; if (directories.Add(prop)) Directory.CreateDirectory(Path.Combine(TargetDirectory, prop)); string assemblyInfo = Path.Combine(prop, "AssemblyInfo.cs"); using (StreamWriter w = new StreamWriter(Path.Combine(TargetDirectory, assemblyInfo))) { syntaxTree.AcceptVisitor(new CSharpOutputVisitor(w, Settings.CSharpFormattingOptions)); } return new[] { ("Compile", assemblyInfo) };
public static string GenerateText(TypeDeclaration type, OrderedPartCollection<AbstractDynamicCompilationExtension> extensions, HashSet<string> namespaces = null) { var unit = new SyntaxTree(); if (namespaces == null) { namespaces = new HashSet<string> { typeof (SystemTime).Namespace, typeof (AbstractViewGenerator).Namespace, typeof (Enumerable).Namespace, typeof (IEnumerable<>).Namespace, typeof (IEnumerable).Namespace, typeof (int).Namespace, typeof (LinqOnDynamic).Namespace, typeof (Field).Namespace, typeof (CultureInfo).Namespace, typeof (Regex).Namespace }; } foreach (var extension in extensions) { foreach (var ns in extension.Value.GetNamespacesToImport()) { namespaces.Add(ns); } } foreach (var ns in namespaces) { unit.Members.Add(new UsingDeclaration(ns)); } unit.Members.Add(new WindowsNewLine()); unit.Members.Add(type); var stringWriter = new StringWriter(); var output = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop()); unit.AcceptVisitor(output); return stringWriter.GetStringBuilder().ToString(); }
private void GenerateClass(object sender, EventArgs e) { windowDrawing.ClosePopups(); List <string> methods = new List <string>(); List <string> properties = new List <string>(); string name = ""; CSharpParser parserTest = new CSharpParser(); SyntaxTree tree = parserTest.Parse(CodeTextBox.Text); CSharpCodeVistor visitor = new CSharpCodeVistor(); tree.AcceptVisitor(visitor); properties = visitor.properties; CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(CodeTextBox.Text, "code.cs"); CSharpUnresolvedFile file = syntaxTree.ToTypeSystem(); foreach (IUnresolvedTypeDefinition type in file.TopLevelTypeDefinitions) { name = type.Name; foreach (IUnresolvedMethod method in type.Methods) { if (method.Accessibility == Accessibility.Public) { methods.Add("+" + method.Name + ": " + method.ReturnType); } else if (method.Accessibility == Accessibility.Private) { methods.Add("-" + method.Name + ": " + method.ReturnType); } else { methods.Add("#" + method.Name + ": " + method.ReturnType); } } } windowDrawing.DrawClass(name, properties, methods); }
//private static EcsFile GenerateFile(TypeDefinition t, CSharpDecompiler codeDomBuilder, string attributeString, OutputMode mode, string ext) //{ // var sourceRes = t.CustomAttributes.SingleOrDefault(x => x.AttributeType.Name == "Custom" + attributeString + "File"); // var sourceAtt = t.CustomAttributes.SingleOrDefault(x => x.AttributeType.Name == "Custom" + attributeString); // if (sourceRes != null) { // var sourceName = t.Name + ext; // sourceName = (string)sourceRes.ConstructorArguments[0].Value; // var sourceContent = EmbeddedFileLoader.GetResourceFile(sourceName, t.Module); // return new EcsFile(sourceName, sourceContent); // } // if (sourceAtt != null) { // var sourceContent = (string)sourceAtt.ConstructorArguments[0].Value; // return new EcsFile(t.Name + ext, sourceContent); // } // return new EcsFile(t.Name + ext, WriteType(codeDomBuilder, mode)); //} string WriteCode(DecompilerSettings settings, SyntaxTree syntaxTree, IDecompilerTypeSystem typeSystem, OutputMode mode) { //syntaxTree.AcceptVisitor(new InsertParenthesesVisitor { InsertParenthesesForReadability = true }); var ms = new MemoryStream(); using (StreamWriter w = new StreamWriter(ms)) { //codeDomBuilder.GenerateCode(new PlainTextOutput(w), mode); TokenWriter tokenWriter = new TextTokenWriter(new PlainTextOutput(w), settings, typeSystem) { FoldBraces = settings.FoldBraces, ExpandMemberDefinitions = settings.ExpandMemberDefinitions }; //syntaxTree.AcceptVisitor(new CSharpOutputVisitor(tokenWriter, settings.CSharpFormattingOptions)); syntaxTree.AcceptVisitor(new COutputVisitor(tokenWriter, settings.CSharpFormattingOptions, mode)); w.Flush(); ms.Position = 0; var sr = new StreamReader(ms); var myStr = sr.ReadToEnd(); return(myStr); } }
/// <summary> /// Instruments the supplied code to call the <see cref="Hook"/> methods. /// </summary> /// <param name="code">The code to instrument.</param> /// <param name="submissionId">The submission ID.</param> /// <returns>A task for a <see cref="string"/> representing the instrumented code.</returns> /// <seealso cref="Hook.CreateSubmission"/> public static Task <Either <string, Error> > Instrument(string code, int submissionId) { if (code == null) { throw new ArgumentNullException("code"); } return(Task <Either <string, Error> > .Factory.StartNew(s => { SyntaxTree tree = SyntaxTree.Parse((string)s); InstrumentingRewriter rewriter = new InstrumentingRewriter(submissionId); tree.AcceptVisitor(rewriter); Error error = tree.Errors.FirstOrDefault(e => e.ErrorType == ErrorType.Error); if (error != null) { return Either <string, Error> .B(error); } return Either <string, Error> .A(tree.GetText()); }, code)); }
/// <summary> /// Analyzes the formatting of a given document and syntax tree. /// </summary> /// <param name="document">Document.</param> /// <param name="syntaxTree">Syntax tree.</param> /// <param name="token">The cancellation token.</param> public FormattingChanges AnalyzeFormatting(IDocument document, SyntaxTree syntaxTree, CancellationToken token = default (CancellationToken)) { if (document == null) throw new ArgumentNullException("document"); if (syntaxTree == null) throw new ArgumentNullException("syntaxTree"); var result = new FormattingChanges(document); var visitor = new FormattingVisitor(this, document, result, token); syntaxTree.AcceptVisitor(visitor); return result; }
List<NewFolding> CreateNewFoldings(SyntaxTree syntaxTree, IDocument document) { FoldingVisitor v = new FoldingVisitor(); v.document = document; syntaxTree.AcceptVisitor(v); return v.foldings; }
public bool ProcessAndReturnTrueIfEverythingIsSupported(SyntaxTree syntaxTree) { _result = true; syntaxTree.AcceptVisitor(this); return _result; }
public static ISet<string> Gather(SyntaxTree syntaxTree, IEnumerable<string> predefinedSymbols) { var obj = new DefinedSymbolsGatherer(predefinedSymbols); syntaxTree.AcceptVisitor(obj); return obj._definedSymbols; }
public static void Roundtrip(CSharpParser parser, string fileName, string code) { // 1. Parse SyntaxTree syntaxTree = parser.Parse(code, fileName); if (parser.HasErrors) { throw new InvalidOperationException("There were parse errors."); } // 2. Output StringWriter w = new StringWriter(); syntaxTree.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateMono())); string generatedCode = w.ToString().TrimEnd(); // 3. Compare output with original (modulo whitespaces) int pos2 = 0; for (int pos1 = 0; pos1 < code.Length; pos1++) { if (!char.IsWhiteSpace(code[pos1])) { while (pos2 < generatedCode.Length && char.IsWhiteSpace(generatedCode[pos2])) { pos2++; } if (pos2 >= generatedCode.Length || code[pos1] != generatedCode[pos2]) { ReadOnlyDocument doc = new ReadOnlyDocument(code); File.WriteAllText(Path.Combine(Program.TempPath, "roundtrip-error.cs"), generatedCode); throw new InvalidOperationException("Mismatch at " + doc.GetLocation(pos1) + " of file " + fileName); } pos2++; } } if (pos2 != generatedCode.Length) { throw new InvalidOperationException("Mismatch at end of file " + fileName); } // 3b - validate that there are no lone \r if (generatedCode.Replace(w.NewLine, "\n").IndexOf('\r') >= 0) { throw new InvalidOperationException(@"Got lone \r in " + fileName); } // 4. Parse generated output SyntaxTree generatedCU; try { generatedCU = parser.Parse(generatedCode, fileName); } catch { File.WriteAllText(Path.Combine(Program.TempPath, "roundtrip-error.cs"), generatedCode, Encoding.Unicode); throw; } if (parser.HasErrors) { File.WriteAllText(Path.Combine(Program.TempPath, "roundtrip-error.cs"), generatedCode); throw new InvalidOperationException("There were parse errors in the roundtripped " + fileName); } // 5. Compare AST1 with AST2 if (!syntaxTree.IsMatch(generatedCU)) { throw new InvalidOperationException("AST match failed for " + fileName + "."); } }
public Node VisitSyntaxTree(SyntaxTree syntaxTree) { var visitor = VisitContext.VisitFactory.GetVisitor(nameof(SyntaxTree)) as ICILVisitor <SyntaxTree>; return(syntaxTree.AcceptVisitor(visitor)); }
internal static void RemoveMethodBodies(SyntaxTree syntaxTree) { syntaxTree.AcceptVisitor(new MethodBodyRemoveVisitor()); }
public override void VisitSyntaxTree(SyntaxTree syntaxTree) { syntaxTree.AcceptVisitor(Types); base.VisitSyntaxTree(syntaxTree); }
public void AcceptAstVisitor(IAstVisitor analyzer) { _syntaxTree.AcceptVisitor(analyzer); }