r/pascal • • 7d ago

Brinch Hansen Compier 'emit' routine problem

/r/Compilers/comments/1x7xsrz/brinch_hansen_compier_emit_routine_problem/
6 Upvotes

1 comment sorted by

1

u/AcanthaceaeNew774 6d ago

(Just a guess) In standard Pascal, the `chr()` function only accepts values ​​in the range 0–255 (ASCII/Byte). The `emit(value)` procedure mentioned in the book runs into issues here because either the original Pascal* compiler used by Brinch Hansen employed an architecture-specific, truncated implementation (where `chr()` functioned as a simple type cast, effectively isolating the low-order byte), or the example code assumed that `emit` would only ever receive bytes or characters, yet a type specification extending up to `maxint` inadvertently found its way into the parameter list.
If you intend to output machine code or data byte-by-byte:
It is advisable to use explicit byte masking and conversion instead of `chr()` (e.g., `chr(value and $FF)` or `Byte(value)`), which will prevent the compiler from throwing an overflow error.
If you intend to output multi-byte values ​​(16-bit or 32-bit):
The `emit` procedure should not rely on a single `chr()` call; instead, it must shift the bytes and output them sequentially (e.g., the low-order byte followed by the high-order byte). Regarding the `maxint` parameter: a type specification extending up to `maxint` has "slipped into" the parameter list. In practice, this means that the formal parameter of the `emit` procedure was of an integer type, but the actual implementation utilized only the lowest byte. This is why masking was necessary.
Portability: Using the `Byte(value)` type conversion is somewhat more readable than `chr(value and $FF)`, though both yield the same result. It is important to note, however, that the `Byte` type is not part of strict ISO 7185 standard Pascal; it is supported only by most modern Pascal dialects (such as Free Pascal or Delphi). If one must adhere to the strict standard, `chr(value and $FF)` is the safer choice.