Beispiel #1
0
        public static void WalkSourceCode(string code, AssemblyBuilder assemblyBuilder)
        {
            var inputStream       = new AntlrInputStream(code);
            var lexer             = new DaedalusLexer(inputStream);
            var commonTokenStream = new CommonTokenStream(lexer);
            var parser            = new DaedalusParser(commonTokenStream);

            ParseTreeWalker.Default.Walk(new DaedalusListener(assemblyBuilder, 0), parser.daedalusFile());
        }
        public void RunCode(string code, string zenContent)
        {
            ZenLoader zenLoader = new ZenLoader();

            if (zenLoader.Load(zenContent) != 0)
            {
                return;
            }
            List <ZenFileNode> zenFileNodes = zenLoader.ZenFileNodes;

            List <IParseTree>        parseTrees             = new List <IParseTree>();
            List <string>            filesPaths             = new List <string>();
            List <string[]>          filesContentsLines     = new List <string[]>();
            List <HashSet <string> > suppressedWarningCodes = new List <HashSet <string> >();

            _syntaxErrorsCount   = 0;
            _syntaxErrorsPerFile = new List <List <SyntaxError> >();

            if (code != "")
            {
                DaedalusParser      parser = Compiler.GetParserForText(code);
                SyntaxErrorListener syntaxErrorListener = new SyntaxErrorListener();
                parser.AddErrorListener(syntaxErrorListener);
                parseTrees.Add(parser.daedalusFile());
                _syntaxErrorsCount += syntaxErrorListener.SyntaxErrors.Count;
                _syntaxErrorsPerFile.Add(syntaxErrorListener.SyntaxErrors);

                string[] fileContentLines = code.Split(Environment.NewLine);
                filesPaths.Add("test.d");
                filesContentsLines.Add(fileContentLines);
                suppressedWarningCodes.Add(SemanticErrorsCollectingVisitor.GetWarningCodesToSuppress(fileContentLines[0]));
            }


            if (_syntaxErrorsCount > 0)
            {
                for (int i = 0; i < _syntaxErrorsPerFile.Count; ++i)
                {
                    List <SyntaxError> syntaxErrors = _syntaxErrorsPerFile[i];
                    if (syntaxErrors.Count > 0)
                    {
                        string filePath = filesPaths[i];
                        string fileName = Path.GetFileName(filePath);
                        _errorLogger.LogLine(filePath);
                        foreach (SyntaxError syntaxError in syntaxErrors)
                        {
                            string line = filesContentsLines[i][syntaxError.LineNo - 1];
                            syntaxError.Print(fileName, line, _errorLogger);
                        }
                    }
                }

                _errorLogger.LogLine($"{_syntaxErrorsCount} syntax {(_syntaxErrorsCount == 1 ? "error" : "errors")} generated.");
                return;
            }

            SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer(
                zenFileNodes,
                parseTrees,
                filesPaths,
                filesContentsLines,
                suppressedWarningCodes
                );

            semanticAnalyzer.Run();
            SymbolTable = semanticAnalyzer.SymbolTable;

            SemanticErrorsCollectingVisitor semanticErrorsCollectingVisitor = new SemanticErrorsCollectingVisitor(_errorLogger, _strictSyntax, _globallySuppressedCodes);

            semanticErrorsCollectingVisitor.FilePathDisplayStatus = FilePathDisplayStatus.NeverDisplay;
            semanticErrorsCollectingVisitor.VisitTree(semanticAnalyzer.AbstractSyntaxTree);

            int    errorsCount   = semanticErrorsCollectingVisitor.ErrorsCount;
            int    warningsCount = semanticErrorsCollectingVisitor.WarningsCount;
            string error         = errorsCount == 1 ? "error" : "errors";
            string warning       = warningsCount == 1 ? "warning" : "warnings";

            if (errorsCount > 0)
            {
                if (warningsCount > 0)
                {
                    _errorLogger.LogLine($"{errorsCount} {error}, {warningsCount} {warning} generated.");
                }
                else
                {
                    _errorLogger.LogLine($"{errorsCount} {error} generated.");
                }
                return;
            }

            if (warningsCount > 0)
            {
                _errorLogger.LogLine($"{warningsCount} {warning} generated.");
            }


            SymbolUpdatingVisitor symbolUpdatingVisitor = new SymbolUpdatingVisitor();

            symbolUpdatingVisitor.VisitTree(semanticAnalyzer.AbstractSyntaxTree);

            AssemblyBuildingVisitor assemblyBuildingVisitor = new AssemblyBuildingVisitor(semanticAnalyzer.SymbolTable);

            assemblyBuildingVisitor.VisitTree(semanticAnalyzer.AbstractSyntaxTree);
        }
