Example #1
0
        public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
        {
            int num = 0;

            if (c.OpCode == OpCodes.Stloc)
            {
                num = (int)c.Operand;
            }
            else
            {
                num = int.Parse(c.OpCode.Name.Split('.').Last());
            }

            var offset = 0;

            /*
             * for (int i = 0; i < num + 1; i++)
             * {
             *  offset += Marshal.SizeOf(Type.GetType(md.Body.Variables[i].VariableType.FullName));
             * }*/
            offset = md.Body.Variables.Count * 4;

            writer.Pop("eax");
            writer.Mov($"[ebp-{offset}]", "eax");
        }
Example #2
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     aOutput.Write(mMnemonic);
     aOutput.Write(" ");
     aOutput.Write(this.GetDestinationAsString());
     aOutput.Write(", ");
     aOutput.Write(this.GetSourceAsString());
     aOutput.Write(", ");
     aOutput.Write(this.pseudoOpcode);
 }
        public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
        {
            aOutput.Write(mMnemonic);
            String destination = this.GetDestinationAsString();

            if (!(DestinationEmpty && destination.Equals("")))
            {
                aOutput.Write(" ");
                aOutput.Write(destination);
            }
        }
Example #4
0
 public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
 {
     if (c.Operand != null)
     {
         writer.Push(c.Operand.ToString());
     }
     else
     {
         writer.Push(c.OpCode.Name.Split('.').Last());
     }
 }
Example #5
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     aOutput.Write(mMnemonic);
     aOutput.Write(" ");
     aOutput.Write(SizeToString(Size));
     if (!DestinationEmpty)
     {
         aOutput.Write(" ");
         aOutput.Write(this.GetDestinationAsString());
     }
 }
Example #6
0
        private void WriteAssembly(string content, string expectedFile, CompilationOptions options)
        {
            var assemblyDef = Compiler.CompileAssembly(content, options);

            using (Stream expected = File.Open(Path.Combine(AppContext.BaseDirectory, expectedFile), FileMode.Open))
                using (Stream actual = new MemoryStream())
                    using (AssemblyWriter writer = new AssemblyWriter(assemblyDef, actual, options))
                    {
                        writer.WriteAssembly();
                        writer.BaseStream.Should().Be(expected, Output);
                    }
        }
Example #7
0
        public static CompileContext CompileGMLText(string input, CompileContext context, bool redoAssets = false)
        {
            context.Setup(redoAssets);                                    // Set up
            List <Lexer.Token> tokens = Lexer.LexString(context, input);  // Peform lexical analysis

            Parser.Statement block = Parser.ParseTokens(context, tokens); // Parse tokens, make syntax tree

            // Optimize and process syntax tree
            Parser.Statement optimizedBlock = null;
            if (Parser.ErrorMessages.Count == 0)
            {
                optimizedBlock = Parser.Optimize(context, block);
            }

            // Handle errors from either function
            if (Parser.ErrorMessages.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Error{0} parsing code:", Parser.ErrorMessages.Count == 1 ? "" : "s");
                sb.AppendLine();
                sb.AppendLine();
                foreach (string msg in Parser.ErrorMessages)
                {
                    sb.AppendLine(msg);
                }
                context.SetError(sb.ToString());
                return(context);
            }

            CodeWriter codeWriter = AssemblyWriter.AssembleStatement(context, optimizedBlock); // Write assembly code

            context.ResultAssembly = codeWriter.Finish();

            if (codeWriter.ErrorMessages.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Error{0} writing assembly code:", codeWriter.ErrorMessages.Count == 1 ? "" : "s");
                sb.AppendLine();
                sb.AppendLine();
                foreach (string msg in codeWriter.ErrorMessages)
                {
                    sb.AppendLine(msg);
                }
                sb.AppendLine();
                sb.Append(context.ResultAssembly);
                context.SetError(sb.ToString());
                return(context);
            }

            context.OnSuccessfulFinish();
            return(context);
        }
Example #8
0
        public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
        {
            writer.Call(Compiler.NormaliseName(c.Operand.ToString()));

            var x = ((MethodReference)c.Operand).Resolve();

            if (!x.HasParameters)
            {
                return;
            }


            writer.Add("esp", ((x.Parameters.Count) * 4).ToString());
        }
Example #9
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     if (DestinationRef != null)
     {
         aOutput.Write("jmp ");
         aOutput.Write(Segment);
         aOutput.Write(":");
         aOutput.Write(DestinationRef.ToString());
     }
     else
     {
         aOutput.Write("jmp ");
         aOutput.Write(Segment);
         aOutput.Write(":0x0");
     }
 }
