87 lines
2.6 KiB
C
87 lines
2.6 KiB
C
/*
|
|
* Copyright (c) 2024 Scott Duensing, scott@kangaroopunch.com
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
* of this software and associated documentation files (the "Software"), to deal
|
|
* in the Software without restriction, including without limitation the rights
|
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the Software is
|
|
* furnished to do so, subject to the following conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be included in
|
|
* all copies or substantial portions of the Software.
|
|
*
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
* SOFTWARE.
|
|
*/
|
|
|
|
|
|
#include "variable.h"
|
|
#include "state.h"
|
|
#include "portme.h"
|
|
#include "messages.h"
|
|
#include "story.h"
|
|
#include "memory.h"
|
|
|
|
|
|
uint32_t variableAddressGlobal(uint16_t var) {
|
|
return storyGlobalVariableTableAddress() + ((var - 0x10) * 2);
|
|
}
|
|
|
|
|
|
uint16_t variableLoad(uint16_t var) {
|
|
// Is it on the stack?
|
|
if (var < 16) return __state.stack[variableAddress(var, 0)];
|
|
// Nope, global.
|
|
return ZPEEKW(variableAddressGlobal(var));
|
|
}
|
|
|
|
|
|
void variableStore(uint16_t var, uint16_t value) {
|
|
uint32_t addr;
|
|
|
|
if (var < 16) {
|
|
// On stack.
|
|
addr = variableAddress(var, 1);
|
|
__state.stack[addr] = value;
|
|
} else {
|
|
// Global.
|
|
addr = variableAddressGlobal(var);
|
|
ZPOKEW(addr, value);
|
|
}
|
|
}
|
|
|
|
|
|
uint8_t variableAddress(uint8_t var, bool writing) {
|
|
uint16_t numLocals;
|
|
|
|
if (var == 0) { // top of stack
|
|
if (writing) {
|
|
if (__state.sp >= sizeof(__state.stack)) portDie(MSG_INT_STACK_OVERFLOW);
|
|
#ifdef DEBUGGING
|
|
printf("Push stack\n");
|
|
#endif
|
|
return __state.sp++;
|
|
} else {
|
|
if (__state.sp == 0) portDie(MSG_INT_STACK_UNDERFLOW);
|
|
numLocals = __state.bp ? __state.stack[__state.bp - 1] : 0;
|
|
if ((__state.bp + numLocals) >= sizeof(__state.stack)) portDie(MSG_INT_STACK_UNDERFLOW);
|
|
#ifdef DEBUGGING
|
|
printf("Pop stack\n");
|
|
#endif
|
|
return --__state.sp;
|
|
} // writing
|
|
} // var
|
|
|
|
if ((var >= 0x1) && (var <= 0xf)) { // Local var.
|
|
if (__state.stack[__state.bp - 1] <= (var - 1)) portDie(MSG_INT_REF_UNALLOCATED_LOCAL);
|
|
return __state.bp + (var - 1);
|
|
}
|
|
|
|
return storyGlobalVariableTableAddress() + ((var - 0x10) * 2);
|
|
}
|