r/dailyprogrammer • u/nint22 1 2 • Aug 20 '13
[08/08/13] Challenge #132 [Intermediate] Tiny Assembler
(Intermediate): Tiny Assembler
Tiny, a very simple fictional computer architecture, is programmed by an assembly language that has 16 mnemonics, with 37 unique op-codes. The system is based on Harvard architecture, and is very straight-forward: program memory is different from working memory, the machine only executes one instruction at a time, memory is an array of bytes from index 0 to index 255 (inclusive), and doesn't have any relative addressing modes. Instructions are multibyte, much like the X86 architecture. Simple instructions like HALT only take one byte, while complex instructions like JLS (Jump if Less-than) take four bytes.
Your goal will be to write an [assembler](http://en.wikipedia.org/wiki/Assembler_(computing)#Assembler) for Tiny: though you don't need to simulate the code or machine components, you must take given assembly-language source code and produce a list of hex op-codes. You are essentially writing code that converts the lowest human-readable language to machine-readable language!
The following are all mnemonics and associated op-codes for the Tiny machine. Note that brackets mean "content of address-index" while non-brackets mean literals. For example, the instruction "AND [0] 1" will set the contents of the first element (at index 0) of memory to 1 if, and only if, the original contents at that element are equal to the given literal 1.
Google Documents of the below found here.
| Group | Instruction | Byte Code | Description |
|---|---|---|---|
| 1. Logic | AND a b | 2 Ops, 3 bytes: | M[a] = M[a] bit-wise and M[b] |
| 0x00 [a] [b] | |||
| 0x01 [a] b | |||
| OR a b | 2 Ops, 3 bytes: | M[a] = M[a] bit-wise or M[b] | |
| 0x02 [a] [b] | |||
| 0x03 [a] b | |||
| XOR a b | 2 Ops, 3 bytes: | M[a] = M[a] bit-wise xor M[b] | |
| 0x04 [a] [b] | |||
| 0x05 [a] b | |||
| NOT a | 1 Op, 2 bytes: | M[a] = bit-wise not M[a] | |
| 0x06 [a] | |||
| 2. Memory | MOV a b | 2 Ops, 3 bytes: | M[a] = M[b], or the literal-set M[a] = b |
| 0x07 [a] [b] | |||
| 0x08 [a] b | |||
| 3. Math | RANDOM a | 2 Ops, 2 bytes: | M[a] = random value (0 to 25; equal probability distribution) |
| 0x09 [a] | |||
| ADD a b | 2 Ops, 3 bytes: | M[a] = M[a] + b; no overflow support | |
| 0x0a [a] [b] | |||
| 0x0b [a] b | |||
| SUB a b | 2 Ops, 3 bytes: | M[a] = M[a] - b; no underflow support | |
| 0x0c [a] [b] | |||
| 0x0d [a] b | |||
| 4. Control | JMP x | 2 Ops, 2 bytes: | Start executing instructions at index of value M[a] (So given a is zero, and M[0] is 10, we then execute instruction 10) or the literal a-value |
| 0x0e [x] | |||
| 0x0f x | |||
| JZ x a | 4 Ops, 3 bytes: | Start executing instructions at index x if M[a] == 0 (This is a nice short-hand version of ) | |
| 0x10 [x] [a] | |||
| 0x11 [x] a | |||
| 0x12 x [a] | |||
| 0x13 x a | |||
| JEQ x a b | 4 Ops, 4 bytes: | Jump to x or M[x] if M[a] is equal to M[b] or if M[a] is equal to the literal b. | |
| 0x14 [x] [a] [b] | |||
| 0x15 x [a] [b] | |||
| 0x16 [x] [a] b | |||
| 0x17 x [a] b | |||
| JLS x a b | 4 Ops, 4 bytes: | Jump to x or M[x] if M[a] is less than M[b] or if M[a] is less than the literal b. | |
| 0x18 [x] [a] [b] | |||
| 0x19 x [a] [b] | |||
| 0x1a [x] [a] b | |||
| 0x1b x [a] b | |||
| JGT x a b | 4 Ops, 4 bytes: | Jump to x or M[x] if M[a] is greater than M[b] or if M[a] is greater than the literal b. | |
| 0x1c [x] [a] [b] | |||
| 0x1d x [a] [b] | |||
| 0x1e [x] [a] b | |||
| 0x1f x [a] b | |||
| HALT | 1 Op, 1 byte: | Halts the program / freeze flow of execution | |
| 0xff | |||
| 5. Utilities | APRINT a | 4 Ops, 2 byte: | Print the contents of M[a] in either ASCII (if using APRINT) or as decimal (if using DPRINT). Memory ref or literals are supported in both instructions. |
| DPRINT a | 0x20 [a] (as ASCII; aprint) | ||
| 0x21 a (as ASCII) | |||
| 0x22 [a] (as Decimal; dprint) | |||
| 0x23 a (as Decimal) |
Original author: /u/nint22
Formal Inputs & Outputs
Input Description
You will be given the contents of a file of Tiny assembly-language source code. This text file will only contain source-code, and no meta-data or comments. The source code is not case-sensitive, so the instruction "and", "And", and "AND" are all the same.
Output Description
Print the resulting op-codes in hexadecimal value. Formatting does not matter, as long as you print the correct hex-code!
Sample Inputs & Outputs
Sample Input
The following Tiny assembly-language code will multiply the numbers at memory-location 0 and 1, putting the result at memory-location 0, while using [2] and [3] as working variables. All of this is done at the lowest 4 bytes of memory.
Mov [2] 0
Mov [3] 0
Jeq 6 [3] [1]
Add [3] 1
Add [2] [0]
Jmp 2
Mov [0] [2]
HaltSample Output
0x08 0x02 0x00
0x08 0x03 0x00
0x15 0x06 0x03 0x01
0x0B 0x03 0x01
0x0A 0x02 0x00
0x0F 0x02
0x07 0x00 0x02
0xFFChallenge Bonus
If you write an interesting Tiny-language program and successfully run it against your assembler, you'll win a silver medal! If you can formally prove (it won't take much effort) that this language / machine is Turing Complete, you'll win a gold medal!
4
u/msiemens 1 1 Aug 29 '13
My submission for the bonus (writing an interisting Tiny program):
I've extended the syntax a bit (labels, constants, ...) and wrote a virtual machine. The program source code with my extended syntax along with the assembler program and the virtual machine can be found here: https://github.com/msiemens/TINY.ASM
What does the program do? It computes π using a stochastic algorithm:
Because of the random values and the word size of 8 bit, the result will have a very low precision and vary between runs. In addition, due to the lack of float point arithmetics, the program will only output the equation to get π (e.g.
78/100*4). I'm still working on implementing 16bit float point arithmetics for Tiny, so it might output the actual result.3
u/NegativeLatency Aug 20 '13
You have to escape the close paren for links to work
[Assembler](http://en.wikipedia.org/wiki/Assembler_(computing)#Assembler)
3
u/zengargoyle Aug 20 '13
MOV a b 2 Ops, 3 bytes: M[a] = M[b], or the literal-set M[a] = b 0x07 [a] [b] 0x08 [a] b
This perturbs me. you had a good streak going of the 0x01 bit being [x][y] vs [x]y and broke it. :P
3
u/zengargoyle Aug 20 '13
A quick Perl programming language solution. When I started, line 7 of the example input was
Mov 0 [2]which gave the helpful errorMov does not support ? [?] at line 7. Assumed it was[0] [2]The point I was trying to make earlier was that the first few operands follow the rule 'last bit 0 = [a] [b], last bit 1 = [a] b' which having NOT,MOV,RANDOM breaks the chain. Opcodes usually break down on the binary level so ops that take 2 args would have form XXXXXX?? with the ?? bits choosing between '11 [a][b], 10 [a]b, 01 a[b], 00 a b' so the individual bits would control direct/indirect.
5
u/Elite6809 1 1 Aug 20 '13 edited Aug 20 '13
I might be wrong here but the machine can't be Turing complete because it only has a limited amount of memory, can it? Therefore it's only a finite state machine. Not much of an expert on that though, correct me if I'm wrong. I know Brainfuck is Turing-complete if given an infinite tape size and Brainfuck could probably translated into this instruction set, however you stated a maximum memory size of 255 bytes.
Still working on the solution, I just thought I'd say this.
Edit:
In your example program you have a syntax error.That doesn't fit either of the two given formats. Which one is it meant to be? I'm presumingMov [0] [2]judging from the output opcode (0x07.)Never mind, you fixed it.
Edit 2: Solution complete, done in C# 5 (it would be a lot shorter if C# wasn't so verbose when it comes to dictionaries/maps and arrays):
11
u/rectal_smasher_2000 1 1 Aug 21 '13
c++ solution. would have been nicer in c++11, unfortunately i haven't managed to set it up on windows, whereas i couldn't be bothered booting up linux, since i was already half way through writing the code.
covers most syntax errors, however not all. here's the example output:
and here be an output with errors:
8
u/lukz 2 0 Aug 21 '13
Common Lisp
7
u/EvanHahn Aug 20 '13
My Ruby solution!
7
u/13467 1 1 Aug 21 '13
Haskell. I'm not very proud of this... it works fine but isn't very pretty. I don't know if it would've been prettier if I used something like Parsec, though.
7
u/shangas Aug 21 '13
Haskell. Because writing the assembler and parser by hand would have been repetitive and boring, the language spec is embedded in the source code and expanded into the actual assembler implementation by a compile-time macro.
13
u/Glassfish 0 0 Aug 21 '13
Python3:
6
u/jpverkamp Aug 21 '13
That was interesting. I worked out a solution using Racket and more macros than I probably should have. I turned out pretty clean though.
And there's a proof for Turning completeness. :) (Assuming that you add the
MMOVopcode that I described below; I'm still not convinced you can do it without...)If you'd like to see a more in depth write up, you can do so on my blog: A 'Tiny' virtual machine in Racket
If you'd rather just see the entire source code, you can do so on GitHub: jpverkamp/tiny
Here's the gist of it though. First, we define the op codes. I have a chain of macros for that:
Next, the definitions. Here are a few. Most are similar or use the same submacro:
From there, assembly is relatively straight forward:
If we assemble the given example (with a tweak to multiple two defined variables):
We can run it as well; go check out the blog post for that.
Finally, the proof of Turing completeness. Basically, you convert any given Turning machine into Tiny code. Basically, you get something like this:
Unfortunately you can't actually have more than 8 transitions (I use 29 bytes per transition plus 16 + 3 * initial bytes for the header) even in the best case without breaking the hex encoding. It still works on my machine because I'm storing everything as integers internally (giving me essentially unlimited memory because Racket integers are really integers), but it won't print nicely.
Well, that's it.
jverkamp.com: A 'Tiny' virtual machine in Racket
If you'd rather just see the entire source code, you can do so on GitHub: GitHub: jpverkamp/tiny
If anyone has a proof for Turning completeness with
MMOVI'd love to see it. I'm just not convinced it's actually possible.5
u/Hakawatha Aug 22 '13
In Bison and Flex.
assembler.l:
assembler.y:
Example I/O:
factorial.asm:
output:
4
u/VerilyAMonkey Aug 20 '13 edited Aug 21 '13
It seems like it's pretty simple in Python:
4
u/Alborak Aug 21 '13
I'm not terribly proud of this, but I've been doing nothing but driver coding in C so wanted a minor break. Basic premise is look up base code in hash table, add offsets to it based on arguments. Error handling is pretty much just to crash. If that.
}
3
u/msiemens 1 1 Aug 20 '13 edited Aug 29 '13
Update: Assembler with extended syntax (labels, constants, ...) + a virtual machine for Tiny can be found here: https://github.com/msiemens/TINY.ASM
My Python 2 solution.
EDIT: Added Enum type for arguments type enum (fallback to ints), added
__main__EDIT: Fixed formatting
3
u/tchakkazulu 0 2 Aug 20 '13
Is it just me? I do not see the use of the
JZ _ aforms. If we are comparing a statically knownaagainst 0, we could just precompute if we're jumping or not, and change it to a no-op or aJMPas appropriate. (also, the description of theJZinstruction ends abruptly).Meanwhile, I'm cooking up something Haskell-y.
3
u/jpverkamp Aug 20 '13 edited Aug 20 '13
Is this language actually Turing complete?
Similar to the comments below from tchakkazulu et al, even if you assume unlimited memory, you can't actually use it. When you have a given program, you're going to use a finite amount of memory defined by the set of every
[a]in the program, yes?So far as I can tell, you'd have to add at least one more operator to make it Turing complete. For my own implementation, I added
mmov:Can it be done without this?
3
u/eBtDMoN2oXemz1iKB Aug 21 '13 edited Aug 21 '13
My solution in Ruby, with much inspiration from /u/EvanHahn
Edit: Improved error handling
3
u/[deleted] Aug 21 '13
My try in Python:
I would appreciate any feedback.
3
u/killedbythegrue Aug 22 '13
In Erlang. There ought to be a shorter way to do this.
Output for the sample;
3
u/eBtDMoN2oXemz1iKB Aug 22 '13 edited Aug 22 '13
A Ruby golf version (with no error checking) based on /u/Glassfish 's Python solution.
3
u/laserdude11 Aug 24 '13
My implementation in good ol' C.
There are still some things to do better; probably should split up the translate() function, used an enum instead of literal 0,1,2 for data types. So far seems pretty robust.
3
u/lukz 2 0 Aug 25 '13
BASIC
I started with programming in BASIC on an 8-bit computer. I don't have that computer anymore but recently I found an emulator and the very same BASIC implementation that I was using at that time. It's been at least 19 years in which I have not seen that system. So, I thought it would be good nostalgia feeling and an interesting challenge to try to re-learn that old basic and implement this problem in it (with some sensible simplifications).
For amusement, the BASIC startup banner:
Now we can type our program:
And here is a sample session (? is the prompt):
3
u/NasenSpray 0 1 Aug 25 '13
C++ Solution using VS2012 (therefore no initializer lists)
I also implemented support for labels and ASCII literals.
Sample program: output prime numbers from 2 to 255.
With labels:
Without:
Hex:
Proof using C++:
3
u/danneu Aug 28 '13 edited Sep 04 '13
Clojure
The approach is pretty simple:
The parsed format is used for the translation lookup in that big hashmap.
Demo:
3
u/Osmandius Aug 30 '13
Rust 0.7
My second attempt at Rust. Any feedback or advice would be greatly appreciated.
3
u/deds_the_scrub Aug 30 '13
Ok - here's my attempt in C.
3
u/[deleted] Aug 30 '13
My entry in Common Lisp... you have to make the #:tiny package the current package in order for it to work (I haven't quite figured out how to make ASSEMBLE external... there's a catch with FIND-SYMBOL that I have to work around to fix this issue). However I'm pretty pleased with it:
3
u/thisguyknowsc Sep 15 '13
Very data-driven implementation in C. Uses compound literals for compact description of the instruction set in data.
6
u/IceDane 0 0 Aug 20 '13
Quoting Wikipedia:
Is that proof enough?
2
u/Edward_H Aug 21 '13
My solution in COBOL, coming in at just under 250 lines of code. Judging by the detail of the descriptions, will the next challenge be to write an interpreter for the assembly?
2
u/[deleted] Aug 21 '13
My solution in Java. It's my first time using the ternary operator and I'm still learning basic java so just happy this works tbh...
2
u/missblit Aug 22 '13
C++
2
u/jimauthors Aug 22 '13
My solution in Python 2
2
u/atomic_cheese Aug 24 '13 edited Nov 29 '23
removed
2
u/Seus2k11 Aug 24 '13
Here's my ruby solution. It made more sense in my head to use regex matching, while not as elegant as some of the dictionary style solutions, I got it to work for my application. I could also incorporate some level of error handling as well if there are no matches for an instruction. Any hints or tips are appreciated as I'm still constantly working on my ruby skills.
2
u/objective_fun Aug 25 '13 edited Aug 25 '13
Here's some Scala. I'm pretty new to the language so if anyone can give me any tips that'd be great.
2
u/KompjoeFriek 1 0 Aug 31 '13
My first submission, straight-forward solution in C C++ PHP and JS: http://home.kompjoefriek.nl/reddit/132/
2
u/Sandor_at_the_Zoo Sep 02 '13
Haskell. After a few rounds of simplifying I rather like it. I'm still learning Haskell, so any comments would be appreciated.
2
u/[deleted] Sep 08 '13
Java - very dirty
2
u/[deleted] Sep 15 '13 edited Sep 15 '13
F# version, using FParsec to parse the string. I did this so I could have nice strong types representing the syntax tree. It's longer than I wanted, but most of it is just data declarations
Sample output:
2
u/plausibility_ Sep 30 '13
Wrote a (somewhat verbose) solution in Python. Call it like
python assembler.py input.txtCan I get some code review on this?2
u/pirate_platypus Nov 07 '13
EDIT: Fixed format
Python 2.7ish. Does both assembly and disassembly; automagically determines if the input file is assembly or byte code.
It's nearly 300 lines. If I got rid of the white space, comments, and doc strings, it'd be about 170.
2
u/Ryven_ Dec 07 '13 edited Dec 07 '13
Made this account to post here, been a long time since I did any c++ so this struck me as a great problem to work on while picking it back up and learning newer stuff. All criticism and comments are welcome. I hope that even though this problem is 3months old already, that I can get some good feedback from others that have done this one. This is a full command line implementation for Tiny. It will parse a text file of tiny instructions and output a hexcode .tny file and optionally run the program. The syntax has been extended for comments and labels. Much thanks for those in this thread that inspired me. This is my 4th iteration of this since I started getting back into c++, and it comes in around 800 lines. Copy the further down tiny code into a text file and name it prim.txt run: tinyasm -d -c prim.txt -o prim.tny -r > log.txt for a nice look over. then run: tinyasm -r prim.tny to see
EDIT: Setup a gist for the c++ file. TinyASM
The Tiny sample program to parse, taken and extended from higher in the thread. This will find and print the first 100 prime numbers.
The hexcode output from the above program
2
u/AultimusPrime Jan 23 '14
Python 2.7 - Could use a more efficient data structure/lookup algorithm
1
u/sinisterEyebrow Oct 18 '13
I'm new to scala so any suggestion would be greatly appreciated.
Assembly class
Main file:
1
u/holoiii Oct 25 '13
My solution in ruby:
Spec:
Input for spec:
Output for spec: