1whatleytay / saturn

A modern MIPS interpreter and assembler.
MIT License
29 stars 6 forks source link

Feature: Label namespaces #23

Open cartoon-raccoon opened 3 months ago

cartoon-raccoon commented 3 months ago

Currently, all labels exist in a global namespace. So labels within subroutines have to be distinctly named so avoid namespace conflicts, and when conflicts do occur, they aren't brought to the user's attention:

subroutine_a:
    # do_something
  part_1:
    # do even more things, then jump back to part_1
    b part_1
  part_2:
    jr $ra

subroutine_b:
    # do something
  part_1: # this clashes with part_1 in subroutine a
    jr $ra

So when this gets assembled, the b part_1 instruction in subroutine_a causes the PC to jump to part_1 in subroutine_b, because that was where the label was most recently defined. This leads to a lot of insidious bugs.

Other assemblers like NASM have support for sub-labels, marked with a period:

subroutine_a:
    # do_something
  .part_1:
    # do even more things, then jump back to part_1
    b part_1
  .part_2:
    jr $ra

subroutine_b:
    # do something
  .part_1: # this no longer clashes
    jr $ra

Sub-labels get tied to the most recent label without a period, so this essentially defines an entire new namespace for that label specifically. Additionally, if label name conflicts do occur, this should be a hard error.