public void LoadSampleSystem() { string path = Assembly.GetAssembly(typeof(SampleSystemLoader)).Location; path = path.Replace("FamixTest.dll", ""); string solutionPath = path + "../../../SampleCode/SampleCode.sln"; importer = new RoslynMonoFamix.InCSharp.InCSharpImporter(metamodel, Path.GetDirectoryName(new Uri(solutionPath).AbsolutePath)); var msWorkspace = MSBuildWorkspace.Create(); msWorkspace.WorkspaceFailed += (o, e) => { System.Console.WriteLine(e.Diagnostic.Message); }; var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result; Boolean fileWasFound = false; foreach (var project in solution.Projects) { foreach (var document in project.Documents) { var targetFile = this.GetType().Name.Replace("Test", ".cs"); targetFile.Replace("2.cs", "1.cs"); if (document.SupportsSyntaxTree && document.FilePath.Replace("2.cs", "1.cs").EndsWith(targetFile)) { var syntaxTree = document.GetSyntaxTreeAsync().Result; var compilationAsync = project.GetCompilationAsync().Result; var semanticModel = compilationAsync.GetSemanticModel(syntaxTree); var visitor = new ASTVisitor(semanticModel, importer); visitor.Visit(syntaxTree.GetRoot()); fileWasFound = true; } } } if (!fileWasFound) { throw new Exception("File was not found!"); } metamodel.ExportMSEFile("SampleCode.mse"); }
public static TranslationUnit GenerateAST(AntlrInputStream inputStream) { // Parse the file var lexer = new CppLexer(inputStream); var tokenStream = new CommonTokenStream(lexer); var parser = new CppParser(tokenStream); // var tokens = lexer.GetAllTokens().Select(token => lexer.Vocabulary.GetSymbolicName(token.Type)).ToList(); // Setup error handling lexer.RemoveErrorListeners(); lexer.AddErrorListener(new LexerExceptionErrorListener()); parser.RemoveErrorListeners(); parser.AddErrorListener(new ParserExceptionErrorListener()); // Parse the concrete syntax tree var translationUnit = parser.translationUnit(); // Convert the the abstract syntax tree var visitor = new ASTVisitor(); var ast = (TranslationUnit)visitor.Visit(translationUnit); return(ast); }
public int Compile(List <ClassDefinition> classDefinitions) { if (programAsset.sourceCsScript == null) { throw new System.ArgumentException($"Asset '{AssetDatabase.GetAssetPath(programAsset)}' does not have a valid program source to compile from"); } Profiler.BeginSample("Compile Module"); programAsset.compileErrors.Clear(); sourceCode = File.ReadAllText(AssetDatabase.GetAssetPath(programAsset.sourceCsScript)); Profiler.BeginSample("Parse AST"); SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); Profiler.EndSample(); int errorCount = 0; string errorString = ""; foreach (Diagnostic diagnostic in tree.GetDiagnostics()) { if (diagnostic.Severity == DiagnosticSeverity.Error) { errorCount++; LinePosition linePosition = diagnostic.Location.GetLineSpan().StartLinePosition; errorString = UdonSharpUtils.LogBuildError($"error {diagnostic.Descriptor.Id}: {diagnostic.GetMessage()}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), linePosition.Line, linePosition.Character); programAsset.compileErrors.Add(errorString); } } if (errorCount > 0) { ErrorCount = errorCount; Profiler.EndSample(); return(errorCount); } Profiler.BeginSample("Visit"); UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers); fieldVisitor.Visit(tree.GetRoot()); MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels); methodVisitor.Visit(tree.GetRoot()); UdonSharpSettings settings = UdonSharpSettings.GetSettings(); ClassDebugInfo debugInfo = null; if (settings == null || settings.buildDebugInfo) { debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode); } ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo); try { visitor.Visit(tree.GetRoot()); visitor.VerifyIntegrity(); } catch (System.Exception e) { SyntaxNode currentNode = visitor.visitorContext.currentNode; string logMessage = ""; if (currentNode != null) { FileLinePositionSpan lineSpan = currentNode.GetLocation().GetLineSpan(); logMessage = UdonSharpUtils.LogBuildError($"{e.GetType()}: {e.Message}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), lineSpan.StartLinePosition.Line, lineSpan.StartLinePosition.Character); } else { logMessage = e.ToString(); Debug.LogException(e); } programAsset.compileErrors.Add(logMessage); errorCount++; } Profiler.EndSample(); if (errorCount == 0) { Profiler.BeginSample("Build assembly"); string dataBlock = BuildHeapDataBlock(); string codeBlock = visitor.GetCompiledUasm(); programAsset.SetUdonAssembly(dataBlock + codeBlock); Profiler.EndSample(); Profiler.BeginSample("Assemble Program"); programAsset.AssembleCsProgram((uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount())); Profiler.EndSample(); programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName(); programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions; if (debugInfo != null) { debugInfo.FinalizeDebugInfo(); } programAsset.debugInfo = debugInfo; } Profiler.EndSample(); return(errorCount); }
override public void Accept(ASTVisitor visitor) { visitor.Visit(this); }
public int Compile(List <ClassDefinition> classDefinitions) { if (programAsset.sourceCsScript == null) { throw new System.ArgumentException($"Asset '{AssetDatabase.GetAssetPath(programAsset)}' does not have a valid program source to compile from"); } sourceCode = File.ReadAllText(AssetDatabase.GetAssetPath(programAsset.sourceCsScript)); SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); int errorCount = 0; foreach (Diagnostic diagnostic in tree.GetDiagnostics()) { if (diagnostic.Severity == DiagnosticSeverity.Error) { errorCount++; LinePosition linePosition = diagnostic.Location.GetLineSpan().StartLinePosition; UdonSharpUtils.LogBuildError($"error {diagnostic.Descriptor.Id}: {diagnostic.GetMessage()}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), linePosition.Line, linePosition.Character); } if (errorCount > 0) { return(errorCount); } } UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers); fieldVisitor.Visit(tree.GetRoot()); MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels); methodVisitor.Visit(tree.GetRoot()); ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions); try { visitor.Visit(tree.GetRoot()); visitor.VerifyIntegrity(); } catch (System.Exception e) { SyntaxNode currentNode = visitor.visitorContext.currentNode; if (currentNode != null) { FileLinePositionSpan lineSpan = currentNode.GetLocation().GetLineSpan(); UdonSharpUtils.LogBuildError($"{e.GetType()}: {e.Message}", AssetDatabase.GetAssetPath(programAsset.sourceCsScript).Replace("/", "\\"), lineSpan.StartLinePosition.Line, lineSpan.StartLinePosition.Character); } else { Debug.LogException(e); } errorCount++; } string dataBlock = BuildHeapDataBlock(); string codeBlock = visitor.GetCompiledUasm(); programAsset.SetUdonAssembly(dataBlock + codeBlock); programAsset.AssembleCsProgram(); programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions; return(errorCount); }
private static void ExportToMSE(string input, string output) { try { string path = Assembly.GetAssembly(typeof(MainClass)).Location; Console.WriteLine("Current executable location " + path); path = path.Replace("RoslynMonoFamix.exe", ""); var metamodel = FamixModel.Metamodel(); var msWorkspace = MSBuildWorkspace.Create(); var solution = msWorkspace.OpenSolutionAsync(input).Result; Uri uri = null; try { uri = new Uri(input);; } catch (UriFormatException e) { var currentFolder = new Uri(Environment.CurrentDirectory + "\\"); uri = new Uri(currentFolder, input.Replace("\\", "/")); Console.WriteLine(e.StackTrace); } var ignoreFolder = Path.GetDirectoryName(uri.AbsolutePath); var importer = new InCSharp.InCSharpImporter(metamodel, ignoreFolder); var documents = new List <Document>(); Console.WriteLine("Solution with id " + solution.Id.Id + " opened and contains " + solution.Projects.Count <Project>() + " projects."); var diagnostics = msWorkspace.Diagnostics; foreach (var diagnostic in diagnostics) { Console.WriteLine(diagnostic.Message); } for (int i = 0; i < solution.Projects.Count <Project>(); i++) { var project = solution.Projects.ElementAt <Project>(i); System.Console.WriteLine("(project " + (i + 1) + " / " + solution.Projects.Count <Project>() + ") contains " + project.Documents.Count <Document>() + " documents."); var projectCompilation = project.GetCompilationAsync().Result; for (int j = 0; j < project.Documents.Count <Document>(); j++) { var document = project.Documents.ElementAt <Document>(j); if (document.SupportsSyntaxTree) { System.Console.Write("(project " + (i + 1) + " / " + solution.Projects.Count <Project>() + ")"); System.Console.WriteLine("(document " + (j + 1) + " / " + project.Documents.Count <Document>() + " " + document.FilePath + ")"); var syntaxTree = document.GetSyntaxTreeAsync().Result; var compilationAsync = project.GetCompilationAsync().Result; var semanticModel = compilationAsync.GetSemanticModel(syntaxTree); semanticModel.ToString(); if (semanticModel.Language == "C#") { var visitor = new ASTVisitor(semanticModel, importer); visitor.Visit(syntaxTree.GetRoot()); } else { var visitor = new VBASTVisitor(semanticModel, importer); visitor.Visit(syntaxTree.GetRoot()); } } } } metamodel.ExportMSEFile(output); } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (System.Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); FileNotFoundException exFileNotFound = exSub as FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); Console.WriteLine(errorMessage); //Display or log the error based on your application. } }
public CompileTaskResult Compile(List <ClassDefinition> classDefinitions, Microsoft.CodeAnalysis.SyntaxTree syntaxTree, string sourceCode, bool isEditorBuild) { programAsset.compileErrors.Clear(); CompileTaskResult result = new CompileTaskResult(); result.programAsset = programAsset; moduleSymbols.OpenSymbolTable(); UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers); fieldVisitor.Visit(syntaxTree.GetRoot()); MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels); int errorCount = 0; try { methodVisitor.Visit(syntaxTree.GetRoot()); } catch (System.Exception e) { LogException(result, e, methodVisitor.visitorContext.currentNode, out string logMessage); programAsset.compileErrors.Add(logMessage); errorCount++; } if (ErrorCount > 0) { return(result); } ClassDebugInfo debugInfo = null; if (settings == null || settings.buildDebugInfo) { debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode); } ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo); try { visitor.Visit(syntaxTree.GetRoot()); visitor.VerifyIntegrity(); } catch (System.Exception e) { LogException(result, e, visitor.visitorContext.currentNode, out string logMessage); programAsset.compileErrors.Add(logMessage); errorCount++; } if (errorCount > 0) { return(result); } moduleSymbols.CloseSymbolTable(); if (errorCount == 0) { compiledClassDefinition = classDefinitions.Find(e => e.userClassType == visitor.visitorContext.behaviourUserType); string dataBlock = BuildHeapDataBlock(); string codeBlock = visitor.GetCompiledUasm(); result.compiledAssembly = dataBlock + codeBlock; result.symbolCount = (uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount()); programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName(); programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions; #if UDON_BETA_SDK programAsset.behaviourSyncMode = visitor.visitorContext.behaviourSyncMode; #endif if (debugInfo != null) { debugInfo.FinalizeDebugInfo(); } UdonSharpEditorCache.Instance.SetDebugInfo(programAsset, isEditorBuild ? UdonSharpEditorCache.DebugInfoType.Editor : UdonSharpEditorCache.DebugInfoType.Client, debugInfo); //programAsset.debugInfo = debugInfo; } return(result); }
public CompileTaskResult Compile(List <ClassDefinition> classDefinitions) { programAsset.compileErrors.Clear(); SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode); CompileTaskResult result = new CompileTaskResult(); result.programAsset = programAsset; int errorCount = 0; foreach (Diagnostic diagnostic in tree.GetDiagnostics()) { if (diagnostic.Severity == DiagnosticSeverity.Error) { errorCount++; LinePosition linePosition = diagnostic.Location.GetLineSpan().StartLinePosition; CompileError error = new CompileError(); error.script = programAsset.sourceCsScript; error.errorStr = $"error {diagnostic.Descriptor.Id}: {diagnostic.GetMessage()}"; error.lineIdx = linePosition.Line; error.charIdx = linePosition.Character; result.compileErrors.Add(error); } } if (errorCount > 0) { return(result); } moduleSymbols.OpenSymbolTable(); UdonSharpFieldVisitor fieldVisitor = new UdonSharpFieldVisitor(fieldsWithInitializers); fieldVisitor.Visit(tree.GetRoot()); MethodVisitor methodVisitor = new MethodVisitor(resolver, moduleSymbols, moduleLabels); methodVisitor.Visit(tree.GetRoot()); ClassDebugInfo debugInfo = null; if (settings == null || settings.buildDebugInfo) { debugInfo = new ClassDebugInfo(sourceCode, settings == null || settings.includeInlineCode); } ASTVisitor visitor = new ASTVisitor(resolver, moduleSymbols, moduleLabels, methodVisitor.definedMethods, classDefinitions, debugInfo); try { visitor.Visit(tree.GetRoot()); visitor.VerifyIntegrity(); } catch (System.Exception e) { SyntaxNode currentNode = visitor.visitorContext.currentNode; string logMessage = ""; if (currentNode != null) { FileLinePositionSpan lineSpan = currentNode.GetLocation().GetLineSpan(); CompileError error = new CompileError(); error.script = programAsset.sourceCsScript; error.errorStr = $"{e.GetType()}: {e.Message}"; error.lineIdx = lineSpan.StartLinePosition.Line; error.charIdx = lineSpan.StartLinePosition.Character; result.compileErrors.Add(error); } else { logMessage = e.ToString(); Debug.LogException(e); } #if UDONSHARP_DEBUG Debug.LogException(e); Debug.LogError(e.StackTrace); #endif programAsset.compileErrors.Add(logMessage); errorCount++; } if (errorCount > 0) { return(result); } moduleSymbols.CloseSymbolTable(); if (errorCount == 0) { compiledClassDefinition = classDefinitions.Find(e => e.userClassType == visitor.visitorContext.behaviourUserType); string dataBlock = BuildHeapDataBlock(); string codeBlock = visitor.GetCompiledUasm(); result.compiledAssembly = dataBlock + codeBlock; result.symbolCount = (uint)(moduleSymbols.GetAllUniqueChildSymbols().Count + visitor.GetExternStrCount()); programAsset.behaviourIDHeapVarName = visitor.GetIDHeapVarName(); programAsset.fieldDefinitions = visitor.visitorContext.localFieldDefinitions; if (debugInfo != null) { debugInfo.FinalizeDebugInfo(); } programAsset.debugInfo = debugInfo; } return(result); }
static void Main(string[] args) { try { //The code that causes the error goes here. ValidateArgs(args);//validates arguments string path = Assembly.GetAssembly(typeof(MainClass)).Location; Console.WriteLine("Current executable location" + path); path = path.Replace("RoslynMonoFamix.exe", ""); string solutionPath = args[0]; var metamodel = FamixModel.Metamodel(); var msWorkspace = MSBuildWorkspace.Create(); var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result; Uri uri = null; try { uri = new Uri(solutionPath);; } catch (UriFormatException e) { var currentFolder = new Uri(Environment.CurrentDirectory + "\\"); uri = new Uri(currentFolder, solutionPath.Replace("\\", "/")); Console.WriteLine(e.StackTrace); } var ignoreFolder = Path.GetDirectoryName(uri.AbsolutePath); var importer = new InCSharp.InCSharpImporter(metamodel, ignoreFolder); var documents = new List <Document>(); for (int i = 0; i < solution.Projects.Count <Project>(); i++) { var project = solution.Projects.ElementAt <Project>(i); for (int j = 0; j < project.Documents.Count <Document>(); j++) { var document = project.Documents.ElementAt <Document>(j); if (document.SupportsSyntaxTree) { System.Console.Write("(project " + (i + 1) + " / " + solution.Projects.Count <Project>() + ")"); System.Console.WriteLine("(document " + (j + 1) + " / " + project.Documents.Count <Document>() + " " + document.FilePath + ")"); var syntaxTree = document.GetSyntaxTreeAsync().Result; var compilationAsync = project.GetCompilationAsync().Result; var semanticModel = compilationAsync.GetSemanticModel(syntaxTree); var visitor = new ASTVisitor(semanticModel, importer); visitor.Visit(syntaxTree.GetRoot()); } } } metamodel.ExportMSEFile(args[1]); } catch (ReflectionTypeLoadException ex) { StringBuilder sb = new StringBuilder(); foreach (System.Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); FileNotFoundException exFileNotFound = exSub as FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); Console.WriteLine(errorMessage); //Display or log the error based on your application. } }
public void LoadSampleSystem() { string path = Assembly.GetAssembly(typeof(SampleSystemLoader)).Location; path = path.Replace("FamixTest.dll", ""); string solutionPath = path + "../../../SampleCode/SampleCode.sln"; importer = new Roslyn2Famix.InCSharp.InCSharpImporter(metamodel, Path.GetDirectoryName(new Uri(solutionPath).AbsolutePath)); var msWorkspace = MSBuildWorkspace.Create(); msWorkspace.WorkspaceFailed += (o, e) => { System.Console.WriteLine(e.Diagnostic.Message); }; var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result; var diagnostics = msWorkspace.Diagnostics; foreach (var diagnostic in diagnostics) { Console.WriteLine(diagnostic.Message); } Boolean fileWasFound = false; foreach (var project in solution.Projects) { foreach (var document in project.Documents) { var targetFile = this.GetType().Name.Replace("Test", ".cs"); targetFile = targetFile.Replace("VB.cs", ".vb"); targetFile.Replace("2.cs", "1.cs"); targetFile.Replace("2.vb", "1.vb"); if (document.SupportsSyntaxTree && (document.FilePath.Replace("2.cs", "1.cs").EndsWith(targetFile) || document.FilePath.Replace("2.vb", "1.vb").EndsWith(targetFile))) { var syntaxTree = document.GetSyntaxTreeAsync().Result; System.Console.WriteLine(syntaxTree.ToString()); var compilationAsync = project.GetCompilationAsync().Result; var semanticModel = compilationAsync.GetSemanticModel(syntaxTree); var syntax = syntaxTree.GetRoot().NormalizeWhitespace().ToFullString(); if (document.FilePath.EndsWith(".vb")) { var visitor = new VBASTVisitor(semanticModel, importer); var printer = new VBPrettyPrinter(); visitor.Visit(syntaxTree.GetRoot()); printer.Visit(syntaxTree.GetRoot()); Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // WriteAllText creates a file, writes the specified string to the file, // and then closes the file. You do NOT need to call Flush() or Close(). System.IO.File.WriteAllText(@targetFile + ".txt", printer.PrettyText); System.Console.WriteLine(printer.PrettyText); } else { var visitor = new ASTVisitor(semanticModel, importer); visitor.Visit(syntaxTree.GetRoot()); } fileWasFound = true; } } } if (!fileWasFound) { throw new Exception("File was not found!"); } metamodel.ExportMSEFile("SampleCode.mse"); }