// The MIT License (MIT)
//
// Copyright (C) 2026 Scott Duensing
//
// 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.

// codegen.h -- DVX BASIC p-code emitter
//
// Builds a p-code byte stream and string constant pool from
// calls made by the parser. Provides helpers for backpatching
// forward jumps.
//
// Embeddable: no DVX dependencies, pure C.

#ifndef DVXBASIC_CODEGEN_H
#define DVXBASIC_CODEGEN_H

#include "../runtime/vm.h"
#include "../runtime/values.h"

#include <stdint.h>
#include <stdbool.h>

// Constant pool index is emitted as uint16_t; pool cannot exceed this.
#define BAS_MAX_CONSTANTS 0x10000

// ============================================================
// Code generator state
// ============================================================

typedef struct {
    uint8_t          *code;             // stb_ds dynamic array
    int32_t           codeLen;
    BasStringT      **constants;        // stb_ds dynamic array
    uint32_t         *constHashes;      // stb_ds dynamic array, parallel to constants (FNV-1a of the text)
    int32_t           constCount;
    int32_t           globalCount;
    BasValueT        *dataPool;         // stb_ds dynamic array
    int32_t           dataCount;
    BasFormVarInfoT  *formVarInfo;      // stb_ds dynamic array
    int32_t           formVarInfoCount;
    BasDebugVarT     *debugVars;       // stb_ds dynamic array
    int32_t           debugVarCount;
    int32_t           debugProcCount;  // incremented per SUB/FUNCTION for debug var tracking
    BasDebugUdtDefT  *debugUdtDefs;   // stb_ds dynamic array
    int32_t           debugUdtDefCount;
    bool              overflow;          // set if a pool index would exceed 16 bits
} BasCodeGenT;

// ============================================================
// API
// ============================================================

void basCodeGenInit(BasCodeGenT *cg);
void basCodeGenFree(BasCodeGenT *cg);

// Emit single byte
void basEmit8(BasCodeGenT *cg, uint8_t b);

// Emit 16-bit signed value
void basEmit16(BasCodeGenT *cg, int16_t v);

// Emit 16-bit unsigned value
void basEmitU16(BasCodeGenT *cg, uint16_t v);

// Emit 32-bit float
void basEmitFloat(BasCodeGenT *cg, float v);

// Emit 64-bit double
void basEmitDouble(BasCodeGenT *cg, double v);

// Get current code position (for jump targets)
int32_t basCodePos(const BasCodeGenT *cg);

// Patch a 16-bit value at a previous position (for backpatching jumps)
void basPatch16(BasCodeGenT *cg, int32_t pos, int16_t val);

// Add a string to the constant pool. Returns the pool index.
uint16_t basAddConstant(BasCodeGenT *cg, const char *text, int32_t len);

// Adds a value to the data pool (for DATA statements).
void basAddData(BasCodeGenT *cg, BasValueT val);

// Build a BasModuleT from the generated code. The caller takes
// ownership of the module and must free it with basModuleFree().
BasModuleT *basCodeGenBuildModule(BasCodeGenT *cg);

// Build a module with procedure table from parser symbol table.
// symtab is a BasSymTabT* (cast to void* to avoid circular include).
BasModuleT *basCodeGenBuildModuleWithProcs(BasCodeGenT *cg, void *symtab);

// Free a module built by basCodeGenBuildModule.
void basModuleFree(BasModuleT *mod);

// Add a debug variable entry (for debugger variable display).
// formName is only used for SCOPE_FORM vars (NULL or "" for others).
void basCodeGenAddDebugVar(BasCodeGenT *cg, const char *name, uint8_t scope, uint8_t dataType, int32_t index, int32_t procIndex, const char *formName);

// Find a procedure by name in a module's procedure table.
// Case-insensitive. Returns NULL if not found.
const BasProcEntryT *basModuleFindProc(const BasModuleT *mod, const char *name);

#endif // DVXBASIC_CODEGEN_H
