コード例 #1
0
 public override void visit(ASTVisitor prefix, ASTVisitor postfix)
 {
     prefix(this);
     expr.visit(prefix, postfix);
     List.visit(sections, prefix, postfix);
     postfix(this);
 }
コード例 #2
0
        public void ObjectChanged()
        {
            object o = model.CurrentObject;

            if (o != null && tracking != null)
            {
                Tracking.Pair span = null;
                if (o is AST)
                {
                    AST        ast   = (AST)o;
                    FindSpan   fs    = new FindSpan(tracking);
                    ASTVisitor visit = new ASTVisitor(fs.Visitor);
                    ast.visit(visit);
                    span = fs.pair;
                }
                if (span != null)
                {
                    rtb.SelectionLength = 0;
                    rtb.SelectionStart  = span.begin;
                    rtb.SelectionLength = span.end - span.begin;
                    rtb.HideSelection   = false;
                }
                else
                {
                    rtb.HideSelection = true;
                }
            }
            else
            {
                rtb.HideSelection = true;
            }
        }
コード例 #3
0
            internal static void EvaluateComplexityMetrics(ICSharpCode.OldNRefactory.Ast.INode method, MethodProperties props)
            {
                props.CyclometricComplexity = 1;
                props.LOCReal           = 0;
                props.NumberOfVariables = 0;

                cls = props.ParentClass;

                ASTVisitor ctxAstVisitor = new ASTVisitor();

                if (method is MethodDeclaration)
                {
                    foreach (var statement in ((MethodDeclaration)method).Body.Children)
                    {
                        ctxAstVisitor.VisitStatement(statement, props);
                    }
                }
                else if (method is ConstructorDeclaration)
                {
                    foreach (var statement in ((ConstructorDeclaration)method).Body.Children)
                    {
                        ctxAstVisitor.VisitStatement(statement, props);
                    }
                }
                cls.CyclometricComplexity += props.CyclometricComplexity;
            }
コード例 #4
0
 public override void visit(ASTVisitor prefix, ASTVisitor postfix)
 {
     prefix(this);
     List.visit(labels, prefix, postfix);
     List.visit(stmts, prefix, postfix);
     postfix(this);
 }
