Skip to content

Instantly share code, notes, and snippets.

@thecoshman
Created March 4, 2017 12:20
Show Gist options
  • Save thecoshman/9b8e581df7230170f504bd661ec62dc4 to your computer and use it in GitHub Desktop.
Save thecoshman/9b8e581df7230170f504bd661ec62dc4 to your computer and use it in GitHub Desktop.
Dcpu16 assembler thing
#!/bin/perl
use warnings;
use strict;
local %patterns = {
"hex" => "0[xX][\da-fA-F]+",
"comment" => "^\s*;",
"label" => ":(\w*)"
"opValue" => "\[?((0[xX][\da-fA-F]+)|([ABCXYZIJO])|(SP)|(PC)|(POP)|(PUSH)|(PEEK))(\+[ABCXYZIJ])?\]?",
"opCode" => "(?:SET)|(?:A[ND]D)|(?:SUB)|(?:MUL)|(?:DIV)|(?:MOD)|(?:SH[LR])|(?:[BX]OR)|(?:IF[ENGB])",
}
while(<>) {
continue if /^\s*;/ # ignore this line as it is a comment
r/^\s*:(\w*)\s*(.*)$/$2/ # $1 is the lable, $2 is the rest of the line (with white space removed from start)
push(@labels, $1); # $1 should be the label found in previous line
/(?:SET)|(?:A[ND]D)|(?:SUB)|(?:MUL)|(?:DIV)|(?:MOD)|(?:SH[LR])|(?:[BX]OR)|(?:IF[ENGB])/ # matches op codes
push(@assembly, $_);
}
sub ASMtoBIN {
local($asm) = ($_[0]);
local(@words)
# strip leading spaces and trailing comments
$asm =~ /^\s*(.*);?.*$/
$asm = $1;
}
sub buildWord {
local($op, $valueA, $valueB) = ($_[0], $_[1], $_[2]);
local($word);
$word = $valueB;
$word << 6;
$word += $valueA;
$word << 4;
$word += $op;
}
sub fixHex {
local($hex) = ($_[0]);
$hex =~ r/X/x;
$hex =~ r/a/A/;
$hex =~ r/b/B/;
$hex =~ r/c/C/;
$hex =~ r/d/D/;
$hex =~ r/e/E/;
$hex =~ r/f/F/;
}
sub stripASM {
local($asm) = ($_[0]);
$asm =~ r/\s*([^;]*;)/$1/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment