Assembler.Assembler.Build C# (CSharp) Method

Build() private method

private Build ( ) : void
return void
        private void Build()
        {
            var offset = 0;

            for (var i = 0; i < instructions.Count; i++)
            {
                var instruction = instructions[i];

                foreach (var label in labels.Values)
                {
                    if (label.Index == i)
                        label.Address = offset;
                }

                var bytes = instruction.Assemble();
                offset += bytes.Length;

                if (offset > 32000)
                    throw new AssemblerException("Program exceeds 32000 bytes");
            }

            foreach (Label label in labels.Values)
            {
                if (label.Address == 0 && label.Index >= instructions.Count)
                    label.Address = offset;
            }

            var assembled = new List<byte>();
            foreach (var instruction in instructions)
            {
                Label label;

                if (instruction.Left != null && instruction.Left.OperandType == OperandType.Label)
                {
                    if (!labels.TryGetValue(instruction.Left.Label, out label))
                        throw new AssemblerException(string.Format("Unresolved label '{0}' on line {1}.", instruction.Left.Label,
                                                                    instruction.Left.Line));

                    instruction.Left.Payload = (short)label.Address;
                }

                if (instruction.Right != null && instruction.Right.OperandType == OperandType.Label)
                {
                    if (!labels.TryGetValue(instruction.Right.Label, out label))
                        throw new AssemblerException(string.Format("Unresolved label '{0}' on line {1}.", instruction.Right.Label, instruction.Right.Line));

                    instruction.Right.Payload = (short)label.Address;
                }

                assembled.AddRange(instruction.Assemble());
            }

            Binary = assembled.ToArray();
        }