Example #10
0
        public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
        {
            aOutput.Write(mMnemonic);
            String destination = this.GetDestinationAsString();

            if (!destination.Equals(""))
            {
                aOutput.Write(" ");
                aOutput.Write(destination);
                string source = this.GetSourceAsString();
                if (!(SourceEmpty && source.Equals("")))
                {
                    aOutput.Write(", ");
                    aOutput.Write(source);
                }
            }
        }
Example #11
0
        static void TestAssemblyWriter()
        {
            using (var aw = new AssemblyWriter()
            {
                Indentation = "  ",
                IndentInstructions = true,
                IndentDirectives = false,
            })
            {
                aw.WriteLine("This is a comment.");
                aw.WriteLine("As is this.");
                aw.WriteLine(AssemblyLine.Label("TEST", -1));
                aw.WriteLine(AssemblyLine.Instruction("add", new[] { "r1", "r2", "r2" }, -1));

                Console.WriteLine(aw);
            }
        }
Example #12
0
        public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
        {
            int num = 0;

            if (c.OpCode == OpCodes.Ldloc)
            {
                num = (int)c.Operand;
            }
            else
            {
                num = int.Parse(c.OpCode.Name.Split('.').Last());
            }

            var offset = md.Body.Variables.Count * 4;

            writer.Mov("eax", $"[ebp-{offset}]");
            writer.Push("eax");
        }
Example #13
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     if (Size == 0)
     {
         Size = 32;
         //Console.WriteLine("ERRROR no size set for Instruction - set to 4 InstructionWithDestinationAndSourceAndSize") ;
     }
     aOutput.Write(mMnemonic);
     aOutput.Write(" ");
     aOutput.Write(SizeToString(Size));
     if (!DestinationEmpty)
     {
         aOutput.Write(" ");
         aOutput.Write(this.GetDestinationAsString());
         aOutput.Write(", ");
         aOutput.Write(this.GetSourceAsString());
     }
 }
Example #14
0
        public static void Main(string[] args)
        {
            //using (var result = File.OpenWrite("TransitionTableSource.cs"))
            //using (var writer = new Lexica.Regexp.TransitionTableBinaryWriter(result))
            //{
            //    var table = Lexica.Regexp.TransitionTable.FromVocabularyFile("vocabulary.txt");
            //    writer.Write(table);
            //}

            if (args.Length < 2)
            {
                throw new ArgumentException(nameof(args));
            }

            string file     = args[0];
            string runtime  = args[1];
            string filePath = Path.Combine(AppContext.BaseDirectory, file);

            if (string.IsNullOrWhiteSpace(runtime))
            {
                throw new ArgumentException(nameof(runtime));
            }
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("File to compile did not found.", filePath);
            }

            string fileName = Path.GetFileNameWithoutExtension(filePath);
            string content  = File.ReadAllText(filePath);

            var options = new CompilationOptions()
            {
                AssemblyName = $"{fileName}.dll"
            };
            var assemblyDef = Compiler.CompileAssembly(content, options);

            using (Stream stream = File.Open(Path.Combine(AppContext.BaseDirectory, options.AssemblyName), FileMode.Create))
                using (AssemblyWriter pe = new AssemblyWriter(assemblyDef, stream, options))
                {
                    pe.WriteAssembly();
                }

            RuntimeManager.WriteManifest(fileName, runtime);
        }
Example #15
0
        public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
        {
            switch (Size)
            {
            case 32:
                aOutput.Write("cdq");
                return;

            case 16:
                aOutput.Write("cwde");
                return;

            case 8:
                aOutput.Write("cbw");
                return;

            default:
                throw new NotSupportedException();
            }
        }
Example #16
0
        public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
        {
            switch (Condition)
            {
            case FloatConditionalMoveTestEnum.Below:
                aOutput.Write("fcmovb");
                break;

            case FloatConditionalMoveTestEnum.Equal:
                aOutput.Write("fcmove");
                break;

            case FloatConditionalMoveTestEnum.BelowOrEqual:
                aOutput.Write("fcmovbe");
                break;

            case FloatConditionalMoveTestEnum.Unordered:
                aOutput.Write("fcmovu");
                break;

            case FloatConditionalMoveTestEnum.NotBelow:
                aOutput.Write("fcmovnb");
                break;

            case FloatConditionalMoveTestEnum.NotEqual:
                aOutput.Write("fcmovne");
                break;

            case FloatConditionalMoveTestEnum.NotBelowOrEqual:
                aOutput.Write("fcmovnbe");
                break;

            case FloatConditionalMoveTestEnum.Ordered:
                aOutput.Write("fcmovnu");
                break;
            }
            aOutput.Write(" ");
            aOutput.Write("ST0");
            aOutput.Write(", ");
            aOutput.Write(this.GetSourceAsString());
        }
