public static void Main(string[] args)
        {
            //construct a simple binary tree using treenodes
            TreeNode Node1 = new TreeNode(3);
            TreeNode Node2 = new TreeNode(9);
            TreeNode Node3 = new TreeNode(20);
            TreeNode Node4 = new TreeNode(15);
            TreeNode Node5 = new TreeNode(17);
            TreeNode Node6 = new TreeNode(11);
            TreeNode Node7 = new TreeNode(13);
            TreeNode Node8 = new TreeNode(71);

            Node1.Left  = Node2;
            Node1.Right = Node3;
            Node3.Left  = Node4;
            Node3.Right = Node5;
            Node4.Left  = Node6;
            Node4.Right = Node7;
            Node5.Left  = Node8;


            TreePrinter printer = new TreePrinter();

            printer.PrintLevel(Node1);
            printer.newPrintLevel(Node1);
        }
Ejemplo n.º 2
0
        public void CodeBytesTest() //no assert!
        {
            Stream       ins    = File.OpenRead(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Ins\simple4.in");
            BinaryReader reader = new BinaryReader(ins);

            HuffmanReader HuffReader = new HuffmanReader(reader);
            bool          NotEmpty   = HuffReader.ReadFileUsingBuffer();
            //Build Huffman tree
            TreeBuilder Builder = new TreeBuilder(HuffReader.ProvideSymbolsWihtWeights());
            Node        Root    = Builder.BuildHuffTree();

            TreePrinter.PrintNiceTree(Root, 0);

            Stack <byte> path = new Stack <byte>();

            HuffCompresor.CodeBytes(Root, path);

            for (int i = 0; i < HuffCompresor.Codes.Length; i++)
            {
                if (HuffCompresor.Codes[i] != null)
                {
                    Console.Write($"{i}: ");
                    for (int j = 0; j < HuffCompresor.Codes[i].Length; j++)
                    {
                        Console.Write($"{HuffCompresor.Codes[i][j]} ");
                    }
                    Console.WriteLine();
                }
            }
        }
Ejemplo n.º 3
0
        public void ReadTreeAndHeaderTest()
        {
            string inputFile = @"TestFiles\Huff3Tests\simple4.in.huff";

            string[] arg = new string[1];
            arg[0] = inputFile;
            Program.Huff3OpenFiles(arg, out BinaryReader reader, out BinaryWriter writer);
            Huff3TreeBuilder b = new Huff3TreeBuilder();

            bool success = b.ReadHeaderAndTreeFromBinaryFile(reader);

            Assert.IsNotNull(b.Root);
            TreePrinter.PrintNiceTree(b.Root, 0);
            reader.Close();
            writer.Close();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Performs the compilation process
        /// </summary>
        public void Compile()
        {
            // Tokenize
            Write("Tokenising...");
            List <Token> tokens = Tokenizer.GetAllTokens();

            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");

            //WriteLine(string.Join("\n", tokens));

            // Parse
            Write("Parsing...");
            ProgramNode tree = Parser.Parse(tokens);

            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done.");

            //Display the Abstract Syntax Tree
            WriteLine(TreePrinter.ToString(tree));

            //Identify
            Write("Identifying...");
            Identifier.PerformIdentification(tree);
            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");

            //Type check
            Write("Type Checking...");
            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");

            WriteLine(TreePrinter.ToString(tree));
        }
Ejemplo n.º 5
0
        public void PrintNiceTreeTest()
        {
            ulong[] Test = new ulong[256];
            Test[97]  = 6;
            Test[98]  = 2;
            Test[32]  = 5;
            Test[99]  = 5;
            Test[100] = 1;
            Test[101] = 2;
            Test[102] = 2;
            Test[52]  = 2;
            TreeBuilder builder = new TreeBuilder(Test);

            Node Root = builder.BuildHuffTree();

            TreePrinter.PrintNiceTree(Root, 0);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Performs the compilation process
        /// </summary>
        public void Compile()
        {
            // Tokenize
            Write("Tokenising...");
            List <Token> tokens = Tokenizer.GetAllTokens();

            // changed this to spit out wats up rather than just killing the process
            //if (Reporter.TokenizerHasErrors) return;
            WriteLine("Done");

            // Parse
            Write("Parsing...");
            ProgramNode tree = Parser.Parse(tokens);

            // by returning it here it kills the process
            //if (Reporter.ParserHasErrors) return;
            WriteLine("Done");

            // Identify
            Write("Identifying...");
            Identifier.PerformIdentification(tree);
            //if (Reporter.ParserHasErrors) return;
            WriteLine("Done");

            // Type check
            Write("Type Checking...");
            Checker.PerformTypeChecking(tree);
            //if (Reporter.CheckingHasErrors) return;
            WriteLine("Done");

            WriteLine(TreePrinter.ToString(tree));
            // Code generation
            Write("Generating code...");
            TargetCode targetCode = Generator.GenerateCodeFor(tree);

            //if (Reporter.HasErrors) return;
            WriteLine("Done");

            // Output
            Write("Writing to file...");
            Writer.WriteToFiles(targetCode);
            //if (Reporter.HasErrors) return;
            WriteLine("Done");
        }
Ejemplo n.º 7
0
        public void ReadTreeTest()
        {
            string inputFile = @"TestFiles\Huff3Tests\simple4.in.huff";

            string[] arg = new string[1];
            arg[0] = inputFile;
            Program.Huff3OpenFiles(arg, out BinaryReader reader, out BinaryWriter writer);
            reader.ReadUInt64(); //skip header
            Huff3TreeBuilder b = new Huff3TreeBuilder();

            bool f = false;
            Node n = b.ReadTreeFromBinaryFile(reader, ref f);

            Assert.IsNotNull(n);
            TreePrinter.PrintNiceTree(n, 0);
            Console.WriteLine(b.NumberOfSymbols);
            reader.Close();
            writer.Close();
        }
Ejemplo n.º 8
0
        public void PrintCompresedTreeTest()
        {
            ulong[] Test = new ulong[256];
            Test[97]  = 6;
            Test[98]  = 2;
            Test[32]  = 5;
            Test[99]  = 5;
            Test[100] = 1;
            Test[101] = 2;
            Test[102] = 2;
            Test[52]  = 2;
            TreeBuilder builder = new TreeBuilder(Test);

            Node         Root = builder.BuildHuffTree();
            StreamWriter sw   = new StreamWriter(@"TestFiles\myCompresTree.txt");

            TreePrinter.PrintCompresedTree(Root, sw);
            //sw.Flush();
        }
Ejemplo n.º 9
0
        private static void InvokeID3Algorithm(IDomainTree data)
        {
            var me = ID3Algorithm.CreateIt(data);

            long startTime = DateTime.Now.Ticks;

            me.BuildDecisionTree();

            long endTime   = DateTime.Now.Ticks;
            long totalTime = (endTime - startTime) / 1000;

            TreePrinter.PrintTree(me.DomainTree);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine();
            Console.WriteLine("Generating tree: {0} ms", totalTime);
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.White;
        }
Ejemplo n.º 10
0
        private static void BuildTree(Stack <List <HufmannLetter> > letters)
        {
            HuffmanTree tree = new HuffmanTree();

            tree.Insert(letters.Peek()[2], 0, null);  //ROOT
            while (letters.Count != 0)
            {
                HufmannLetter parent = letters.Peek()[2];  //2A and 3D 's parent is 5AD

                for (int i = letters.Peek().Count - 2; i >= 0; i--)
                {
                    tree.Insert(letters.Peek()[i], i, parent); //if i =0, left child, else right child. Parent 5AD
                }
                letters.Pop();
            }

            TreePrinter btr = new TreePrinter();  //Print the tree

            btr.Print(tree.Root);
            Console.WriteLine();
        }
Ejemplo n.º 11
0
        public void PrintTreeBinaryTest()
        {
            Stream       s      = File.OpenWrite(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Outs\PrintTreeBin.out");
            BinaryWriter writer = new BinaryWriter(s);

            Stream        ins        = File.OpenRead(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Ins\simple4.in");
            BinaryReader  reader     = new BinaryReader(ins);
            HuffmanReader HuffReader = new HuffmanReader(reader);
            bool          NotEmpty   = HuffReader.ReadFileUsingBuffer();
            //Build Huffman tree
            TreeBuilder Builder = new TreeBuilder(HuffReader.ProvideSymbolsWihtWeights());
            Node        Root    = Builder.BuildHuffTree();

            TreePrinter.PrintTreeBinary(Root, writer);
            writer.Flush();
            writer.Close();
            reader.Close();
            bool same = Utils.FileDiff(@"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Ins\Tree.in", @"D:\MFF\ZS_2019\c#_repos\Huffman1\Huffman1Tests\bin\Debug\netcoreapp3.0\TestFiles\Huff2\Outs\PrintTreeBin.out");

            Assert.IsTrue(same);
        }
Ejemplo n.º 12
0
        public void JustPrintTree()
        {
            string inputFile = @"TestFiles\Huff3Tests\simple4.in";

            string[] args = new string[1];
            args[0] = inputFile;
            bool opened = Program.OpenFile(args, out BinaryReader Reader, out BinaryWriter Writer);

            if (!opened)
            {
                return;
            }
            //create HuffmanReader, that is going to count occurences of bytes in input file
            HuffmanReader HuffReader = new HuffmanReader(Reader);
            bool          NotEmpty   = HuffReader.ReadFileUsingBuffer();
            //Build Huffman tree
            TreeBuilder Builder = new TreeBuilder(HuffReader.ProvideSymbolsWihtWeights());
            Node        Root    = Builder.BuildHuffTree();

            TreePrinter.PrintNiceTree(Root, 0);
            Reader.Close();
            Writer.Close();
        }
Ejemplo n.º 13
0
 public override string ToString()
     {
     TreePrinter printer = new TreePrinter();
     printer.PrintTree(this);
     return printer.PrettyPrintedOutputString();
     }
Ejemplo n.º 14
0
    void DoMain()
        {
        try {
            NadirHelper.InitializeHelper();
            ParseProgramArguments(args);
            ProcessProgramArguments();
            //
            bool anyErrors = false;

            switch (action)
                {
            case ACTION.None:
                Usage();
                break;
            case ACTION.Test:
                {
                switch (this.test)
                    {
                case 1:     ThermodynamicsData.TestNearestNeighborCalculations(); break;
                case 2:     Verifier.TestRegEx(); break;
                    }
                }
                break;
            case ACTION.Felony:
                ProcessFelony();
                break;
            case ACTION.Parse:
                { 
                // Do the heavy lifting of parsing the files that have been specified
                //
                NadirContext context = ParseInputs();
                //
                // Set up for debugging if we need to
                //
                TreePrinter printer = new TreePrinter();
                //
                // Run the remaining phases of the parse
                // 
                if (!context.ExceptionOccurred)
                    {
                    if (this.FDumpParse) DumpTrees(printer, context);
                    //
                    ValidateAST(context);   // 2
                    //
                    if (!context.ExceptionOccurred)
                        {
                        OptimizeAST(context);                                       // 3
                        //
                        if (!context.ExceptionOccurred) DefineSymbols(context);             // 4
                        if (!context.ExceptionOccurred) AutoDefineVariables(context);       // 5
                        if (!context.ExceptionOccurred) ResolveSymbols(context);            // 6
                        if (!context.ExceptionOccurred) DefineTypes(context);               // 7
                        if (!context.ExceptionOccurred) ResolveTypes(context);              // 8
                        //
                        if (!context.ExceptionOccurred && this.FDumpTrees) DumpTrees(printer, context);
                        }
                    }
                //
                this.resultToOutput = null;

                SequenceDesigner designer = null;
                try {
                    // Run distillation and sequence design. Only worth designing
                    // if something has been distilled.
                    //
                    if (!context.ExceptionOccurred && context.ParseResults.Count > 0)
                        {
                        this.parseResult     = context.ParseResults[0].Tree;
                        this.resultToOutput  = this.parseResult;
                        //
                        if (!this.fNoDistill)
                            {
                            // If we are to distill, but he hasn't given us a name, then
                            // distill the first distillable thing in the file.
                            if (null == this.globalToDistill)
                                {
                                foreach (NadirAST global in ((NadirAST)parseResult).NadirChildren)
                                    {
                                    if (global.Symbol.IsDistillable)
                                        {
                                        this.globalToDistill = global.Symbol.Name;
                                        break;
                                        }
                                    }
                                }

                            // If there's something to distill, then distill it!
                            if (this.globalToDistill != null)
                                {
                                this.distillationResult = Distill(context, this.globalToDistill);
                                this.resultToOutput     = this.distillationResult;
                                //
                                // Design the result if we're asked
                                //
                                if (!this.fNoDesign && !context.ExceptionOccurred)
                                    {
                                    if (this.globalToDesign != null)
                                        {
                                        designer = Design(context, this.distillationResult, this, true);
                                        }
                                    }
                                }
                            }
                        }
                    //
                    // Emit the output
                    //
                    if (!context.ExceptionOccurred)
                        {
                        PrintFinalOutput(designer, context);
                        }
                    anyErrors = anyErrors || context.ExceptionOccurred;
                    }
                finally 
                    { 
                    designer?.Dispose();
                    }

                break;
                }
            // end switch
                }
            //
            NadirHelper.TerminateHelper();
            Environment.Exit(anyErrors ? -1 : 0);
            }
        catch (Exception e)
            {
            MiscUtil.DisplayException(new WrappedException(e));
            }
        }
        protected override void ExecuteCmd(List <string> args)
        {
            if (!File.Exists(args[0]))
            {
                BetterConsole.WriteOnNextLine($"Grammar file does not exist.", ConsoleColor.Red);
                return;
            }

            if (!Directory.Exists(args[1]))
            {
                BetterConsole.WriteOnNextLine($"Output directory does not exist.", ConsoleColor.Red);
                return;
            }

            InterpreterCodeGenerator.LanguageName = args[2];
            var results = DescriptionLanguageInterpreter.Execute(File.ReadAllText(args[0]));

            if (results.Item2.Count > 0)
            {
                BetterConsole.WriteOnNextLine($"Failure to load language: {string.Join("\n\n", results.Item2.Select(y => TreePrinter.ToString(y, z => z.SubErrors)))}", ConsoleColor.Red);
            }

            var fileContents = results.Item1.Cast <string>().ToArray();

            File.WriteAllText(Path.Combine(args[1], $"{args[2]}Interpreter_NoEdit.cs"), fileContents[0]);
            File.WriteAllText(Path.Combine(args[1], $"{args[2]}Interpreter_Edit.cs"), fileContents[1]);
            File.WriteAllText(Path.Combine(args[1], "InterpreterSupport_NoEdit.cs"), fileContents[2]);
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            Console.Clear();

            while (true)  //handle switching prompts
            {
                Prompt(Constants.ReplPromptName, x => { REPLCommandInterpreter.Execute(x); }, _cmdBuffer);
                Prompt(LanguageName, x => {
                    if (_languageInterp != null)
                    {
                        var results = _languageInterp(x);
                        if (results.Item1.Count > 0)
                        {
                            BetterConsole.WriteOnNextLine($"Result: ({string.Join(", ", results.Item1)})", ConsoleColor.Green);
                        }
                        if (results.Item2.Count > 0)
                        {
                            BetterConsole.WriteOnNextLine($"Errors: \n{string.Join("\n\n", results.Item2.Select(y => TreePrinter.ToString(y, z => z.SubErrors)))}", ConsoleColor.Red);
                        }
                    }
                    else
                    {
                        BetterConsole.WriteOnNextLine("Language not loaded. Use REPL Command {Language} to load a language assembly.");
                    }
                }, _langBuffer);
            }
        }
Ejemplo n.º 17
0
        protected override void ExecuteCmd(List <string> args)
        {
            if (_languagedLoaded)
            {
                BetterConsole.WriteOnNextLine("Language already loaded, unloading languages is not currently supported.");
                return;
            }

            if (!File.Exists(args[0]))
            {
                BetterConsole.WriteOnNextLine($"No file named {args[0]}");
                return;
            }

            try {
                var assem        = Assembly.LoadFile(args[0]);
                var handlers     = assem.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(ISymbolHandler))).Select(x => (ISymbolHandler)Activator.CreateInstance(x)).ToArray();
                var languageInfo = (ILanguageInfo)Activator.CreateInstance(assem.GetTypes().First(x => x.GetInterfaces().Contains(typeof(ILanguageInfo))));
                Program.LanguageName = languageInfo.Name;

                var results = LoadLanguageInterpreter.MakeTemporaryParser(languageInfo.Grammar);
                if (results.Item2.Count > 0)
                {
                    BetterConsole.WriteOnNextLine($"Failure to load language: {string.Join("\n\n", results.Item2.Select(y => TreePrinter.ToString(y, z => z.SubErrors)))}", ConsoleColor.Red);
                    return;
                }

                Program._languageInterp = code => results.Item1(code, handlers);
                _languagedLoaded        = true;
                BetterConsole.WriteOnNextLine($"{languageInfo.Name} loaded.");
            } catch (Exception ex) {
                BetterConsole.WriteOnNextLine($"{args[0]} is not a path to a valid language assembly.");
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Performs the compilation process
        /// </summary>
        public void Compile()
        {
            // Tokenize
            Write("Tokenising...");
            List <Token> tokens = Tokenizer.GetAllTokens();

            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");

            //WriteLine(string.Join("\n", tokens));

            //Parse
            Write("Parsing...");
            //Parser.Parse(tokens);
            ProgramNode tree = Parser.Parse(tokens);

            if (Reporter.HasErrors)
            {
                WriteLine("ERRORS");
                return;
            }
            WriteLine("Done");
            //WriteLine(TreePrinter.ToString(tree));

            Write("Identifying...");
            Identifier.PerformIdentification(tree);
            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");
            //WriteLine(TreePrinter.ToString(tree));

            //Type checking
            Write("Type Checking...");
            Checker.PerformTypeChecking(tree);
            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");
            WriteLine(TreePrinter.ToString(tree));

            // Code generation
            Write("Generating code...");
            TargetCode targetCode = Generator.GenerateCodeFor(tree);

            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");

            // Output
            Write("Writing to file...");
            Writer.WriteToFiles(targetCode);
            if (Reporter.HasErrors)
            {
                return;
            }
            WriteLine("Done");
        }
Ejemplo n.º 19
0
    //-----------------------------------------------------      

    void DumpTrees(TreePrinter printer, NadirContext context)
        {
        MiscUtil.TraceLine("-------------------------", this.FTracingToDebug);
        foreach (ParseResult parseResult in context.ParseResults)
            {
            printer.DumpTree(parseResult.Tree, this.FTracingToDebug);
            }
        }