コード例 #5
0
        public void CFG()
        {
            const int COUNT  = 6;
            Parser    parser = new Parser(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data\cfg.gngr"));

            parser.parse();
            ASTVisitor  astv = new ASTVisitor(parser.ast);
            TestVisitor tv   = new TestVisitor(astv.cfg);

            // create new instance to fool compiler
            CFGEntry      entry = new CFGEntry();
            CFGBasicBlock b1    = new CFGBasicBlock();
            CFGBasicBlock b2    = new CFGBasicBlock();
            CFGBasicBlock b3    = new CFGBasicBlock();
            CFGBasicBlock b4    = new CFGBasicBlock();

            for (int i = 0; i < COUNT; i++)
            {
                switch (i)
                {
                case 0:
                    entry = (CFGEntry)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(entry, typeof(CFGEntry), $"{i}/1");
                    break;

                case 1:
                    b1 = (CFGBasicBlock)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(b1, typeof(CFGBasicBlock), $"{i}/1");
                    Assert.AreEqual(entry, b1.parents[0], $"{i}/1");
                    break;

                case 2:
                    b2 = (CFGBasicBlock)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(b2, typeof(CFGBasicBlock), $"{i}/1");
                    Assert.AreEqual(b1, b2.parents[0], $"{i}/2");
                    break;

                case 3:
                    b3 = (CFGBasicBlock)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(b3, typeof(CFGBasicBlock), $"{i}/1");
                    Assert.AreEqual(b2, b3.parents[0], $"{i}/2");
                    Assert.AreEqual(b1, b3.parents[1], $"{i}/3");
                    break;

                case 4:
                    b4 = (CFGBasicBlock)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(b4, typeof(CFGBasicBlock), $"{i}/1");
                    Assert.AreEqual(b3, b4.parents[0], $"{i}/2");
                    break;

                case 6:
                    CFGExit exit = (CFGExit)tv.visitedNodes[i];
                    Assert.IsInstanceOfType(exit, typeof(CFGExit), $"{i}/1");
                    Assert.AreEqual(b4, exit.parents[0], $"{i}/2");
                    Assert.AreEqual(b3, exit.parents[1], $"{i}/2");
                    break;
                }
            }
        }
コード例 #6
0
ファイル: GingerCFGTest.cs プロジェクト: noilly/ginger
        public void BlockSurroundedIf()
        {
            const int COUNT = 7;
            Parser parser = new Parser(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data\BlockSurroundedIf.gngr"));
            parser.parse();
            ASTVisitor astv = new ASTVisitor(parser.ast);
            TestVisitor tv = new TestVisitor(astv.cfg);

            // create new instance to fool compiler
            CFGEntry entry = new CFGEntry();
            CFGBasicBlock b1 = new CFGBasicBlock();
            CFGBasicBlock b2 = new CFGBasicBlock();
            CFGBasicBlock b3 = new CFGBasicBlock();
            CFGBasicBlock b4 = new CFGBasicBlock();
            CFGBasicBlock b5 = new CFGBasicBlock();

            for (int i = 0; i < COUNT; i++)
            {
                switch (i)
                {
                    case 0:
                        entry = (CFGEntry)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(entry, typeof(CFGEntry), $"{i}/1");
                        break;
                    case 1:
                        b1 = (CFGBasicBlock)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(b1, typeof(CFGBasicBlock), $"{i}/1");
                        Assert.AreEqual(entry, b1.parents[0], $"{i}/1");
                        break;
                    case 2:
                        b2 = (CFGBasicBlock)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(b2, typeof(CFGBasicBlock), $"{i}/1");
                        Assert.AreEqual(b1, b2.parents[0], $"{i}/2");
                        break;
                    case 3:
                        b3 = (CFGBasicBlock)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(b3, typeof(CFGBasicBlock), $"{i}/1");
                        Assert.AreEqual(b2, b3.parents[0], $"{i}/2");
                        break;
                    case 4:
                        b4 = (CFGBasicBlock)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(b4, typeof(CFGBasicBlock), $"{i}/1");
                        Assert.AreEqual(b3, b4.parents[0], $"{i}/2");
                        Assert.AreEqual(b2, b4.parents[1], $"{i}/3");
                        break;
                    case 5:
                        b5 = (CFGBasicBlock)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(b5, typeof(CFGBasicBlock), $"{i}/1");
                        Assert.AreEqual(b4, b5.parents[0], $"{i}/2");
                        Assert.AreEqual(b1, b5.parents[1], $"{i}/3");
                        break;
                    case 6:
                        CFGExit exit = (CFGExit)tv.visitedNodes[i];
                        Assert.IsInstanceOfType(exit, typeof(CFGExit), $"{i}/1");
                        Assert.AreEqual(b5, exit.parents[0], $"{i}/2");
                        break;
                }
            }
        }
コード例 #7
0
        public void Select()
        {
            FindObject fo    = new FindObject(tracking, rtb.SelectionStart, rtb.SelectionStart + rtb.SelectionLength);
            ASTVisitor visit = new ASTVisitor(fo.Visitor);

            this.ASTRoot.visit(visit);
            model.ChangeObject(fo.FoundObject);
        }
コード例 #8
0
ファイル: disambiguate.cs プロジェクト: Paul1nh0/Singularity
    static int TypeArgumentCount(expression ast)
    {
        ArgumentCounter c = new ArgumentCounter();
        ASTVisitor      v = new ASTVisitor(c.fn);

        ast.visit(v);
        return(c.Count);
    }
コード例 #9
0
ファイル: ASTRoot.cs プロジェクト: vmkc/research-environment
    public AST find(Coordinate begin, Coordinate end)
    {
        findHelper o    = new findHelper(begin, end);
        ASTVisitor dele = new ASTVisitor(o.fn);

        this.visit(dele);
        return(o.ast);
    }
コード例 #10
0
ファイル: disambiguate.cs プロジェクト: Paul1nh0/Singularity
    static expression fix_cast(expression e1, expression e2)
    {
        // the first two cases are simple optimizations for the common case.
        if (e1 is cast_expression)
        {
            if (e2 is invocation_expression)
            {
                return(e1);
            }
            return(e2);
        }
        else if (e2 is cast_expression)
        {
            if (e1 is invocation_expression)
            {
                return(e2);
            }
            return(e1);
        }
        else
        {
            //
            // This is to handle the pathological case of (a+(b)-c)
            // or worse, ((a+b)+c-(d)e)
            //
            // The code is complicated because neither parse is rooted with a cast...
            //
            CastCounter c1 = new CastCounter();
            ASTVisitor  a1 = new ASTVisitor(c1.fn);
            e1.visit(a1);

            CastCounter c2 = new CastCounter();
            ASTVisitor  a2 = new ASTVisitor(c2.fn);
            e2.visit(a2);

            if (c1.Count == c2.Count + 1)
            {
                return(e1);
            }
            else if (c1.Count == c2.Count - 1)
            {
                return(e2);
            }
            else
            {
                // fall off into error message.
            }
        }
        throw new System.Exception("failed to disambiguate expressions");
    }
コード例 #11
0
        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");
        }
コード例 #12
0
ファイル: TestUtils.cs プロジェクト: Tembocs/Soup
        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);
        }
コード例 #13
0
        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.
            }
        }
コード例 #14
0
ファイル: ASTNode.cs プロジェクト: hannuorn/Mini-PL
 public abstract void Accept(ASTVisitor visitor);
コード例 #15
0
        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);
        }
コード例 #16
0
 protected internal override void Accept(ASTVisitor visitor) => visitor.VisitAST(this);