Example #17
0
        public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
        {
            if ((Prefixes & InstructionPrefixes.Repeat) != 0)
            {
                aOutput.Write("rep ");
            }
            switch (Size)
            {
            case 32:
                aOutput.Write("stosd");
                return;

            case 16:
                aOutput.Write("stosw");
                return;

            case 8:
                aOutput.Write("stosb");
                return;

            default: throw new Exception("Size not supported!");
            }
        }
Example #18
0
 // This is a hack for now to just get DR6 support. DR can only be used with move, so its best to keep it a separate
 // op anwyays and not give it general support in the register list.
 // We we clean up the assemblers take this into consideration.
 public override void WriteText(AsmContext aAssembler, AssemblyWriter aOutput)
 {
     aOutput.WriteLine("mov DR6, " + mValue);
 }
Example #19
0
 public void WriteToFile(string filename)
 {
     AssemblyWriter.WriteToFile(this, filename);
 }
Example #20
0
 public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
 {
     writer.Push(c.Operand.ToString());
 }
Example #21
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     mMnemonic = String.Intern("j" + Condition.GetMnemonic() + " ");
     base.WriteText(aAssembler, aOutput);
 }
Example #22
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     mMnemonic = "set" + Condition.GetMnemonic();
     base.WriteText(aAssembler, aOutput);
 }
Example #23
0
 public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
 {
     writer.Pop("eax"); // address
     writer.Pop("ebx"); // value
     writer.Mov("[eax]", "ebx");
 }
Example #24
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     aOutput.Write("extern ");
     aOutput.Write(Name);
 }
Example #25
0
        public static void WriteToFile(XzaarAssembly xzaarAssembly, string filename)
        {
            var writer = new AssemblyWriter();

            writer.Write(new AssemblyWriterContext(xzaarAssembly, filename));
        }
Example #26
0
        public void TestParser2()
        {
            //const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\FunctionCalls\NestedCall";
            //const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\ProgramFlow\BasicLoop";
            const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\ProgramFlow\FibonacciSeries";
            //const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\FunctionCalls\SimpleFunction";
            //const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\FunctionCalls\FibonacciElement";
            //const string root = @"C:\Users\Dean.Pavlovsky\Projects\nand2tetris\08\FunctionCalls\StaticsTest";
            var paths = Directory.EnumerateFiles(root, "*.vm", SearchOption.AllDirectories);
            //var paths = new[]
            //{
            //    $@"{root}\MemoryAccess\BasicTest\BasicTest.vm",
            //    $@"{root}\MemoryAccess\PointerTest\PointerTest.vm",
            //    $@"{root}\MemoryAccess\StaticTest\StaticTest.vm",
            //    $@"{root}\StackArithmetic\SimpleAdd\SimpleAdd.vm",
            //    $@"{root}\StackArithmetic\StackTest\StackTest.vm"
            //};
            var dirName = Path.GetFileName(root);
            var outFile = Path.Combine(root, $"{dirName}.asm");

            using (var ctx = new Context(File.CreateText(outFile) /*new StringWriter(sb)*/))
            {
                ctx.Writer.WriteLine("@256");
                ctx.Writer.WriteLine("D=A");
                ctx.Writer.WriteLine("@SP");
                ctx.Writer.WriteLine("M=D");
                var sysInit = Path.Combine(root, "Sys.vm");
                if (File.Exists(sysInit))
                {
                    string EntryPoint = "Sys.Init".ToUpper();
                    ctx.CurrentFunction = new FunctionContext(EntryPoint, 0);
                    ctx.InputFilePath   = "Sys.vm";
                    AssemblyWriter.EmitCall(ctx, EntryPoint, 0);
                }
                foreach (var path in paths)
                {
                    Console.WriteLine($"processing {path}");
                    var inputFile = Path.GetFileName(path);
                    ctx.InputFilePath = inputFile;


                    var callbacks = new ParserCallBacks
                    {
                        OnPop =
                            (segment, index) =>
                            AssemblyWriter.EmitPop(ctx, segment, index),
                        OnPush = (segment, index) =>
                                 AssemblyWriter.EmitPush(ctx, segment, index),
                        OnArithmeticCommand = command =>
                                              AssemblyWriter.EmitOperator(ctx.Writer, command),
                        OnGoTo = label =>
                                 AssemblyWriter.EmitGoTo(ctx, label),
                        OnIfGoTo = label =>
                                   AssemblyWriter.EmitIfGoTo(ctx, label),
                        OnLabelDeclaration = label =>
                                             AssemblyWriter.EmitLabel(ctx, label),
                        OnCall = (command, n) =>
                                 AssemblyWriter.EmitCall(ctx, command.ToUpper(), n),
                        //Console.WriteLine($">> call {command},{n}"),
                        OnFuncDef = (functionName, n) =>
                        {
                            var name = functionName.ToUpper();
                            ctx.CurrentFunction = new FunctionContext(name, n);
                            AssemblyWriter.EmitFunction(ctx, name, n);
                        },
                        OnReturn = () =>
                        {
                            AssemblyWriter.EmitReturn(ctx);
                            //ctx.CurrentFunction = null;
                        },
                    };
                    Parser.Parse(File.ReadAllLines(path), callbacks);
                    ctx.Writer.Flush();
                }
            }
        }
