Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""dictionary.py — FORTH dictionary structure.
Each entry in the dictionary: +0: link (u32) — address of previous entry, 0 = end of list +4: name_len (u8) — length of name string +5: name (name_len bytes) — the word name (uppercase ASCII) +5+name_len: code_field (u32) — address of code to execute (Thumb bit set) +9+name_len: body — for colon words: [word1_addr, word2_addr, ...]
The dictionary grows upward from a base address (HERE/DP).Newest entry's address is stored in LATEST (a variable in SRAM).FIND walks the list backward from LATEST, comparing names."""import struct
# SRAM variables for dictionary stateLATEST_ADDR = 0x00803000 # u32: address of most recent dictionary entryDP_ADDR = 0x00803004 # u32: dictionary pointer (grows up)
def pack_entry(name, code_field, link=0): """Build a dictionary entry as bytes.
name: the word name (string, will be uppercased) code_field: address of the code to execute (Thumb addr, with bit 0) link: address of previous entry (0 = first entry) """ name = name.upper().encode('ascii') name_len = len(name) entry = struct.pack('<I', link) # link entry += bytes([name_len]) # name length entry += name # name string # Align code_field to 4-byte boundary while len(entry) % 4 != 0: entry += b'\x00' entry += struct.pack('<I', code_field) # code field return entry
class Dictionary: """Builds a dictionary in a memory image for testing."""
def __init__(self, base_addr=0x00804000): self.base = base_addr self.here = base_addr self.entries = {} # name -> entry_addr self.latest = 0 self.image = bytearray(0x1000)
def add_primitive(self, name, code_addr): """Add a primitive word to the dictionary. code_addr: the Thumb address of the machine code. """ entry = pack_entry(name, code_addr | 1, link=self.latest) offset = self.here - self.base self.image[offset:offset + len(entry)] = entry self.entries[name.upper()] = self.here self.latest = self.here self.here += len(entry) return self.here
def add_colon(self, name, body_words, docol_addr): """Add a colon word. body_words: list of entry addresses of words in the body. docol_addr: Thumb address of DOCOL. """ entry = pack_entry(name, docol_addr | 1, link=self.latest) offset = self.here - self.base self.image[offset:offset + len(entry)] = entry body_offset = offset + len(entry) for w in body_words: self.image[body_offset:body_offset + 4] = struct.pack('<I', w) body_offset += 4 self.entries[name.upper()] = self.here self.latest = self.here self.here += len(entry) + len(body_words) * 4 return self.here
def find(self, name): """Find a word by name, return its entry address or None.""" return self.entries.get(name.upper())
def entry_addr(self, name): """Get the entry address for a word (for use in threads).""" return self.entries.get(name.upper())