public static ISyntaxTree CreateSyntaxTree(Stream file, string filePath, out IReadOnlyList <ParseError> parseErrors)
        {
            var input = new AntlrInputStream(file);
            var lexer = new TypemakerLexer(input);

            var errors        = new List <ParseError>();
            var errorListener = new ReportingErrorListener(errors, lexer.Vocabulary);

            lexer.AddErrorListener(errorListener);

            var tokenStream = new CommonTokenStream(lexer);
            var parser      = new TypemakerParser(tokenStream);

            parser.AddErrorListener(errorListener);

            var compilationUnitContext = parser.compilation_unit();

            parseErrors = errors;
            if (errors.Count > 0)
            {
                return(null);
            }

            var visitor = new CompilationUnitVisitor(filePath);
            var tree    = visitor.Visit(compilationUnitContext);
            var tokens  = tokenStream.GetTokens();

            tree.Build(tokens);

            return(tree);
        }
Пример #2
0
        private CecilifierResult Run(Stream content, IList <string> references)
        {
            var syntaxTree = CSharpSyntaxTree.ParseText(new StreamReader(content).ReadToEnd(), new CSharpParseOptions(LanguageVersion.CSharp8));
            var comp       = CSharpCompilation.Create(
                "CecilifiedAssembly",
                new[] { syntaxTree },
                references.Select(refPath => MetadataReference.CreateFromFile(refPath)),
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));

            var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Select(s => s.ToString()).ToArray();

            if (errors.Length > 0)
            {
                throw new SyntaxErrorException($"Code contains compiler errors:\n\n{string.Join("\n", errors)}");
            }

            var semanticModel = comp.GetSemanticModel(syntaxTree);

            var ctx     = new CecilifierContext(semanticModel);
            var visitor = new CompilationUnitVisitor(ctx);

            syntaxTree.TryGetRoot(out var root);
            visitor.Visit(root);

            //new SyntaxTreeDump("TREE: ", root);

            return(new CecilifierResult(new StringReader(ctx.Output.AsCecilApplication()), visitor.MainType != null ? visitor.MainType.Identifier.Text : "Cecilified"));
        }