Example #27
0
File: Nop.cs Project: djlw78/cs2asm
 public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
 {
 }
Example #28
0
File: Ret.cs Project: djlw78/cs2asm
 public override void Emit(MethodDefinition md, Instruction c, AssemblyWriter writer)
 {
     writer.Jmp(Compiler.NormaliseName(md.FullName) + "_ret");
 }
Example #29
0
 public override void WriteText(NCAsm.AsmContext aAssembler, AssemblyWriter aOutput)
 {
     base.WriteText(aAssembler, aOutput);
     aOutput.Write(", DX");
 }
Example #30
0
        private static void Main(string[] args)
        {
            var file = new AssemblyWriter();
            var meta = new AssemblyInfo {
                Version = "1.0.0.0", ID = Guid.NewGuid()
            };

            file.AddMeta(meta);

            var typeinfo  = file.CreateSection(AssemblySections.TypeInfo);
            var debuginfo = file.CreateSection(AssemblySections.DebugInfo);
            var ro        = file.CreateSection(AssemblySections.ReadOnly);
            var data      = file.CreateSection(AssemblySections.Code);

            ro.Raw = BitConverter.GetBytes(0x2A);

            var ass = new CommandWriter();

            //inc-method at 0
            ass.Add(OpCode.LOAD, (int)Registers.A, 0x2A);
            ass.Add(OpCode.INC, (int)Registers.A);
            ass.Add(OpCode.LOADRO, 0x0, (int)Registers.D);
            ass.Add(OpCode.PUSHRO, 0x0);

            ass.Add(OpCode.PUSHL, 9);
            ass.Add(OpCode.OUT, 0xABC, 2); // change foreground

            ass.Add(OpCode.PUSHL, 10);
            ass.Add(OpCode.OUT, 0xABC, 3); // change background

            ass.Add(OpCode.PUSHL, 'e');
            ass.Add(OpCode.OUT, 0xABC, 1); // write e to console

            ass.Add(OpCode.PUSHL, ':');
            ass.Add(OpCode.OUT, 0xABC, 1); // write : to console

            var inputloop = ass.MakeLabel();

            ass.Add(OpCode.IN, 0xABC1, (int)Registers.C); // wait for input char
            // ass.Add(OpCode.JMP, inputloop);

            ass.Add(OpCode.PUSHL, '\n'); // write new line to console
            ass.Add(OpCode.OUT, 0xABC, 1);

            var loop = ass.MakeLabel();

            ass.Add(OpCode.MOV, (int)Registers.ACC, (int)Registers.A);
            ass.Add(OpCode.INT, 0x123);    // print registers
            ass.Add(OpCode.OUT, 0xABC, 0); //clear console
            //ass.Add(OpCode.JMP, loop);

            ass.Add(OpCode.OUT, 0xABC, 4); // Reset colors

            //Beep
            ass.Add(OpCode.PUSHL, 15000);
            ass.Add(OpCode.PUSHL, 1500);
            ass.Add(OpCode.OUT, 0xABC, 5);
            //.Add(OpCode.CALL, loop);

            data.Raw = ass.Save();
            var vm = new VirtualMachine(Assembly.Load(file.Save()));

            vm.Run();

            Utils.PrintRegisters(vm.Register);

            Console.WriteLine("Register: " + vm.ViewMemoryOf <Register>().ToHex());
            Console.WriteLine("Stack: " + vm.ViewMemoryOf <Stack>().ToHex());

            Console.ReadLine();
        }