コード例 #17
0
			internal static void EvaluateComplexityMetrics (ICSharpCode.NRefactory.Ast.INode method, MethodProperties props)
			{
				props.CyclometricComplexity = 1;
				props.LOCReal=0;
				props.NumberOfVariables=0;
				
				cls = props.ParentClass;
				
				ASTVisitor ctxAstVisitor = new ASTVisitor();
				if(method is MethodDeclaration) {
					foreach (var statement in ((MethodDeclaration)method).Body.Children) {
						ctxAstVisitor.VisitStatement(statement, props);
					}
				} else if (method is ConstructorDeclaration) {
					foreach (var statement in ((ConstructorDeclaration)method).Body.Children) {
						ctxAstVisitor.VisitStatement(statement, props);
					}
				}
				cls.CyclometricComplexity += props.CyclometricComplexity;
			}
コード例 #18
0
ファイル: ASTRoot.cs プロジェクト: vmkc/research-environment
 public virtual void visit(ASTVisitor prefix, ASTVisitor postfix)
 {
     prefix(this);
     postfix(this);
 }
コード例 #19
0
ファイル: Node.cs プロジェクト: LayeLang/Laye
 internal abstract void Visit(ASTVisitor visitor);
コード例 #20
0
        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");
        }
コード例 #21
0
ファイル: MainClass.cs プロジェクト: fmoessbauer/roslyn2famix
        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.
            }
        }
コード例 #22
0
        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);
        }
コード例 #23
0
ファイル: ASTRoot.cs プロジェクト: vmkc/research-environment
 public virtual void visit(ASTVisitor map)
 {
     visit(map, postfix);
 }
コード例 #24
0
        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);
        }
コード例 #25
0
 public override void visit(ASTVisitor prefix, ASTVisitor postfix)
 {
     prefix(this);
     typelabel.visit(prefix, postfix);
     postfix(this);
 }
コード例 #26
0
 override public void Accept(ASTVisitor visitor)
 {
     visitor.Visit(this);
 }
コード例 #27
0
ファイル: Parser.cs プロジェクト: Stu042/SimpleC
 public object Accept(ASTVisitor visitor, object options = null)
 {
     return(visitor.DoForArg(this, options));
 }
コード例 #28
0
        private static void ProcessMethod(MetricsContext ctx, ICSharpCode.OldNRefactory.Ast.INode method, IProperties parentClass)
        {
            if (method == null)
            {
                return;
            }

            StringBuilder methodName = new StringBuilder("");

            string[] PrefixArray = PrefixName.ToArray();
            for (int i = 0; i < PrefixArray.Length; i++)
            {
                methodName.Append(PrefixArray[PrefixArray.Length - i - 1] + ".");
            }
            List <string> methodParameterList = new List <string>(0);

            if (method is MethodDeclaration)
            {
                methodName.Append(((MethodDeclaration)method).Name);
                foreach (ParameterDeclarationExpression pde in ((MethodDeclaration)method).Parameters)
                {
                    string type = pde.TypeReference.Type;
                    if (type.Contains("."))
                    {
                        type = type.Substring(type.LastIndexOf(".") + 1);
                    }
                    methodParameterList.Add(type);
                }
            }
            else if (method is ConstructorDeclaration)
            {
                methodName.Append(((ConstructorDeclaration)method).Name);
                foreach (ParameterDeclarationExpression pde in ((ConstructorDeclaration)method).Parameters)
                {
                    string type = pde.TypeReference.Type;
                    if (type.Contains("."))
                    {
                        type = type.Substring(type.LastIndexOf(".") + 1);
                    }
                    methodParameterList.Add(type);
                }
            }

            StringBuilder MethodKey = new StringBuilder();

            MethodKey.Append(methodName.ToString() + " ");
            foreach (string paramName in methodParameterList)
            {
                MethodKey.Append(paramName + " ");
            }
            try{
                if (parentClass is ClassProperties)
                {
                    if (!(parentClass as ClassProperties).Methods.ContainsKey(MethodKey.ToString()))
                    {
                        if (method is MethodDeclaration)
                        {
                            (parentClass as ClassProperties).Methods.Add(MethodKey.ToString(), new MethodProperties((MethodDeclaration)method, parentClass as ClassProperties));
                        }
                        else if (method is ConstructorDeclaration)
                        {
                            (parentClass as ClassProperties).Methods.Add(MethodKey.ToString(), new MethodProperties((ConstructorDeclaration)method, parentClass as ClassProperties));
                        }
                    }
                    var currentMethodReference = (parentClass as ClassProperties).Methods[MethodKey.ToString()];
                    //Calculate all metrics here
                    ASTVisitor.EvaluateComplexityMetrics(method, currentMethodReference);
                    LOCEvaluate.EvaluateMethodLOC(currentMethodReference, FileText, FileDoc);
                    currentMethodReference.FilePath = File.FilePath;
                }
            } catch (NullReferenceException ex) {
                LoggingService.LogError("Error in '" + methodName.ToString() + "'", ex);
                Console.WriteLine(MethodKey.ToString() + " hoo");
            }
        }
コード例 #29
0
ファイル: Parser.cs プロジェクト: Stu042/SimpleC
 public object Accept(ASTVisitor visitor, object options)
 {
     return(visitor.DoForBinOp(this, options));
 }
コード例 #30
0
ファイル: NodeList.cs プロジェクト: LayeLang/Laye
 internal override void Visit(ASTVisitor visitor)
 {
     visitor.Accept(this);
 }
コード例 #31
0
        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);
        }