Beispiel #3
0
        public bool CompileFromSrc(
            string srcFilePath,
            bool compileToAssembly,
            bool verbose             = true,
            bool generateOutputUnits = true
            )
        {
            var absoluteSrcFilePath = Path.GetFullPath(srcFilePath);

            try
            {
                string[] paths       = SrcFileHelper.LoadScriptsFilePaths(absoluteSrcFilePath).ToArray();
                string   srcFileName = Path.GetFileNameWithoutExtension(absoluteSrcFilePath).ToLower();

                string runtimePath = Path.Combine(GetBuiltinsPath(), srcFileName + ".d");
                if (File.Exists(runtimePath))
                {
                    _assemblyBuilder.IsCurrentlyParsingExternals = true;
                    if (verbose)
                    {
                        Console.WriteLine($"[0/{paths.Length}]Compiling runtime: {runtimePath}");
                    }
                    DaedalusParser parser = GetParserForScriptsFile(runtimePath);
                    ParseTreeWalker.Default.Walk(new DaedalusListener(_assemblyBuilder, 0), parser.daedalusFile());
                    _assemblyBuilder.IsCurrentlyParsingExternals = false;
                }

                for (int i = 0; i < paths.Length; i++)
                {
                    if (verbose)
                    {
                        Console.WriteLine($"[{i + 1}/{paths.Length}]Compiling: {paths[i]}");
                    }

                    string         fileContent = GetFileContent(paths[i]);
                    DaedalusParser parser      = GetParserForText(fileContent);

                    _assemblyBuilder.ErrorContext.FileContentLines = fileContent.Split(Environment.NewLine);
                    _assemblyBuilder.ErrorContext.FilePath         = paths[i];
                    _assemblyBuilder.ErrorContext.FileIndex        = i;
                    ParseTreeWalker.Default.Walk(new DaedalusListener(_assemblyBuilder, i), parser.daedalusFile());
                    if (generateOutputUnits)
                    {
                        _ouBuilder.ParseText(fileContent);
                    }
                }

                if (!compileToAssembly)
                {
                    Directory.CreateDirectory(_outputDirPath);
                }

                if (generateOutputUnits)
                {
                    _ouBuilder.SaveOutputUnits(_outputDirPath);
                }

                _assemblyBuilder.Finish();
                if (_assemblyBuilder.Errors.Any())
                {
                    _assemblyBuilder.Errors.Sort((x, y) => x.CompareTo(y));

                    string lastErrorFilePath  = "";
                    string lastErrorBlockName = null;
                    var    logger             = new StdErrorLogger();
                    foreach (CompilationMessage error in _assemblyBuilder.Errors)
                    {
                        if (lastErrorFilePath != error.FilePath)
                        {
                            lastErrorFilePath = error.FilePath;
                            Console.WriteLine(error.FilePath);
                        }

                        if (lastErrorBlockName != error.ExecBlockName)
                        {
                            lastErrorBlockName = error.ExecBlockName;
                            if (error.ExecBlockName == null)
                            {
                                Console.WriteLine($"{error.FileName}: In global scope:");
                            }
                            else
                            {
                                Console.WriteLine($"{error.FileName}: In {error.ExecBlockType} ‘{error.ExecBlockName}’:");
                            }
                        }

                        error.Print(logger);
                    }
                    return(false);
                }

                if (compileToAssembly)
                {
                    Console.WriteLine(_assemblyBuilder.GetAssembler());
                }
                else
                {
                    Directory.CreateDirectory(_outputDirPath);
                    string datPath = Path.Combine(_outputDirPath, srcFileName + ".dat");
                    _assemblyBuilder.SaveToDat(datPath);
                }

                return(true);
            }
            catch (Exception exc)
            {
                Console.WriteLine("SRC compilation failed");
                Console.WriteLine($"{exc}");
                return(false);
            }
        }
        public ParseResult Parse()
        {
            ZenLoader zenLoader = new ZenLoader(_zenPaths, _verbose);

            if (zenLoader.Load() != 0)
            {
                return(null);
            }

            List <IParseTree>        parseTrees             = new List <IParseTree>();
            List <string>            filesPaths             = new List <string>();
            List <string[]>          filesContentsLines     = new List <string[]>();
            List <string>            filesContents          = new List <string>();
            List <HashSet <string> > suppressedWarningCodes = new List <HashSet <string> >();

            int syntaxErrorsCount = 0;
            List <List <SyntaxError> > syntaxErrorsPerFile = new List <List <SyntaxError> >();

            int runtimeIndex = -1;

            if (File.Exists(_runtimePath))
            {
                runtimeIndex = 0;
            }

            for (int i = 0; i < _scriptPaths.Count; i++)
            {
                if (_verbose)
                {
                    Console.WriteLine($"[{i + 1}/{_scriptPaths.Count}]Parsing{(runtimeIndex==i ? " runtime":"")}: {_scriptPaths[i]}");
                }

                string         fileContent = GetFileContent(_scriptPaths[i]);
                DaedalusParser parser      = GetParserForText(fileContent);

                SyntaxErrorListener syntaxErrorListener = new SyntaxErrorListener();
                parser.RemoveErrorListeners();
                parser.AddErrorListener(syntaxErrorListener);
                parseTrees.Add(parser.daedalusFile());
                syntaxErrorsCount += syntaxErrorListener.SyntaxErrors.Count;
                syntaxErrorsPerFile.Add(syntaxErrorListener.SyntaxErrors);

                string[] fileContentLines = fileContent.Split(Environment.NewLine);
                filesPaths.Add(_scriptPaths[i]);
                filesContentsLines.Add(fileContentLines);
                filesContents.Add(fileContent);

                suppressedWarningCodes.Add(
                    SemanticErrorsCollectingVisitor.GetWarningCodesToSuppress(fileContentLines[0]));
            }

            if (syntaxErrorsCount > 0)
            {
                for (int i = 0; i < syntaxErrorsPerFile.Count; ++i)
                {
                    List <SyntaxError> syntaxErrors = syntaxErrorsPerFile[i];
                    if (syntaxErrors.Count > 0)
                    {
                        string filePath = filesPaths[i];
                        string fileName = Path.GetFileName(filePath);
                        _errorLogger.LogLine(filePath);
                        foreach (SyntaxError syntaxError in syntaxErrors)
                        {
                            string line = filesContentsLines[i][syntaxError.LineNo - 1];
                            syntaxError.Print(fileName, line, _errorLogger);
                        }
                    }
                }

                _errorLogger.LogLine(
                    $"{syntaxErrorsCount} syntax {(syntaxErrorsCount == 1 ? "error" : "errors")} generated.");
                return(null);
            }

            return(new ParseResult
            {
                ZenFileNodes = zenLoader.ZenFileNodes,
                ParseTrees = parseTrees,
                FilesPaths = filesPaths,
                FilesContentsLines = filesContentsLines,
                FilesContents = filesContents,
                SuppressedWarningCodes = suppressedWarningCodes
            });
        }