From 72f801283df68672dc568c6acd9345bb4f01d46f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Antonio=20Ni=C3=B1o=20D=C3=ADaz?= Date: Tue, 2 Jan 2018 03:04:26 +0100 Subject: [PATCH] Cleanup code of rgbasm MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow Linux kernel coding style. Signed-off-by: Antonio Niño Díaz --- include/asm/asm.h | 14 +- include/asm/charmap.h | 3 +- include/asm/fstack.h | 24 +- include/asm/lexer.h | 64 +- include/asm/localasm.h | 194 ++- include/asm/main.h | 23 +- include/asm/mylink.h | 3 +- include/asm/mymath.h | 2 +- include/asm/output.h | 16 +- include/asm/rpn.h | 82 +- include/asm/symbol.h | 46 +- src/asm/asmy.y | 2643 ++++++++++++++++++++++------------------ src/asm/charmap.c | 109 +- src/asm/fstack.c | 340 +++--- src/asm/globlex.c | 147 ++- src/asm/lexer.c | 391 +++--- src/asm/locallex.c | 2 +- src/asm/main.c | 219 ++-- src/asm/math.c | 77 +- src/asm/output.c | 383 +++--- src/asm/rpn.c | 178 ++- src/asm/symbol.c | 570 ++++----- 22 files changed, 2852 insertions(+), 2678 deletions(-) diff --git a/include/asm/asm.h b/include/asm/asm.h index 10289e42..aa48d979 100644 --- a/include/asm/asm.h +++ b/include/asm/asm.h @@ -1,9 +1,9 @@ -/* asm.h +/* + * asm.h * - * Contains some assembler-wide defines and externs - * - * Copyright 1997 Carsten Sorensen + * Contains some assembler-wide defines and externs * + * Copyright 1997 Carsten Sorensen */ #ifndef RGBDS_ASM_ASM_H @@ -17,9 +17,9 @@ #include "asm/localasm.h" #include "asm/symbol.h" -#define MAXUNIONS 128 +#define MAXUNIONS 128 #define MAXMACROARGS 256 -#define MAXINCPATHS 128 +#define MAXINCPATHS 128 extern int32_t nLineNo; extern uint32_t nTotalLines; @@ -36,4 +36,4 @@ extern struct sSymbol *tHashedSymbols[HASHSIZE]; extern struct sSymbol *pPCSymbol; extern bool oDontExpandStrings; -#endif /* // ASM_H */ +#endif /* RGBDS_ASM_ASM_H */ diff --git a/include/asm/charmap.h b/include/asm/charmap.h index 44512d4c..db425a1f 100644 --- a/include/asm/charmap.h +++ b/include/asm/charmap.h @@ -13,8 +13,7 @@ struct Charmap { }; int32_t readUTF8Char(char *destination, char *source); -void charmap_Sort(); int32_t charmap_Add(char *input, uint8_t output); int32_t charmap_Convert(char **input); -#endif +#endif /* RGBDS_ASM_CHARMAP_H */ diff --git a/include/asm/fstack.h b/include/asm/fstack.h index dfa6bce2..3d14c792 100644 --- a/include/asm/fstack.h +++ b/include/asm/fstack.h @@ -1,8 +1,8 @@ -/* fstack.h +/* fstack.h * - * Contains some assembler-wide defines and externs + * Contains some assembler-wide defines and externs * - * Copyright 1997 Carsten Sorensen + * Copyright 1997 Carsten Sorensen * */ @@ -31,16 +31,16 @@ struct sContext { uint32_t nREPTBlockSize; }; -void fstk_RunInclude(char *); -extern void fstk_RunMacroArg(int32_t s); -void fstk_Init(char *); -extern void fstk_Dump(void); -extern void fstk_AddIncludePath(char *s); -extern uint32_t fstk_RunMacro(char *s); -extern void fstk_RunRept(uint32_t count); -FILE * fstk_FindFile(char *); +void fstk_RunInclude(char *tzFileName); +void fstk_RunMacroArg(int32_t s); +void fstk_Init(char *s); +void fstk_Dump(void); +void fstk_AddIncludePath(char *s); +uint32_t fstk_RunMacro(char *s); +void fstk_RunRept(uint32_t count); +FILE *fstk_FindFile(char *fname); int32_t fstk_GetLine(void); extern int yywrap(void); -#endif +#endif /* RGBDS_ASM_FSTACK_H */ diff --git a/include/asm/lexer.h b/include/asm/lexer.h index 5db2329c..dde7ece4 100644 --- a/include/asm/lexer.h +++ b/include/asm/lexer.h @@ -4,8 +4,8 @@ #include #include -#define LEXHASHSIZE (1 << 11) -#define MAXSTRLEN 255 +#define LEXHASHSIZE (1 << 11) +#define MAXSTRLEN 255 struct sLexInitString { char *tzName; @@ -13,14 +13,15 @@ struct sLexInitString { }; struct sLexFloat { - uint32_t(*Callback) (char *s, uint32_t size); + uint32_t (*Callback)(char *s, uint32_t size); uint32_t nToken; }; struct yy_buffer_state { - char *pBufferRealStart; // actual starting address - char *pBufferStart; // address where the data is initially written - // after the "safety margin" + /* Actual starting address */ + char *pBufferRealStart; + /* Address where the data is initially written after a safety margin */ + char *pBufferStart; char *pBuffer; uint32_t nBufferSize; uint32_t oAtLineStart; @@ -30,35 +31,36 @@ enum eLexerState { LEX_STATE_NORMAL, LEX_STATE_MACROARGS }; -#define INITIAL 0 -#define macroarg 3 + +#define INITIAL 0 +#define macroarg 3 typedef struct yy_buffer_state *YY_BUFFER_STATE; -extern void yy_set_state(enum eLexerState i); -extern YY_BUFFER_STATE yy_create_buffer(FILE * f); -extern YY_BUFFER_STATE yy_scan_bytes(char *mem, uint32_t size); -extern void yy_delete_buffer(YY_BUFFER_STATE); -extern void yy_switch_to_buffer(YY_BUFFER_STATE); -extern uint32_t lex_FloatAlloc(struct sLexFloat * tok); -extern void lex_FloatAddRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_FloatDeleteRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_FloatAddFirstRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_FloatDeleteFirstRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_FloatAddSecondRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_FloatDeleteSecondRange(uint32_t id, uint16_t start, uint16_t end); -extern void lex_Init(void); -extern void lex_AddStrings(struct sLexInitString * lex); -extern void lex_SetBuffer(char *buffer, uint32_t len); -extern uint32_t yylex(void); -extern void yyunput(char c); -extern void yyunputstr(char *s); -extern void yyskipbytes(uint32_t count); -extern void yyunputbytes(uint32_t count); +void yy_set_state(enum eLexerState i); +YY_BUFFER_STATE yy_create_buffer(FILE *f); +YY_BUFFER_STATE yy_scan_bytes(char *mem, uint32_t size); +void yy_delete_buffer(YY_BUFFER_STATE buf); +void yy_switch_to_buffer(YY_BUFFER_STATE buf); +uint32_t lex_FloatAlloc(const struct sLexFloat *tok); +void lex_FloatAddRange(uint32_t id, uint16_t start, uint16_t end); +void lex_FloatDeleteRange(uint32_t id, uint16_t start, uint16_t end); +void lex_FloatAddFirstRange(uint32_t id, uint16_t start, uint16_t end); +void lex_FloatDeleteFirstRange(uint32_t id, uint16_t start, uint16_t end); +void lex_FloatAddSecondRange(uint32_t id, uint16_t start, uint16_t end); +void lex_FloatDeleteSecondRange(uint32_t id, uint16_t start, uint16_t end); +void lex_Init(void); +void lex_AddStrings(const struct sLexInitString *lex); +void lex_SetBuffer(char *buffer, uint32_t len); +uint32_t yylex(void); +void yyunput(char c); +void yyunputstr(char *s); +void yyskipbytes(uint32_t count); +void yyunputbytes(uint32_t count); extern YY_BUFFER_STATE pCurrentBuffer; -extern void upperstring(char *s); -extern void lowerstring(char *s); +void upperstring(char *s); +void lowerstring(char *s); -#endif +#endif /* RGBDS_ASM_LEXER_H */ diff --git a/include/asm/localasm.h b/include/asm/localasm.h index ff5f3e7c..6a78c17e 100644 --- a/include/asm/localasm.h +++ b/include/asm/localasm.h @@ -1,93 +1,95 @@ -/* GB Z80 instruction groups - - n3 = 3-bit - n = 8-bit - nn = 16-bit - -* ADC A,n : 0xCE -* ADC A,r : 0x88|r -* ADD A,n : 0xC6 -* ADD A,r : 0x80|r -* ADD HL,ss : 0x09|(ss<<4) -* ADD SP,n : 0xE8 -* AND A,n : 0xE6 -* AND A,r : 0xA0|r -* BIT n3,r : 0xCB 0x40|(n3<<3)|r -* CALL cc,nn : 0xC4|(cc<<3) -* CALL nn : 0xCD -* CCF : 0x3F -* CP A,n : 0xFE -* CP A,r : 0xB8|r -* CPL : 0x2F -* DAA : 0x27 -* DEC r : 0x05|(r<<3) -* DEC ss : 0x0B|(ss<<4) -* DI : 0xF3 -* EI : 0xFB -* HALT : 0x76 -* INC r : 0x04|(r<<3) -* INC ss : 0x03|(ss<<4) -* JP HL : 0xE9 -* JP cc,nn : 0xC2|(cc<<3) -* JP nn : 0xC3|(cc<<3) -* JR n : 0x18 -* JR cc,n : 0x20|(cc<<3) -* LD (nn),SP : 0x08 -* LD ($FF00+C),A : 0xE2 -* LD ($FF00+n),A : 0xE0 -* LD (nn),A : 0xEA -* LD (rr),A : 0x02|(rr<<4) // HL+ and HL- included -* LD A,($FF00+C) : 0xF2 -* LD A,($FF00+n) : 0xF0 -* LD A,(nn) : 0xFA -* LD A,(rr) : 0x0A|(rr<<4) // HL+ and HL- included -* LD HL,SP+n : 0xF8 -* LD SP,HL : 0xF9 -* LD r,n : 0x06|(r<<3) -* LD r,r' : 0x40|(r<<3)|r' // NOTE: LD (HL),(HL) not allowed -* LD ss,nn : 0x01|(ss<<4) -* NOP : 0x00 -* OR A,n : 0xF6 -* OR A,r : 0xB0|r -* POP tt : 0xC1|(tt<<4) -* PUSH tt : 0xC5|(tt<<4) -* RES n3,r : 0xCB 0x80|(n3<<3)|r -* RET : 0xC9 -* RET cc : 0xC0|(cc<<3) -* RETI : 0xD9 -* RL r : 0xCB 0x10|r -* RLA : 0x17 -* RLC r : 0xCB 0x00|r -* RLCA : 0x07 -* RR r : 0xCB 0x18|r -* RRA : 0x1F -* RRC r : 0xCB 0x08|r -* RRCA : 0x0F -* RST n : 0xC7|n -* SBC A,n : 0xDE -* SBC A,r : 0x98|r -* SCF : 0x37 -* SET n3,r : 0xCB 0xC0|(n8<<3)|r -* SLA r : 0xCB 0x20|r -* SRA r : 0xCB 0x28|r -* SRL r : 0xCB 0x38|r -* STOP : 0x10 0x00 -* SUB A,n : 0xD6 -* SUB A,r : 0x90|r -* SWAP r : 0xCB 0x30|r -* XOR A,n : 0xEE -* XOR A,r : 0xA8|r +#ifndef RGBDS_ASM_LOCALASM_H +#define RGBDS_ASM_LOCALASM_H +/* + * GB Z80 instruction groups + * + * n3 = 3-bit + * n = 8-bit + * nn = 16-bit + * + * ADC A,n : 0xCE + * ADC A,r : 0x88|r + * ADD A,n : 0xC6 + * ADD A,r : 0x80|r + * ADD HL,ss : 0x09|(ss<<4) + * ADD SP,n : 0xE8 + * AND A,n : 0xE6 + * AND A,r : 0xA0|r + * BIT n3,r : 0xCB 0x40|(n3<<3)|r + * CALL cc,nn : 0xC4|(cc<<3) + * CALL nn : 0xCD + * CCF : 0x3F + * CP A,n : 0xFE + * CP A,r : 0xB8|r + * CPL : 0x2F + * DAA : 0x27 + * DEC r : 0x05|(r<<3) + * DEC ss : 0x0B|(ss<<4) + * DI : 0xF3 + * EI : 0xFB + * HALT : 0x76 + * INC r : 0x04|(r<<3) + * INC ss : 0x03|(ss<<4) + * JP HL : 0xE9 + * JP cc,nn : 0xC2|(cc<<3) + * JP nn : 0xC3|(cc<<3) + * JR n : 0x18 + * JR cc,n : 0x20|(cc<<3) + * LD (nn),SP : 0x08 + * LD ($FF00+C),A : 0xE2 + * LD ($FF00+n),A : 0xE0 + * LD (nn),A : 0xEA + * LD (rr),A : 0x02|(rr<<4) // HL+ and HL- included + * LD A,($FF00+C) : 0xF2 + * LD A,($FF00+n) : 0xF0 + * LD A,(nn) : 0xFA + * LD A,(rr) : 0x0A|(rr<<4) // HL+ and HL- included + * LD HL,SP+n : 0xF8 + * LD SP,HL : 0xF9 + * LD r,n : 0x06|(r<<3) + * LD r,r' : 0x40|(r<<3)|r' // NOTE: LD (HL),(HL) not allowed + * LD ss,nn : 0x01|(ss<<4) + * NOP : 0x00 + * OR A,n : 0xF6 + * OR A,r : 0xB0|r + * POP tt : 0xC1|(tt<<4) + * PUSH tt : 0xC5|(tt<<4) + * RES n3,r : 0xCB 0x80|(n3<<3)|r + * RET : 0xC9 + * RET cc : 0xC0|(cc<<3) + * RETI : 0xD9 + * RL r : 0xCB 0x10|r + * RLA : 0x17 + * RLC r : 0xCB 0x00|r + * RLCA : 0x07 + * RR r : 0xCB 0x18|r + * RRA : 0x1F + * RRC r : 0xCB 0x08|r + * RRCA : 0x0F + * RST n : 0xC7|n + * SBC A,n : 0xDE + * SBC A,r : 0x98|r + * SCF : 0x37 + * SET n3,r : 0xCB 0xC0|(n8<<3)|r + * SLA r : 0xCB 0x20|r + * SRA r : 0xCB 0x28|r + * SRL r : 0xCB 0x38|r + * STOP : 0x10 0x00 + * SUB A,n : 0xD6 + * SUB A,r : 0x90|r + * SWAP r : 0xCB 0x30|r + * XOR A,n : 0xEE + * XOR A,r : 0xA8|r */ -#define NAME_DB "db" -#define NAME_DW "dw" -#define NAME_DL "dl" -#define NAME_RB "rb" -#define NAME_RW "rw" +#define NAME_DB "db" +#define NAME_DW "dw" +#define NAME_DL "dl" +#define NAME_RB "rb" +#define NAME_RW "rw" /* "r" defs */ - enum { REG_B = 0, REG_C, @@ -98,36 +100,30 @@ enum { REG_HL_IND, REG_A }; -/* "rr" defs */ +/* "rr" defs */ enum { REG_BC_IND = 0, REG_DE_IND, REG_HL_INDINC, REG_HL_INDDEC, }; -/* "ss" defs */ +/* "ss" defs (SP) and "tt" defs (AF) */ enum { REG_BC = 0, - REG_DE, - REG_HL, - REG_SP + REG_DE = 1, + REG_HL = 2, + REG_SP = 3, + REG_AF = 3 }; -/* "tt" defs */ - -/* -#define REG_BC 0 -#define REG_DE 1 -#define REG_HL 2 - */ -#define REG_AF 3 /* "cc" defs */ - enum { CC_NZ = 0, CC_Z, CC_NC, CC_C }; + +#endif /* RGBDS_ASM_LOCALASM_H */ diff --git a/include/asm/main.h b/include/asm/main.h index 9f62b1a8..8133aa82 100644 --- a/include/asm/main.h +++ b/include/asm/main.h @@ -1,8 +1,9 @@ #ifndef RGBDS_MAIN_H #define RGBDS_MAIN_H -#include #include +#include + #include "extern/stdnoreturn.h" struct sOptions { @@ -12,8 +13,7 @@ struct sOptions { bool verbose; bool haltnop; bool exportall; - bool warnings; /* true to enable warnings, false to disable them. */ - //-1 == random + bool warnings; /* True to enable warnings, false to disable them. */ }; extern char *tzNewMacro; @@ -23,9 +23,10 @@ extern int32_t nBinaryID; extern struct sOptions DefaultOptions; extern struct sOptions CurrentOptions; -extern void opt_Push(void); -extern void opt_Pop(void); -extern void opt_Parse(char *s); + +void opt_Push(void); +void opt_Pop(void); +void opt_Parse(char *s); /* * Used for errors that compromise the whole assembly process by affecting the @@ -35,6 +36,7 @@ extern void opt_Parse(char *s); * when it fails to allocate memory). */ noreturn void fatalerror(const char *fmt, ...); + /* * Used for errors that make it impossible to assemble correctly, but don't * affect the following code. The code will fail to assemble but the user will @@ -42,17 +44,18 @@ noreturn void fatalerror(const char *fmt, ...); * once. */ void yyerror(const char *fmt, ...); + /* * Used to warn the user about problems that don't prevent the generation of * valid code. */ void warning(const char *fmt, ...); -#define YY_FATAL_ERROR fatalerror +#define YY_FATAL_ERROR fatalerror -#ifdef YYLMAX -#undef YYLMAX +#ifdef YYLMAX +#undef YYLMAX #endif #define YYLMAX 65536 -#endif +#endif /* RGBDS_MAIN_H */ diff --git a/include/asm/mylink.h b/include/asm/mylink.h index 65b98bad..c6771069 100644 --- a/include/asm/mylink.h +++ b/include/asm/mylink.h @@ -58,4 +58,5 @@ enum { PATCH_WORD_L, PATCH_LONG_L }; -#endif + +#endif /* RGBDS_ASM_LINK_H */ diff --git a/include/asm/mymath.h b/include/asm/mymath.h index 246009d7..513abc64 100644 --- a/include/asm/mymath.h +++ b/include/asm/mymath.h @@ -18,4 +18,4 @@ int32_t math_Round(int32_t i); int32_t math_Ceil(int32_t i); int32_t math_Floor(int32_t i); -#endif +#endif /* RGBDS_ASM_MATH_H */ diff --git a/include/asm/output.h b/include/asm/output.h index cc8f9543..452f2c31 100644 --- a/include/asm/output.h +++ b/include/asm/output.h @@ -21,21 +21,23 @@ struct Section { void out_PrepPass2(void); void out_SetFileName(char *s); void out_NewSection(char *pzName, uint32_t secttype); -void out_NewAbsSection(char *pzName, uint32_t secttype, int32_t org, int32_t bank); -void out_NewAlignedSection(char *pzName, uint32_t secttype, int32_t alignment, int32_t bank); +void out_NewAbsSection(char *pzName, uint32_t secttype, int32_t org, + int32_t bank); +void out_NewAlignedSection(char *pzName, uint32_t secttype, int32_t alignment, + int32_t bank); void out_AbsByte(int32_t b); void out_AbsByteGroup(char *s, int32_t length); -void out_RelByte(struct Expression * expr); -void out_RelWord(struct Expression * expr); -void out_PCRelByte(struct Expression * expr); +void out_RelByte(struct Expression *expr); +void out_RelWord(struct Expression *expr); +void out_PCRelByte(struct Expression *expr); void out_WriteObject(void); void out_Skip(int32_t skip); void out_BinaryFile(char *s); void out_BinaryFileSlice(char *s, int32_t start_pos, int32_t length); void out_String(char *s); void out_AbsLong(int32_t b); -void out_RelLong(struct Expression * expr); +void out_RelLong(struct Expression *expr); void out_PushSection(void); void out_PopSection(void); -#endif +#endif /* RGBDS_ASM_OUTPUT_H */ diff --git a/include/asm/rpn.h b/include/asm/rpn.h index fe8743ba..1059b2ab 100644 --- a/include/asm/rpn.h +++ b/include/asm/rpn.h @@ -12,36 +12,54 @@ struct Expression { uint32_t isPCRel; }; -uint32_t rpn_isReloc(struct Expression * expr); -uint32_t rpn_isPCRelative(struct Expression * expr); -void rpn_Symbol(struct Expression * expr, char *tzSym); -void rpn_Number(struct Expression * expr, uint32_t i); -void rpn_LOGNOT(struct Expression * expr, struct Expression * src1); -void rpn_LOGOR(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGAND(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGEQU(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGGT(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGLT(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGGE(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGLE(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_LOGNE(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_ADD(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_SUB(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_XOR(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_OR(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_AND(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_SHL(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_SHR(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_MUL(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_DIV(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_MOD(struct Expression * expr, struct Expression * src1, struct Expression * src2); -void rpn_HIGH(struct Expression * expr, struct Expression * src); -void rpn_LOW(struct Expression * expr, struct Expression * src); -void rpn_UNNEG(struct Expression * expr, struct Expression * src); -void rpn_UNNOT(struct Expression * expr, struct Expression * src); -uint16_t rpn_PopByte(struct Expression * expr); -void rpn_Bank(struct Expression * expr, char *tzSym); -void rpn_Reset(struct Expression * expr); -void rpn_CheckHRAM(struct Expression * expr, struct Expression * src1); +uint32_t rpn_isReloc(const struct Expression *expr); +uint32_t rpn_isPCRelative(const struct Expression *expr); +void rpn_Symbol(struct Expression *expr, char *tzSym); +void rpn_Number(struct Expression *expr, uint32_t i); +void rpn_LOGNOT(struct Expression *expr, const struct Expression *src); +void rpn_LOGOR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGAND(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGEQU(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGGT(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGLT(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGGE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGLE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_LOGNE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_ADD(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_SUB(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_XOR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_OR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_AND(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_SHL(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_SHR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_MUL(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_DIV(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_MOD(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2); +void rpn_HIGH(struct Expression *expr, const struct Expression *src); +void rpn_LOW(struct Expression *expr, const struct Expression *src); +void rpn_UNNEG(struct Expression *expr, const struct Expression *src); +void rpn_UNNOT(struct Expression *expr, const struct Expression *src); +uint16_t rpn_PopByte(struct Expression *expr); +void rpn_Bank(struct Expression *expr, char *tzSym); +void rpn_Reset(struct Expression *expr); +void rpn_CheckHRAM(struct Expression *expr, const struct Expression *src); -#endif +#endif /* RGBDS_ASM_RPN_H */ diff --git a/include/asm/symbol.h b/include/asm/symbol.h index b353f1e7..606cb97a 100644 --- a/include/asm/symbol.h +++ b/include/asm/symbol.h @@ -5,8 +5,8 @@ #include "types.h" -#define HASHSIZE (1 << 16) -#define MAXSYMLEN 256 +#define HASHSIZE (1 << 16) +#define MAXSYMLEN 256 struct sSymbol { char tzName[MAXSYMLEN + 1]; @@ -17,27 +17,31 @@ struct sSymbol { struct Section *pSection; uint32_t ulMacroSize; char *pMacro; - int32_t(*Callback) (struct sSymbol *); + int32_t (*Callback)(struct sSymbol *); char tzFileName[_MAX_PATH + 1]; /* File where the symbol was defined. */ uint32_t nFileLine; /* Line where the symbol was defined. */ }; -#define SYMF_RELOC 0x001 /* symbol will be reloc'ed during - * linking, it's absolute value is - * unknown */ -#define SYMF_EQU 0x002 /* symbol is defined using EQU, will - * not be changed during linking */ -#define SYMF_SET 0x004 /* symbol is (re)defined using SET, - * will not be changed during linking */ -#define SYMF_EXPORT 0x008 /* symbol should be exported */ -#define SYMF_IMPORT 0x010 /* symbol is imported, it's value is - * unknown */ -#define SYMF_LOCAL 0x020 /* symbol is a local symbol */ -#define SYMF_DEFINED 0x040 /* symbol has been defined, not only - * referenced */ -#define SYMF_MACRO 0x080 /* symbol is a macro */ -#define SYMF_STRING 0x100 /* symbol is a stringsymbol */ -#define SYMF_CONST 0x200 /* symbol has a constant value, will - * not be changed during linking */ + +/* Symbol will be relocated during linking, it's absolute value is unknown */ +#define SYMF_RELOC 0x001 +/* Symbol is defined using EQU, will not be changed during linking */ +#define SYMF_EQU 0x002 +/* Symbol is (re)defined using SET, will not be changed during linking */ +#define SYMF_SET 0x004 +/* Symbol should be exported */ +#define SYMF_EXPORT 0x008 +/* Symbol is imported, it's value is unknown */ +#define SYMF_IMPORT 0x010 +/* Symbol is a local symbol */ +#define SYMF_LOCAL 0x020 +/* Symbol has been defined, not only referenced */ +#define SYMF_DEFINED 0x040 +/* Symbol is a macro */ +#define SYMF_MACRO 0x080 +/* Symbol is a stringsymbol */ +#define SYMF_STRING 0x100 +/* Symbol has a constant value, will not be changed during linking */ +#define SYMF_CONST 0x200 uint32_t calchash(char *s); void sym_SetExportAll(uint8_t set); @@ -76,4 +80,4 @@ void sym_Purge(char *tzName); uint32_t sym_isConstDefined(char *tzName); int32_t sym_IsRelocDiffDefined(char *tzSym1, char *tzSym2); -#endif +#endif /* RGBDS_SYMBOL_H */ diff --git a/src/asm/asmy.y b/src/asm/asmy.y index fa2f0aa6..59237b19 100644 --- a/src/asm/asmy.y +++ b/src/asm/asmy.y @@ -7,25 +7,26 @@ #include #include -#include "asm/symbol.h" #include "asm/asm.h" #include "asm/charmap.h" -#include "asm/output.h" -#include "asm/mylink.h" #include "asm/fstack.h" -#include "asm/mymath.h" -#include "asm/rpn.h" -#include "asm/main.h" #include "asm/lexer.h" +#include "asm/main.h" +#include "asm/mylink.h" +#include "asm/mymath.h" +#include "asm/output.h" +#include "asm/rpn.h" +#include "asm/symbol.h" char *tzNewMacro; uint32_t ulNewMacroSize; -void -bankrangecheck(char *name, uint32_t secttype, int32_t org, int32_t bank) +static void bankrangecheck(char *name, uint32_t secttype, int32_t org, + int32_t bank) { int32_t minbank = 0, maxbank = 0; char *stype = NULL; + switch (secttype) { case SECT_ROMX: stype = "ROMX"; @@ -48,18 +49,16 @@ bankrangecheck(char *name, uint32_t secttype, int32_t org, int32_t bank) maxbank = 1; break; default: - yyerror("BANK only allowed for " - "ROMX, WRAMX, SRAM, or VRAM sections"); + yyerror("BANK only allowed for ROMX, WRAMX, SRAM, or VRAM sections"); } if (stype && (bank < minbank || bank > maxbank)) { yyerror("%s bank value $%x out of range ($%x to $%x)", - stype, bank, minbank, maxbank); + stype, bank, minbank, maxbank); } - if (secttype == SECT_WRAMX) { + if (secttype == SECT_WRAMX) bank -= minbank; - } out_NewAbsSection(name, secttype, org, bank); } @@ -73,253 +72,235 @@ size_t symvaluetostring(char *dest, size_t maxLength, char *sym) size_t i; for (i = 0; src[i] != 0; i++) { - if (i >= maxLength) { + if (i >= maxLength) fatalerror("Symbol value too long to fit buffer"); - } + dest[i] = src[i]; } length = i; + } else { uint32_t value = sym_GetConstantValue(sym); - int32_t fullLength = snprintf(dest, maxLength + 1, "$%X", value); + int32_t fullLength = snprintf(dest, maxLength + 1, "$%X", + value); if (fullLength < 0) { fatalerror("snprintf encoding error"); } else { length = (size_t)fullLength; - - if (length > maxLength) { + if (length > maxLength) fatalerror("Symbol value too long to fit buffer"); - } } } return length; } -uint32_t str2int( char *s ) +static uint32_t str2int(char *s) { - uint32_t r=0; - while( *s ) - { - r<<=8; - r|=(uint8_t)(*s++); + uint32_t r = 0; + + while (*s) { + r <<= 8; + r |= (uint8_t)(*s++); } - return( r ); + + return r; } -uint32_t str2int2( char *s, int32_t length ) +static uint32_t str2int2(char *s, int32_t length) { int32_t i; - uint32_t r=0; - i = (length - 4 < 0 ? 0 : length - 4); - while(i < length) - { - r<<=8; - r|=(uint8_t)(s[i]); + uint32_t r = 0; + + i = ((length - 4) < 0) ? 0 : length - 4; + while (i < length) { + r <<= 8; + r |= (uint8_t)s[i]; i++; } - return( r ); + + return r; } -uint32_t isWhiteSpace( char s ) +static uint32_t isWhiteSpace(char s) { - return( s==' ' || s=='\t' || s=='\0' || s=='\n' ); + return (s == ' ') || (s == '\t') || (s == '\0') || (s == '\n'); } -uint32_t isRept( char *s ) +static uint32_t isRept(char *s) { - return( (strncasecmp(s,"REPT",4)==0) && isWhiteSpace(*(s-1)) && isWhiteSpace(s[4]) ); + return (strncasecmp(s, "REPT", 4) == 0) + && isWhiteSpace(*(s - 1)) && isWhiteSpace(s[4]); } -uint32_t isEndr( char *s ) +static uint32_t isEndr(char *s) { - return( (strncasecmp(s,"Endr",4)==0) && isWhiteSpace(*(s-1)) && isWhiteSpace(s[4]) ); + return (strncasecmp(s, "ENDR", 4) == 0) + && isWhiteSpace(*(s - 1)) && isWhiteSpace(s[4]); } -void copyrept( void ) +static void copyrept(void) { - int32_t level=1, len, instring=0; - char *src=pCurrentBuffer->pBuffer; - char *bufferEnd = pCurrentBuffer->pBufferStart + pCurrentBuffer->nBufferSize; + int32_t level = 1, len, instring = 0; + char *src = pCurrentBuffer->pBuffer; + char *bufferEnd = pCurrentBuffer->pBufferStart + + pCurrentBuffer->nBufferSize; - while( src < bufferEnd && level ) - { - if( instring==0 ) - { - if( isRept(src) ) - { - level+=1; - src+=4; + while (src < bufferEnd && level) { + if (instring == 0) { + if (isRept(src)) { + level += 1; + src += 4; + } else if (isEndr(src)) { + level -= 1; + src += 4; + } else { + if (*src == '\"') + instring = 1; + src += 1; } - else if( isEndr(src) ) - { - level-=1; - src+=4; - } - else - { - if( *src=='\"' ) - instring=1; - src+=1; - } - } - else - { - if( *src=='\\' ) - { - src+=2; - } - else if( *src=='\"' ) - { - src+=1; - instring=0; - } - else - { - src+=1; + } else { + if (*src == '\\') { + src += 2; + } else if (*src == '\"') { + src += 1; + instring = 0; + } else { + src += 1; } } } - if (level != 0) { + if (level != 0) fatalerror("Unterminated REPT block"); + + len = src - pCurrentBuffer->pBuffer - 4; + + src = pCurrentBuffer->pBuffer; + ulNewMacroSize = len; + + tzNewMacro = malloc(ulNewMacroSize + 1); + + if (tzNewMacro == NULL) + fatalerror("Not enough memory for REPT block."); + + uint32_t i; + + tzNewMacro[ulNewMacroSize] = 0; + for (i = 0; i < ulNewMacroSize; i += 1) { + tzNewMacro[i] = src[i]; + if (src[i] == '\n') + nLineNo+=1; } - len=src-pCurrentBuffer->pBuffer-4; - - src=pCurrentBuffer->pBuffer; - ulNewMacroSize=len; - - if ((tzNewMacro = malloc(ulNewMacroSize + 1)) != NULL) { - uint32_t i; - - tzNewMacro[ulNewMacroSize]=0; - for( i=0; ipBuffer; - char *bufferEnd = pCurrentBuffer->pBufferStart + pCurrentBuffer->nBufferSize; + int32_t level = 1, len, instring = 0; + char *src = pCurrentBuffer->pBuffer; + char *bufferEnd = pCurrentBuffer->pBufferStart + + pCurrentBuffer->nBufferSize; - while( src < bufferEnd && level ) - { - if( instring==0 ) - { - if( isMacro(src) ) - { - level+=1; - src+=4; + while (src < bufferEnd && level) { + if (instring == 0) { + if (isMacro(src)) { + level += 1; + src += 4; + } else if (isEndm(src)) { + level -= 1; + src += 4; + } else { + if(*src == '\"') + instring = 1; + src += 1; } - else if( isEndm(src) ) - { - level-=1; - src+=4; - } - else - { - if( *src=='\"' ) - instring=1; - src+=1; - } - } - else - { - if( *src=='\\' ) - { - src+=2; - } - else if( *src=='\"' ) - { - src+=1; - instring=0; - } - else - { - src+=1; + } else { + if (*src == '\\') { + src += 2; + } else if (*src == '\"') { + src += 1; + instring = 0; + } else { + src += 1; } } } - if (level != 0) { - fatalerror("Unterminated MACRO definition"); + if (level != 0) + fatalerror("Unterminated MACRO definition."); + + len = src - pCurrentBuffer->pBuffer - 4; + + src = pCurrentBuffer->pBuffer; + ulNewMacroSize = len; + + tzNewMacro = (char *)malloc(ulNewMacroSize+2); + if (tzNewMacro == NULL) + fatalerror("Not enough memory for MACRO definition."); + + uint32_t i; + + tzNewMacro[ulNewMacroSize] = '\n'; + tzNewMacro[ulNewMacroSize+1] = 0; + for (i = 0; i < ulNewMacroSize; i += 1) { + tzNewMacro[i] = src[i]; + if (src[i] == '\n') + nLineNo += 1; } - len=src-pCurrentBuffer->pBuffer-4; - - src=pCurrentBuffer->pBuffer; - ulNewMacroSize=len; - - if( (tzNewMacro=(char *)malloc(ulNewMacroSize+2))!=NULL ) - { - uint32_t i; - - tzNewMacro[ulNewMacroSize]='\n'; - tzNewMacro[ulNewMacroSize+1]=0; - for( i=0; ipBuffer; + char *src = pCurrentBuffer->pBuffer; while (*src && level) { - if (*src == '\n') { + if (*src == '\n') nLineNo++; - } if (!inString) { if (isIf(src)) { @@ -336,14 +317,12 @@ void if_skip_to_else() } else if (isEndc(src)) { level--; - if (level != 0) { + if (level != 0) src += 4; - } } else { - if (*src=='\"') { + if (*src == '\"') inString = true; - } src++; } } else { @@ -363,9 +342,8 @@ void if_skip_to_else() } } - if (level != 0) { + if (level != 0) fatalerror("Unterminated IF construct"); - } int32_t len = src - pCurrentBuffer->pBuffer; @@ -374,37 +352,32 @@ void if_skip_to_else() nLineNo--; } -void if_skip_to_endc() +static void if_skip_to_endc(void) { int32_t level = 1; bool inString = false; - char *src=pCurrentBuffer->pBuffer; + char *src = pCurrentBuffer->pBuffer; while (*src && level) { - if (*src == '\n') { + if (*src == '\n') nLineNo++; - } if (!inString) { if (isIf(src)) { level++; src += 2; - } else if (isEndc(src)) { level--; - if (level != 0) { + if (level != 0) src += 4; - } - } else { - if (*src=='\"') { + if (*src == '\"') inString = true; - } src++; } - } - else { + } else { switch (*src) { + case '\\': src += 2; break; @@ -421,9 +394,8 @@ void if_skip_to_endc() } } - if (level != 0) { + if (level != 0) fatalerror("Unterminated IF construct"); - } int32_t len = src - pCurrentBuffer->pBuffer; @@ -432,28 +404,28 @@ void if_skip_to_endc() nLineNo--; } -void startUnion() { - if (!pCurrentSection) { +static void startUnion(void) +{ + if (!pCurrentSection) fatalerror("UNIONs must be inside a SECTION"); - } uint32_t unionIndex = nUnionDepth; + nUnionDepth++; - if (nUnionDepth > MAXUNIONS) { + if (nUnionDepth > MAXUNIONS) fatalerror("Too many nested UNIONs"); - } unionStart[unionIndex] = nPC; unionSize[unionIndex] = 0; } -void updateUnion() { +static void updateUnion(void) +{ uint32_t unionIndex = nUnionDepth - 1; uint32_t size = nPC - unionStart[unionIndex]; - if (size > unionSize[unionIndex]) { + if (size > unionSize[unionIndex]) unionSize[unionIndex] = size; - } nPC = unionStart[unionIndex]; pCurrentSection->nPC = unionStart[unionIndex]; @@ -464,24 +436,24 @@ void updateUnion() { %union { - char tzSym[MAXSYMLEN + 1]; - char tzString[MAXSTRLEN + 1]; - struct Expression sVal; - int32_t nConstValue; + char tzSym[MAXSYMLEN + 1]; + char tzString[MAXSTRLEN + 1]; + struct Expression sVal; + int32_t nConstValue; } -%type relocconst +%type relocconst %type const %type uconst %type const_3bit -%type const_8bit -%type const_16bit -%type const_PCrel +%type const_8bit +%type const_16bit +%type const_PCrel %type sectiontype %type string -%token T_NUMBER +%token T_NUMBER %token T_STRING %left T_OP_LOGICNOT @@ -517,7 +489,7 @@ void updateUnion() { %left T_OP_STRUPR %left T_OP_STRLWR -%left NEG /* negation--unary minus */ +%left NEG /* negation -- unary minus */ %token T_LABEL %token T_ID @@ -525,7 +497,8 @@ void updateUnion() { %token T_POP_SET %token T_POP_EQUS -%token T_POP_INCLUDE T_POP_PRINTF T_POP_PRINTT T_POP_PRINTV T_POP_IF T_POP_ELIF T_POP_ELSE T_POP_ENDC +%token T_POP_INCLUDE T_POP_PRINTF T_POP_PRINTT T_POP_PRINTV +%token T_POP_IF T_POP_ELIF T_POP_ELSE T_POP_ENDC %token T_POP_IMPORT T_POP_EXPORT T_POP_GLOBAL %token T_POP_DB T_POP_DS T_POP_DW T_POP_DL %token T_POP_SECTION @@ -548,7 +521,8 @@ void updateUnion() { %token T_POP_POPO %token T_POP_PUSHO %token T_POP_OPT -%token T_SECT_WRAM0 T_SECT_VRAM T_SECT_ROMX T_SECT_ROM0 T_SECT_HRAM T_SECT_WRAMX T_SECT_SRAM T_SECT_OAM +%token T_SECT_WRAM0 T_SECT_VRAM T_SECT_ROMX T_SECT_ROM0 T_SECT_HRAM +%token T_SECT_WRAMX T_SECT_SRAM T_SECT_OAM %token T_SECT_HOME T_SECT_DATA T_SECT_CODE T_SECT_BSS %token T_Z80_ADC T_Z80_ADD T_Z80_AND @@ -587,1249 +561,1504 @@ void updateUnion() { %type reg_rr %type reg_tt %type ccode -%type op_a_n +%type op_a_n %type op_a_r %type op_hl_ss -%type op_mem_ind +%type op_mem_ind %start asmfile %% -asmfile : lines; +asmfile : lines; -/* Note: The lexer add '\n' at the end of the input */ -lines : /* empty */ - | lines line '\n' { - nLineNo += 1; - nTotalLines += 1; - }; - -line : label - | label cpu_command - | label macro - | label simple_pseudoop - | pseudoop; - -label : /* empty */ - | T_LABEL { - if ($1[0] == '.') - sym_AddLocalReloc($1); - else - sym_AddReloc($1); - } | T_LABEL ':' { - if ($1[0] == '.') - sym_AddLocalReloc($1); - else - sym_AddReloc($1); - } | T_LABEL ':' ':' { - if ($1[0] == '.') { - sym_AddLocalReloc($1); - } else { - sym_AddReloc($1); +/* Note: The lexer adds '\n' at the end of the input */ +lines : /* empty */ + | lines line '\n' { + nLineNo += 1; + nTotalLines += 1; } - sym_Export($1); - }; +; -macro : T_ID { - yy_set_state(LEX_STATE_MACROARGS); - } macroargs { - yy_set_state(LEX_STATE_NORMAL); +line : label + | label cpu_command + | label macro + | label simple_pseudoop + | pseudoop +; - if (!fstk_RunMacro($1)) { - fatalerror("Macro '%s' not defined", $1); +label : /* empty */ + | T_LABEL + { + if ($1[0] == '.') + sym_AddLocalReloc($1); + else + sym_AddReloc($1); + } + | T_LABEL ':' + { + if ($1[0] == '.') + sym_AddLocalReloc($1); + else + sym_AddReloc($1); + } + | T_LABEL ':' ':' + { + if ($1[0] == '.') + sym_AddLocalReloc($1); + else + sym_AddReloc($1); + sym_Export($1); } - }; - -macroargs : /* empty */ - | macroarg - | macroarg ',' macroargs; - -macroarg : T_STRING { - sym_AddNewMacroArg($1); - }; - -pseudoop : equ - | set - | rb - | rw - | rl - | equs - | macrodef; - -simple_pseudoop : include - | printf - | printt - | printv - | if - | elif - | else - | endc - | import - | export - | global - | db - | dw - | dl - | ds - | section - | rsreset - | rsset - | union - | nextu - | endu - | incbin - | charmap - | rept - | shift - | fail - | warn - | purge - | pops - | pushs - | popo - | pusho - | opt; - -opt : T_POP_OPT { - yy_set_state(LEX_STATE_MACROARGS); - } opt_list { - yy_set_state(LEX_STATE_NORMAL); - }; - -opt_list : opt_list_entry - | opt_list_entry ',' opt_list; - -opt_list_entry : T_STRING { - opt_Parse($1); - }; - -popo : T_POP_POPO { - opt_Pop(); - }; - -pusho : T_POP_PUSHO { - opt_Push(); - }; - -pops : T_POP_POPS { - out_PopSection(); - }; - -pushs : T_POP_PUSHS { - out_PushSection(); - }; - -fail : T_POP_FAIL string { - fatalerror("%s", $2); - }; - -warn : T_POP_WARN string { - warning("%s", $2); - }; - -shift : T_POP_SHIFT - { sym_ShiftCurrentMacroArgs(); } ; -rept : T_POP_REPT uconst - { - copyrept(); - fstk_RunRept( $2 ); - } +macro : T_ID { + yy_set_state(LEX_STATE_MACROARGS); + } macroargs { + yy_set_state(LEX_STATE_NORMAL); + if (!fstk_RunMacro($1)) + fatalerror("Macro '%s' not defined", $1); + } ; -macrodef : T_LABEL ':' T_POP_MACRO - { - copymacro(); - sym_AddMacro($1); - } +macroargs : /* empty */ + | macroarg + | macroarg comma macroargs ; -equs : T_LABEL T_POP_EQUS string - { sym_AddString( $1, $3 ); } +macroarg : T_STRING { sym_AddNewMacroArg($1); } ; -rsset : T_POP_RSSET uconst - { sym_AddSet( "_RS", $2 ); } +pseudoop : equ + | set + | rb + | rw + | rl + | equs + | macrodef ; -rsreset : T_POP_RSRESET - { sym_AddSet( "_RS", 0 ); } +simple_pseudoop : include + | printf + | printt + | printv + | if + | elif + | else + | endc + | import + | export + | global + | db + | dw + | dl + | ds + | section + | rsreset + | rsset + | union + | nextu + | endu + | incbin + | charmap + | rept + | shift + | fail + | warn + | purge + | pops + | pushs + | popo + | pusho + | opt ; -rl : T_LABEL T_POP_RL uconst - { - sym_AddEqu( $1, sym_GetConstantValue("_RS") ); - sym_AddSet( "_RS", sym_GetConstantValue("_RS")+4*$3 ); - } +opt : T_POP_OPT { + yy_set_state(LEX_STATE_MACROARGS); + } opt_list { + yy_set_state(LEX_STATE_NORMAL); + } ; -rw : T_LABEL T_POP_RW uconst - { - sym_AddEqu( $1, sym_GetConstantValue("_RS") ); - sym_AddSet( "_RS", sym_GetConstantValue("_RS")+2*$3 ); - } +opt_list : opt_list_entry + | opt_list_entry comma opt_list ; -rb : T_LABEL T_POP_RB uconst - { - sym_AddEqu( $1, sym_GetConstantValue("_RS") ); - sym_AddSet( "_RS", sym_GetConstantValue("_RS")+$3 ); - } +opt_list_entry : T_STRING { opt_Parse($1); } ; -union : T_POP_UNION { - startUnion(); - }; - -nextu : T_POP_NEXTU { - if (nUnionDepth <= 0) { - fatalerror("Found NEXTU outside of a UNION construct"); - } - - updateUnion(); - }; - -endu : T_POP_ENDU { - if (nUnionDepth <= 0) { - fatalerror("Found ENDU outside of a UNION construct"); - } - - updateUnion(); - - nUnionDepth--; - nPC = unionStart[nUnionDepth] + unionSize[nUnionDepth]; - pCurrentSection->nPC = nPC; - pPCSymbol->nValue = nPC; - }; - -ds : T_POP_DS uconst - { out_Skip( $2 ); } +popo : T_POP_POPO { opt_Pop(); } ; -db : T_POP_DB constlist_8bit_entry ',' constlist_8bit - | T_POP_DB constlist_8bit_entry_single +pusho : T_POP_PUSHO { opt_Push(); } ; -dw : T_POP_DW constlist_16bit_entry ',' constlist_16bit - | T_POP_DW constlist_16bit_entry_single +pops : T_POP_POPS { out_PopSection(); } ; -dl : T_POP_DL constlist_32bit_entry ',' constlist_32bit - | T_POP_DL constlist_32bit_entry_single +pushs : T_POP_PUSHS { out_PushSection(); } ; -purge : T_POP_PURGE - { - oDontExpandStrings = true; - } - purge_list - { - oDontExpandStrings = false; - } +fail : T_POP_FAIL string { fatalerror("%s", $2); } ; -purge_list : purge_list_entry - | purge_list_entry ',' purge_list +warn : T_POP_WARN string { warning("%s", $2); } ; -purge_list_entry : T_ID { sym_Purge($1); } +shift : T_POP_SHIFT { sym_ShiftCurrentMacroArgs(); } ; -import : T_POP_IMPORT import_list +rept : T_POP_REPT uconst + { + copyrept(); + fstk_RunRept($2); + } ; -import_list : import_list_entry - | import_list_entry ',' import_list +macrodef : T_LABEL ':' T_POP_MACRO + { + copymacro(); + sym_AddMacro($1); + } ; -import_list_entry : T_ID { - /* This is done automatically if the label isn't found - * in the list of defined symbols. */ - if( nPass==1 ) - warning("IMPORT is a deprecated keyword with no effect: %s", $1); - } +equs : T_LABEL T_POP_EQUS string + { + sym_AddString($1, $3); + } ; -export : T_POP_EXPORT export_list +rsset : T_POP_RSSET uconst + { + sym_AddSet("_RS", $2); + } ; -export_list : export_list_entry - | export_list_entry ',' export_list +rsreset : T_POP_RSRESET + { + sym_AddSet("_RS", 0); + } ; -export_list_entry : T_ID { sym_Export($1); } +rl : T_LABEL T_POP_RL uconst + { + sym_AddEqu($1, sym_GetConstantValue("_RS")); + sym_AddSet("_RS", sym_GetConstantValue("_RS") + 4 * $3); + } ; -global : T_POP_GLOBAL global_list +rw : T_LABEL T_POP_RW uconst + { + sym_AddEqu($1, sym_GetConstantValue("_RS")); + sym_AddSet("_RS", sym_GetConstantValue("_RS") + 2 * $3); + } ; -global_list : global_list_entry - | global_list_entry ',' global_list +rb : T_LABEL T_POP_RB uconst + { + sym_AddEqu($1, sym_GetConstantValue("_RS")); + sym_AddSet("_RS", sym_GetConstantValue("_RS") + $3); + } ; -global_list_entry : T_ID { sym_Global($1); } +union : T_POP_UNION + { + startUnion(); + } ; -equ : T_LABEL T_POP_EQU const - { sym_AddEqu( $1, $3 ); } +nextu : T_POP_NEXTU + { + if (nUnionDepth <= 0) + fatalerror("Found NEXTU outside of a UNION construct"); + + updateUnion(); + } ; -set : T_LABEL T_POP_SET const - { sym_AddSet( $1, $3 ); } +endu : T_POP_ENDU + { + if (nUnionDepth <= 0) + fatalerror("Found ENDU outside of a UNION construct"); + + updateUnion(); + + nUnionDepth--; + nPC = unionStart[nUnionDepth] + unionSize[nUnionDepth]; + pCurrentSection->nPC = nPC; + pPCSymbol->nValue = nPC; + } ; -include : T_POP_INCLUDE string - { - fstk_RunInclude($2); - } +ds : T_POP_DS uconst + { + out_Skip($2); + } ; -incbin : T_POP_INCBIN string - { out_BinaryFile( $2 ); } - | T_POP_INCBIN string ',' uconst ',' uconst - { - out_BinaryFileSlice( $2, $4, $6 ); - } +db : T_POP_DB constlist_8bit_entry comma constlist_8bit + | T_POP_DB constlist_8bit_entry_single ; -charmap : T_POP_CHARMAP string ',' string - { - if(charmap_Add($2, $4[0] & 0xFF) == -1) - { - fprintf(stderr, "Error parsing charmap. Either you've added too many (%i), or the input character length is too long (%i)' : %s\n", MAXCHARMAPS, CHARMAPLENGTH, strerror(errno)); - yyerror("Error parsing charmap."); - } - } - | T_POP_CHARMAP string ',' const - { - if(charmap_Add($2, $4 & 0xFF) == -1) - { - fprintf(stderr, "Error parsing charmap. Either you've added too many (%i), or the input character length is too long (%i)' : %s\n", MAXCHARMAPS, CHARMAPLENGTH, strerror(errno)); - yyerror("Error parsing charmap."); - } - } +dw : T_POP_DW constlist_16bit_entry comma constlist_16bit + | T_POP_DW constlist_16bit_entry_single ; -printt : T_POP_PRINTT string - { - if( nPass==1 ) - printf( "%s", $2 ); - } +dl : T_POP_DL constlist_32bit_entry comma constlist_32bit + | T_POP_DL constlist_32bit_entry_single ; -printv : T_POP_PRINTV const - { - if( nPass==1 ) - printf( "$%X", $2 ); - } +purge : T_POP_PURGE { + oDontExpandStrings = true; + } purge_list { + oDontExpandStrings = false; + } ; -printf : T_POP_PRINTF const - { - if( nPass==1 ) - math_Print( $2 ); - } +purge_list : purge_list_entry + | purge_list_entry comma purge_list ; -if : T_POP_IF const { - nIFDepth++; - if (!$2) { - if_skip_to_else(); // Continue parsing after ELSE, or at ELIF or ENDC keyword - } - }; - -elif : T_POP_ELIF const { - if (nIFDepth <= 0) { - fatalerror("Found ELIF outside an IF construct"); - } - - if (skipElif) { - // This is for when ELIF is reached at the end of an IF or ELIF block for which the condition was true. - if_skip_to_endc(); // Continue parsing at ENDC keyword - - } else { - // This is for when ELIF is skipped to because the condition of the previous IF or ELIF block was false. - skipElif = true; - - if (!$2) { - if_skip_to_else(); // Continue parsing after ELSE, or at ELIF or ENDC keyword - } - } - }; - -else : T_POP_ELSE { - if (nIFDepth <= 0) { - fatalerror("Found ELSE outside an IF construct"); - } - - if_skip_to_endc(); // Continue parsing at ENDC keyword - }; - -endc : T_POP_ENDC { - if (nIFDepth <= 0) { - fatalerror("Found ENDC outside an IF construct"); - } - - nIFDepth--; - }; - -const_3bit : const - { - if( ($1<0) || ($1>7) ) - { - yyerror("Immediate value must be 3-bit"); - } - else - $$=$1&0x7; - } +purge_list_entry : T_ID + { + sym_Purge($1); + } ; -constlist_8bit : constlist_8bit_entry - | constlist_8bit_entry ',' constlist_8bit +import : T_POP_IMPORT import_list ; -constlist_8bit_entry : /* empty */ { - out_Skip( 1 ); - if( nPass==1 ) - warning("Empty entry in list of 8-bit elements (treated as 0)."); - } | const_8bit { - out_RelByte( &$1 ); - } | string { - char *s = $1; - int32_t length = charmap_Convert(&s); - out_AbsByteGroup(s, length); - free(s); - } +import_list : import_list_entry + | import_list_entry comma import_list ; -constlist_8bit_entry_single : /* empty */ { - out_Skip( 1 ); - } | const_8bit { - out_RelByte( &$1 ); - } | string { - char *s = $1; - int32_t length = charmap_Convert(&s); - out_AbsByteGroup(s, length); - free(s); - } +import_list_entry : T_ID + { + /* + * This is done automatically if the label isn't found + * in the list of defined symbols. + */ + if (nPass == 1) + warning("IMPORT is a deprecated keyword with no effect: %s", $1); + } +; + +export : T_POP_EXPORT export_list +; + +export_list : export_list_entry + | export_list_entry comma export_list +; + +export_list_entry : T_ID + { + sym_Export($1); + } +; + +global : T_POP_GLOBAL global_list +; + +global_list : global_list_entry + | global_list_entry comma global_list +; + +global_list_entry : T_ID + { + sym_Global($1); + } +; + +equ : T_LABEL T_POP_EQU const + { + sym_AddEqu($1, $3); + } +; + +set : T_LABEL T_POP_SET const + { + sym_AddSet($1, $3); + } +; + +include : T_POP_INCLUDE string + { + fstk_RunInclude($2); + } +; + +incbin : T_POP_INCBIN string + { + out_BinaryFile($2); + } + | T_POP_INCBIN string comma uconst comma uconst + { + out_BinaryFileSlice($2, $4, $6); + } +; + +charmap : T_POP_CHARMAP string comma string + { + if (charmap_Add($2, $4[0] & 0xFF) == -1) { + fprintf(stderr, "Error parsing charmap. Either you've added too many (%i), or the input character length is too long (%i)' : %s\n", MAXCHARMAPS, CHARMAPLENGTH, strerror(errno)); + yyerror("Error parsing charmap."); + } + } + | T_POP_CHARMAP string comma const + { + if (charmap_Add($2, $4 & 0xFF) == -1) { + fprintf(stderr, "Error parsing charmap. Either you've added too many (%i), or the input character length is too long (%i)' : %s\n", MAXCHARMAPS, CHARMAPLENGTH, strerror(errno)); + yyerror("Error parsing charmap."); + } + } +; + +printt : T_POP_PRINTT string + { + if (nPass == 1) + printf("%s", $2); + } +; + +printv : T_POP_PRINTV const + { + if (nPass == 1) + printf("$%X", $2); + } +; + +printf : T_POP_PRINTF const + { + if (nPass == 1) + math_Print($2); + } +; + +if : T_POP_IF const + { + nIFDepth++; + if (!$2) { + /* + * Continue parsing after ELSE, or at ELIF or + * ENDC keyword. + */ + if_skip_to_else(); + } + } +; + +elif : T_POP_ELIF const + { + if (nIFDepth <= 0) + fatalerror("Found ELIF outside an IF construct"); + + if (skipElif) { + /* + * Executed when ELIF is reached at the end of + * an IF or ELIF block for which the condition + * was true. + * + * Continue parsing at ENDC keyword + */ + if_skip_to_endc(); + } else { + /* + * Executed when ELIF is skipped to because the + * condition of the previous IF or ELIF block + * was false. + */ + skipElif = true; + + if (!$2) { + /* + * Continue parsing after ELSE, or at + * ELIF or ENDC keyword. + */ + if_skip_to_else(); + } + } + } +; + +else : T_POP_ELSE + { + if (nIFDepth <= 0) + fatalerror("Found ELSE outside an IF construct"); + + /* Continue parsing at ENDC keyword */ + if_skip_to_endc(); + } +; + +endc : T_POP_ENDC + { + if (nIFDepth <= 0) + fatalerror("Found ENDC outside an IF construct"); + + nIFDepth--; + } +; + +const_3bit : const + { + if (($1 < 0) || ($1 > 7)) + yyerror("Immediate value must be 3-bit"); + else + $$ = $1 & 0x7; + } +; + +constlist_8bit : constlist_8bit_entry + | constlist_8bit_entry comma constlist_8bit +; + +constlist_8bit_entry : /* empty */ + { + out_Skip(1); + if (nPass == 1) + warning("Empty entry in list of 8-bit elements (treated as 0)."); + } + | const_8bit + { + out_RelByte(&$1); + } + | string + { + char *s = $1; + int32_t length = charmap_Convert(&s); + + out_AbsByteGroup(s, length); + free(s); + } +; + +constlist_8bit_entry_single : /* empty */ + { + out_Skip(1); + } + | const_8bit + { + out_RelByte(&$1); + } + | string + { + char *s = $1; + int32_t length = charmap_Convert(&s); + + out_AbsByteGroup(s, length); + free(s); + } ; constlist_16bit : constlist_16bit_entry - | constlist_16bit_entry ',' constlist_16bit + | constlist_16bit_entry comma constlist_16bit ; -constlist_16bit_entry : /* empty */ { - out_Skip( 2 ); - if( nPass==1 ) - warning("Empty entry in list of 16-bit elements (treated as 0)."); - } | const_16bit { - out_RelWord( &$1 ); - } +constlist_16bit_entry : /* empty */ + { + out_Skip(2); + if (nPass == 1) + warning("Empty entry in list of 16-bit elements (treated as 0)."); + } + | const_16bit + { + out_RelWord(&$1); + } ; -constlist_16bit_entry_single : /* empty */ { - out_Skip( 2 ); - } | const_16bit { - out_RelWord( &$1 ); - } +constlist_16bit_entry_single : /* empty */ + { + out_Skip(2); + } + | const_16bit + { + out_RelWord(&$1); + } ; constlist_32bit : constlist_32bit_entry - | constlist_32bit_entry ',' constlist_32bit + | constlist_32bit_entry comma constlist_32bit ; -constlist_32bit_entry : /* empty */ { - out_Skip( 4 ); - if( nPass==1 ) - warning("Empty entry in list of 32-bit elements (treated as 0)."); - } | relocconst { - out_RelLong( &$1 ); - } -; - -constlist_32bit_entry_single : /* empty */ { - out_Skip( 4 ); - } | relocconst { - out_RelLong( &$1 ); - } -; - -const_PCrel : relocconst - { - $$ = $1; - if( !rpn_isPCRelative(&$1) ) - yyerror("Expression must be PC-relative"); - } -; - -const_8bit : relocconst - { - if( (!rpn_isReloc(&$1)) && (($1.nVal<-128) || ($1.nVal>255)) ) - { - yyerror("Expression must be 8-bit"); - } - $$=$1; - } -; - -const_16bit : relocconst - { - if( (!rpn_isReloc(&$1)) && (($1.nVal<-32768) || ($1.nVal>65535)) ) - { - yyerror("Expression must be 16-bit"); - } - $$=$1; - } -; - - -relocconst : T_ID - { rpn_Symbol(&$$,$1); $$.nVal = sym_GetValue($1); } - | T_NUMBER - { rpn_Number(&$$,$1); $$.nVal = $1; } - | string - { - char *s = $1; - int32_t length = charmap_Convert(&s); - uint32_t r = str2int2(s, length); - free(s); - rpn_Number(&$$,r); - $$.nVal=r; - } - | T_OP_LOGICNOT relocconst %prec NEG - { rpn_LOGNOT(&$$,&$2); } - | relocconst T_OP_LOGICOR relocconst - { rpn_LOGOR(&$$,&$1,&$3); } - | relocconst T_OP_LOGICAND relocconst - { rpn_LOGAND(&$$,&$1,&$3); } - | relocconst T_OP_LOGICEQU relocconst - { rpn_LOGEQU(&$$,&$1,&$3); } - | relocconst T_OP_LOGICGT relocconst - { rpn_LOGGT(&$$,&$1,&$3); } - | relocconst T_OP_LOGICLT relocconst - { rpn_LOGLT(&$$,&$1,&$3); } - | relocconst T_OP_LOGICGE relocconst - { rpn_LOGGE(&$$,&$1,&$3); } - | relocconst T_OP_LOGICLE relocconst - { rpn_LOGLE(&$$,&$1,&$3); } - | relocconst T_OP_LOGICNE relocconst - { rpn_LOGNE(&$$,&$1,&$3); } - | relocconst T_OP_ADD relocconst - { rpn_ADD(&$$,&$1,&$3); } - | relocconst T_OP_SUB relocconst - { rpn_SUB(&$$,&$1,&$3); } - | relocconst T_OP_XOR relocconst - { rpn_XOR(&$$,&$1,&$3); } - | relocconst T_OP_OR relocconst - { rpn_OR(&$$,&$1,&$3); } - | relocconst T_OP_AND relocconst - { rpn_AND(&$$,&$1,&$3); } - | relocconst T_OP_SHL relocconst - { rpn_SHL(&$$,&$1,&$3); } - | relocconst T_OP_SHR relocconst - { rpn_SHR(&$$,&$1,&$3); } - | relocconst T_OP_MUL relocconst - { rpn_MUL(&$$,&$1,&$3); } - | relocconst T_OP_DIV relocconst - { rpn_DIV(&$$,&$1,&$3); } - | relocconst T_OP_MOD relocconst - { rpn_MOD(&$$,&$1,&$3); } - | T_OP_ADD relocconst %prec NEG - { $$ = $2; } - | T_OP_SUB relocconst %prec NEG - { rpn_UNNEG(&$$,&$2); } - | T_OP_NOT relocconst %prec NEG - { rpn_UNNOT(&$$,&$2); } - | T_OP_HIGH '(' relocconst ')' - { rpn_HIGH(&$$, &$3); } - | T_OP_LOW '(' relocconst ')' - { rpn_LOW(&$$, &$3); } - | T_OP_BANK '(' T_ID ')' - { rpn_Bank(&$$,$3); $$.nVal = 0; } - | T_OP_DEF { oDontExpandStrings = true; } '(' T_ID ')' - { rpn_Number(&$$,sym_isConstDefined($4)); oDontExpandStrings = false; } - | T_OP_ROUND '(' const ')' { rpn_Number(&$$,math_Round($3)); } - | T_OP_CEIL '(' const ')' { rpn_Number(&$$,math_Ceil($3)); } - | T_OP_FLOOR '(' const ')' { rpn_Number(&$$,math_Floor($3)); } - | T_OP_FDIV '(' const ',' const ')' { rpn_Number(&$$,math_Div($3,$5)); } - | T_OP_FMUL '(' const ',' const ')' { rpn_Number(&$$,math_Mul($3,$5)); } - | T_OP_SIN '(' const ')' { rpn_Number(&$$,math_Sin($3)); } - | T_OP_COS '(' const ')' { rpn_Number(&$$,math_Cos($3)); } - | T_OP_TAN '(' const ')' { rpn_Number(&$$,math_Tan($3)); } - | T_OP_ASIN '(' const ')' { rpn_Number(&$$,math_ASin($3)); } - | T_OP_ACOS '(' const ')' { rpn_Number(&$$,math_ACos($3)); } - | T_OP_ATAN '(' const ')' { rpn_Number(&$$,math_ATan($3)); } - | T_OP_ATAN2 '(' const ',' const ')' { rpn_Number(&$$,math_ATan2($3,$5)); } - | T_OP_STRCMP '(' string ',' string ')' { rpn_Number(&$$,strcmp($3,$5)); } - | T_OP_STRIN '(' string ',' string ')' - { - char *p; - if( (p=strstr($3,$5))!=NULL ) - { - rpn_Number(&$$,p-$3+1); - } - else - { - rpn_Number(&$$,0); - } - } - | T_OP_STRLEN '(' string ')' { rpn_Number(&$$,strlen($3)); } - | '(' relocconst ')' - { $$ = $2; } -; - -uconst : const - { - if($1 < 0) - fatalerror("Constant mustn't be negative: %d", $1); - $$=$1; - } -; - -const : T_ID { $$ = sym_GetConstantValue($1); } - | T_NUMBER { $$ = $1; } - | string { $$ = str2int($1); } - | T_OP_LOGICNOT const %prec NEG { $$ = !$2; } - | const T_OP_LOGICOR const { $$ = $1 || $3; } - | const T_OP_LOGICAND const { $$ = $1 && $3; } - | const T_OP_LOGICEQU const { $$ = $1 == $3; } - | const T_OP_LOGICGT const { $$ = $1 > $3; } - | const T_OP_LOGICLT const { $$ = $1 < $3; } - | const T_OP_LOGICGE const { $$ = $1 >= $3; } - | const T_OP_LOGICLE const { $$ = $1 <= $3; } - | const T_OP_LOGICNE const { $$ = $1 != $3; } - | const T_OP_ADD const { $$ = $1 + $3; } - | const T_OP_SUB const { $$ = $1 - $3; } - | T_ID T_OP_SUB T_ID - { - if (sym_IsRelocDiffDefined($1, $3) == 0) - fatalerror("'%s - %s' not defined.", $1, $3); - $$ = sym_GetDefinedValue($1) - sym_GetDefinedValue($3); - } - | const T_OP_XOR const { $$ = $1 ^ $3; } - | const T_OP_OR const { $$ = $1 | $3; } - | const T_OP_AND const { $$ = $1 & $3; } - | const T_OP_SHL const { $$ = $1 << $3; } - | const T_OP_SHR const { $$ = $1 >> $3; } - | const T_OP_MUL const { $$ = $1 * $3; } - | const T_OP_DIV const - { - if ($3 == 0) - fatalerror("division by zero"); - $$ = $1 / $3; - } - | const T_OP_MOD const - { - if ($3 == 0) - fatalerror("division by zero"); - $$ = $1 % $3; - } - | T_OP_ADD const %prec NEG { $$ = +$2; } - | T_OP_SUB const %prec NEG { $$ = -$2; } - | T_OP_NOT const %prec NEG { $$ = ~$2; } - | T_OP_ROUND '(' const ')' { $$ = math_Round($3); } - | T_OP_CEIL '(' const ')' { $$ = math_Ceil($3); } - | T_OP_FLOOR '(' const ')' { $$ = math_Floor($3); } - | T_OP_FDIV '(' const ',' const ')' { $$ = math_Div($3,$5); } - | T_OP_FMUL '(' const ',' const ')' { $$ = math_Mul($3,$5); } - | T_OP_SIN '(' const ')' { $$ = math_Sin($3); } - | T_OP_COS '(' const ')' { $$ = math_Cos($3); } - | T_OP_TAN '(' const ')' { $$ = math_Tan($3); } - | T_OP_ASIN '(' const ')' { $$ = math_ASin($3); } - | T_OP_ACOS '(' const ')' { $$ = math_ACos($3); } - | T_OP_ATAN '(' const ')' { $$ = math_ATan($3); } - | T_OP_ATAN2 '(' const ',' const ')' { $$ = math_ATan2($3,$5); } - | T_OP_DEF { oDontExpandStrings = true; } '(' T_ID ')' { $$ = sym_isConstDefined($4); oDontExpandStrings = false; } - | T_OP_STRCMP '(' string ',' string ')' { $$ = strcmp( $3, $5 ); } - | T_OP_STRIN '(' string ',' string ')' - { - char *p; - if( (p=strstr($3,$5))!=NULL ) - { - $$ = p-$3+1; - } - else - { - $$ = 0; - } - } - | T_OP_STRLEN '(' string ')' { $$ = strlen($3); } - | '(' const ')' { $$ = $2; } -; - -string : T_STRING - { strcpy($$,$1); } - | T_OP_STRSUB '(' string ',' uconst ',' uconst ')' - { strncpy($$,$3+$5-1,$7); $$[$7]=0; } - | T_OP_STRCAT '(' string ',' string ')' - { strcpy($$,$3); strcat($$,$5); } - | T_OP_STRUPR '(' string ')' - { strcpy($$,$3); upperstring($$); } - | T_OP_STRLWR '(' string ')' - { strcpy($$,$3); lowerstring($$); } -; -section: - T_POP_SECTION string ',' sectiontype +constlist_32bit_entry : /* empty */ { - out_NewSection($2,$4); + out_Skip(4); + if (nPass == 1) + warning("Empty entry in list of 32-bit elements (treated as 0)."); } - | T_POP_SECTION string ',' sectiontype '[' uconst ']' + | relocconst { - if( $6>=0 && $6<0x10000 ) - out_NewAbsSection($2,$4,$6,-1); + out_RelLong(&$1); + } +; + +constlist_32bit_entry_single : /* empty */ + { + out_Skip(4); + } + | relocconst + { + out_RelLong(&$1); + } +; + +const_PCrel : relocconst + { + if (!rpn_isPCRelative(&$1)) + yyerror("Expression must be PC-relative"); + $$ = $1; + } +; + +const_8bit : relocconst + { + if( (!rpn_isReloc(&$1)) && (($1.nVal < -128) || ($1.nVal > 255)) ) + yyerror("Expression must be 8-bit"); + $$ = $1; + } +; + +const_16bit : relocconst + { + if ((!rpn_isReloc(&$1)) && (($1.nVal < -32768) || ($1.nVal > 65535))) + yyerror("Expression must be 16-bit"); + $$ = $1; + } +; + + +relocconst : T_ID + { + rpn_Symbol(&$$, $1); + $$.nVal = sym_GetValue($1); + } + | T_NUMBER + { + rpn_Number(&$$, $1); + $$.nVal = $1; + } + | string + { + char *s = $1; + int32_t length = charmap_Convert(&s); + uint32_t r = str2int2(s, length); + + free(s); + rpn_Number(&$$, r); + $$.nVal = r; + } + | T_OP_LOGICNOT relocconst %prec NEG { rpn_LOGNOT(&$$, &$2); } + | relocconst T_OP_LOGICOR relocconst { rpn_LOGOR(&$$, &$1, &$3); } + | relocconst T_OP_LOGICAND relocconst { rpn_LOGAND(&$$, &$1, &$3); } + | relocconst T_OP_LOGICEQU relocconst { rpn_LOGEQU(&$$, &$1, &$3); } + | relocconst T_OP_LOGICGT relocconst { rpn_LOGGT(&$$, &$1, &$3); } + | relocconst T_OP_LOGICLT relocconst { rpn_LOGLT(&$$, &$1, &$3); } + | relocconst T_OP_LOGICGE relocconst { rpn_LOGGE(&$$, &$1, &$3); } + | relocconst T_OP_LOGICLE relocconst { rpn_LOGLE(&$$, &$1, &$3); } + | relocconst T_OP_LOGICNE relocconst { rpn_LOGNE(&$$, &$1, &$3); } + | relocconst T_OP_ADD relocconst { rpn_ADD(&$$, &$1, &$3); } + | relocconst T_OP_SUB relocconst { rpn_SUB(&$$, &$1, &$3); } + | relocconst T_OP_XOR relocconst { rpn_XOR(&$$, &$1, &$3); } + | relocconst T_OP_OR relocconst { rpn_OR(&$$, &$1, &$3); } + | relocconst T_OP_AND relocconst { rpn_AND(&$$, &$1, &$3); } + | relocconst T_OP_SHL relocconst { rpn_SHL(&$$, &$1, &$3); } + | relocconst T_OP_SHR relocconst { rpn_SHR(&$$, &$1, &$3); } + | relocconst T_OP_MUL relocconst { rpn_MUL(&$$, &$1, &$3); } + | relocconst T_OP_DIV relocconst { rpn_DIV(&$$, &$1, &$3); } + | relocconst T_OP_MOD relocconst { rpn_MOD(&$$, &$1, &$3); } + | T_OP_ADD relocconst %prec NEG { $$ = $2; } + | T_OP_SUB relocconst %prec NEG { rpn_UNNEG(&$$, &$2); } + | T_OP_NOT relocconst %prec NEG { rpn_UNNOT(&$$, &$2); } + | T_OP_HIGH '(' relocconst ')' { rpn_HIGH(&$$, &$3); } + | T_OP_LOW '(' relocconst ')' { rpn_LOW(&$$, &$3); } + | T_OP_BANK '(' T_ID ')' + { + rpn_Bank(&$$, $3); + $$.nVal = 0; + } + | T_OP_DEF { + oDontExpandStrings = true; + } '(' T_ID ')' + { + rpn_Number(&$$, sym_isConstDefined($4)); + oDontExpandStrings = false; + } + | T_OP_ROUND '(' const ')' { rpn_Number(&$$, math_Round($3)); } + | T_OP_CEIL '(' const ')' { rpn_Number(&$$, math_Ceil($3)); } + | T_OP_FLOOR '(' const ')' { rpn_Number(&$$, math_Floor($3)); } + | T_OP_FDIV '(' const comma const ')' { rpn_Number(&$$, math_Div($3, $5)); } + | T_OP_FMUL '(' const comma const ')' { rpn_Number(&$$, math_Mul($3, $5)); } + | T_OP_SIN '(' const ')' { rpn_Number(&$$, math_Sin($3)); } + | T_OP_COS '(' const ')' { rpn_Number(&$$, math_Cos($3)); } + | T_OP_TAN '(' const ')' { rpn_Number(&$$, math_Tan($3)); } + | T_OP_ASIN '(' const ')' { rpn_Number(&$$, math_ASin($3)); } + | T_OP_ACOS '(' const ')' { rpn_Number(&$$, math_ACos($3)); } + | T_OP_ATAN '(' const ')' { rpn_Number(&$$, math_ATan($3)); } + | T_OP_ATAN2 '(' const comma const ')' { rpn_Number(&$$, math_ATan2($3, $5)); } + | T_OP_STRCMP '(' string comma string ')' + { + rpn_Number(&$$, strcmp($3, $5)); + } + | T_OP_STRIN '(' string comma string ')' + { + char *p = strstr($3, $5); + + if (p != NULL) + rpn_Number(&$$, p - $3 + 1); + else + rpn_Number(&$$, 0); + } + | T_OP_STRLEN '(' string ')' { rpn_Number(&$$, strlen($3)); } + | '(' relocconst ')' { $$ = $2; } +; + +uconst : const + { + if ($1 < 0) + fatalerror("Constant mustn't be negative: %d", $1); + $$ = $1; + } +; + +const : T_ID { $$ = sym_GetConstantValue($1); } + | T_NUMBER { $$ = $1; } + | string { $$ = str2int($1); } + | T_OP_LOGICNOT const %prec NEG { $$ = !$2; } + | const T_OP_LOGICOR const { $$ = $1 || $3; } + | const T_OP_LOGICAND const { $$ = $1 && $3; } + | const T_OP_LOGICEQU const { $$ = $1 == $3; } + | const T_OP_LOGICGT const { $$ = $1 > $3; } + | const T_OP_LOGICLT const { $$ = $1 < $3; } + | const T_OP_LOGICGE const { $$ = $1 >= $3; } + | const T_OP_LOGICLE const { $$ = $1 <= $3; } + | const T_OP_LOGICNE const { $$ = $1 != $3; } + | const T_OP_ADD const { $$ = $1 + $3; } + | const T_OP_SUB const { $$ = $1 - $3; } + | T_ID T_OP_SUB T_ID + { + if (sym_IsRelocDiffDefined($1, $3) == 0) + fatalerror("'%s - %s' not defined.", $1, $3); + $$ = sym_GetDefinedValue($1) - sym_GetDefinedValue($3); + } + | const T_OP_XOR const { $$ = $1 ^ $3; } + | const T_OP_OR const { $$ = $1 | $3; } + | const T_OP_AND const { $$ = $1 & $3; } + | const T_OP_SHL const { $$ = $1 << $3; } + | const T_OP_SHR const { $$ = $1 >> $3; } + | const T_OP_MUL const { $$ = $1 * $3; } + | const T_OP_DIV const + { + if ($3 == 0) + fatalerror("division by zero"); + $$ = $1 / $3; + } + | const T_OP_MOD const + { + if ($3 == 0) + fatalerror("division by zero"); + $$ = $1 % $3; + } + | T_OP_ADD const %prec NEG { $$ = +$2; } + | T_OP_SUB const %prec NEG { $$ = -$2; } + | T_OP_NOT const %prec NEG { $$ = ~$2; } + | T_OP_ROUND '(' const ')' { $$ = math_Round($3); } + | T_OP_CEIL '(' const ')' { $$ = math_Ceil($3); } + | T_OP_FLOOR '(' const ')' { $$ = math_Floor($3); } + | T_OP_FDIV '(' const comma const ')' { $$ = math_Div($3,$5); } + | T_OP_FMUL '(' const comma const ')' { $$ = math_Mul($3,$5); } + | T_OP_SIN '(' const ')' { $$ = math_Sin($3); } + | T_OP_COS '(' const ')' { $$ = math_Cos($3); } + | T_OP_TAN '(' const ')' { $$ = math_Tan($3); } + | T_OP_ASIN '(' const ')' { $$ = math_ASin($3); } + | T_OP_ACOS '(' const ')' { $$ = math_ACos($3); } + | T_OP_ATAN '(' const ')' { $$ = math_ATan($3); } + | T_OP_ATAN2 '(' const comma const ')' { $$ = math_ATan2($3,$5); } + | T_OP_DEF { + oDontExpandStrings = true; + } '(' T_ID ')' + { + $$ = sym_isConstDefined($4); + oDontExpandStrings = false; + } + | T_OP_STRCMP '(' string comma string ')' + { + $$ = strcmp($3, $5); + } + | T_OP_STRIN '(' string comma string ')' + { + char *p = strstr($3, $5); + + if (p != NULL) + $$ = p - $3 + 1; + else + $$ = 0; + } + | T_OP_STRLEN '(' string ')' { $$ = strlen($3); } + | '(' const ')' { $$ = $2; } +; + +string : T_STRING + { + strcpy($$, $1); + } + | T_OP_STRSUB '(' string comma uconst comma uconst ')' + { + strncpy($$, $3 + $5 - 1, $7); + $$[$7] = 0; + } + | T_OP_STRCAT '(' string comma string ')' + { + strcpy($$, $3); + strcat($$, $5); + } + | T_OP_STRUPR '(' string ')' + { + strcpy($$, $3); + upperstring($$); + } + | T_OP_STRLWR '(' string ')' + { + strcpy($$, $3); + lowerstring($$); + } +; + +section : T_POP_SECTION string comma sectiontype + { + out_NewSection($2, $4); + } + | T_POP_SECTION string comma sectiontype '[' uconst ']' + { + if (($6 >= 0) && ($6 < 0x10000)) + out_NewAbsSection($2, $4, $6, -1); else yyerror("Address $%x not 16-bit", $6); } - | T_POP_SECTION string ',' sectiontype ',' T_OP_ALIGN '[' uconst ']' + | T_POP_SECTION string comma sectiontype comma T_OP_ALIGN '[' uconst ']' { out_NewAlignedSection($2, $4, $8, -1); } - | T_POP_SECTION string ',' sectiontype ',' T_OP_BANK '[' uconst ']' + | T_POP_SECTION string comma sectiontype comma T_OP_BANK '[' uconst ']' { bankrangecheck($2, $4, -1, $8); } - | T_POP_SECTION string ',' sectiontype '[' uconst ']' ',' T_OP_BANK '[' uconst ']' + | T_POP_SECTION string comma sectiontype '[' uconst ']' comma T_OP_BANK '[' uconst ']' { - if ($6 < 0 || $6 > 0x10000) { + if (($6 < 0) || ($6 > 0x10000)) yyerror("Address $%x not 16-bit", $6); - } bankrangecheck($2, $4, $6, $11); } - | T_POP_SECTION string ',' sectiontype ',' T_OP_ALIGN '[' uconst ']' ',' T_OP_BANK '[' uconst ']' + | T_POP_SECTION string comma sectiontype comma T_OP_ALIGN '[' uconst ']' comma T_OP_BANK '[' uconst ']' { out_NewAlignedSection($2, $4, $8, $13); } - | T_POP_SECTION string ',' sectiontype ',' T_OP_BANK '[' uconst ']' ',' T_OP_ALIGN '[' uconst ']' + | T_POP_SECTION string comma sectiontype comma T_OP_BANK '[' uconst ']' comma T_OP_ALIGN '[' uconst ']' { out_NewAlignedSection($2, $4, $13, $8); } ; -sectiontype: - T_SECT_WRAM0 { $$=SECT_WRAM0; } - | T_SECT_VRAM { $$=SECT_VRAM; } - | T_SECT_ROMX { $$=SECT_ROMX; } - | T_SECT_ROM0 { $$=SECT_ROM0; } - | T_SECT_HRAM { $$=SECT_HRAM; } - | T_SECT_WRAMX { $$=SECT_WRAMX; } - | T_SECT_SRAM { $$=SECT_SRAM; } - | T_SECT_OAM { $$=SECT_OAM; } - | T_SECT_HOME { - warning("HOME section name is deprecated, use ROM0 instead."); - $$=SECT_ROM0; - } - | T_SECT_DATA { - warning("DATA section name is deprecated, use ROMX instead."); - $$=SECT_ROMX; - } - | T_SECT_CODE { - warning("CODE section name is deprecated, use ROMX instead."); - $$=SECT_ROMX; - } - | T_SECT_BSS { - warning("BSS section name is deprecated, use WRAM0 instead."); - $$=SECT_WRAM0; - } +sectiontype : T_SECT_WRAM0 { $$ = SECT_WRAM0; } + | T_SECT_VRAM { $$ = SECT_VRAM; } + | T_SECT_ROMX { $$ = SECT_ROMX; } + | T_SECT_ROM0 { $$ = SECT_ROM0; } + | T_SECT_HRAM { $$ = SECT_HRAM; } + | T_SECT_WRAMX { $$ = SECT_WRAMX; } + | T_SECT_SRAM { $$ = SECT_SRAM; } + | T_SECT_OAM { $$ = SECT_OAM; } + | T_SECT_HOME + { + warning("HOME section name is deprecated, use ROM0 instead."); + $$ = SECT_ROM0; + } + | T_SECT_DATA + { + warning("DATA section name is deprecated, use ROMX instead."); + $$ = SECT_ROMX; + } + | T_SECT_CODE + { + warning("CODE section name is deprecated, use ROMX instead."); + $$ = SECT_ROMX; + } + | T_SECT_BSS + { + warning("BSS section name is deprecated, use WRAM0 instead."); + $$ = SECT_WRAM0; + } ; -cpu_command : z80_adc - | z80_add - | z80_and - | z80_bit - | z80_call - | z80_ccf - | z80_cp - | z80_cpl - | z80_daa - | z80_dec - | z80_di - | z80_ei - | z80_halt - | z80_inc - | z80_jp - | z80_jr - | z80_ld - | z80_ldd - | z80_ldi - | z80_ldio - | z80_nop - | z80_or - | z80_pop - | z80_push - | z80_res - | z80_ret - | z80_reti - | z80_rl - | z80_rla - | z80_rlc - | z80_rlca - | z80_rr - | z80_rra - | z80_rrc - | z80_rrca - | z80_rst - | z80_sbc - | z80_scf - | z80_set - | z80_sla - | z80_sra - | z80_srl - | z80_stop - | z80_sub - | z80_swap - | z80_xor +cpu_command : z80_adc + | z80_add + | z80_and + | z80_bit + | z80_call + | z80_ccf + | z80_cp + | z80_cpl + | z80_daa + | z80_dec + | z80_di + | z80_ei + | z80_halt + | z80_inc + | z80_jp + | z80_jr + | z80_ld + | z80_ldd + | z80_ldi + | z80_ldio + | z80_nop + | z80_or + | z80_pop + | z80_push + | z80_res + | z80_ret + | z80_reti + | z80_rl + | z80_rla + | z80_rlc + | z80_rlca + | z80_rr + | z80_rra + | z80_rrc + | z80_rrca + | z80_rst + | z80_sbc + | z80_scf + | z80_set + | z80_sla + | z80_sra + | z80_srl + | z80_stop + | z80_sub + | z80_swap + | z80_xor ; -z80_adc : T_Z80_ADC op_a_n { out_AbsByte(0xCE); out_RelByte(&$2); } - | T_Z80_ADC op_a_r { out_AbsByte(0x88|$2); } +z80_adc : T_Z80_ADC op_a_n + { + out_AbsByte(0xCE); + out_RelByte(&$2); + } + | T_Z80_ADC op_a_r + { + out_AbsByte(0x88 | $2); + } ; -z80_add : T_Z80_ADD op_a_n { out_AbsByte(0xC6); out_RelByte(&$2); } - | T_Z80_ADD op_a_r { out_AbsByte(0x80|$2); } - | T_Z80_ADD op_hl_ss { out_AbsByte(0x09|($2<<4)); } - | T_Z80_ADD T_MODE_SP comma const_8bit - { out_AbsByte(0xE8); out_RelByte(&$4); } +z80_add : T_Z80_ADD op_a_n + { + out_AbsByte(0xC6); + out_RelByte(&$2); + } + | T_Z80_ADD op_a_r + { + out_AbsByte(0x80 | $2); + } + | T_Z80_ADD op_hl_ss + { + out_AbsByte(0x09 | ($2 << 4)); + } + | T_Z80_ADD T_MODE_SP comma const_8bit + { + out_AbsByte(0xE8); + out_RelByte(&$4); + } ; -z80_and : T_Z80_AND op_a_n { out_AbsByte(0xE6); out_RelByte(&$2); } - | T_Z80_AND op_a_r { out_AbsByte(0xA0|$2); } +z80_and : T_Z80_AND op_a_n + { + out_AbsByte(0xE6); + out_RelByte(&$2); + } + | T_Z80_AND op_a_r + { + out_AbsByte(0xA0 | $2); + } ; -z80_bit : T_Z80_BIT const_3bit comma reg_r - { out_AbsByte(0xCB); out_AbsByte(0x40|($2<<3)|$4); } +z80_bit : T_Z80_BIT const_3bit comma reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x40 | ($2 << 3) | $4); + } ; -z80_call : T_Z80_CALL const_16bit - { out_AbsByte(0xCD); out_RelWord(&$2); } - | T_Z80_CALL ccode comma const_16bit - { out_AbsByte(0xC4|($2<<3)); out_RelWord(&$4); } +z80_call : T_Z80_CALL const_16bit + { + out_AbsByte(0xCD); + out_RelWord(&$2); + } + | T_Z80_CALL ccode comma const_16bit + { + out_AbsByte(0xC4 | ($2 << 3)); + out_RelWord(&$4); + } ; -z80_ccf : T_Z80_CCF - { out_AbsByte(0x3F); } +z80_ccf : T_Z80_CCF + { + out_AbsByte(0x3F); + } ; -z80_cp : T_Z80_CP op_a_n { out_AbsByte(0xFE); out_RelByte(&$2); } - | T_Z80_CP op_a_r { out_AbsByte(0xB8|$2); } +z80_cp : T_Z80_CP op_a_n + { + out_AbsByte(0xFE); + out_RelByte(&$2); + } + | T_Z80_CP op_a_r + { + out_AbsByte(0xB8 | $2); + } ; -z80_cpl : T_Z80_CPL { out_AbsByte(0x2F); } +z80_cpl : T_Z80_CPL + { + out_AbsByte(0x2F); + } ; -z80_daa : T_Z80_DAA { out_AbsByte(0x27); } +z80_daa : T_Z80_DAA + { + out_AbsByte(0x27); + } ; -z80_dec : T_Z80_DEC reg_r - { out_AbsByte(0x05|($2<<3)); } - | T_Z80_DEC reg_ss - { out_AbsByte(0x0B|($2<<4)); } +z80_dec : T_Z80_DEC reg_r + { + out_AbsByte(0x05 | ($2 << 3)); + } + | T_Z80_DEC reg_ss + { + out_AbsByte(0x0B | ($2 << 4)); + } ; -z80_di : T_Z80_DI - { out_AbsByte(0xF3); } +z80_di : T_Z80_DI + { + out_AbsByte(0xF3); + } ; -z80_ei : T_Z80_EI - { out_AbsByte(0xFB); } +z80_ei : T_Z80_EI + { + out_AbsByte(0xFB); + } ; -z80_halt: T_Z80_HALT +z80_halt : T_Z80_HALT { out_AbsByte(0x76); - if (CurrentOptions.haltnop) { + if (CurrentOptions.haltnop) out_AbsByte(0x00); + } +; + +z80_inc : T_Z80_INC reg_r + { + out_AbsByte(0x04 | ($2 << 3)); + } + | T_Z80_INC reg_ss + { + out_AbsByte(0x03 | ($2 << 4)); + } +; + +z80_jp : T_Z80_JP const_16bit + { + out_AbsByte(0xC3); + out_RelWord(&$2); + } + | T_Z80_JP ccode comma const_16bit + { + out_AbsByte(0xC2 | ($2 << 3)); + out_RelWord(&$4); + } + | T_Z80_JP T_MODE_HL_IND + { + out_AbsByte(0xE9); + if (nPass == 1) + warning("'JP [HL]' is obsolete, use 'JP HL' instead."); + } + | T_Z80_JP T_MODE_HL + { + out_AbsByte(0xE9); + } +; + +z80_jr : T_Z80_JR const_PCrel + { + out_AbsByte(0x18); + out_PCRelByte(&$2); + } + | T_Z80_JR ccode comma const_PCrel + { + out_AbsByte(0x20 | ($2 << 3)); + out_PCRelByte(&$4); + } +; + +z80_ldi : T_Z80_LDI T_MODE_HL_IND comma T_MODE_A + { + out_AbsByte(0x02 | (2 << 4)); + } + | T_Z80_LDI T_MODE_A comma T_MODE_HL + { + out_AbsByte(0x0A | (2 << 4)); + if (nPass == 1) + warning("'LDI A,HL' is obsolete, use 'LDI A,[HL]' or 'LD A,[HL+] instead."); + } + | T_Z80_LDI T_MODE_A comma T_MODE_HL_IND + { + out_AbsByte(0x0A | (2 << 4)); + } +; + +z80_ldd : T_Z80_LDD T_MODE_HL_IND comma T_MODE_A + { + out_AbsByte(0x02 | (3 << 4)); + } + | T_Z80_LDD T_MODE_A comma T_MODE_HL + { + out_AbsByte(0x0A | (3 << 4)); + if (nPass == 1) + warning("'LDD A,HL' is obsolete, use 'LDD A,[HL]' or 'LD A,[HL-] instead."); + } + | T_Z80_LDD T_MODE_A comma T_MODE_HL_IND + { + out_AbsByte(0x0A | (3 << 4)); + } +; + +z80_ldio : T_Z80_LDIO T_MODE_A comma op_mem_ind + { + rpn_CheckHRAM(&$4, &$4); + + if ((!rpn_isReloc(&$4)) && ($4.nVal < 0 || ($4.nVal > 0xFF && $4.nVal < 0xFF00) || $4.nVal > 0xFFFF)) + yyerror("Source address $%x not in $FF00 to $FFFF", $4.nVal); + + out_AbsByte(0xF0); + $4.nVal &= 0xFF; + out_RelByte(&$4); + } + | T_Z80_LDIO op_mem_ind comma T_MODE_A + { + rpn_CheckHRAM(&$2, &$2); + + if ((!rpn_isReloc(&$2)) && ($2.nVal < 0 || ($2.nVal > 0xFF && $2.nVal < 0xFF00) || $2.nVal > 0xFFFF)) + yyerror("Destination address $%x not in $FF00 to $FFFF", $2.nVal); + + out_AbsByte(0xE0); + $2.nVal &= 0xFF; + out_RelByte(&$2); + } +; + +z80_ld : z80_ld_mem + | z80_ld_cind + | z80_ld_rr + | z80_ld_ss + | z80_ld_hl + | z80_ld_sp + | z80_ld_r + | z80_ld_a +; + +z80_ld_hl : T_Z80_LD T_MODE_HL comma '[' T_MODE_SP const_8bit ']' + { + out_AbsByte(0xF8); + out_RelByte(&$6); + warning("'LD HL,[SP+e8]' is obsolete, use 'LD HL,SP+e8' instead."); + } + | T_Z80_LD T_MODE_HL comma T_MODE_SP const_8bit + { + out_AbsByte(0xF8); + out_RelByte(&$5); + } + | T_Z80_LD T_MODE_HL comma const_16bit + { + out_AbsByte(0x01 | (REG_HL << 4)); + out_RelWord(&$4); + } +; + +z80_ld_sp : T_Z80_LD T_MODE_SP comma T_MODE_HL + { + out_AbsByte(0xF9); + } + | T_Z80_LD T_MODE_SP comma const_16bit + { + out_AbsByte(0x01 | (REG_SP << 4)); + out_RelWord(&$4); + } +; + +z80_ld_mem : T_Z80_LD op_mem_ind comma T_MODE_SP + { + out_AbsByte(0x08); + out_RelWord(&$2); + } + | T_Z80_LD op_mem_ind comma T_MODE_A + { + if ((!rpn_isReloc(&$2)) && ($2.nVal >= 0xFF00)) { + out_AbsByte(0xE0); + out_AbsByte($2.nVal & 0xFF); + } else { + out_AbsByte(0xEA); + out_RelWord(&$2); } } ; -z80_inc : T_Z80_INC reg_r - { out_AbsByte(0x04|($2<<3)); } - | T_Z80_INC reg_ss - { out_AbsByte(0x03|($2<<4)); } +z80_ld_cind : T_Z80_LD T_MODE_C_IND comma T_MODE_A + { + out_AbsByte(0xE2); + } ; -z80_jp : T_Z80_JP const_16bit - { out_AbsByte(0xC3); out_RelWord(&$2); } - | T_Z80_JP ccode comma const_16bit - { out_AbsByte(0xC2|($2<<3)); out_RelWord(&$4); } - | T_Z80_JP T_MODE_HL_IND - { - out_AbsByte(0xE9); - if( nPass==1 ) - warning("'JP [HL]' is obsolete, use 'JP HL' instead."); - } - | T_Z80_JP T_MODE_HL - { out_AbsByte(0xE9); } +z80_ld_rr : T_Z80_LD reg_rr comma T_MODE_A + { + out_AbsByte(0x02 | ($2 << 4)); + } ; -z80_jr : T_Z80_JR const_PCrel - { out_AbsByte(0x18); out_PCRelByte(&$2); } - | T_Z80_JR ccode comma const_PCrel - { out_AbsByte(0x20|($2<<3)); out_PCRelByte(&$4); } +z80_ld_r : T_Z80_LD reg_r comma const_8bit + { + out_AbsByte(0x06 | ($2 << 3)); + out_RelByte(&$4); + } + | T_Z80_LD reg_r comma reg_r + { + if (($2 == REG_HL_IND) && ($4 == REG_HL_IND)) + yyerror("LD [HL],[HL] not a valid instruction"); + else + out_AbsByte(0x40 | ($2 << 3) | $4); + } ; -z80_ldi : T_Z80_LDI T_MODE_HL_IND comma T_MODE_A - { out_AbsByte(0x02|(2<<4)); } - | T_Z80_LDI T_MODE_A comma T_MODE_HL - { - out_AbsByte(0x0A|(2<<4)); - if( nPass==1 ) - warning("'LDI A,HL' is obsolete, use 'LDI A,[HL]' or 'LD A,[HL+] instead."); - } - | T_Z80_LDI T_MODE_A comma T_MODE_HL_IND - { out_AbsByte(0x0A|(2<<4)); } +z80_ld_a : T_Z80_LD reg_r comma T_MODE_C_IND + { + if ($2 == REG_A) + out_AbsByte(0xF2); + else + yyerror("Destination operand must be A"); + } + | T_Z80_LD reg_r comma reg_rr + { + if ($2 == REG_A) + out_AbsByte(0x0A | ($4 << 4)); + else + yyerror("Destination operand must be A"); + } + | T_Z80_LD reg_r comma op_mem_ind + { + if ($2 == REG_A) { + if ((!rpn_isReloc(&$4)) && ($4.nVal >= 0xFF00)) { + out_AbsByte(0xF0); + out_AbsByte($4.nVal & 0xFF); + } else { + out_AbsByte(0xFA); + out_RelWord(&$4); + } + } else { + yyerror("Destination operand must be A"); + } + } ; -z80_ldd : T_Z80_LDD T_MODE_HL_IND comma T_MODE_A - { out_AbsByte(0x02|(3<<4)); } - | T_Z80_LDD T_MODE_A comma T_MODE_HL - { - out_AbsByte(0x0A|(3<<4)); - if( nPass==1 ) - warning("'LDD A,HL' is obsolete, use 'LDD A,[HL]' or 'LD A,[HL-] instead."); - } - | T_Z80_LDD T_MODE_A comma T_MODE_HL_IND - { out_AbsByte(0x0A|(3<<4)); } +z80_ld_ss : T_Z80_LD T_MODE_BC comma const_16bit + { + out_AbsByte(0x01 | (REG_BC << 4)); + out_RelWord(&$4); + } + | T_Z80_LD T_MODE_DE comma const_16bit + { + out_AbsByte(0x01 | (REG_DE << 4)); + out_RelWord(&$4); + } + /* + * HL is taken care of in z80_ld_hl + * SP is taken care of in z80_ld_sp + */ ; -z80_ldio : T_Z80_LDIO T_MODE_A comma op_mem_ind - { - rpn_CheckHRAM(&$4,&$4); - - if( (!rpn_isReloc(&$4)) - && ($4.nVal<0 || ($4.nVal>0xFF && $4.nVal<0xFF00) || $4.nVal>0xFFFF) ) - { - yyerror("Source address $%x not in $FF00 to $FFFF", $4.nVal); - } - - out_AbsByte(0xF0); - $4.nVal&=0xFF; - out_RelByte(&$4); - } - | T_Z80_LDIO op_mem_ind comma T_MODE_A - { - rpn_CheckHRAM(&$2,&$2); - - if( (!rpn_isReloc(&$2)) - && ($2.nVal<0 || ($2.nVal>0xFF && $2.nVal<0xFF00) || $2.nVal>0xFFFF) ) - { - yyerror("Destination address $%x not in $FF00 to $FFFF", $2.nVal); - } - - out_AbsByte(0xE0); - $2.nVal&=0xFF; - out_RelByte(&$2); - } +z80_nop : T_Z80_NOP + { + out_AbsByte(0x00); + } ; -z80_ld : z80_ld_mem - | z80_ld_cind - | z80_ld_rr - | z80_ld_ss - | z80_ld_hl - | z80_ld_sp - | z80_ld_r - | z80_ld_a +z80_or : T_Z80_OR op_a_n + { + out_AbsByte(0xF6); + out_RelByte(&$2); + } + | T_Z80_OR op_a_r + { + out_AbsByte(0xB0 | $2); + } ; -z80_ld_hl : T_Z80_LD T_MODE_HL comma '[' T_MODE_SP const_8bit ']' - { - out_AbsByte(0xF8); out_RelByte(&$6); - warning("'LD HL,[SP+e8]' is obsolete, use 'LD HL,SP+e8' instead."); - } - | T_Z80_LD T_MODE_HL comma T_MODE_SP const_8bit - { out_AbsByte(0xF8); out_RelByte(&$5); } - | T_Z80_LD T_MODE_HL comma const_16bit - { out_AbsByte(0x01|(REG_HL<<4)); out_RelWord(&$4); } -; -z80_ld_sp : T_Z80_LD T_MODE_SP comma T_MODE_HL - { out_AbsByte(0xF9); } - | T_Z80_LD T_MODE_SP comma const_16bit - { out_AbsByte(0x01|(REG_SP<<4)); out_RelWord(&$4); } +z80_pop : T_Z80_POP reg_tt + { + out_AbsByte(0xC1 | ($2 << 4)); + } ; -z80_ld_mem : T_Z80_LD op_mem_ind comma T_MODE_SP - { out_AbsByte(0x08); out_RelWord(&$2); } - | T_Z80_LD op_mem_ind comma T_MODE_A - { - if( (!rpn_isReloc(&$2)) && $2.nVal>=0xFF00) - { - out_AbsByte(0xE0); - out_AbsByte($2.nVal&0xFF); - } - else - { - out_AbsByte(0xEA); - out_RelWord(&$2); - } - } +z80_push : T_Z80_PUSH reg_tt + { + out_AbsByte(0xC5 | ($2 << 4)); + } ; -z80_ld_cind : T_Z80_LD T_MODE_C_IND comma T_MODE_A - { out_AbsByte(0xE2); } +z80_res : T_Z80_RES const_3bit comma reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x80 | ($2 << 3) | $4); + } ; -z80_ld_rr : T_Z80_LD reg_rr comma T_MODE_A - { out_AbsByte(0x02|($2<<4)); } +z80_ret : T_Z80_RET + { + out_AbsByte(0xC9); + } + | T_Z80_RET ccode + { + out_AbsByte(0xC0 | ($2 << 3)); + } ; -z80_ld_r : T_Z80_LD reg_r comma const_8bit - { out_AbsByte(0x06|($2<<3)); out_RelByte(&$4); } - | T_Z80_LD reg_r comma reg_r - { - if( ($2==REG_HL_IND) && ($4==REG_HL_IND) ) - { - yyerror("LD [HL],[HL] not a valid instruction"); - } - else - out_AbsByte(0x40|($2<<3)|$4); - } +z80_reti : T_Z80_RETI + { + out_AbsByte(0xD9); + } ; -z80_ld_a : T_Z80_LD reg_r comma T_MODE_C_IND - { - if( $2==REG_A ) - out_AbsByte(0xF2); - else - { - yyerror("Destination operand must be A"); - } - } - | T_Z80_LD reg_r comma reg_rr - { - if( $2==REG_A ) - out_AbsByte(0x0A|($4<<4)); - else - { - yyerror("Destination operand must be A"); - } - } - | T_Z80_LD reg_r comma op_mem_ind - { - if( $2==REG_A ) - { - if( (!rpn_isReloc(&$4)) && $4.nVal>=0xFF00 ) - { - out_AbsByte(0xF0); - out_AbsByte($4.nVal&0xFF); - } - else - { - out_AbsByte(0xFA); - out_RelWord(&$4); - } - } - else - { - yyerror("Destination operand must be A"); - } - } +z80_rl : T_Z80_RL reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x10 | $2); + } ; -z80_ld_ss : T_Z80_LD T_MODE_BC comma const_16bit - { out_AbsByte(0x01|(REG_BC<<4)); out_RelWord(&$4); } - | T_Z80_LD T_MODE_DE comma const_16bit - { out_AbsByte(0x01|(REG_DE<<4)); out_RelWord(&$4); } - /* - * HL is taken care of in z80_ld_hl - * SP is taken care of in z80_ld_sp - */ +z80_rla : T_Z80_RLA + { + out_AbsByte(0x17); + } ; -z80_nop : T_Z80_NOP - { out_AbsByte(0x00); } +z80_rlc : T_Z80_RLC reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x00 | $2); + } ; -z80_or : T_Z80_OR op_a_n - { out_AbsByte(0xF6); out_RelByte(&$2); } - | T_Z80_OR op_a_r - { out_AbsByte(0xB0|$2); } +z80_rlca : T_Z80_RLCA + { + out_AbsByte(0x07); + } ; -z80_pop : T_Z80_POP reg_tt - { out_AbsByte(0xC1|($2<<4)); } +z80_rr : T_Z80_RR reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x18 | $2); + } ; -z80_push : T_Z80_PUSH reg_tt - { out_AbsByte(0xC5|($2<<4)); } +z80_rra : T_Z80_RRA + { + out_AbsByte(0x1F); + } ; -z80_res : T_Z80_RES const_3bit comma reg_r - { out_AbsByte(0xCB); out_AbsByte(0x80|($2<<3)|$4); } +z80_rrc : T_Z80_RRC reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x08 | $2); + } ; -z80_ret : T_Z80_RET - { out_AbsByte(0xC9); } - | T_Z80_RET ccode - { out_AbsByte(0xC0|($2<<3)); } +z80_rrca : T_Z80_RRCA + { + out_AbsByte(0x0F); + } ; -z80_reti : T_Z80_RETI - { out_AbsByte(0xD9); } +z80_rst : T_Z80_RST const_8bit + { + if (rpn_isReloc(&$2)) + yyerror("Address for RST must be absolute"); + else if (($2.nVal & 0x38) != $2.nVal) + yyerror("Invalid address $%x for RST", $2.nVal); + else + out_AbsByte(0xC7 | $2.nVal); + } ; -z80_rl : T_Z80_RL reg_r - { out_AbsByte(0xCB); out_AbsByte(0x10|$2); } +z80_sbc : T_Z80_SBC op_a_n + { + out_AbsByte(0xDE); + out_RelByte(&$2); + } + | T_Z80_SBC op_a_r + { + out_AbsByte(0x98 | $2); + } ; -z80_rla : T_Z80_RLA - { out_AbsByte(0x17); } +z80_scf : T_Z80_SCF + { + out_AbsByte(0x37); + } ; -z80_rlc : T_Z80_RLC reg_r - { out_AbsByte(0xCB); out_AbsByte(0x00|$2); } +z80_set : T_POP_SET const_3bit comma reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0xC0 | ($2 << 3) | $4); + } ; -z80_rlca : T_Z80_RLCA - { out_AbsByte(0x07); } +z80_sla : T_Z80_SLA reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x20 | $2); + } ; -z80_rr : T_Z80_RR reg_r - { out_AbsByte(0xCB); out_AbsByte(0x18|$2); } +z80_sra : T_Z80_SRA reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x28 | $2); + } ; -z80_rra : T_Z80_RRA - { out_AbsByte(0x1F); } +z80_srl : T_Z80_SRL reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x38 | $2); + } ; -z80_rrc : T_Z80_RRC reg_r - { out_AbsByte(0xCB); out_AbsByte(0x08|$2); } +z80_stop : T_Z80_STOP + { + out_AbsByte(0x10); + out_AbsByte(0x00); + } ; -z80_rrca : T_Z80_RRCA - { out_AbsByte(0x0F); } +z80_sub : T_Z80_SUB op_a_n + { + out_AbsByte(0xD6); + out_RelByte(&$2); + } + | T_Z80_SUB op_a_r + { + out_AbsByte(0x90 | $2); + } ; -z80_rst : T_Z80_RST const_8bit - { - if( rpn_isReloc(&$2) ) - { - yyerror("Address for RST must be absolute"); - } - else if( ($2.nVal&0x38)!=$2.nVal ) - { - yyerror("Invalid address $%x for RST", $2.nVal); - } - else - out_AbsByte(0xC7|$2.nVal); - } +z80_swap : T_Z80_SWAP reg_r + { + out_AbsByte(0xCB); + out_AbsByte(0x30 | $2); + } ; -z80_sbc : T_Z80_SBC op_a_n { out_AbsByte(0xDE); out_RelByte(&$2); } - | T_Z80_SBC op_a_r { out_AbsByte(0x98|$2); } +z80_xor : T_Z80_XOR op_a_n + { + out_AbsByte(0xEE); + out_RelByte(&$2); + } + | T_Z80_XOR op_a_r + { + out_AbsByte(0xA8 | $2); + } ; -z80_scf : T_Z80_SCF - { out_AbsByte(0x37); } +op_mem_ind : '[' const_16bit ']' { $$ = $2; } ; -z80_set : T_POP_SET const_3bit comma reg_r - { out_AbsByte(0xCB); out_AbsByte(0xC0|($2<<3)|$4); } +op_hl_ss : reg_ss { $$ = $1; } + | T_MODE_HL comma reg_ss { $$ = $3; } ; -z80_sla : T_Z80_SLA reg_r - { out_AbsByte(0xCB); out_AbsByte(0x20|$2); } +op_a_r : reg_r { $$ = $1; } + | T_MODE_A comma reg_r { $$ = $3; } ; -z80_sra : T_Z80_SRA reg_r - { out_AbsByte(0xCB); out_AbsByte(0x28|$2); } +op_a_n : const_8bit { $$ = $1; } + | T_MODE_A comma const_8bit { $$ = $3; } ; -z80_srl : T_Z80_SRL reg_r - { out_AbsByte(0xCB); out_AbsByte(0x38|$2); } +comma : ',' ; -z80_stop : T_Z80_STOP - { out_AbsByte(0x10); out_AbsByte(0x00); } +T_MODE_A : T_TOKEN_A + | T_OP_HIGH '(' T_MODE_AF ')' ; -z80_sub : T_Z80_SUB op_a_n { out_AbsByte(0xD6); out_RelByte(&$2); } - | T_Z80_SUB op_a_r { out_AbsByte(0x90|$2); } +T_MODE_B : T_TOKEN_B + | T_OP_HIGH '(' T_MODE_BC ')' ; -z80_swap : T_Z80_SWAP reg_r - { out_AbsByte(0xCB); out_AbsByte(0x30|$2); } +T_MODE_C : T_TOKEN_C + | T_OP_LOW '(' T_MODE_BC ')' ; -z80_xor : T_Z80_XOR op_a_n { out_AbsByte(0xEE); out_RelByte(&$2); } - | T_Z80_XOR op_a_r { out_AbsByte(0xA8|$2); } +T_MODE_D : T_TOKEN_D + | T_OP_HIGH '(' T_MODE_DE ')' ; -op_mem_ind : '[' const_16bit ']' { $$ = $2; } +T_MODE_E : T_TOKEN_E + | T_OP_LOW '(' T_MODE_DE ')' ; -op_hl_ss : reg_ss { $$ = $1; } - | T_MODE_HL comma reg_ss { $$ = $3; } +T_MODE_H : T_TOKEN_H + | T_OP_HIGH '(' T_MODE_HL ')' ; -op_a_r : reg_r { $$ = $1; } - | T_MODE_A comma reg_r { $$ = $3; } +T_MODE_L : T_TOKEN_L + | T_OP_LOW '(' T_MODE_HL ')' ; -op_a_n : const_8bit { $$ = $1; } - | T_MODE_A comma const_8bit { $$ = $3; } +ccode : T_CC_NZ { $$ = CC_NZ; } + | T_CC_Z { $$ = CC_Z; } + | T_CC_NC { $$ = CC_NC; } + | T_TOKEN_C { $$ = CC_C; } ; -comma : ',' +reg_r : T_MODE_B { $$ = REG_B; } + | T_MODE_C { $$ = REG_C; } + | T_MODE_D { $$ = REG_D; } + | T_MODE_E { $$ = REG_E; } + | T_MODE_H { $$ = REG_H; } + | T_MODE_L { $$ = REG_L; } + | T_MODE_HL_IND { $$ = REG_HL_IND; } + | T_MODE_A { $$ = REG_A; } ; -T_MODE_A : T_TOKEN_A - | T_OP_HIGH '(' T_MODE_AF ')' -; -T_MODE_B : T_TOKEN_B - | T_OP_HIGH '(' T_MODE_BC ')' -; -T_MODE_C : T_TOKEN_C - | T_OP_LOW '(' T_MODE_BC ')' -; -T_MODE_D : T_TOKEN_D - | T_OP_HIGH '(' T_MODE_DE ')' -; -T_MODE_E : T_TOKEN_E - | T_OP_LOW '(' T_MODE_DE ')' -; -T_MODE_H : T_TOKEN_H - | T_OP_HIGH '(' T_MODE_HL ')' -; -T_MODE_L : T_TOKEN_L - | T_OP_LOW '(' T_MODE_HL ')' +reg_tt : T_MODE_BC { $$ = REG_BC; } + | T_MODE_DE { $$ = REG_DE; } + | T_MODE_HL { $$ = REG_HL; } + | T_MODE_AF { $$ = REG_AF; } ; -ccode : T_CC_NZ { $$ = CC_NZ; } - | T_CC_Z { $$ = CC_Z; } - | T_CC_NC { $$ = CC_NC; } - | T_TOKEN_C { $$ = CC_C; } +reg_ss : T_MODE_BC { $$ = REG_BC; } + | T_MODE_DE { $$ = REG_DE; } + | T_MODE_HL { $$ = REG_HL; } + | T_MODE_SP { $$ = REG_SP; } ; -reg_r : T_MODE_B { $$ = REG_B; } - | T_MODE_C { $$ = REG_C; } - | T_MODE_D { $$ = REG_D; } - | T_MODE_E { $$ = REG_E; } - | T_MODE_H { $$ = REG_H; } - | T_MODE_L { $$ = REG_L; } - | T_MODE_HL_IND { $$ = REG_HL_IND; } - | T_MODE_A { $$ = REG_A; } -; - -reg_tt : T_MODE_BC { $$ = REG_BC; } - | T_MODE_DE { $$ = REG_DE; } - | T_MODE_HL { $$ = REG_HL; } - | T_MODE_AF { $$ = REG_AF; } -; - -reg_ss : T_MODE_BC { $$ = REG_BC; } - | T_MODE_DE { $$ = REG_DE; } - | T_MODE_HL { $$ = REG_HL; } - | T_MODE_SP { $$ = REG_SP; } -; - -reg_rr : T_MODE_BC_IND { $$ = REG_BC_IND; } - | T_MODE_DE_IND { $$ = REG_DE_IND; } - | T_MODE_HL_INDINC { $$ = REG_HL_INDINC; } - | T_MODE_HL_INDDEC { $$ = REG_HL_INDDEC; } +reg_rr : T_MODE_BC_IND { $$ = REG_BC_IND; } + | T_MODE_DE_IND { $$ = REG_DE_IND; } + | T_MODE_HL_INDINC { $$ = REG_HL_INDINC; } + | T_MODE_HL_INDDEC { $$ = REG_HL_INDDEC; } ; %% diff --git a/src/asm/charmap.c b/src/asm/charmap.c index c3d5c666..1c0f4070 100644 --- a/src/asm/charmap.c +++ b/src/asm/charmap.c @@ -24,32 +24,46 @@ #include static const uint8_t utf8d[] = { - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf - 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df - 0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef - 0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff - 0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0 - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2 - 1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4 - 1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6 - 1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00..0f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10..1f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 20..2f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 30..3f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40..4f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50..5f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60..6f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 70..7f */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80..8f */ + 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, /* 90..9f */ + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, /* a0..af */ + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, /* b0..bf */ + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* c0..cf */ + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* d0..df */ + 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, /* e0..e7 */ + 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, /* e8..ef */ + 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, /* f0..f7 */ + 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, /* f8..ff */ + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, /* s0.. */ + 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, /* ..s0 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* s1 */ + 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, /* s1 */ + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, /* s3 */ + 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, /* s4 */ + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, /* s5 */ + 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, /* s6 */ + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, /* s7 */ + 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* s8 */ }; -uint32_t -decode(uint32_t* state, uint32_t* codep, uint32_t byte) { - uint32_t type = utf8d[byte]; +uint32_t decode(uint32_t *state, uint32_t *codep, uint32_t byte) +{ + uint32_t type = utf8d[byte]; - *codep = (*state != 0) ? - (byte & 0x3fu) | (*codep << 6) : - (0xff >> type) & (byte); + *codep = (*state != 0) ? + (byte & 0x3fu) | (*codep << 6) : + (0xff >> type) & (byte); - *state = utf8d[256 + *state*16 + type]; - return *state; + *state = utf8d[256 + *state * 16 + type]; + return *state; } /* @@ -79,19 +93,15 @@ decode(uint32_t* state, uint32_t* codep, uint32_t byte) { struct Charmap globalCharmap = {0}; -extern struct Section *pCurrentSection; - -int32_t -readUTF8Char(char *dest, char *src) +int32_t readUTF8Char(char *dest, char *src) { uint32_t state; uint32_t codep; int32_t i; for (i = 0, state = 0;; i++) { - if (decode(&state, &codep, (uint8_t)src[i]) == 1) { + if (decode(&state, &codep, (uint8_t)src[i]) == 1) fatalerror("invalid UTF-8 character"); - } dest[i] = src[i]; @@ -104,13 +114,12 @@ readUTF8Char(char *dest, char *src) } } -int32_t -charmap_Add(char *input, uint8_t output) +int32_t charmap_Add(char *input, uint8_t output) { int32_t i; size_t input_length; - char temp1i[CHARMAPLENGTH + 1], temp2i[CHARMAPLENGTH + 1], temp1o = 0, - temp2o = 0; + char temp1i[CHARMAPLENGTH + 1], temp2i[CHARMAPLENGTH + 1]; + char temp1o = 0, temp2o = 0; struct Charmap *charmap; @@ -118,23 +127,21 @@ charmap_Add(char *input, uint8_t output) if (pCurrentSection->charmap) { charmap = pCurrentSection->charmap; } else { - if ((charmap = calloc(1, sizeof(struct Charmap))) == - NULL) { + charmap = calloc(1, sizeof(struct Charmap)); + if (charmap == NULL) fatalerror("Not enough memory for charmap"); - } + pCurrentSection->charmap = charmap; } } else { charmap = &globalCharmap; } - if (nPass == 2) { + if (nPass == 2) return charmap->count; - } - if (charmap->count > MAXCHARMAPS || strlen(input) > CHARMAPLENGTH) { + if (charmap->count > MAXCHARMAPS || strlen(input) > CHARMAPLENGTH) return -1; - } input_length = strlen(input); if (input_length > 1) { @@ -142,7 +149,7 @@ charmap_Add(char *input, uint8_t output) while (i < charmap->count + 1) { if (input_length > strlen(charmap->input[i])) { memcpy(temp1i, charmap->input[i], - CHARMAPLENGTH + 1); + CHARMAPLENGTH + 1); memcpy(charmap->input[i], input, input_length); temp1o = charmap->output[i]; charmap->output[i] = output; @@ -161,7 +168,7 @@ charmap_Add(char *input, uint8_t output) i++; } memcpy(charmap->input[charmap->count + 1], temp1i, - CHARMAPLENGTH + 1); + CHARMAPLENGTH + 1); charmap->output[charmap->count + 1] = temp1o; } else { memcpy(charmap->input[charmap->count], input, input_length); @@ -170,8 +177,7 @@ charmap_Add(char *input, uint8_t output) return ++charmap->count; } -int32_t -charmap_Convert(char **input) +int32_t charmap_Convert(char **input) { struct Charmap *charmap; @@ -179,15 +185,14 @@ charmap_Convert(char **input) char *buffer; int32_t i, j, length; - if (pCurrentSection && pCurrentSection->charmap) { + if (pCurrentSection && pCurrentSection->charmap) charmap = pCurrentSection->charmap; - } else { + else charmap = &globalCharmap; - } - if ((buffer = malloc(strlen(*input))) == NULL) { + buffer = malloc(strlen(*input)); + if (buffer == NULL) fatalerror("Not enough memory for buffer"); - } length = 0; while (**input) { @@ -201,15 +206,15 @@ charmap_Convert(char **input) } j = 0; } - if (!j) { + + if (!j) j = readUTF8Char(outchar, *input); - } + if (!outchar[0]) { buffer[length++] = 0; } else { - for (i = 0; outchar[i]; i++) { + for (i = 0; outchar[i]; i++) buffer[length++] = outchar[i]; - } } *input += j; } diff --git a/src/asm/fstack.c b/src/asm/fstack.c index cf2ac6ee..e5b57fad 100644 --- a/src/asm/fstack.c +++ b/src/asm/fstack.c @@ -19,19 +19,19 @@ #include "types.h" -struct sContext *pFileStack; -struct sSymbol *pCurrentMacro; -YY_BUFFER_STATE CurrentFlexHandle; -FILE *pCurrentFile; -uint32_t nCurrentStatus; +static struct sContext *pFileStack; +static struct sSymbol *pCurrentMacro; +static YY_BUFFER_STATE CurrentFlexHandle; +static FILE *pCurrentFile; +static uint32_t nCurrentStatus; char tzCurrentFileName[_MAX_PATH + 1]; -char IncludePaths[MAXINCPATHS][_MAX_PATH + 1]; -int32_t NextIncPath = 0; -uint32_t nMacroCount; +static char IncludePaths[MAXINCPATHS][_MAX_PATH + 1]; +static int32_t NextIncPath; +static uint32_t nMacroCount; -char *pCurrentREPTBlock; -uint32_t nCurrentREPTBlockSize; -uint32_t nCurrentREPTBlockCount; +static char *pCurrentREPTBlock; +static uint32_t nCurrentREPTBlockSize; +static uint32_t nCurrentREPTBlockCount; uint32_t ulMacroReturnValue; @@ -49,8 +49,7 @@ extern FILE *dependfile; /* * Context push and pop */ -void -pushcontext(void) +static void pushcontext(void) { struct sContext **ppFileStack; @@ -58,36 +57,37 @@ pushcontext(void) while (*ppFileStack) ppFileStack = &((*ppFileStack)->pNext); - if ((*ppFileStack = malloc(sizeof(struct sContext))) != NULL) { - (*ppFileStack)->FlexHandle = CurrentFlexHandle; - (*ppFileStack)->pNext = NULL; - strcpy((char *) (*ppFileStack)->tzFileName, - (char *) tzCurrentFileName); - (*ppFileStack)->nLine = nLineNo; - switch ((*ppFileStack)->nStatus = nCurrentStatus) { - case STAT_isMacroArg: - case STAT_isMacro: - sym_SaveCurrentMacroArgs((*ppFileStack)->tzMacroArgs); - (*ppFileStack)->pMacro = pCurrentMacro; - break; - case STAT_isInclude: - (*ppFileStack)->pFile = pCurrentFile; - break; - case STAT_isREPTBlock: - sym_SaveCurrentMacroArgs((*ppFileStack)->tzMacroArgs); - (*ppFileStack)->pREPTBlock = pCurrentREPTBlock; - (*ppFileStack)->nREPTBlockSize = nCurrentREPTBlockSize; - (*ppFileStack)->nREPTBlockCount = - nCurrentREPTBlockCount; - break; - } - nLineNo = 0; - } else + *ppFileStack = malloc(sizeof(struct sContext)); + + if (*ppFileStack == NULL) fatalerror("No memory for context"); + + (*ppFileStack)->FlexHandle = CurrentFlexHandle; + (*ppFileStack)->pNext = NULL; + strcpy((char *)(*ppFileStack)->tzFileName, (char *)tzCurrentFileName); + (*ppFileStack)->nLine = nLineNo; + + switch ((*ppFileStack)->nStatus = nCurrentStatus) { + case STAT_isMacroArg: + case STAT_isMacro: + sym_SaveCurrentMacroArgs((*ppFileStack)->tzMacroArgs); + (*ppFileStack)->pMacro = pCurrentMacro; + break; + case STAT_isInclude: + (*ppFileStack)->pFile = pCurrentFile; + break; + case STAT_isREPTBlock: + sym_SaveCurrentMacroArgs((*ppFileStack)->tzMacroArgs); + (*ppFileStack)->pREPTBlock = pCurrentREPTBlock; + (*ppFileStack)->nREPTBlockSize = nCurrentREPTBlockSize; + (*ppFileStack)->nREPTBlockCount = nCurrentREPTBlockCount; + break; + } + + nLineNo = 0; } -static int32_t -popcontext(void) +static int32_t popcontext(void) { struct sContext *pLastFile, **ppLastFile; @@ -95,63 +95,67 @@ popcontext(void) if (--nCurrentREPTBlockCount) { yy_delete_buffer(CurrentFlexHandle); CurrentFlexHandle = - yy_scan_bytes(pCurrentREPTBlock, - nCurrentREPTBlockSize); + yy_scan_bytes(pCurrentREPTBlock, + nCurrentREPTBlockSize); yy_switch_to_buffer(CurrentFlexHandle); sym_UseCurrentMacroArgs(); sym_SetMacroArgID(nMacroCount++); sym_UseNewMacroArgs(); - return (0); + return 0; } } - if ((pLastFile = pFileStack) != NULL) { - ppLastFile = &pFileStack; - while (pLastFile->pNext) { - ppLastFile = &(pLastFile->pNext); - pLastFile = *ppLastFile; - } - yy_delete_buffer(CurrentFlexHandle); - nLineNo = pLastFile->nLine; - if (nCurrentStatus == STAT_isInclude) - fclose(pCurrentFile); - if (nCurrentStatus == STAT_isMacro) { - sym_FreeCurrentMacroArgs(); - nLineNo += 1; - } - if (nCurrentStatus == STAT_isREPTBlock) - nLineNo += 1; + pLastFile = pFileStack; + if (pLastFile == NULL) + return 1; - CurrentFlexHandle = pLastFile->FlexHandle; - strcpy((char *) tzCurrentFileName, - (char *) pLastFile->tzFileName); - switch (nCurrentStatus = pLastFile->nStatus) { - case STAT_isMacroArg: - case STAT_isMacro: - sym_RestoreCurrentMacroArgs(pLastFile->tzMacroArgs); - pCurrentMacro = pLastFile->pMacro; - break; - case STAT_isInclude: - pCurrentFile = pLastFile->pFile; - break; - case STAT_isREPTBlock: - sym_RestoreCurrentMacroArgs(pLastFile->tzMacroArgs); - pCurrentREPTBlock = pLastFile->pREPTBlock; - nCurrentREPTBlockSize = pLastFile->nREPTBlockSize; - nCurrentREPTBlockCount = pLastFile->nREPTBlockCount; - break; - } + ppLastFile = &pFileStack; + while (pLastFile->pNext) { + ppLastFile = &(pLastFile->pNext); + pLastFile = *ppLastFile; + } - free(*ppLastFile); - *ppLastFile = NULL; - yy_switch_to_buffer(CurrentFlexHandle); - return (0); - } else - return (1); + yy_delete_buffer(CurrentFlexHandle); + nLineNo = pLastFile->nLine; + + if (nCurrentStatus == STAT_isInclude) + fclose(pCurrentFile); + + if (nCurrentStatus == STAT_isMacro) { + sym_FreeCurrentMacroArgs(); + nLineNo += 1; + } + + if (nCurrentStatus == STAT_isREPTBlock) + nLineNo += 1; + + CurrentFlexHandle = pLastFile->FlexHandle; + strcpy((char *)tzCurrentFileName, (char *)pLastFile->tzFileName); + + switch (nCurrentStatus = pLastFile->nStatus) { + case STAT_isMacroArg: + case STAT_isMacro: + sym_RestoreCurrentMacroArgs(pLastFile->tzMacroArgs); + pCurrentMacro = pLastFile->pMacro; + break; + case STAT_isInclude: + pCurrentFile = pLastFile->pFile; + break; + case STAT_isREPTBlock: + sym_RestoreCurrentMacroArgs(pLastFile->tzMacroArgs); + pCurrentREPTBlock = pLastFile->pREPTBlock; + nCurrentREPTBlockSize = pLastFile->nREPTBlockSize; + nCurrentREPTBlockCount = pLastFile->nREPTBlockCount; + break; + } + + free(*ppLastFile); + *ppLastFile = NULL; + yy_switch_to_buffer(CurrentFlexHandle); + return 0; } -int32_t -fstk_GetLine(void) +int32_t fstk_GetLine(void) { struct sContext *pLastFile, **ppLastFile; @@ -167,7 +171,9 @@ fstk_GetLine(void) break; /* Peek top file of the stack */ } - if ((pLastFile = pFileStack) != NULL) { + pLastFile = pFileStack; + + if (pLastFile != NULL) { ppLastFile = &pFileStack; while (pLastFile->pNext) { ppLastFile = &(pLastFile->pNext); @@ -176,24 +182,24 @@ fstk_GetLine(void) return pLastFile->nLine; } - /* This is only reached if the lexer is in REPT or MACRO mode but there - * are no saved contexts with the origin of said REPT or MACRO. */ - fatalerror("fstk_GetLine: Internal error."); + /* + * This is only reached if the lexer is in REPT or MACRO mode but there + * are no saved contexts with the origin of said REPT or MACRO. + */ + fatalerror("%s: Internal error.", __func__); } -int -yywrap(void) +int yywrap(void) { - return (popcontext()); + return popcontext(); } /* * Dump the context stack to stderr */ -void -fstk_Dump(void) +void fstk_Dump(void) { - struct sContext *pLastFile; + const struct sContext *pLastFile; pLastFile = pFileStack; @@ -209,46 +215,44 @@ fstk_Dump(void) /* * Extra includepath stuff */ -void -fstk_AddIncludePath(char *s) +void fstk_AddIncludePath(char *s) { - if (NextIncPath == MAXINCPATHS) { + if (NextIncPath == MAXINCPATHS) fatalerror("Too many include directories passed from command line"); - return; - } - if (strlcpy(IncludePaths[NextIncPath++], s, _MAX_PATH) >= _MAX_PATH) { - fatalerror("Include path too long '%s'",s); - return; - } + if (strlcpy(IncludePaths[NextIncPath++], s, _MAX_PATH) >= _MAX_PATH) + fatalerror("Include path too long '%s'", s); } -FILE * -fstk_FindFile(char *fname) +FILE *fstk_FindFile(char *fname) { char path[_MAX_PATH]; int32_t i; FILE *f; - if ((f = fopen(fname, "rb")) != NULL || errno != ENOENT) { - if (dependfile) { + f = fopen(fname, "rb"); + + if (f != NULL || errno != ENOENT) { + if (dependfile) fprintf(dependfile, "%s: %s\n", tzObjectname, fname); - } + return f; } for (i = 0; i < NextIncPath; ++i) { - if (strlcpy(path, IncludePaths[i], sizeof path) >= - sizeof path) { + if (strlcpy(path, IncludePaths[i], sizeof(path)) + >= sizeof(path)) continue; - } - if (strlcat(path, fname, sizeof path) >= sizeof path) { - continue; - } - if ((f = fopen(path, "rb")) != NULL || errno != ENOENT) { + if (strlcat(path, fname, sizeof(path)) >= sizeof(path)) + continue; + + f = fopen(path, "rb"); + + if (f != NULL || errno != ENOENT) { if (dependfile) { - fprintf(dependfile, "%s: %s\n", tzObjectname, path); + fprintf(dependfile, "%s: %s\n", tzObjectname, + path); } return f; } @@ -261,17 +265,12 @@ fstk_FindFile(char *fname) /* * Set up an include file for parsing */ -void -fstk_RunInclude(char *tzFileName) +void fstk_RunInclude(char *tzFileName) { - FILE *f; + FILE *f = fstk_FindFile(tzFileName); - f = fstk_FindFile(tzFileName); - - if (f == NULL) { - err(1, "Unable to open included file '%s'", - tzFileName); - } + if (f == NULL) + err(1, "Unable to open included file '%s'", tzFileName); pushcontext(); nLineNo = 1; @@ -281,7 +280,7 @@ fstk_RunInclude(char *tzFileName) CurrentFlexHandle = yy_create_buffer(pCurrentFile); yy_switch_to_buffer(CurrentFlexHandle); - //Dirty hack to give the INCLUDE directive a linefeed + /* Dirty hack to give the INCLUDE directive a linefeed */ yyunput('\n'); nLineNo -= 1; @@ -290,35 +289,35 @@ fstk_RunInclude(char *tzFileName) /* * Set up a macro for parsing */ -uint32_t -fstk_RunMacro(char *s) +uint32_t fstk_RunMacro(char *s) { - struct sSymbol *sym; + struct sSymbol *sym = sym_FindMacro(s); - if ((sym = sym_FindMacro(s)) != NULL) { - pushcontext(); - sym_SetMacroArgID(nMacroCount++); - nLineNo = -1; - sym_UseNewMacroArgs(); - nCurrentStatus = STAT_isMacro; - strcpy(tzCurrentFileName, s); - if (sym->pMacro == NULL) - return 0; - pCurrentMacro = sym; - CurrentFlexHandle = - yy_scan_bytes(pCurrentMacro->pMacro, - strlen(pCurrentMacro->pMacro)); - yy_switch_to_buffer(CurrentFlexHandle); - return (1); - } else - return (0); + if (sym == NULL) + return 0; + + pushcontext(); + sym_SetMacroArgID(nMacroCount++); + nLineNo = -1; + sym_UseNewMacroArgs(); + nCurrentStatus = STAT_isMacro; + strcpy(tzCurrentFileName, s); + + if (sym->pMacro == NULL) + return 0; + + pCurrentMacro = sym; + CurrentFlexHandle = yy_scan_bytes(pCurrentMacro->pMacro, + strlen(pCurrentMacro->pMacro)); + yy_switch_to_buffer(CurrentFlexHandle); + + return 1; } /* * Set up a macroargument for parsing */ -void -fstk_RunMacroArg(int32_t s) +void fstk_RunMacroArg(int32_t s) { char *sym; @@ -327,40 +326,41 @@ fstk_RunMacroArg(int32_t s) else s -= '0'; - if ((sym = sym_FindMacroArg(s)) != NULL) { - pushcontext(); - nCurrentStatus = STAT_isMacroArg; - sprintf(tzCurrentFileName, "%c", (uint8_t) s); - CurrentFlexHandle = yy_scan_bytes(sym, strlen(sym)); - yy_switch_to_buffer(CurrentFlexHandle); - } else + sym = sym_FindMacroArg(s); + + if (sym == NULL) fatalerror("No such macroargument"); + + pushcontext(); + nCurrentStatus = STAT_isMacroArg; + sprintf(tzCurrentFileName, "%c", (uint8_t)s); + CurrentFlexHandle = yy_scan_bytes(sym, strlen(sym)); + yy_switch_to_buffer(CurrentFlexHandle); } /* * Set up a stringequate for parsing */ -void -fstk_RunString(char *s) +void fstk_RunString(char *s) { - struct sSymbol *pSym; + const struct sSymbol *pSym = sym_FindSymbol(s); - if ((pSym = sym_FindSymbol(s)) != NULL) { + if (pSym != NULL) { pushcontext(); nCurrentStatus = STAT_isMacroArg; strcpy(tzCurrentFileName, s); CurrentFlexHandle = - yy_scan_bytes(pSym->pMacro, strlen(pSym->pMacro)); + yy_scan_bytes(pSym->pMacro, strlen(pSym->pMacro)); yy_switch_to_buffer(CurrentFlexHandle); - } else + } else { yyerror("No such string symbol '%s'", s); + } } /* * Set up a repeat block for parsing */ -void -fstk_RunRept(uint32_t count) +void fstk_RunRept(uint32_t count) { if (count) { pushcontext(); @@ -372,7 +372,7 @@ fstk_RunRept(uint32_t count) nCurrentREPTBlockSize = ulNewMacroSize; pCurrentREPTBlock = tzNewMacro; CurrentFlexHandle = - yy_scan_bytes(pCurrentREPTBlock, nCurrentREPTBlockSize); + yy_scan_bytes(pCurrentREPTBlock, nCurrentREPTBlockSize); yy_switch_to_buffer(CurrentFlexHandle); } } @@ -380,21 +380,19 @@ fstk_RunRept(uint32_t count) /* * Initialize the filestack routines */ -void -fstk_Init(char *s) +void fstk_Init(char *s) { char tzFileName[_MAX_PATH + 1]; - char tzSymFileName[_MAX_PATH + 1 + 2]; + snprintf(tzSymFileName, sizeof(tzSymFileName), "\"%s\"", s); sym_AddString("__FILE__", tzSymFileName); strcpy(tzFileName, s); pFileStack = NULL; pCurrentFile = fopen(tzFileName, "rb"); - if (pCurrentFile == NULL) { + if (pCurrentFile == NULL) err(1, "Unable to open file '%s'", tzFileName); - } nMacroCount = 0; nCurrentStatus = STAT_isInclude; diff --git a/src/asm/globlex.c b/src/asm/globlex.c index eb41c7ab..b3940cc7 100644 --- a/src/asm/globlex.c +++ b/src/asm/globlex.c @@ -14,40 +14,35 @@ #include #include -bool oDontExpandStrings = false; +bool oDontExpandStrings; int32_t nGBGfxID = -1; int32_t nBinaryID = -1; -int32_t -gbgfx2bin(char ch) +static int32_t gbgfx2bin(char ch) { int32_t i; for (i = 0; i <= 3; i += 1) { - if (CurrentOptions.gbgfx[i] == ch) { - return (i); - } + if (CurrentOptions.gbgfx[i] == ch) + return i; } - return (0); + return 0; } -int32_t -binary2bin(char ch) +static int32_t binary2bin(char ch) { int32_t i; for (i = 0; i <= 1; i += 1) { - if (CurrentOptions.binary[i] == ch) { - return (i); - } + if (CurrentOptions.binary[i] == ch) + return i; } - return (0); + return 0; } -int32_t -char2bin(char ch) +static int32_t char2bin(char ch) { if (ch >= 'a' && ch <= 'f') return (ch - 'a' + 10); @@ -58,13 +53,12 @@ char2bin(char ch) if (ch >= '0' && ch <= '9') return (ch - '0'); - return (0); + return 0; } typedef int32_t(*x2bin) (char ch); -int32_t -ascii2bin(char *s) +static int32_t ascii2bin(char *s) { int32_t radix = 10; int32_t result = 0; @@ -105,11 +99,10 @@ ascii2bin(char *s) result = result * radix + convertfunc(*s++); } - return (result); + return result; } -uint32_t -ParseFixedPoint(char *s, uint32_t size) +uint32_t ParseFixedPoint(char *s, uint32_t size) { uint32_t i = 0, dot = 0; @@ -125,13 +118,12 @@ ParseFixedPoint(char *s, uint32_t size) yyunputbytes(size); - yylval.nConstValue = (int32_t) (atof(s) * 65536); + yylval.nConstValue = (int32_t)(atof(s) * 65536); - return (1); + return 1; } -uint32_t -ParseNumber(char *s, uint32_t size) +uint32_t ParseNumber(char *s, uint32_t size) { char dest[256]; @@ -139,11 +131,10 @@ ParseNumber(char *s, uint32_t size) dest[size] = 0; yylval.nConstValue = ascii2bin(dest); - return (1); + return 1; } -uint32_t -ParseSymbol(char *src, uint32_t size) +uint32_t ParseSymbol(char *src, uint32_t size) { char dest[MAXSYMLEN + 1]; int32_t copied = 0, size_backup = size; @@ -155,13 +146,13 @@ ParseSymbol(char *src, uint32_t size) src += 1; size -= 1; - if (*src == '@') + if (*src == '@') { marg = sym_FindMacroArg(-1); - else if (*src >= '0' && *src <= '9') + } else if (*src >= '0' && *src <= '9') { marg = sym_FindMacroArg(*src - '0'); - else { + } else { fatalerror("Malformed ID"); - return (0); + return 0; } src += 1; @@ -189,47 +180,48 @@ ParseSymbol(char *src, uint32_t size) yyunputstr(s = sym_GetStringValue(dest)); while (*s) { - if (*s++ == '\n') { + if (*s++ == '\n') nLineNo -= 1; - } } - return (0); - } else { - strcpy(yylval.tzString, dest); - return (1); + return 0; } + + strcpy(yylval.tzString, dest); + return 1; } -uint32_t -PutMacroArg(char *src, uint32_t size) +uint32_t PutMacroArg(char *src, uint32_t size) { char *s; yyskipbytes(size); if ((size == 2 && src[1] >= '1' && src[1] <= '9')) { - if ((s = sym_FindMacroArg(src[1] - '0')) != NULL) { + s = sym_FindMacroArg(src[1] - '0'); + + if (s != NULL) yyunputstr(s); - } else { + else yyerror("Macro argument not defined"); - } } else { yyerror("Invalid macro argument"); } - return (0); + return 0; } -uint32_t -PutUniqueArg(char *src, uint32_t size) +uint32_t PutUniqueArg(char *src, uint32_t size) { char *s; yyskipbytes(size); - if ((s = sym_FindMacroArg(-1)) != NULL) { + + s = sym_FindMacroArg(-1); + + if (s != NULL) yyunputstr(s); - } else { + else yyerror("Macro unique label string not defined"); - } - return (0); + + return 0; } enum { @@ -237,9 +229,9 @@ enum { T_LEX_MACROUNIQUE }; -extern struct sLexInitString localstrings[]; +extern const struct sLexInitString localstrings[]; -struct sLexInitString staticstrings[] = { +const struct sLexInitString staticstrings[] = { {"||", T_OP_LOGICOR}, {"&&", T_OP_LOGICAND}, {"==", T_OP_LOGICEQU}, @@ -329,7 +321,7 @@ struct sLexInitString staticstrings[] = { {"else", T_POP_ELSE}, {"elif", T_POP_ELIF}, {"endc", T_POP_ENDC}, - + {"union", T_POP_UNION}, {"nextu", T_POP_NEXTU}, {"endu", T_POP_ENDU}, @@ -367,27 +359,27 @@ struct sLexInitString staticstrings[] = { {NULL, 0} }; -struct sLexFloat tNumberToken = { +const struct sLexFloat tNumberToken = { ParseNumber, T_NUMBER }; -struct sLexFloat tFixedPointToken = { +const struct sLexFloat tFixedPointToken = { ParseFixedPoint, T_NUMBER }; -struct sLexFloat tIDToken = { +const struct sLexFloat tIDToken = { ParseSymbol, T_ID }; -struct sLexFloat tMacroArgToken = { +const struct sLexFloat tMacroArgToken = { PutMacroArg, T_LEX_MACROARG }; -struct sLexFloat tMacroUniqueToken = { +const struct sLexFloat tMacroUniqueToken = { PutUniqueArg, T_LEX_MACROUNIQUE }; @@ -403,7 +395,7 @@ setuplex(void) //Macro arguments - id = lex_FloatAlloc(&tMacroArgToken); + id = lex_FloatAlloc(&tMacroArgToken); lex_FloatAddFirstRange(id, '\\', '\\'); lex_FloatAddSecondRange(id, '1', '9'); id = lex_FloatAlloc(&tMacroUniqueToken); @@ -412,43 +404,45 @@ setuplex(void) //Decimal constants - id = lex_FloatAlloc(&tNumberToken); + id = lex_FloatAlloc(&tNumberToken); lex_FloatAddFirstRange(id, '0', '9'); lex_FloatAddSecondRange(id, '0', '9'); lex_FloatAddRange(id, '0', '9'); //Binary constants - nBinaryID = id = lex_FloatAlloc(&tNumberToken); + id = lex_FloatAlloc(&tNumberToken); + nBinaryID = id; lex_FloatAddFirstRange(id, '%', '%'); lex_FloatAddSecondRange(id, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatAddSecondRange(id, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); lex_FloatAddRange(id, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatAddRange(id, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); //Octal constants - id = lex_FloatAlloc(&tNumberToken); + id = lex_FloatAlloc(&tNumberToken); lex_FloatAddFirstRange(id, '&', '&'); lex_FloatAddSecondRange(id, '0', '7'); lex_FloatAddRange(id, '0', '7'); //Gameboy gfx constants - nGBGfxID = id = lex_FloatAlloc(&tNumberToken); + id = lex_FloatAlloc(&tNumberToken); + nGBGfxID = id; lex_FloatAddFirstRange(id, '`', '`'); lex_FloatAddSecondRange(id, CurrentOptions.gbgfx[0], - CurrentOptions.gbgfx[0]); + CurrentOptions.gbgfx[0]); lex_FloatAddSecondRange(id, CurrentOptions.gbgfx[1], - CurrentOptions.gbgfx[1]); + CurrentOptions.gbgfx[1]); lex_FloatAddSecondRange(id, CurrentOptions.gbgfx[2], - CurrentOptions.gbgfx[2]); + CurrentOptions.gbgfx[2]); lex_FloatAddSecondRange(id, CurrentOptions.gbgfx[3], - CurrentOptions.gbgfx[3]); + CurrentOptions.gbgfx[3]); lex_FloatAddRange(id, CurrentOptions.gbgfx[0], CurrentOptions.gbgfx[0]); lex_FloatAddRange(id, CurrentOptions.gbgfx[1], CurrentOptions.gbgfx[1]); lex_FloatAddRange(id, CurrentOptions.gbgfx[2], CurrentOptions.gbgfx[2]); @@ -456,7 +450,7 @@ setuplex(void) //Hex constants - id = lex_FloatAlloc(&tNumberToken); + id = lex_FloatAlloc(&tNumberToken); lex_FloatAddFirstRange(id, '$', '$'); lex_FloatAddSecondRange(id, '0', '9'); lex_FloatAddSecondRange(id, 'A', 'F'); @@ -467,7 +461,7 @@ setuplex(void) //ID 's - id = lex_FloatAlloc(&tIDToken); + id = lex_FloatAlloc(&tIDToken); lex_FloatAddFirstRange(id, 'a', 'z'); lex_FloatAddFirstRange(id, 'A', 'Z'); lex_FloatAddFirstRange(id, '_', '_'); @@ -489,7 +483,7 @@ setuplex(void) //Local ID - id = lex_FloatAlloc(&tIDToken); + id = lex_FloatAlloc(&tIDToken); lex_FloatAddFirstRange(id, '.', '.'); lex_FloatAddSecondRange(id, 'a', 'z'); lex_FloatAddSecondRange(id, 'A', 'Z'); @@ -504,17 +498,16 @@ setuplex(void) //@ID - id = lex_FloatAlloc(&tIDToken); + id = lex_FloatAlloc(&tIDToken); lex_FloatAddFirstRange(id, '@', '@'); //Fixed point constants - id = lex_FloatAlloc(&tFixedPointToken); + id = lex_FloatAlloc(&tFixedPointToken); lex_FloatAddFirstRange(id, '.', '.'); lex_FloatAddFirstRange(id, '0', '9'); lex_FloatAddSecondRange(id, '.', '.'); lex_FloatAddSecondRange(id, '0', '9'); lex_FloatAddRange(id, '.', '.'); lex_FloatAddRange(id, '0', '9'); - } diff --git a/src/asm/lexer.c b/src/asm/lexer.c index 4678f34f..4da26ef9 100644 --- a/src/asm/lexer.c +++ b/src/asm/lexer.c @@ -21,11 +21,12 @@ struct sLexString { uint32_t nNameLength; struct sLexString *pNext; }; -#define pLexBufferRealStart (pCurrentBuffer->pBufferRealStart) -#define pLexBuffer (pCurrentBuffer->pBuffer) -#define AtLineStart (pCurrentBuffer->oAtLineStart) -#define SAFETYMARGIN 1024 +#define pLexBufferRealStart (pCurrentBuffer->pBufferRealStart) +#define pLexBuffer (pCurrentBuffer->pBuffer) +#define AtLineStart (pCurrentBuffer->oAtLineStart) + +#define SAFETYMARGIN 1024 extern size_t symvaluetostring(char *dest, size_t maxLength, char *sym); @@ -40,8 +41,7 @@ uint32_t tFloatingChars[256]; uint32_t nFloating; enum eLexerState lexerstate = LEX_STATE_NORMAL; -void -upperstring(char *s) +void upperstring(char *s) { while (*s) { *s = toupper(*s); @@ -49,8 +49,7 @@ upperstring(char *s) } } -void -lowerstring(char *s) +void lowerstring(char *s) { while (*s) { *s = tolower(*s); @@ -58,20 +57,17 @@ lowerstring(char *s) } } -void -yyskipbytes(uint32_t count) +void yyskipbytes(uint32_t count) { pLexBuffer += count; } -void -yyunputbytes(uint32_t count) +void yyunputbytes(uint32_t count) { pLexBuffer -= count; } -void -yyunput(char c) +void yyunput(char c) { if (pLexBuffer <= pLexBufferRealStart) fatalerror("Buffer safety margin exceeded"); @@ -79,8 +75,7 @@ yyunput(char c) *(--pLexBuffer) = c; } -void -yyunputstr(char *s) +void yyunputstr(char *s) { int32_t i, len; @@ -93,114 +88,109 @@ yyunputstr(char *s) *(--pLexBuffer) = s[i]; } -void -yy_switch_to_buffer(YY_BUFFER_STATE buf) +void yy_switch_to_buffer(YY_BUFFER_STATE buf) { pCurrentBuffer = buf; } -void -yy_set_state(enum eLexerState i) +void yy_set_state(enum eLexerState i) { lexerstate = i; } -void -yy_delete_buffer(YY_BUFFER_STATE buf) +void yy_delete_buffer(YY_BUFFER_STATE buf) { free(buf->pBufferStart - SAFETYMARGIN); free(buf); } -YY_BUFFER_STATE -yy_scan_bytes(char *mem, uint32_t size) +YY_BUFFER_STATE yy_scan_bytes(char *mem, uint32_t size) { - YY_BUFFER_STATE pBuffer; + YY_BUFFER_STATE pBuffer = malloc(sizeof(struct yy_buffer_state)); - if ((pBuffer = malloc(sizeof(struct yy_buffer_state))) != NULL) { - if ((pBuffer->pBufferRealStart = - malloc(size + 1 + SAFETYMARGIN)) != NULL) { - pBuffer->pBufferStart = pBuffer->pBufferRealStart + SAFETYMARGIN; - pBuffer->pBuffer = pBuffer->pBufferRealStart + SAFETYMARGIN; - memcpy(pBuffer->pBuffer, mem, size); - pBuffer->nBufferSize = size; - pBuffer->oAtLineStart = 1; - pBuffer->pBuffer[size] = 0; - return (pBuffer); - } - } - fatalerror("Out of memory!"); - return (NULL); + if (pBuffer == NULL) + fatalerror("%s: Out of memory!", __func__); + + pBuffer->pBufferRealStart = malloc(size + 1 + SAFETYMARGIN); + + if (pBuffer->pBufferRealStart == NULL) + fatalerror("%s: Out of memory for buffer!", __func__); + + pBuffer->pBufferStart = pBuffer->pBufferRealStart + SAFETYMARGIN; + pBuffer->pBuffer = pBuffer->pBufferRealStart + SAFETYMARGIN; + memcpy(pBuffer->pBuffer, mem, size); + pBuffer->nBufferSize = size; + pBuffer->oAtLineStart = 1; + pBuffer->pBuffer[size] = 0; + + return pBuffer; } -YY_BUFFER_STATE -yy_create_buffer(FILE * f) +YY_BUFFER_STATE yy_create_buffer(FILE *f) { - YY_BUFFER_STATE pBuffer; + YY_BUFFER_STATE pBuffer = malloc(sizeof(struct yy_buffer_state)); - if ((pBuffer = malloc(sizeof(struct yy_buffer_state))) != NULL) { - uint32_t size; + if (pBuffer == NULL) + fatalerror("%s: Out of memory!", __func__); - fseek(f, 0, SEEK_END); - size = ftell(f); - fseek(f, 0, SEEK_SET); + uint32_t size; - if ((pBuffer->pBufferRealStart = - malloc(size + 2 + SAFETYMARGIN)) != NULL) { - char *mem; - uint32_t instring = 0; + fseek(f, 0, SEEK_END); + size = ftell(f); + fseek(f, 0, SEEK_SET); - pBuffer->pBufferStart = pBuffer->pBufferRealStart + SAFETYMARGIN; - pBuffer->pBuffer = pBuffer->pBufferRealStart + SAFETYMARGIN; + pBuffer->pBufferRealStart = malloc(size + 2 + SAFETYMARGIN); - size = fread(pBuffer->pBuffer, sizeof(uint8_t), size, f); + if (pBuffer->pBufferRealStart == NULL) + fatalerror("%s: Out of memory for buffer!", __func__); - pBuffer->pBuffer[size] = '\n'; - pBuffer->pBuffer[size + 1] = 0; - pBuffer->nBufferSize = size + 1; + pBuffer->pBufferStart = pBuffer->pBufferRealStart + SAFETYMARGIN; + pBuffer->pBuffer = pBuffer->pBufferRealStart + SAFETYMARGIN; - mem = pBuffer->pBuffer; + size = fread(pBuffer->pBuffer, sizeof(uint8_t), size, f); - while (*mem) { - if (*mem == '\"') - instring = 1 - instring; + pBuffer->pBuffer[size] = '\n'; + pBuffer->pBuffer[size + 1] = 0; + pBuffer->nBufferSize = size + 1; - if (mem[0] == '\\' && - (mem[1] == '\"' || mem[1] == '\\')) { - mem += 2; - } else if (instring) { - mem += 1; - } else { - if ((mem[0] == 10 && mem[1] == 13) - || (mem[0] == 13 && mem[1] == 10)) { - mem[0] = ' '; - mem[1] = '\n'; - mem += 2; - } else if (mem[0] == 10 || mem[0] == 13) { - mem[0] = '\n'; - mem += 1; - } else if (mem[0] == '\n' && mem[1] == '*') { - mem += 1; - while (!(*mem == '\n' || *mem == '\0')) - *mem++ = ' '; - } else if (*mem == ';') { - while (!(*mem == '\n' || *mem == '\0')) - *mem++ = ' '; - } else - mem += 1; - } + char *mem = pBuffer->pBuffer; + uint32_t instring = 0; + + while (*mem) { + if (*mem == '\"') + instring = 1 - instring; + + if ((mem[0] == '\\') && (mem[1] == '\"' || mem[1] == '\\')) { + mem += 2; + } else if (instring) { + mem += 1; + } else { + if ((mem[0] == 10 && mem[1] == 13) + || (mem[0] == 13 && mem[1] == 10)) { + mem[0] = ' '; + mem[1] = '\n'; + mem += 2; + } else if (mem[0] == 10 || mem[0] == 13) { + mem[0] = '\n'; + mem += 1; + } else if (mem[0] == '\n' && mem[1] == '*') { + mem += 1; + while (!(*mem == '\n' || *mem == '\0')) + *mem++ = ' '; + } else if (*mem == ';') { + while (!(*mem == '\n' || *mem == '\0')) + *mem++ = ' '; + } else { + mem += 1; } - - pBuffer->oAtLineStart = 1; - return (pBuffer); } } - fatalerror("Out of memory!"); - return (NULL); + + pBuffer->oAtLineStart = 1; + return pBuffer; } -uint32_t -lex_FloatAlloc(struct sLexFloat *token) +uint32_t lex_FloatAlloc(const struct sLexFloat *token) { tLexFloat[nFloating] = *token; @@ -211,17 +201,15 @@ lex_FloatAlloc(struct sLexFloat *token) * Make sure that only non-zero ASCII characters are used. Also, check if the * start is greater than the end of the range. */ -void -lex_CheckCharacterRange(uint16_t start, uint16_t end) +void lex_CheckCharacterRange(uint16_t start, uint16_t end) { if (start > end || start < 1 || end > 127) { errx(1, "Invalid character range (start: %u, end: %u)", - start, end); + start, end); } } -void -lex_FloatDeleteRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatDeleteRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -231,8 +219,7 @@ lex_FloatDeleteRange(uint32_t id, uint16_t start, uint16_t end) } } -void -lex_FloatAddRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatAddRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -242,8 +229,7 @@ lex_FloatAddRange(uint32_t id, uint16_t start, uint16_t end) } } -void -lex_FloatDeleteFirstRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatDeleteFirstRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -253,8 +239,7 @@ lex_FloatDeleteFirstRange(uint32_t id, uint16_t start, uint16_t end) } } -void -lex_FloatAddFirstRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatAddFirstRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -264,8 +249,7 @@ lex_FloatAddFirstRange(uint32_t id, uint16_t start, uint16_t end) } } -void -lex_FloatDeleteSecondRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatDeleteSecondRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -275,8 +259,7 @@ lex_FloatDeleteSecondRange(uint32_t id, uint16_t start, uint16_t end) } } -void -lex_FloatAddSecondRange(uint32_t id, uint16_t start, uint16_t end) +void lex_FloatAddSecondRange(uint32_t id, uint16_t start, uint16_t end) { lex_CheckCharacterRange(start, end); @@ -286,12 +269,10 @@ lex_FloatAddSecondRange(uint32_t id, uint16_t start, uint16_t end) } } -struct sLexFloat * -lexgetfloat(uint32_t nFloatMask) +static struct sLexFloat *lexgetfloat(uint32_t nFloatMask) { - if (nFloatMask == 0) { - fatalerror("Internal error in lexgetfloat"); - } + if (nFloatMask == 0) + fatalerror("Internal error in %s", __func__); int32_t i = 0; @@ -300,29 +281,25 @@ lexgetfloat(uint32_t nFloatMask) i++; } - return (&tLexFloat[i]); + return &tLexFloat[i]; } -uint32_t -lexcalchash(char *s) +static uint32_t lexcalchash(char *s) { uint32_t hash = 0; - while (*s) { + while (*s) hash = (hash * 283) ^ toupper(*s++); - } - return (hash % LEXHASHSIZE); + return hash % LEXHASHSIZE; } -void -lex_Init(void) +void lex_Init(void) { uint32_t i; - for (i = 0; i < LEXHASHSIZE; i++) { + for (i = 0; i < LEXHASHSIZE; i++) tLexHash[i] = NULL; - } for (i = 0; i < 256; i++) { tFloatingFirstChar[i] = 0; @@ -334,8 +311,7 @@ lex_Init(void) nFloating = 0; } -void -lex_AddStrings(struct sLexInitString * lex) +void lex_AddStrings(const struct sLexInitString *lex) { while (lex->tzName) { struct sLexString **ppHash; @@ -345,23 +321,23 @@ lex_AddStrings(struct sLexInitString * lex) while (*ppHash) ppHash = &((*ppHash)->pNext); - if (((*ppHash) = malloc(sizeof(struct sLexString))) != NULL) { - if (((*ppHash)->tzName = - (char *) strdup(lex->tzName)) != NULL) { - (*ppHash)->nNameLength = strlen(lex->tzName); - (*ppHash)->nToken = lex->nToken; - (*ppHash)->pNext = NULL; - - upperstring((*ppHash)->tzName); - - if ((*ppHash)->nNameLength > nLexMaxLength) - nLexMaxLength = (*ppHash)->nNameLength; - - } else - fatalerror("Out of memory!"); - } else + *ppHash = malloc(sizeof(struct sLexString)); + if (*ppHash == NULL) fatalerror("Out of memory!"); + (*ppHash)->tzName = (char *)strdup(lex->tzName); + if ((*ppHash)->tzName == NULL) + fatalerror("Out of memory!"); + + (*ppHash)->nNameLength = strlen(lex->tzName); + (*ppHash)->nToken = lex->nToken; + (*ppHash)->pNext = NULL; + + upperstring((*ppHash)->tzName); + + if ((*ppHash)->nNameLength > nLexMaxLength) + nLexMaxLength = (*ppHash)->nNameLength; + lex += 1; } } @@ -376,11 +352,12 @@ lex_AddStrings(struct sLexInitString * lex) * The token types with the longest match from the current position in the * buffer will have their bits set in the float mask. */ -void -yylex_GetFloatMaskAndFloatLen(uint32_t *pnFloatMask, uint32_t *pnFloatLen) +void yylex_GetFloatMaskAndFloatLen(uint32_t *pnFloatMask, uint32_t *pnFloatLen) { - // Note that '\0' should always have a bit mask of 0 in the "floating" - // tables, so it doesn't need to be checked for separately. + /* + * Note that '\0' should always have a bit mask of 0 in the "floating" + * tables, so it doesn't need to be checked for separately. + */ char *s = pLexBuffer; uint32_t nOldFloatMask = 0; @@ -405,8 +382,7 @@ yylex_GetFloatMaskAndFloatLen(uint32_t *pnFloatMask, uint32_t *pnFloatLen) /* * Gets the longest keyword/operator from the current position in the buffer. */ -struct sLexString * -yylex_GetLongestFixed() +struct sLexString *yylex_GetLongestFixed() { struct sLexString *pLongestFixed = NULL; char *s = pLexBuffer; @@ -433,8 +409,7 @@ yylex_GetLongestFixed() return pLongestFixed; } -size_t -CopyMacroArg(char *dest, size_t maxLength, char c) +size_t CopyMacroArg(char *dest, size_t maxLength, char c) { size_t i; char *s; @@ -459,35 +434,33 @@ CopyMacroArg(char *dest, size_t maxLength, char c) return 0; } - if ((s = sym_FindMacroArg(argNum)) == NULL) + s = sym_FindMacroArg(argNum); + + if (s == NULL) fatalerror("Macro argument not defined"); for (i = 0; s[i] != 0; i++) { - if (i >= maxLength) { + if (i >= maxLength) fatalerror("Macro argument too long to fit buffer"); - } + dest[i] = s[i]; } return i; } -static inline void -yylex_StringWriteChar(char *s, size_t index, char c) +static inline void yylex_StringWriteChar(char *s, size_t index, char c) { - if (index >= MAXSTRLEN) { + if (index >= MAXSTRLEN) fatalerror("String too long"); - } s[index] = c; } -static inline void -yylex_SymbolWriteChar(char *s, size_t index, char c) +static inline void yylex_SymbolWriteChar(char *s, size_t index, char c) { - if (index >= MAXSYMLEN) { + if (index >= MAXSYMLEN) fatalerror("Symbol too long"); - } s[index] = c; } @@ -498,14 +471,15 @@ yylex_SymbolWriteChar(char *s, size_t index, char c) */ void yylex_TrimEnd(char *s, size_t index) { - int32_t i; + int32_t i = (int32_t)index - 1; - for (i = (int32_t)index - 1; i >= 0 && (s[i] == ' ' || s[i] == '\t'); i--) + while ((i >= 0) && (s[i] == ' ' || s[i] == '\t')) { s[i] = 0; + i--; + } } -size_t -yylex_ReadBracketedSymbol(char *dest, size_t index) +size_t yylex_ReadBracketedSymbol(char *dest, size_t index) { char sym[MAXSYMLEN + 1]; char ch; @@ -524,13 +498,15 @@ yylex_ReadBracketedSymbol(char *dest, size_t index) i += length; else fatalerror("Illegal character escape '%c'", ch); - } else + } else { yylex_SymbolWriteChar(sym, i++, ch); + } } yylex_SymbolWriteChar(sym, i, 0); - maxLength = MAXSTRLEN - index; // it's assumed we're writing to a T_STRING + /* It's assumed we're writing to a T_STRING */ + maxLength = MAXSTRLEN - index; length = symvaluetostring(&dest[index], maxLength, sym); if (*pLexBuffer == '}') @@ -541,8 +517,7 @@ yylex_ReadBracketedSymbol(char *dest, size_t index) return length; } -void -yylex_ReadQuotedString() +static void yylex_ReadQuotedString(void) { size_t index = 0; size_t length, maxLength; @@ -577,19 +552,22 @@ yylex_ReadQuotedString() break; default: maxLength = MAXSTRLEN - index; - length = CopyMacroArg(&yylval.tzString[index], maxLength, ch); + length = CopyMacroArg(&yylval.tzString[index], + maxLength, ch); if (length != 0) index += length; else - fatalerror("Illegal character escape '%c'", ch); + fatalerror("Illegal character escape '%c'", + ch); ch = 0; break; } } else if (ch == '{') { // Get bracketed symbol within string. - index += yylex_ReadBracketedSymbol(yylval.tzString, index); + index += yylex_ReadBracketedSymbol(yylval.tzString, + index); ch = 0; } @@ -605,8 +583,7 @@ yylex_ReadQuotedString() fatalerror("Unterminated string"); } -uint32_t -yylex_NORMAL() +static uint32_t yylex_NORMAL(void) { struct sLexString *pLongestFixed = NULL; uint32_t nFloatMask, nFloatLen; @@ -629,15 +606,20 @@ scanagain: } } - // Try to match an identifier, macro argument (e.g. \1), - // or numeric literal. + /* + * Try to match an identifier, macro argument (e.g. \1), + * or numeric literal. + */ yylex_GetFloatMaskAndFloatLen(&nFloatMask, &nFloatLen); - // Try to match a keyword or operator. + /* Try to match a keyword or operator. */ pLongestFixed = yylex_GetLongestFixed(); if (nFloatLen == 0 && pLongestFixed == NULL) { - // No keyword, identifier, operator, or numerical literal matches. + /* + * No keyword, identifier, operator, or numerical literal + * matches. + */ if (*pLexBuffer == '"') { pLexBuffer++; @@ -647,52 +629,55 @@ scanagain: pLexBuffer++; yylex_ReadBracketedSymbol(yylval.tzString, 0); return T_STRING; - } else { - // It's not a keyword, operator, identifier, macro argument, - // numeric literal, string, or bracketed symbol, so just return - // the ASCII character. - if (*pLexBuffer == '\n') - AtLineStart = 1; - - return *pLexBuffer++; } + + /* + * It's not a keyword, operator, identifier, macro argument, + * numeric literal, string, or bracketed symbol, so just return + * the ASCII character. + */ + if (*pLexBuffer == '\n') + AtLineStart = 1; + + return *pLexBuffer++; } if (pLongestFixed == NULL || nFloatLen > pLongestFixed->nNameLength) { - // Longest match was an identifier, macro argument, or numeric literal. + /* + * Longest match was an identifier, macro argument, or numeric + * literal. + */ struct sLexFloat *token = lexgetfloat(nFloatMask); if (token->Callback) { int32_t done = token->Callback(pLexBuffer, nFloatLen); + if (!done) goto scanagain; } pLexBuffer += nFloatLen; - if (token->nToken == T_ID && linestart) { + if (token->nToken == T_ID && linestart) return T_LABEL; - } else { + else return token->nToken; - } } - // Longest match was a keyword or operator. + /* Longest match was a keyword or operator. */ pLexBuffer += pLongestFixed->nNameLength; return pLongestFixed->nToken; } -uint32_t -yylex_MACROARGS() +static uint32_t yylex_MACROARGS(void) { size_t index = 0; size_t length, maxLength; - while (*pLexBuffer == ' ' || *pLexBuffer == '\t') { + while ((*pLexBuffer == ' ') || (*pLexBuffer == '\t')) pLexBuffer++; - } - while (*pLexBuffer != ',' && (*pLexBuffer != '\n')) { + while ((*pLexBuffer != ',') && (*pLexBuffer != '\n')) { char ch = *pLexBuffer++; if (ch == '\\') { @@ -719,18 +704,21 @@ yylex_MACROARGS() break; default: maxLength = MAXSTRLEN - index; - length = CopyMacroArg(&yylval.tzString[index], maxLength, ch); + length = CopyMacroArg(&yylval.tzString[index], + maxLength, ch); if (length != 0) index += length; else - fatalerror("Illegal character escape '%c'", ch); + fatalerror("Illegal character escape '%c'", + ch); ch = 0; break; } } else if (ch == '{') { - index += yylex_ReadBracketedSymbol(yylval.tzString, index); + index += yylex_ReadBracketedSymbol(yylval.tzString, + index); ch = 0; } if (ch) @@ -740,7 +728,7 @@ yylex_MACROARGS() if (index) { yylex_StringWriteChar(yylval.tzString, index, 0); - // trim trailing white space at the end of the line + /* trim trailing white space at the end of the line */ if (*pLexBuffer == '\n') yylex_TrimEnd(yylval.tzString, index); @@ -754,12 +742,10 @@ yylex_MACROARGS() return ','; } - fatalerror("Internal error in yylex_MACROARGS"); - return 0; + fatalerror("Internal error in %s", __func__); } -uint32_t -yylex(void) +uint32_t yylex(void) { switch (lexerstate) { case LEX_STATE_NORMAL: @@ -768,6 +754,5 @@ yylex(void) return yylex_MACROARGS(); } - fatalerror("Internal error in yylex"); - return 0; + fatalerror("Internal error in %s", __func__); } diff --git a/src/asm/locallex.c b/src/asm/locallex.c index 7620f956..ba43a199 100644 --- a/src/asm/locallex.c +++ b/src/asm/locallex.c @@ -4,7 +4,7 @@ #include "asmy.h" -struct sLexInitString localstrings[] = { +const struct sLexInitString localstrings[] = { {"adc", T_Z80_ADC}, {"add", T_Z80_ADD}, {"and", T_Z80_AND}, diff --git a/src/asm/main.c b/src/asm/main.c index 2cabd81c..9f130282 100644 --- a/src/asm/main.c +++ b/src/asm/main.c @@ -11,6 +11,7 @@ #include "asm/fstack.h" #include "asm/output.h" #include "asm/main.h" + #include "extern/err.h" #include "extern/reallocarray.h" #include "extern/version.h" @@ -28,7 +29,7 @@ uint32_t nTotalLines, nPass, nPC, nIFDepth, nUnionDepth, nErrors; bool skipElif; uint32_t unionStart[128], unionSize[128]; -extern int yydebug; +/* extern int yydebug; */ FILE *dependfile; extern char *tzObjectname; @@ -45,73 +46,71 @@ struct sOptionStackEntry { struct sOptionStackEntry *pNext; }; -struct sOptionStackEntry *pOptionStack = NULL; +struct sOptionStackEntry *pOptionStack; -void -opt_SetCurrentOptions(struct sOptions * pOpt) +void opt_SetCurrentOptions(struct sOptions *pOpt) { if (nGBGfxID != -1) { lex_FloatDeleteRange(nGBGfxID, CurrentOptions.gbgfx[0], - CurrentOptions.gbgfx[0]); + CurrentOptions.gbgfx[0]); lex_FloatDeleteRange(nGBGfxID, CurrentOptions.gbgfx[1], - CurrentOptions.gbgfx[1]); + CurrentOptions.gbgfx[1]); lex_FloatDeleteRange(nGBGfxID, CurrentOptions.gbgfx[2], - CurrentOptions.gbgfx[2]); + CurrentOptions.gbgfx[2]); lex_FloatDeleteRange(nGBGfxID, CurrentOptions.gbgfx[3], - CurrentOptions.gbgfx[3]); + CurrentOptions.gbgfx[3]); lex_FloatDeleteSecondRange(nGBGfxID, CurrentOptions.gbgfx[0], - CurrentOptions.gbgfx[0]); + CurrentOptions.gbgfx[0]); lex_FloatDeleteSecondRange(nGBGfxID, CurrentOptions.gbgfx[1], - CurrentOptions.gbgfx[1]); + CurrentOptions.gbgfx[1]); lex_FloatDeleteSecondRange(nGBGfxID, CurrentOptions.gbgfx[2], - CurrentOptions.gbgfx[2]); + CurrentOptions.gbgfx[2]); lex_FloatDeleteSecondRange(nGBGfxID, CurrentOptions.gbgfx[3], - CurrentOptions.gbgfx[3]); + CurrentOptions.gbgfx[3]); } if (nBinaryID != -1) { lex_FloatDeleteRange(nBinaryID, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatDeleteRange(nBinaryID, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); lex_FloatDeleteSecondRange(nBinaryID, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatDeleteSecondRange(nBinaryID, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); } CurrentOptions = *pOpt; if (nGBGfxID != -1) { lex_FloatAddRange(nGBGfxID, CurrentOptions.gbgfx[0], - CurrentOptions.gbgfx[0]); + CurrentOptions.gbgfx[0]); lex_FloatAddRange(nGBGfxID, CurrentOptions.gbgfx[1], - CurrentOptions.gbgfx[1]); + CurrentOptions.gbgfx[1]); lex_FloatAddRange(nGBGfxID, CurrentOptions.gbgfx[2], - CurrentOptions.gbgfx[2]); + CurrentOptions.gbgfx[2]); lex_FloatAddRange(nGBGfxID, CurrentOptions.gbgfx[3], - CurrentOptions.gbgfx[3]); + CurrentOptions.gbgfx[3]); lex_FloatAddSecondRange(nGBGfxID, CurrentOptions.gbgfx[0], - CurrentOptions.gbgfx[0]); + CurrentOptions.gbgfx[0]); lex_FloatAddSecondRange(nGBGfxID, CurrentOptions.gbgfx[1], - CurrentOptions.gbgfx[1]); + CurrentOptions.gbgfx[1]); lex_FloatAddSecondRange(nGBGfxID, CurrentOptions.gbgfx[2], - CurrentOptions.gbgfx[2]); + CurrentOptions.gbgfx[2]); lex_FloatAddSecondRange(nGBGfxID, CurrentOptions.gbgfx[3], - CurrentOptions.gbgfx[3]); + CurrentOptions.gbgfx[3]); } if (nBinaryID != -1) { lex_FloatAddRange(nBinaryID, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatAddRange(nBinaryID, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); lex_FloatAddSecondRange(nBinaryID, CurrentOptions.binary[0], - CurrentOptions.binary[0]); + CurrentOptions.binary[0]); lex_FloatAddSecondRange(nBinaryID, CurrentOptions.binary[1], - CurrentOptions.binary[1]); + CurrentOptions.binary[1]); } } -void -opt_Parse(char *s) +void opt_Parse(char *s) { struct sOptions newopt; @@ -125,8 +124,7 @@ opt_Parse(char *s) newopt.gbgfx[2] = s[3]; newopt.gbgfx[3] = s[4]; } else { - errx(1, "Must specify exactly 4 characters for " - "option 'g'"); + errx(1, "Must specify exactly 4 characters for option 'g'"); } break; case 'b': @@ -134,8 +132,7 @@ opt_Parse(char *s) newopt.binary[0] = s[1]; newopt.binary[1] = s[2]; } else { - errx(1, "Must specify exactly 2 characters for option " - "'b'"); + errx(1, "Must specify exactly 2 characters for option 'b'"); } break; case 'z': @@ -143,12 +140,10 @@ opt_Parse(char *s) int32_t result; result = sscanf(&s[1], "%x", &newopt.fillchar); - if (!((result == EOF) || (result == 1))) { + if (!((result == EOF) || (result == 1))) errx(1, "Invalid argument for option 'z'"); - } } else { errx(1, "Invalid argument for option 'z'"); - exit(1); } break; default: @@ -159,77 +154,67 @@ opt_Parse(char *s) opt_SetCurrentOptions(&newopt); } -void -opt_Push(void) +void opt_Push(void) { struct sOptionStackEntry *pOpt; - if ((pOpt = malloc(sizeof(struct sOptionStackEntry))) != NULL) { - pOpt->Options = CurrentOptions; - pOpt->pNext = pOptionStack; - pOptionStack = pOpt; - } else + pOpt = malloc(sizeof(struct sOptionStackEntry)); + + if (pOpt == NULL) fatalerror("No memory for option stack"); + + pOpt->Options = CurrentOptions; + pOpt->pNext = pOptionStack; + pOptionStack = pOpt; } -void -opt_Pop(void) +void opt_Pop(void) { - if (pOptionStack) { - struct sOptionStackEntry *pOpt; - - pOpt = pOptionStack; - opt_SetCurrentOptions(&(pOpt->Options)); - pOptionStack = pOpt->pNext; - free(pOpt); - } else + if (pOptionStack == NULL) fatalerror("No entries in the option stack"); + + struct sOptionStackEntry *pOpt; + + pOpt = pOptionStack; + opt_SetCurrentOptions(&(pOpt->Options)); + pOptionStack = pOpt->pNext; + free(pOpt); } -void -opt_AddDefine(char *s) +void opt_AddDefine(char *s) { char *value, *equals; - if(cldefines_index >= cldefines_size) - { + + if (cldefines_index >= cldefines_size) { cldefines_size *= 2; cldefines = reallocarray(cldefines, cldefines_size, - 2 * sizeof(void *)); - if(!cldefines) - { + 2 * sizeof(void *)); + if (!cldefines) fatalerror("No memory for command line defines"); - } } equals = strchr(s, '='); - if(equals) - { + if (equals) { *equals = '\0'; value = equals + 1; - } - else - { + } else { value = "1"; } cldefines[cldefines_index++] = s; cldefines[cldefines_index++] = value; } -void -opt_ParseDefines() +static void opt_ParseDefines(void) { int32_t i; - for(i = 0; i < cldefines_index; i += 2) - { + for (i = 0; i < cldefines_index; i += 2) sym_AddString(cldefines[i], cldefines[i + 1]); - } } /* * Error handling */ -void -verror(const char *fmt, va_list args) +void verror(const char *fmt, va_list args) { fprintf(stderr, "ERROR: "); fstk_Dump(); @@ -239,32 +224,33 @@ verror(const char *fmt, va_list args) nErrors += 1; } -void -yyerror(const char *fmt, ...) +void yyerror(const char *fmt, ...) { va_list args; + va_start(args, fmt); verror(fmt, args); va_end(args); } -void -fatalerror(const char *fmt, ...) +void fatalerror(const char *fmt, ...) { va_list args; + va_start(args, fmt); verror(fmt, args); va_end(args); + exit(5); } -void -warning(const char *fmt, ...) +void warning(const char *fmt, ...) { if (!CurrentOptions.warnings) return; va_list args; + va_start(args, fmt); fprintf(stderr, "warning: "); @@ -276,17 +262,15 @@ warning(const char *fmt, ...) va_end(args); } -static void -usage(void) +static void print_usage(void) { printf( -"Usage: rgbasm [-EhVvw] [-b chars] [-Dname[=value]] [-g chars] [-i path]\n" +"usage: rgbasm [-EhVvw] [-b chars] [-Dname[=value]] [-g chars] [-i path]\n" " [-M dependfile] [-o outfile] [-p pad_value] file.asm\n"); exit(1); } -int -main(int argc, char *argv[]) +int main(int argc, char *argv[]) { int ch; char *ep; @@ -298,15 +282,12 @@ main(int argc, char *argv[]) dependfile = NULL; cldefines_size = 32; - cldefines = reallocarray(cldefines, cldefines_size, - 2 * sizeof(void *)); - if(!cldefines) - { + cldefines = reallocarray(cldefines, cldefines_size, 2 * sizeof(void *)); + if (!cldefines) fatalerror("No memory for command line defines"); - } if (argc == 1) - usage(); + print_usage(); /* yydebug=1; */ @@ -333,8 +314,7 @@ main(int argc, char *argv[]) newopt.binary[0] = optarg[1]; newopt.binary[1] = optarg[2]; } else { - errx(1, "Must specify exactly 2 characters for " - "option 'b'"); + errx(1, "Must specify exactly 2 characters for option 'b'"); } break; case 'D': @@ -350,8 +330,7 @@ main(int argc, char *argv[]) newopt.gbgfx[2] = optarg[3]; newopt.gbgfx[3] = optarg[4]; } else { - errx(1, "Must specify exactly 4 characters for " - "option 'g'"); + errx(1, "Must specify exactly 4 characters for option 'g'"); } break; case 'h': @@ -361,22 +340,23 @@ main(int argc, char *argv[]) fstk_AddIncludePath(optarg); break; case 'M': - if ((dependfile = fopen(optarg, "w")) == NULL) { + dependfile = fopen(optarg, "w"); + if (dependfile == NULL) err(1, "Could not open dependfile %s", optarg); - } + break; case 'o': out_SetFileName(optarg); break; case 'p': newopt.fillchar = strtoul(optarg, &ep, 0); - if (optarg[0] == '\0' || *ep != '\0') { + + if (optarg[0] == '\0' || *ep != '\0') errx(1, "Invalid argument for option 'p'"); - } - if (newopt.fillchar < 0 || newopt.fillchar > 0xFF) { - errx(1, "Argument for option 'p' must be " - "between 0 and 0xFF"); - } + + if (newopt.fillchar < 0 || newopt.fillchar > 0xFF) + errx(1, "Argument for option 'p' must be between 0 and 0xFF"); + break; case 'V': printf("rgbasm %s\n", get_package_version_string()); @@ -388,7 +368,7 @@ main(int argc, char *argv[]) newopt.warnings = false; break; default: - usage(); + print_usage(); /* NOTREACHED */ } } @@ -400,15 +380,14 @@ main(int argc, char *argv[]) DefaultOptions = CurrentOptions; if (argc == 0) - usage(); + print_usage(); tzMainfile = argv[argc - 1]; setuplex(); - if (CurrentOptions.verbose) { + if (CurrentOptions.verbose) printf("Assembling %s\n", tzMainfile); - } if (dependfile) { if (!tzObjectname) @@ -432,23 +411,21 @@ main(int argc, char *argv[]) fstk_Init(tzMainfile); opt_ParseDefines(); - if (CurrentOptions.verbose) { + if (CurrentOptions.verbose) printf("Pass 1...\n"); - } yy_set_state(LEX_STATE_NORMAL); opt_SetCurrentOptions(&DefaultOptions); - if (yyparse() != 0 || nErrors != 0) { + if (yyparse() != 0 || nErrors != 0) errx(1, "Assembly aborted in pass 1 (%ld errors)!", nErrors); - } - if (nIFDepth != 0) { + if (nIFDepth != 0) errx(1, "Unterminated IF construct (%ld levels)!", nIFDepth); - } - + if (nUnionDepth != 0) { - errx(1, "Unterminated UNION construct (%ld levels)!", nUnionDepth); + errx(1, "Unterminated UNION construct (%ld levels)!", + nUnionDepth); } nTotalLines = 0; @@ -466,27 +443,25 @@ main(int argc, char *argv[]) opt_SetCurrentOptions(&DefaultOptions); opt_ParseDefines(); - if (CurrentOptions.verbose) { + if (CurrentOptions.verbose) printf("Pass 2...\n"); - } - if (yyparse() != 0 || nErrors != 0) { + if (yyparse() != 0 || nErrors != 0) errx(1, "Assembly aborted in pass 2 (%ld errors)!", nErrors); - } double timespent; nEndClock = clock(); timespent = ((double)(nEndClock - nStartClock)) - / (double)CLOCKS_PER_SEC; + / (double)CLOCKS_PER_SEC; if (CurrentOptions.verbose) { printf("Success! %u lines in %d.%02d seconds ", nTotalLines, - (int) timespent, ((int) (timespent * 100.0)) % 100); + (int)timespent, ((int)(timespent * 100.0)) % 100); if (timespent == 0) printf("(INFINITY lines/minute)\n"); else printf("(%d lines/minute)\n", - (int) (60 / timespent * nTotalLines)); + (int)(60 / timespent * nTotalLines)); } out_WriteObject(); return 0; diff --git a/src/asm/math.c b/src/asm/math.c index 6892dd24..50b2a651 100644 --- a/src/asm/math.c +++ b/src/asm/math.c @@ -9,8 +9,8 @@ #include "asm/mymath.h" #include "asm/symbol.h" -#define fix2double(i) ((double)(i/65536.0)) -#define double2fix(d) ((int32_t)(d*65536.0)) +#define fx2double(i) ((double)((i) / 65536.0)) +#define double2fx(d) ((int32_t)((d) * 65536.0)) #ifndef M_PI #define M_PI 3.14159265358979323846 @@ -19,131 +19,116 @@ /* * Define the _PI symbol */ -void -math_DefinePI(void) +void math_DefinePI(void) { - sym_AddEqu("_PI", double2fix(M_PI)); + sym_AddEqu("_PI", double2fx(M_PI)); } /* * Print a fixed point value */ -void -math_Print(int32_t i) +void math_Print(int32_t i) { if (i >= 0) printf("%d.%05d", i >> 16, - ((int32_t) (fix2double(i) * 100000 + 0.5)) % 100000); + ((int32_t)(fx2double(i) * 100000 + 0.5)) % 100000); else printf("-%d.%05d", (-i) >> 16, - ((int32_t) (fix2double(-i) * 100000 + 0.5)) % 100000); + ((int32_t)(fx2double(-i) * 100000 + 0.5)) % 100000); } /* * Calculate sine */ -int32_t -math_Sin(int32_t i) +int32_t math_Sin(int32_t i) { - return (double2fix(sin(fix2double(i) * 2 * M_PI / 65536))); + return double2fx(sin(fx2double(i) * 2 * M_PI / 65536)); } /* * Calculate cosine */ -int32_t -math_Cos(int32_t i) +int32_t math_Cos(int32_t i) { - return (double2fix(cos(fix2double(i) * 2 * M_PI / 65536))); + return double2fx(cos(fx2double(i) * 2 * M_PI / 65536)); } /* * Calculate tangent */ -int32_t -math_Tan(int32_t i) +int32_t math_Tan(int32_t i) { - return (double2fix(tan(fix2double(i) * 2 * M_PI / 65536))); + return double2fx(tan(fx2double(i) * 2 * M_PI / 65536)); } /* * Calculate arcsine */ -int32_t -math_ASin(int32_t i) +int32_t math_ASin(int32_t i) { - return (double2fix(asin(fix2double(i)) / 2 / M_PI * 65536)); + return double2fx(asin(fx2double(i)) / 2 / M_PI * 65536); } /* * Calculate arccosine */ -int32_t -math_ACos(int32_t i) +int32_t math_ACos(int32_t i) { - return (double2fix(acos(fix2double(i)) / 2 / M_PI * 65536)); + return double2fx(acos(fx2double(i)) / 2 / M_PI * 65536); } /* * Calculate arctangent */ -int32_t -math_ATan(int32_t i) +int32_t math_ATan(int32_t i) { - return (double2fix(atan(fix2double(i)) / 2 / M_PI * 65536)); + return double2fx(atan(fx2double(i)) / 2 / M_PI * 65536); } /* * Calculate atan2 */ -int32_t -math_ATan2(int32_t i, int32_t j) +int32_t math_ATan2(int32_t i, int32_t j) { - return (double2fix - (atan2(fix2double(i), fix2double(j)) / 2 / M_PI * 65536)); + return double2fx(atan2(fx2double(i), fx2double(j)) / 2 / M_PI * 65536); } /* * Multiplication */ -int32_t -math_Mul(int32_t i, int32_t j) +int32_t math_Mul(int32_t i, int32_t j) { - return (double2fix(fix2double(i) * fix2double(j))); + return double2fx(fx2double(i) * fx2double(j)); } /* * Division */ -int32_t -math_Div(int32_t i, int32_t j) +int32_t math_Div(int32_t i, int32_t j) { - return (double2fix(fix2double(i) / fix2double(j))); + return double2fx(fx2double(i) / fx2double(j)); } /* * Round */ -int32_t -math_Round(int32_t i) +int32_t math_Round(int32_t i) { - return double2fix(round(fix2double(i))); + return double2fx(round(fx2double(i))); } /* * Ceil */ -int32_t -math_Ceil(int32_t i) +int32_t math_Ceil(int32_t i) { - return double2fix(ceil(fix2double(i))); + return double2fx(ceil(fx2double(i))); } /* * Floor */ -int32_t -math_Floor(int32_t i) +int32_t math_Floor(int32_t i) { - return double2fix(floor(fix2double(i))); + return double2fx(floor(fx2double(i))); } diff --git a/src/asm/output.c b/src/asm/output.c index 3297c61b..5354d39a 100644 --- a/src/asm/output.c +++ b/src/asm/output.c @@ -10,16 +10,18 @@ #include "asm/asm.h" #include "asm/charmap.h" -#include "asm/output.h" -#include "asm/symbol.h" -#include "asm/mylink.h" -#include "asm/main.h" -#include "asm/rpn.h" #include "asm/fstack.h" +#include "asm/main.h" +#include "asm/mylink.h" +#include "asm/output.h" +#include "asm/rpn.h" +#include "asm/symbol.h" + #include "common.h" + #include "extern/err.h" -void out_SetCurrentSection(struct Section * pSect); +void out_SetCurrentSection(struct Section *pSect); struct Patch { char tzFilename[_MAX_PATH + 1]; @@ -35,7 +37,7 @@ struct PatchSymbol { uint32_t ID; struct sSymbol *pSymbol; struct PatchSymbol *pNext; - struct PatchSymbol *pBucketNext; // next symbol in hash table bucket + struct PatchSymbol *pBucketNext; /* next symbol in hash table bucket */ }; struct SectionStackEntry { @@ -44,56 +46,62 @@ struct SectionStackEntry { }; struct PatchSymbol *tHashedPatchSymbols[HASHSIZE]; -struct Section *pSectionList = NULL, *pCurrentSection = NULL; -struct PatchSymbol *pPatchSymbols = NULL; +struct Section *pSectionList, *pCurrentSection; +struct PatchSymbol *pPatchSymbols; struct PatchSymbol **ppPatchSymbolsTail = &pPatchSymbols; char *tzObjectname; -struct SectionStackEntry *pSectionStack = NULL; +struct SectionStackEntry *pSectionStack; /* * Section stack routines */ -void -out_PushSection(void) +void out_PushSection(void) { struct SectionStackEntry *pSect; - if ((pSect = malloc(sizeof(struct SectionStackEntry))) != NULL) { - pSect->pSection = pCurrentSection; - pSect->pNext = pSectionStack; - pSectionStack = pSect; - } else + pSect = malloc(sizeof(struct SectionStackEntry)); + if (pSect == NULL) fatalerror("No memory for section stack"); + + pSect->pSection = pCurrentSection; + pSect->pNext = pSectionStack; + pSectionStack = pSect; } -void -out_PopSection(void) +void out_PopSection(void) { - if (pSectionStack) { - struct SectionStackEntry *pSect; - - pSect = pSectionStack; - out_SetCurrentSection(pSect->pSection); - pSectionStack = pSect->pNext; - free(pSect); - } else + if (pSectionStack == NULL) fatalerror("No entries in the section stack"); + + struct SectionStackEntry *pSect; + + pSect = pSectionStack; + out_SetCurrentSection(pSect->pSection); + pSectionStack = pSect->pNext; + free(pSect); } -uint32_t -getmaxsectionsize(uint32_t secttype, char * sectname) +static uint32_t getmaxsectionsize(uint32_t secttype, char *sectname) { - switch (secttype) - { - case SECT_ROM0: return 0x8000; /* If ROMX sections not used. */ - case SECT_ROMX: return 0x4000; - case SECT_VRAM: return 0x2000; - case SECT_SRAM: return 0x2000; - case SECT_WRAM0: return 0x2000; /* If WRAMX sections not used. */ - case SECT_WRAMX: return 0x1000; - case SECT_OAM: return 0xA0; - case SECT_HRAM: return 0x7F; - default: break; + switch (secttype) { + case SECT_ROM0: + return 0x8000; /* If ROMX sections not used */ + case SECT_ROMX: + return 0x4000; + case SECT_VRAM: + return 0x2000; + case SECT_SRAM: + return 0x2000; + case SECT_WRAM0: + return 0x2000; /* If WRAMX sections not used */ + case SECT_WRAMX: + return 0x1000; + case SECT_OAM: + return 0xA0; + case SECT_HRAM: + return 0x7F; + default: + break; } errx(1, "Section \"%s\" has an invalid section type.", sectname); } @@ -101,8 +109,7 @@ getmaxsectionsize(uint32_t secttype, char * sectname) /* * Count the number of symbols used in this object */ -uint32_t -countsymbols(void) +static uint32_t countsymbols(void) { struct PatchSymbol *pSym; uint32_t count = 0; @@ -120,8 +127,7 @@ countsymbols(void) /* * Count the number of sections used in this object */ -uint32_t -countsections(void) +static uint32_t countsections(void) { struct Section *pSect; uint32_t count = 0; @@ -139,8 +145,7 @@ countsections(void) /* * Count the number of patches used in this object */ -uint32_t -countpatches(struct Section * pSect) +static uint32_t countpatches(struct Section *pSect) { struct Patch *pPatch; uint32_t r = 0; @@ -157,8 +162,7 @@ countpatches(struct Section * pSect) /* * Write a long to a file (little-endian) */ -void -fputlong(uint32_t i, FILE * f) +static void fputlong(uint32_t i, FILE *f) { fputc(i, f); fputc(i >> 8, f); @@ -169,8 +173,7 @@ fputlong(uint32_t i, FILE * f) /* * Write a NULL-terminated string to a file */ -void -fputstring(char *s, FILE * f) +static void fputstring(char *s, FILE *f) { while (*s) fputc(*s++, f); @@ -180,8 +183,7 @@ fputstring(char *s, FILE * f) /* * Return a section's ID */ -uint32_t -getsectid(struct Section * pSect) +static uint32_t getsectid(struct Section *pSect) { struct Section *sec; uint32_t ID = 0; @@ -190,20 +192,19 @@ getsectid(struct Section * pSect) while (sec) { if (sec == pSect) - return (ID); + return ID; ID += 1; sec = sec->pNext; } fatalerror("INTERNAL: Unknown section"); - return ((uint32_t) - 1); + return (uint32_t)(-1); } /* * Write a patch to a file */ -void -writepatch(struct Patch * pPatch, FILE * f) +static void writepatch(struct Patch *pPatch, FILE *f) { fputstring(pPatch->tzFilename, f); fputlong(pPatch->nLine, f); @@ -216,8 +217,7 @@ writepatch(struct Patch * pPatch, FILE * f) /* * Write a section to a file */ -void -writesection(struct Section * pSect, FILE * f) +static void writesection(struct Section *pSect, FILE *f) { fputstring(pSect->pzName, f); @@ -229,8 +229,7 @@ writesection(struct Section * pSect, FILE * f) fputlong(pSect->nBank, f); fputlong(pSect->nAlign, f); - if ((pSect->nType == SECT_ROM0) - || (pSect->nType == SECT_ROMX)) { + if ((pSect->nType == SECT_ROM0) || (pSect->nType == SECT_ROMX)) { struct Patch *pPatch; fwrite(pSect->tData, 1, pSect->nPC, f); @@ -247,8 +246,7 @@ writesection(struct Section * pSect, FILE * f) /* * Write a symbol to a file */ -void -writesymbol(struct sSymbol * pSym, FILE * f) +static void writesymbol(struct sSymbol *pSym, FILE *f) { char symname[MAXSYMLEN * 2 + 1]; uint32_t type; @@ -295,11 +293,11 @@ writesymbol(struct sSymbol * pSym, FILE * f) /* * Add a symbol to the object */ -uint32_t -addsymbol(struct sSymbol * pSym) +static uint32_t nextID; + +static uint32_t addsymbol(struct sSymbol *pSym) { struct PatchSymbol *pPSym, **ppPSym; - static uint32_t nextID = 0; uint32_t hash; hash = calchash(pSym->tzName); @@ -311,14 +309,17 @@ addsymbol(struct sSymbol * pSym) ppPSym = &((*ppPSym)->pBucketNext); } - if ((*ppPSym = pPSym = malloc(sizeof(struct PatchSymbol))) != NULL) { - pPSym->pNext = NULL; - pPSym->pBucketNext = NULL; - pPSym->pSymbol = pSym; - pPSym->ID = nextID++; - } else + pPSym = malloc(sizeof(struct PatchSymbol)); + *ppPSym = pPSym; + + if (pPSym == NULL) fatalerror("No memory for patchsymbol"); + pPSym->pNext = NULL; + pPSym->pBucketNext = NULL; + pPSym->pSymbol = pSym; + pPSym->ID = nextID++; + *ppPatchSymbolsTail = pPSym; ppPatchSymbolsTail = &(pPSym->pNext); @@ -328,8 +329,7 @@ addsymbol(struct sSymbol * pSym) /* * Add all exported symbols to the object */ -void -addexports(void) +static void addexports(void) { int32_t i; @@ -348,28 +348,27 @@ addexports(void) /* * Allocate a new patchstructure and link it into the list */ -struct Patch * -allocpatch(void) +struct Patch *allocpatch(void) { struct Patch *pPatch; - if ((pPatch = malloc(sizeof(struct Patch))) != NULL) { - pPatch->pNext = pCurrentSection->pPatches; - pPatch->nRPNSize = 0; - pPatch->pRPN = NULL; - } else + pPatch = malloc(sizeof(struct Patch)); + + if (pPatch == NULL) fatalerror("No memory for patch"); + pPatch->pNext = pCurrentSection->pPatches; + pPatch->nRPNSize = 0; + pPatch->pRPN = NULL; pCurrentSection->pPatches = pPatch; - return (pPatch); + return pPatch; } /* * Create a new patch (includes the rpn expr) */ -void -createpatch(uint32_t type, struct Expression * expr) +void createpatch(uint32_t type, struct Expression *expr) { struct Patch *pPatch; uint16_t rpndata; @@ -394,7 +393,9 @@ createpatch(uint32_t type, struct Expression * expr) break; case RPN_SYM: symptr = 0; - while ((tzSym[symptr++] = rpn_PopByte(expr)) != 0); + while ((tzSym[symptr++] = rpn_PopByte(expr)) != 0) + ; + if (sym_isConstant(tzSym)) { uint32_t value; @@ -405,9 +406,11 @@ createpatch(uint32_t type, struct Expression * expr) rpnexpr[rpnptr++] = value >> 16; rpnexpr[rpnptr++] = value >> 24; } else { - struct sSymbol *sym; - if ((sym = sym_FindSymbol(tzSym)) == NULL) + struct sSymbol *sym = sym_FindSymbol(tzSym); + + if (sym == NULL) break; + symptr = addsymbol(sym); rpnexpr[rpnptr++] = RPN_SYM; rpnexpr[rpnptr++] = symptr & 0xFF; @@ -416,26 +419,34 @@ createpatch(uint32_t type, struct Expression * expr) rpnexpr[rpnptr++] = symptr >> 24; } break; - case RPN_BANK: { + case RPN_BANK: + { struct sSymbol *sym; + symptr = 0; - while ((tzSym[symptr++] = rpn_PopByte(expr)) != 0); - if ((sym = sym_FindSymbol(tzSym)) == NULL) + while ((tzSym[symptr++] = rpn_PopByte(expr)) != 0) + ; + + sym = sym_FindSymbol(tzSym); + if (sym == NULL) break; + symptr = addsymbol(sym); rpnexpr[rpnptr++] = RPN_BANK; rpnexpr[rpnptr++] = symptr & 0xFF; rpnexpr[rpnptr++] = symptr >> 8; rpnexpr[rpnptr++] = symptr >> 16; rpnexpr[rpnptr++] = symptr >> 24; - } break; + } default: rpnexpr[rpnptr++] = rpndata; break; } } - if ((pPatch->pRPN = malloc(rpnptr)) != NULL) { + + pPatch->pRPN = malloc(rpnptr); + if (pPatch->pRPN != NULL) { memcpy(pPatch->pRPN, rpnexpr, rpnptr); pPatch->nRPNSize = rpnptr; } @@ -444,12 +455,9 @@ createpatch(uint32_t type, struct Expression * expr) /* * A quick check to see if we have an initialized section */ -void -checksection(void) +static void checksection(void) { - if (pCurrentSection) - return; - else + if (pCurrentSection == NULL) fatalerror("Code generation before SECTION directive"); } @@ -457,14 +465,13 @@ checksection(void) * A quick check to see if we have an initialized section that can contain * this much initialized data */ -void -checkcodesection(void) +static void checkcodesection(void) { checksection(); if (pCurrentSection->nType != SECT_ROM0 && pCurrentSection->nType != SECT_ROMX) { fatalerror("Section '%s' cannot contain code or data (not ROM0 or ROMX)", - pCurrentSection->pzName); + pCurrentSection->pzName); } else if (nUnionDepth > 0) { fatalerror("UNIONs cannot contain code or data"); } @@ -473,8 +480,7 @@ checkcodesection(void) /* * Check if the section has grown too much. */ -void -checksectionoverflow(uint32_t delta_size) +static void checksectionoverflow(uint32_t delta_size) { uint32_t maxsize = getmaxsectionsize(pCurrentSection->nType, pCurrentSection->pzName); @@ -488,21 +494,21 @@ checksectionoverflow(uint32_t delta_size) * The real check must be done at the linking stage. */ fatalerror("Section '%s' is too big (max size = 0x%X bytes).", - pCurrentSection->pzName, maxsize); + pCurrentSection->pzName, maxsize); } } /* * Write an objectfile */ -void -out_WriteObject(void) +void out_WriteObject(void) { FILE *f; addexports(); - if ((f = fopen(tzObjectname, "wb")) != NULL) { + f = fopen(tzObjectname, "wb"); + if (f != NULL) { struct PatchSymbol *pSym; struct Section *pSect; @@ -531,8 +537,7 @@ out_WriteObject(void) /* * Prepare for pass #2 */ -void -out_PrepPass2(void) +void out_PrepPass2(void) { struct Section *pSect; @@ -548,13 +553,12 @@ out_PrepPass2(void) /* * Set the objectfilename */ -void -out_SetFileName(char *s) +void out_SetFileName(char *s) { tzObjectname = s; - if (CurrentOptions.verbose) { + if (CurrentOptions.verbose) printf("Output filename %s\n", s); - } + pSectionList = NULL; pCurrentSection = NULL; pPatchSymbols = NULL; @@ -563,8 +567,8 @@ out_SetFileName(char *s) /* * Find a section by name and type. If it doesn't exist, create it */ -struct Section * -out_FindSection(char *pzName, uint32_t secttype, int32_t org, int32_t bank, int32_t alignment) +struct Section *out_FindSection(char *pzName, uint32_t secttype, int32_t org, + int32_t bank, int32_t alignment) { struct Section *pSect, **ppSect; @@ -574,58 +578,61 @@ out_FindSection(char *pzName, uint32_t secttype, int32_t org, int32_t bank, int3 while (pSect) { if (strcmp(pzName, pSect->pzName) == 0) { if (secttype == pSect->nType - && ((uint32_t) org) == pSect->nOrg - && ((uint32_t) bank) == pSect->nBank - && ((uint32_t) alignment == pSect->nAlign)) { - return (pSect); - } else - fatalerror - ("Section already exists but with a different type"); + && ((uint32_t)org) == pSect->nOrg + && ((uint32_t)bank) == pSect->nBank + && ((uint32_t)alignment == pSect->nAlign)) { + return pSect; + } + + fatalerror("Section already exists but with a different type"); } ppSect = &(pSect->pNext); pSect = pSect->pNext; } - if ((*ppSect = (pSect = malloc(sizeof(struct Section)))) != NULL) { - if ((pSect->pzName = malloc(strlen(pzName) + 1)) != NULL) { - strcpy(pSect->pzName, pzName); - pSect->nType = secttype; - pSect->nPC = 0; - pSect->nOrg = org; - pSect->nBank = bank; - pSect->nAlign = alignment; - pSect->pNext = NULL; - pSect->pPatches = NULL; - pSect->charmap = NULL; - pPatchSymbols = NULL; - - pSect->tData = NULL; - if (secttype == SECT_ROM0 || secttype == SECT_ROMX) { - /* It is only needed to allocate memory for ROM - * sections. */ - uint32_t sectsize = getmaxsectionsize(secttype, pzName); - if ((pSect->tData = malloc(sectsize)) == NULL) - fatalerror("Not enough memory for section"); - } - return (pSect); - } else - fatalerror("Not enough memory for sectionname"); - } else + pSect = malloc(sizeof(struct Section)); + *ppSect = pSect; + if (pSect == NULL) fatalerror("Not enough memory for section"); - return (NULL); + pSect->pzName = malloc(strlen(pzName) + 1); + if (pSect->pzName == NULL) + fatalerror("Not enough memory for sectionname"); + + strcpy(pSect->pzName, pzName); + pSect->nType = secttype; + pSect->nPC = 0; + pSect->nOrg = org; + pSect->nBank = bank; + pSect->nAlign = alignment; + pSect->pNext = NULL; + pSect->pPatches = NULL; + pSect->charmap = NULL; + pPatchSymbols = NULL; + + /* It is only needed to allocate memory for ROM sections. */ + if (secttype == SECT_ROM0 || secttype == SECT_ROMX) { + uint32_t sectsize; + + sectsize = getmaxsectionsize(secttype, pzName); + pSect->tData = malloc(sectsize); + if (pSect->tData == NULL) + fatalerror("Not enough memory for section"); + } else { + pSect->tData = NULL; + } + + return (pSect); } /* * Set the current section */ -void -out_SetCurrentSection(struct Section * pSect) +void out_SetCurrentSection(struct Section *pSect) { - if (nUnionDepth > 0) { + if (nUnionDepth > 0) fatalerror("Cannot change the section within a UNION"); - } - + pCurrentSection = pSect; nPC = pSect->nPC; @@ -636,8 +643,7 @@ out_SetCurrentSection(struct Section * pSect) /* * Set the current section by name and type */ -void -out_NewSection(char *pzName, uint32_t secttype) +void out_NewSection(char *pzName, uint32_t secttype) { out_SetCurrentSection(out_FindSection(pzName, secttype, -1, -1, 1)); } @@ -645,8 +651,8 @@ out_NewSection(char *pzName, uint32_t secttype) /* * Set the current section by name and type */ -void -out_NewAbsSection(char *pzName, uint32_t secttype, int32_t org, int32_t bank) +void out_NewAbsSection(char *pzName, uint32_t secttype, int32_t org, + int32_t bank) { out_SetCurrentSection(out_FindSection(pzName, secttype, org, bank, 1)); } @@ -654,20 +660,20 @@ out_NewAbsSection(char *pzName, uint32_t secttype, int32_t org, int32_t bank) /* * Set the current section by name and type, using a given byte alignment */ -void -out_NewAlignedSection(char *pzName, uint32_t secttype, int32_t alignment, int32_t bank) +void out_NewAlignedSection(char *pzName, uint32_t secttype, int32_t alignment, + int32_t bank) { - if (alignment < 0 || alignment > 16) { + if (alignment < 0 || alignment > 16) yyerror("Alignment must be between 0-16 bits."); - } - out_SetCurrentSection(out_FindSection(pzName, secttype, -1, bank, 1 << alignment)); + + out_SetCurrentSection(out_FindSection(pzName, secttype, -1, bank, + 1 << alignment)); } /* * Output an absolute byte (bypassing ROM/union checks) */ -void -out_AbsByteBypassCheck(int32_t b) +void out_AbsByteBypassCheck(int32_t b) { checksectionoverflow(1); b &= 0xFF; @@ -682,15 +688,13 @@ out_AbsByteBypassCheck(int32_t b) /* * Output an absolute byte */ -void -out_AbsByte(int32_t b) +void out_AbsByte(int32_t b) { checkcodesection(); out_AbsByteBypassCheck(b); } -void -out_AbsByteGroup(char *s, int32_t length) +void out_AbsByteGroup(char *s, int32_t length) { checkcodesection(); checksectionoverflow(length); @@ -701,8 +705,7 @@ out_AbsByteGroup(char *s, int32_t length) /* * Skip this many bytes */ -void -out_Skip(int32_t skip) +void out_Skip(int32_t skip) { checksection(); checksectionoverflow(skip); @@ -724,8 +727,7 @@ out_Skip(int32_t skip) /* * Output a NULL terminated string (excluding the NULL-character) */ -void -out_String(char *s) +void out_String(char *s) { checkcodesection(); checksectionoverflow(strlen(s)); @@ -737,9 +739,7 @@ out_String(char *s) * Output a relocatable byte. Checking will be done to see if it * is an absolute value in disguise. */ - -void -out_RelByte(struct Expression * expr) +void out_RelByte(struct Expression *expr) { checkcodesection(); checksectionoverflow(1); @@ -751,17 +751,16 @@ out_RelByte(struct Expression * expr) pCurrentSection->nPC += 1; nPC += 1; pPCSymbol->nValue += 1; - } else + } else { out_AbsByte(expr->nVal); - + } rpn_Reset(expr); } /* * Output an absolute word */ -void -out_AbsWord(int32_t b) +void out_AbsWord(int32_t b) { checkcodesection(); checksectionoverflow(2); @@ -779,8 +778,7 @@ out_AbsWord(int32_t b) * Output a relocatable word. Checking will be done to see if * it's an absolute value in disguise. */ -void -out_RelWord(struct Expression * expr) +void out_RelWord(struct Expression *expr) { uint32_t b; @@ -796,16 +794,16 @@ out_RelWord(struct Expression * expr) pCurrentSection->nPC += 2; nPC += 2; pPCSymbol->nValue += 2; - } else + } else { out_AbsWord(expr->nVal); + } rpn_Reset(expr); } /* * Output an absolute longword */ -void -out_AbsLong(int32_t b) +void out_AbsLong(int32_t b) { checkcodesection(); checksectionoverflow(sizeof(int32_t)); @@ -824,8 +822,7 @@ out_AbsLong(int32_t b) * Output a relocatable longword. Checking will be done to see if * is an absolute value in disguise. */ -void -out_RelLong(struct Expression * expr) +void out_RelLong(struct Expression *expr) { int32_t b; @@ -843,16 +840,16 @@ out_RelLong(struct Expression * expr) pCurrentSection->nPC += 4; nPC += 4; pPCSymbol->nValue += 4; - } else + } else { out_AbsLong(expr->nVal); + } rpn_Reset(expr); } /* * Output a PC-relative byte */ -void -out_PCRelByte(struct Expression * expr) +void out_PCRelByte(struct Expression *expr) { int32_t b = expr->nVal; @@ -869,15 +866,13 @@ out_PCRelByte(struct Expression * expr) /* * Output a binary file */ -void -out_BinaryFile(char *s) +void out_BinaryFile(char *s) { FILE *f; f = fstk_FindFile(s); - if (f == NULL) { + if (f == NULL) err(1, "Unable to open incbin file '%s'", s); - } int32_t fsize; @@ -901,8 +896,7 @@ out_BinaryFile(char *s) fclose(f); } -void -out_BinaryFileSlice(char *s, int32_t start_pos, int32_t length) +void out_BinaryFileSlice(char *s, int32_t start_pos, int32_t length) { FILE *f; @@ -913,9 +907,8 @@ out_BinaryFileSlice(char *s, int32_t start_pos, int32_t length) fatalerror("Number of bytes to read must be greater than zero"); f = fstk_FindFile(s); - if (f == NULL) { + if (f == NULL) err(1, "Unable to open included file '%s'", s); - } int32_t fsize; diff --git a/src/asm/rpn.c b/src/asm/rpn.c index 03dec7fd..380bca5a 100644 --- a/src/asm/rpn.c +++ b/src/asm/rpn.c @@ -12,9 +12,8 @@ #include "asm/rpn.h" #include "asm/symbol.h" -void -mergetwoexpressions(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void mergetwoexpressions(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { *expr = *src1; memcpy(&(expr->tRPN[expr->nRPNLength]), src2->tRPN, src2->nRPNLength); @@ -23,13 +22,13 @@ mergetwoexpressions(struct Expression * expr, struct Expression * src1, expr->isReloc |= src2->isReloc; expr->isPCRel |= src2->isPCRel; } -#define joinexpr() mergetwoexpressions(expr,src1,src2) + +#define joinexpr() mergetwoexpressions(expr, src1, src2) /* * Add a byte to the RPN expression */ -void -pushbyte(struct Expression * expr, int b) +void pushbyte(struct Expression *expr, int b) { expr->tRPN[expr->nRPNLength++] = b & 0xFF; } @@ -37,47 +36,45 @@ pushbyte(struct Expression * expr, int b) /* * Reset the RPN module */ -void -rpn_Reset(struct Expression * expr) +void rpn_Reset(struct Expression *expr) { - expr->nRPNLength = expr->nRPNOut = expr->isReloc = expr->isPCRel = 0; + expr->nRPNLength = 0; + expr->nRPNOut = 0; + expr->isReloc = 0; + expr->isPCRel = 0; } /* * Returns the next rpn byte in expression */ -uint16_t -rpn_PopByte(struct Expression * expr) +uint16_t rpn_PopByte(struct Expression *expr) { - if (expr->nRPNOut == expr->nRPNLength) { - return (0xDEAD); - } else - return (expr->tRPN[expr->nRPNOut++]); + if (expr->nRPNOut == expr->nRPNLength) + return 0xDEAD; + + return expr->tRPN[expr->nRPNOut++]; } /* * Determine if the current expression is relocatable */ -uint32_t -rpn_isReloc(struct Expression * expr) +uint32_t rpn_isReloc(const struct Expression *expr) { - return (expr->isReloc); + return expr->isReloc; } /* * Determine if the current expression can be pc-relative */ -uint32_t -rpn_isPCRelative(struct Expression * expr) +uint32_t rpn_isPCRelative(const struct Expression *expr) { - return (expr->isPCRel); + return expr->isPCRel; } /* * Add symbols, constants and operators to expression */ -void -rpn_Number(struct Expression * expr, uint32_t i) +void rpn_Number(struct Expression *expr, uint32_t i) { rpn_Reset(expr); pushbyte(expr, RPN_CONST); @@ -88,11 +85,10 @@ rpn_Number(struct Expression * expr, uint32_t i) expr->nVal = i; } -void -rpn_Symbol(struct Expression * expr, char *tzSym) +void rpn_Symbol(struct Expression *expr, char *tzSym) { if (!sym_isConstant(tzSym)) { - struct sSymbol *psym; + const struct sSymbol *psym; rpn_Reset(expr); @@ -106,17 +102,20 @@ rpn_Symbol(struct Expression * expr, char *tzSym) while (*tzSym) pushbyte(expr, *tzSym++); pushbyte(expr, 0); - } else + } else { rpn_Number(expr, sym_GetConstantValue(tzSym)); + } } -void -rpn_Bank(struct Expression * expr, char *tzSym) +void rpn_Bank(struct Expression *expr, char *tzSym) { if (!sym_isConstant(tzSym)) { rpn_Reset(expr); - /* Check that the symbol exists by evaluating and discarding the value. */ + /* + * Check that the symbol exists by evaluating and discarding the + * value. + */ sym_GetValue(tzSym); expr->isReloc = 1; @@ -124,44 +123,40 @@ rpn_Bank(struct Expression * expr, char *tzSym) while (*tzSym) pushbyte(expr, *tzSym++); pushbyte(expr, 0); - } else + } else { yyerror("BANK argument must be a relocatable identifier"); + } } -void -rpn_CheckHRAM(struct Expression * expr, struct Expression * src) +void rpn_CheckHRAM(struct Expression *expr, const struct Expression *src) { *expr = *src; pushbyte(expr, RPN_HRAM); } -void -rpn_LOGNOT(struct Expression * expr, struct Expression * src) +void rpn_LOGNOT(struct Expression *expr, const struct Expression *src) { *expr = *src; pushbyte(expr, RPN_LOGUNNOT); } -void -rpn_LOGOR(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGOR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal || src2->nVal); pushbyte(expr, RPN_LOGOR); } -void -rpn_LOGAND(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGAND(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal && src2->nVal); pushbyte(expr, RPN_LOGAND); } -void -rpn_HIGH(struct Expression * expr, struct Expression * src) +void rpn_HIGH(struct Expression *expr, const struct Expression *src) { *expr = *src; @@ -184,8 +179,7 @@ rpn_HIGH(struct Expression * expr, struct Expression * src) pushbyte(expr, RPN_AND); } -void -rpn_LOW(struct Expression * expr, struct Expression * src) +void rpn_LOW(struct Expression *expr, const struct Expression *src) { *expr = *src; @@ -200,166 +194,148 @@ rpn_LOW(struct Expression * expr, struct Expression * src) pushbyte(expr, RPN_AND); } -void -rpn_LOGEQU(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGEQU(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal == src2->nVal); pushbyte(expr, RPN_LOGEQ); } -void -rpn_LOGGT(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGGT(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal > src2->nVal); pushbyte(expr, RPN_LOGGT); } -void -rpn_LOGLT(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGLT(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal < src2->nVal); pushbyte(expr, RPN_LOGLT); } -void -rpn_LOGGE(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGGE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal >= src2->nVal); pushbyte(expr, RPN_LOGGE); } -void -rpn_LOGLE(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGLE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal <= src2->nVal); pushbyte(expr, RPN_LOGLE); } -void -rpn_LOGNE(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_LOGNE(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal != src2->nVal); pushbyte(expr, RPN_LOGNE); } -void -rpn_ADD(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_ADD(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal + src2->nVal); pushbyte(expr, RPN_ADD); } -void -rpn_SUB(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_SUB(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal - src2->nVal); pushbyte(expr, RPN_SUB); } -void -rpn_XOR(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_XOR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal ^ src2->nVal); pushbyte(expr, RPN_XOR); } -void -rpn_OR(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_OR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal | src2->nVal); pushbyte(expr, RPN_OR); } -void -rpn_AND(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_AND(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal & src2->nVal); pushbyte(expr, RPN_AND); } -void -rpn_SHL(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_SHL(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal << src2->nVal); pushbyte(expr, RPN_SHL); } -void -rpn_SHR(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_SHR(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal >> src2->nVal); pushbyte(expr, RPN_SHR); } -void -rpn_MUL(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_MUL(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); expr->nVal = (expr->nVal * src2->nVal); pushbyte(expr, RPN_MUL); } -void -rpn_DIV(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_DIV(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); - if (src2->nVal == 0) { + if (src2->nVal == 0) fatalerror("division by zero"); - } + expr->nVal = (expr->nVal / src2->nVal); pushbyte(expr, RPN_DIV); } -void -rpn_MOD(struct Expression * expr, struct Expression * src1, - struct Expression * src2) +void rpn_MOD(struct Expression *expr, const struct Expression *src1, + const struct Expression *src2) { joinexpr(); - if (src2->nVal == 0) { + if (src2->nVal == 0) fatalerror("division by zero"); - } + expr->nVal = (expr->nVal % src2->nVal); pushbyte(expr, RPN_MOD); } -void -rpn_UNNEG(struct Expression * expr, struct Expression * src) +void rpn_UNNEG(struct Expression *expr, const struct Expression *src) { *expr = *src; expr->nVal = -expr->nVal; pushbyte(expr, RPN_UNSUB); } -void -rpn_UNNOT(struct Expression * expr, struct Expression * src) +void rpn_UNNOT(struct Expression *expr, const struct Expression *src) { *expr = *src; expr->nVal = ~expr->nVal; diff --git a/src/asm/symbol.c b/src/asm/symbol.c index 0e4ef63f..948d691a 100644 --- a/src/asm/symbol.c +++ b/src/asm/symbol.c @@ -14,91 +14,88 @@ #include "asm/main.h" #include "asm/mymath.h" #include "asm/output.h" + #include "extern/err.h" #include "extern/version.h" struct sSymbol *tHashedSymbols[HASHSIZE]; -struct sSymbol *pScope = NULL; -struct sSymbol *pPCSymbol = NULL; -struct sSymbol *p_NARGSymbol = NULL; -struct sSymbol *p__LINE__Symbol = NULL; -char *currentmacroargs[MAXMACROARGS + 1]; -char *newmacroargs[MAXMACROARGS + 1]; -char SavedTIME[256]; -char SavedDATE[256]; -char SavedTIMESTAMP_ISO8601_LOCAL[256]; -char SavedTIMESTAMP_ISO8601_UTC[256]; -char SavedDAY[3]; -char SavedMONTH[3]; -char SavedYEAR[5]; -char SavedHOUR[3]; -char SavedMINUTE[3]; -char SavedSECOND[3]; -bool exportall; +static struct sSymbol *pScope; +struct sSymbol *pPCSymbol; +static struct sSymbol *p_NARGSymbol; +static struct sSymbol *p__LINE__Symbol; +static char *currentmacroargs[MAXMACROARGS + 1]; +static char *newmacroargs[MAXMACROARGS + 1]; +static char SavedTIME[256]; +static char SavedDATE[256]; +static char SavedTIMESTAMP_ISO8601_LOCAL[256]; +static char SavedTIMESTAMP_ISO8601_UTC[256]; +static char SavedDAY[3]; +static char SavedMONTH[3]; +static char SavedYEAR[5]; +static char SavedHOUR[3]; +static char SavedMINUTE[3]; +static char SavedSECOND[3]; +static bool exportall; -void helper_RemoveLeadingZeros(char * string){ - char * new_beginning = string; +void helper_RemoveLeadingZeros(char *string) +{ + char *new_beginning = string; - while(*new_beginning == '0') + while (*new_beginning == '0') new_beginning++; - if(new_beginning == string) + if (new_beginning == string) return; - if(*new_beginning == '\0') + if (*new_beginning == '\0') new_beginning--; memmove(string, new_beginning, strlen(new_beginning) + 1); } -int32_t -Callback_NARG(struct sSymbol * sym) +int32_t Callback_NARG(struct sSymbol *sym) { uint32_t i = 0; while (currentmacroargs[i] && i < MAXMACROARGS) i += 1; - return (i); + return i; } -int32_t -Callback__LINE__(struct sSymbol __attribute__((unused)) * sym) +int32_t Callback__LINE__(struct sSymbol __attribute__((unused)) *sym) { - return (nLineNo); + return nLineNo; } /* * Get the nValue field of a symbol */ -int32_t -getvaluefield(struct sSymbol * sym) +static int32_t getvaluefield(struct sSymbol *sym) { - if (sym->Callback) { - return (sym->Callback(sym)); - } else - return (sym->nValue); + if (sym->Callback) + return sym->Callback(sym); + + return sym->nValue; } /* * Calculate the hash value for a string */ -uint32_t -calchash(char *s) +uint32_t calchash(char *s) { uint32_t hash = 5381; while (*s != 0) hash = (hash * 33) ^ (*s++); - return (hash % HASHSIZE); + return hash % HASHSIZE; } /* * Create a new symbol by name */ -struct sSymbol * -createsymbol(char *s) +struct sSymbol *createsymbol(char *s) { struct sSymbol **ppsym; uint32_t hash; @@ -109,84 +106,86 @@ createsymbol(char *s) while ((*ppsym) != NULL) ppsym = &((*ppsym)->pNext); - if (((*ppsym) = malloc(sizeof(struct sSymbol))) != NULL) { - strcpy((*ppsym)->tzName, s); - (*ppsym)->nValue = 0; - (*ppsym)->nType = 0; - (*ppsym)->pScope = NULL; - (*ppsym)->pNext = NULL; - (*ppsym)->pMacro = NULL; - (*ppsym)->pSection = NULL; - (*ppsym)->Callback = NULL; - strcpy((*ppsym)->tzFileName, tzCurrentFileName); - (*ppsym)->nFileLine = fstk_GetLine(); - return (*ppsym); - } else { + (*ppsym) = malloc(sizeof(struct sSymbol)); + + if ((*ppsym) == NULL) { fatalerror("No memory for symbol"); - return (NULL); + return NULL; } + + strcpy((*ppsym)->tzName, s); + (*ppsym)->nValue = 0; + (*ppsym)->nType = 0; + (*ppsym)->pScope = NULL; + (*ppsym)->pNext = NULL; + (*ppsym)->pMacro = NULL; + (*ppsym)->pSection = NULL; + (*ppsym)->Callback = NULL; + strcpy((*ppsym)->tzFileName, tzCurrentFileName); + (*ppsym)->nFileLine = fstk_GetLine(); + return *ppsym; } /* * Creates the full name of a local symbol in a given scope, by prepending * the name with the parent symbol's name. */ -size_t -fullSymbolName(char *output, size_t outputSize, char *localName, struct sSymbol *scope) +static size_t fullSymbolName(char *output, size_t outputSize, char *localName, + const struct sSymbol *scope) { - struct sSymbol *parent = scope->pScope ? scope->pScope : scope; + const struct sSymbol *parent = scope->pScope ? scope->pScope : scope; + return snprintf(output, outputSize, "%s%s", parent->tzName, localName); } /* * Find the pointer to a symbol by name and scope */ -struct sSymbol ** -findpsymbol(char *s, struct sSymbol * scope) +struct sSymbol **findpsymbol(char *s, struct sSymbol *scope) { struct sSymbol **ppsym; int32_t hash; char fullname[MAXSYMLEN + 1]; - + if (s[0] == '.' && scope) { fullSymbolName(fullname, sizeof(fullname), s, scope); s = fullname; } - - char *seperator; - if ((seperator = strchr(s, '.'))) { - if (strchr(seperator + 1, '.')) { - fatalerror("'%s' is a nonsensical reference to a nested local symbol", s); - } + + char *separator = strchr(s, '.'); + + if (separator) { + if (strchr(separator + 1, '.')) + fatalerror("'%s' is a nonsensical reference to a nested local symbol", + s); } hash = calchash(s); ppsym = &(tHashedSymbols[hash]); while ((*ppsym) != NULL) { - if ((strcmp(s, (*ppsym)->tzName) == 0)) { - return (ppsym); - } else - ppsym = &((*ppsym)->pNext); + if ((strcmp(s, (*ppsym)->tzName) == 0)) + return ppsym; + + ppsym = &((*ppsym)->pNext); } - return (NULL); + return NULL; } /* * Find a symbol by name and scope */ -struct sSymbol * -findsymbol(char *s, struct sSymbol * scope) +struct sSymbol *findsymbol(char *s, struct sSymbol *scope) { struct sSymbol **ppsym = findpsymbol(s, scope); + return ppsym ? *ppsym : NULL; } /* * Find a symbol by name and scope */ -struct sSymbol * -sym_FindSymbol(char *tzName) +struct sSymbol *sym_FindSymbol(char *tzName) { struct sSymbol *pscope; @@ -195,14 +194,13 @@ sym_FindSymbol(char *tzName) else pscope = NULL; - return (findsymbol(tzName, pscope)); + return findsymbol(tzName, pscope); } /* * Purge a symbol */ -void -sym_Purge(char *tzName) +void sym_Purge(char *tzName) { struct sSymbol **ppSym; struct sSymbol *pscope; @@ -232,8 +230,7 @@ sym_Purge(char *tzName) /* * Determine if a symbol has been defined */ -uint32_t -sym_isConstDefined(char *tzName) +uint32_t sym_isConstDefined(char *tzName) { struct sSymbol *psym, *pscope; @@ -245,19 +242,19 @@ sym_isConstDefined(char *tzName) psym = findsymbol(tzName, pscope); if (psym && (psym->nType & SYMF_DEFINED)) { - if (psym-> - nType & (SYMF_EQU | SYMF_SET | SYMF_MACRO | SYMF_STRING)) { - return (1); - } else { - fatalerror("'%s' is not allowed as argument to the " - "DEF function", tzName); - } + uint32_t mask = SYMF_EQU | SYMF_SET | SYMF_MACRO | SYMF_STRING; + + if (psym->nType & mask) + return 1; + + fatalerror("'%s' is not allowed as argument to the DEF function", + tzName); } - return (0); + + return 0; } -uint32_t -sym_isDefined(char *tzName) +uint32_t sym_isDefined(char *tzName) { struct sSymbol *psym, *pscope; @@ -269,16 +266,15 @@ sym_isDefined(char *tzName) psym = findsymbol(tzName, pscope); if (psym && (psym->nType & SYMF_DEFINED)) - return (1); + return 1; else - return (0); + return 0; } /* * Determine if the symbol is a constant */ -uint32_t -sym_isConstant(char *s) +uint32_t sym_isConstant(char *s) { struct sSymbol *psym, *pscope; @@ -287,35 +283,35 @@ sym_isConstant(char *s) else pscope = NULL; - if ((psym = findsymbol(s, pscope)) != NULL) { + psym = findsymbol(s, pscope); + + if (psym != NULL) { if (psym->nType & SYMF_CONST) - return (1); + return 1; } - return (0); + + return 0; } /* * Get a string equate's value */ -char * -sym_GetStringValue(char *tzSym) +char *sym_GetStringValue(char *tzSym) { - struct sSymbol *pSym; + const struct sSymbol *pSym = sym_FindSymbol(tzSym); - if ((pSym = sym_FindSymbol(tzSym)) != NULL) - return (pSym->pMacro); - else { - yyerror("Stringsymbol '%s' not defined", tzSym); - } + if (pSym != NULL) + return pSym->pMacro; - return (NULL); + yyerror("Stringsymbol '%s' not defined", tzSym); + + return NULL; } /* * Return a constant symbols value */ -uint32_t -sym_GetConstantValue(char *s) +uint32_t sym_GetConstantValue(char *s) { struct sSymbol *psym, *pscope; @@ -324,24 +320,24 @@ sym_GetConstantValue(char *s) else pscope = NULL; - if ((psym = findsymbol(s, pscope)) != NULL) { + psym = findsymbol(s, pscope); + + if (psym != NULL) { if (psym->nType & SYMF_CONST) - return (getvaluefield(psym)); - else { - fatalerror("Expression must have a constant value"); - } - } else { - yyerror("'%s' not defined", s); + return getvaluefield(psym); + + fatalerror("Expression must have a constant value"); } - return (0); + yyerror("'%s' not defined", s); + + return 0; } /* * Return a symbols value... "estimated" if not defined yet */ -uint32_t -sym_GetValue(char *s) +uint32_t sym_GetValue(char *s) { struct sSymbol *psym, *pscope; @@ -350,37 +346,42 @@ sym_GetValue(char *s) else pscope = NULL; - if ((psym = findsymbol(s, pscope)) != NULL) { + psym = findsymbol(s, pscope); + + if (psym != NULL) { if (psym->nType & SYMF_DEFINED) { - if (psym->nType & (SYMF_MACRO | SYMF_STRING)) { + if (psym->nType & (SYMF_MACRO | SYMF_STRING)) yyerror("'%s' is a macro or string symbol", s); - } - return (getvaluefield(psym)); - } else { - if (nPass == 2) { - /* Assume undefined symbols are imported from somewhere else */ - psym->nType |= SYMF_IMPORT; - } - /* 0x80 seems like a good default value... */ - return (0x80); + + return getvaluefield(psym); } - } else { - if (nPass == 1) { - createsymbol(s); - return (0x80); - } else { - yyerror("'%s' not defined", s); + + if (nPass == 2) { + /* + * Assume undefined symbols are imported from + * somwehere else + */ + psym->nType |= SYMF_IMPORT; } + + /* 0x80 seems like a good default value... */ + return 0x80; } - return (0); + if (nPass == 1) { + createsymbol(s); + return 0x80; + } + + yyerror("'%s' not defined", s); + + return 0; } /* * Return a defined symbols value... aborts if not defined yet */ -uint32_t -sym_GetDefinedValue(char *s) +uint32_t sym_GetDefinedValue(char *s) { struct sSymbol *psym, *pscope; @@ -389,51 +390,50 @@ sym_GetDefinedValue(char *s) else pscope = NULL; - if ((psym = findsymbol(s, pscope)) != NULL) { + psym = findsymbol(s, pscope); + + if (psym != NULL) { if ((psym->nType & SYMF_DEFINED)) { - if (psym->nType & (SYMF_MACRO | SYMF_STRING)) { + if (psym->nType & (SYMF_MACRO | SYMF_STRING)) yyerror("'%s' is a macro or string symbol", s); - } - return (getvaluefield(psym)); - } else { - yyerror("'%s' not defined", s); + + return getvaluefield(psym); } - } else { - yyerror("'%s' not defined", s); } - return (0); + yyerror("'%s' not defined", s); + + return 0; } /* * Macro argument stuff */ -void -sym_ShiftCurrentMacroArgs(void) +void sym_ShiftCurrentMacroArgs(void) { int32_t i; free(currentmacroargs[0]); - for (i = 0; i < MAXMACROARGS - 1; i += 1) { + for (i = 0; i < MAXMACROARGS - 1; i += 1) currentmacroargs[i] = currentmacroargs[i + 1]; - } + currentmacroargs[MAXMACROARGS - 1] = NULL; } -char * -sym_FindMacroArg(int32_t i) +char *sym_FindMacroArg(int32_t i) { if (i == -1) i = MAXMACROARGS + 1; - assert(i-1 >= 0); - assert((size_t)(i-1) < sizeof(currentmacroargs)/sizeof(*currentmacroargs)); + assert(i - 1 >= 0); - return (currentmacroargs[i - 1]); + assert((size_t)(i - 1) + < sizeof(currentmacroargs) / sizeof(*currentmacroargs)); + + return currentmacroargs[i - 1]; } -void -sym_UseNewMacroArgs(void) +void sym_UseNewMacroArgs(void) { int32_t i; @@ -443,8 +443,7 @@ sym_UseNewMacroArgs(void) } } -void -sym_SaveCurrentMacroArgs(char *save[]) +void sym_SaveCurrentMacroArgs(char *save[]) { int32_t i; @@ -452,8 +451,7 @@ sym_SaveCurrentMacroArgs(char *save[]) save[i] = currentmacroargs[i]; } -void -sym_RestoreCurrentMacroArgs(char *save[]) +void sym_RestoreCurrentMacroArgs(char *save[]) { int32_t i; @@ -461,8 +459,7 @@ sym_RestoreCurrentMacroArgs(char *save[]) currentmacroargs[i] = save[i]; } -void -sym_FreeCurrentMacroArgs(void) +void sym_FreeCurrentMacroArgs(void) { int32_t i; @@ -472,8 +469,7 @@ sym_FreeCurrentMacroArgs(void) } } -void -sym_AddNewMacroArg(char *s) +void sym_AddNewMacroArg(char *s) { int32_t i = 0; @@ -485,12 +481,12 @@ sym_AddNewMacroArg(char *s) newmacroargs[i] = strdup(s); else newmacroargs[i] = NULL; - } else + } else { yyerror("A maximum of %d arguments allowed", MAXMACROARGS); + } } -void -sym_SetMacroArgID(uint32_t nMacroCount) +void sym_SetMacroArgID(uint32_t nMacroCount) { char s[256]; @@ -498,8 +494,7 @@ sym_SetMacroArgID(uint32_t nMacroCount) newmacroargs[MAXMACROARGS] = strdup(s); } -void -sym_UseCurrentMacroArgs(void) +void sym_UseCurrentMacroArgs(void) { int32_t i; @@ -510,30 +505,28 @@ sym_UseCurrentMacroArgs(void) /* * Find a macro by name */ -struct sSymbol * -sym_FindMacro(char *s) +struct sSymbol *sym_FindMacro(char *s) { - return (findsymbol(s, NULL)); + return findsymbol(s, NULL); } /* * Add an equated symbol */ -void -sym_AddEqu(char *tzSym, int32_t value) +void sym_AddEqu(char *tzSym, int32_t value) { - if ((nPass == 1) - || ((nPass == 2) && (sym_isDefined(tzSym) == 0))) { + if ((nPass == 1) || ((nPass == 2) && (sym_isDefined(tzSym) == 0))) { /* only add equated symbols in pass 1 */ - struct sSymbol *nsym; + struct sSymbol *nsym = findsymbol(tzSym, NULL); - if ((nsym = findsymbol(tzSym, NULL)) != NULL) { + if (nsym != NULL) { if (nsym->nType & SYMF_DEFINED) { - yyerror("'%s' already defined in %s(%d)", - tzSym, nsym->tzFileName, nsym->nFileLine); + yyerror("'%s' already defined in %s(%d)", tzSym, + nsym->tzFileName, nsym->nFileLine); } - } else + } else { nsym = createsymbol(tzSym); + } if (nsym) { nsym->nValue = value; @@ -555,24 +548,27 @@ sym_AddEqu(char *tzSym, int32_t value) * of the string are enough: sym_AddString("M_PI", "3.1415"). This is the same * as ``` M_PI EQUS "3.1415" ``` */ -void -sym_AddString(char *tzSym, char *tzValue) +void sym_AddString(char *tzSym, char *tzValue) { - struct sSymbol *nsym; + struct sSymbol *nsym = findsymbol(tzSym, NULL); - if ((nsym = findsymbol(tzSym, NULL)) != NULL) { + if (nsym != NULL) { if (nsym->nType & SYMF_DEFINED) { yyerror("'%s' already defined in %s(%d)", tzSym, nsym->tzFileName, nsym->nFileLine); } - } else + } else { nsym = createsymbol(tzSym); + } if (nsym) { - if ((nsym->pMacro = malloc(strlen(tzValue) + 1)) != NULL) + nsym->pMacro = malloc(strlen(tzValue) + 1); + + if (nsym->pMacro != NULL) strcpy(nsym->pMacro, tzValue); else fatalerror("No memory for stringequate"); + nsym->nType |= SYMF_STRING | SYMF_DEFINED; nsym->ulMacroSize = strlen(tzValue); nsym->pScope = NULL; @@ -582,29 +578,28 @@ sym_AddString(char *tzSym, char *tzValue) /* * check if symbol is a string equated symbol */ -uint32_t -sym_isString(char *tzSym) +uint32_t sym_isString(char *tzSym) { - struct sSymbol *pSym; + const struct sSymbol *pSym = findsymbol(tzSym, NULL); - if ((pSym = findsymbol(tzSym, NULL)) != NULL) { + if (pSym != NULL) { if (pSym->nType & SYMF_STRING) - return (1); + return 1; } - return (0); + return 0; } /* * Alter a SET symbols value */ -void -sym_AddSet(char *tzSym, int32_t value) +void sym_AddSet(char *tzSym, int32_t value) { - struct sSymbol *nsym; + struct sSymbol *nsym = findsymbol(tzSym, NULL); - if ((nsym = findsymbol(tzSym, NULL)) != NULL) { - } else + if (nsym == NULL) { + /* Symbol hasn been found, create */ nsym = createsymbol(tzSym); + } if (nsym) { nsym->nValue = value; @@ -616,18 +611,17 @@ sym_AddSet(char *tzSym, int32_t value) /* * Add a local (.name) relocatable symbol */ -void -sym_AddLocalReloc(char *tzSym) +void sym_AddLocalReloc(char *tzSym) { if (pScope) { - if (strlen(tzSym) + strlen(pScope->tzName) > MAXSYMLEN) { + if (strlen(tzSym) + strlen(pScope->tzName) > MAXSYMLEN) fatalerror("Symbol too long"); - } - + char fullname[MAXSYMLEN + 1]; + fullSymbolName(fullname, sizeof(fullname), tzSym, pScope); sym_AddReloc(fullname); - + } else { fatalerror("Local label in main scope"); } @@ -636,51 +630,56 @@ sym_AddLocalReloc(char *tzSym) /* * Add a relocatable symbol */ -void -sym_AddReloc(char *tzSym) +void sym_AddReloc(char *tzSym) { - struct sSymbol* scope = NULL; - + struct sSymbol *scope = NULL; + if ((nPass == 1) || ((nPass == 2) && (sym_isDefined(tzSym) == 0))) { /* only add reloc symbols in pass 1 */ struct sSymbol *nsym; - char *localPtr = NULL; - - if ((localPtr = strchr(tzSym, '.')) != NULL) { - if (!pScope) { + char *localPtr = strchr(tzSym, '.'); + + if (localPtr != NULL) { + if (!pScope) fatalerror("Local label in main scope"); - } - - struct sSymbol *parent = pScope->pScope ? pScope->pScope : pScope; + + struct sSymbol *parent = pScope->pScope ? + pScope->pScope : pScope; int32_t parentLen = localPtr - tzSym; - + if (strchr(localPtr + 1, '.') != NULL) { - fatalerror("'%s' is a nonsensical reference to a nested local symbol", tzSym); - } else if (strlen(parent->tzName) != parentLen || strncmp(tzSym, parent->tzName, parentLen) != 0) { - yyerror("Not currently in the scope of '%.*s'", parentLen, tzSym); + fatalerror("'%s' is a nonsensical reference to a nested local symbol", + tzSym); + } else if (strlen(parent->tzName) != parentLen + || strncmp(tzSym, parent->tzName, parentLen) != 0) { + yyerror("Not currently in the scope of '%.*s'", + parentLen, tzSym); } - + scope = parent; } - if ((nsym = findsymbol(tzSym, scope)) != NULL) { + nsym = findsymbol(tzSym, scope); + + if (nsym != NULL) { if (nsym->nType & SYMF_DEFINED) { - yyerror("'%s' already defined in %s(%d)", - tzSym, nsym->tzFileName, nsym->nFileLine); + yyerror("'%s' already defined in %s(%d)", tzSym, + nsym->tzFileName, nsym->nFileLine); } - } else + } else { nsym = createsymbol(tzSym); + } if (nsym) { nsym->nValue = nPC; nsym->nType |= SYMF_RELOC | SYMF_DEFINED; - if (localPtr) { + if (localPtr) nsym->nType |= SYMF_LOCAL; - } - if (exportall) { - nsym->nType |= SYMF_EXPORT; - } + + if (exportall) + nsym->nType |= SYMF_EXPORT; + nsym->pScope = scope; nsym->pSection = pCurrentSection; } @@ -695,80 +694,83 @@ sym_AddReloc(char *tzSym) * * It returns 1 if the difference is defined, 0 if not. */ -int32_t -sym_IsRelocDiffDefined(char *tzSym1, char *tzSym2) +int32_t sym_IsRelocDiffDefined(char *tzSym1, char *tzSym2) { /* Do nothing the first pass. */ if (nPass != 2) return 1; - struct sSymbol *nsym1, *nsym2; + const struct sSymbol *nsym1 = sym_FindSymbol(tzSym1); + const struct sSymbol *nsym2 = sym_FindSymbol(tzSym2); /* Do the symbols exist? */ - if ((nsym1 = sym_FindSymbol(tzSym1)) == NULL) + if (nsym1 == NULL) fatalerror("Symbol \"%s\" isn't defined.", tzSym1); - if ((nsym2 = sym_FindSymbol(tzSym2)) == NULL) + + if (nsym2 == NULL) fatalerror("Symbol \"%s\" isn't defined.", tzSym2); int32_t s1reloc = (nsym1->nType & SYMF_RELOC) != 0; int32_t s2reloc = (nsym2->nType & SYMF_RELOC) != 0; /* Both are non-relocatable */ - if (!s1reloc && !s2reloc) return 1; + if (!s1reloc && !s2reloc) + return 1; - /* One of them relocatable, the other one not. */ - if (s1reloc ^ s2reloc) return 0; + /* One of them is relocatable, the other one is not. */ + if (s1reloc ^ s2reloc) + return 0; - /* Both of them are relocatable. Make sure they are defined (internal - * coherency with sym_AddReloc and sym_AddLocalReloc). */ + /* + * Both of them are relocatable. Make sure they are defined (internal + * coherency with sym_AddReloc and sym_AddLocalReloc). + */ if (!(nsym1->nType & SYMF_DEFINED)) fatalerror("Relocatable symbol \"%s\" isn't defined.", tzSym1); + if (!(nsym2->nType & SYMF_DEFINED)) fatalerror("Relocatable symbol \"%s\" isn't defined.", tzSym2); - /* Both of them must be in the same section for the difference to be - * defined. */ + /* + * Both of them must be in the same section for the difference to be + * defined. + */ return nsym1->pSection == nsym2->pSection; } /* * Export a symbol */ -void -sym_Export(char *tzSym) +void sym_Export(char *tzSym) { if (nPass == 1) { /* only export symbols in pass 1 */ - struct sSymbol *nsym; + struct sSymbol *nsym = sym_FindSymbol(tzSym); - if ((nsym = sym_FindSymbol(tzSym)) == NULL) + if (nsym == NULL) nsym = createsymbol(tzSym); if (nsym) nsym->nType |= SYMF_EXPORT; } else { - struct sSymbol *nsym; + const struct sSymbol *nsym = sym_FindSymbol(tzSym); - if ((nsym = sym_FindSymbol(tzSym)) != NULL) { + if (nsym != NULL) { if (nsym->nType & SYMF_DEFINED) return; } yyerror("'%s' not defined", tzSym); } - } /* * Globalize a symbol (export if defined, import if not) */ -void -sym_Global(char *tzSym) +void sym_Global(char *tzSym) { if (nPass == 2) { /* only globalize symbols in pass 2 */ - struct sSymbol *nsym; - - nsym = sym_FindSymbol(tzSym); + struct sSymbol *nsym = sym_FindSymbol(tzSym); if ((nsym == NULL) || ((nsym->nType & SYMF_DEFINED) == 0)) { if (nsym == NULL) @@ -786,21 +788,23 @@ sym_Global(char *tzSym) /* * Add a macro definition */ -void -sym_AddMacro(char *tzSym) +void sym_AddMacro(char *tzSym) { - if ((nPass == 1) - || ((nPass == 2) && (sym_isDefined(tzSym) == 0))) { + if ((nPass == 1) || ((nPass == 2) && (sym_isDefined(tzSym) == 0))) { /* only add macros in pass 1 */ struct sSymbol *nsym; - if ((nsym = findsymbol(tzSym, NULL)) != NULL) { + nsym = findsymbol(tzSym, NULL); + + if (nsym != NULL) { if (nsym->nType & SYMF_DEFINED) { yyerror("'%s' already defined in %s(%d)", - tzSym, nsym->tzFileName, nsym->nFileLine); + tzSym, nsym->tzFileName, + nsym->nFileLine); } - } else + } else { nsym = createsymbol(tzSym); + } if (nsym) { nsym->nValue = nPC; @@ -815,15 +819,15 @@ sym_AddMacro(char *tzSym) /* * Set whether to export all relocable symbols by default */ -void sym_SetExportAll(uint8_t set) { +void sym_SetExportAll(uint8_t set) +{ exportall = set; } /* * Prepare for pass #1 */ -void -sym_PrepPass1(void) +void sym_PrepPass1(void) { sym_Init(); } @@ -831,8 +835,7 @@ sym_PrepPass1(void) /* * Prepare for pass #2 */ -void -sym_PrepPass2(void) +void sym_PrepPass2(void) { int32_t i; @@ -840,15 +843,17 @@ sym_PrepPass2(void) struct sSymbol **ppSym = &(tHashedSymbols[i]); while (*ppSym) { - if ((*ppSym)-> - nType & (SYMF_SET | SYMF_STRING | SYMF_EQU)) { + uint32_t mask = SYMF_SET | SYMF_STRING | SYMF_EQU; + + if ((*ppSym)->nType & mask) { struct sSymbol *pTemp; pTemp = (*ppSym)->pNext; free(*ppSym); *ppSym = pTemp; - } else + } else { ppSym = &((*ppSym)->pNext); + } } } pScope = NULL; @@ -882,8 +887,7 @@ sym_PrepPass2(void) /* * Initialize the symboltable */ -void -sym_Init(void) +void sym_Init(void) { int32_t i; time_t now; @@ -908,16 +912,21 @@ sym_Init(void) sym_AddSet("_RS", 0); if (time(&now) != -1) { - struct tm *time_local = localtime(&now); + const struct tm *time_local = localtime(&now); - strftime(SavedTIME, sizeof(SavedTIME), "\"%H:%M:%S\"", time_local); - strftime(SavedDATE, sizeof(SavedDATE), "\"%d %B %Y\"", time_local); + strftime(SavedTIME, sizeof(SavedTIME), "\"%H:%M:%S\"", + time_local); + strftime(SavedDATE, sizeof(SavedDATE), "\"%d %B %Y\"", + time_local); strftime(SavedTIMESTAMP_ISO8601_LOCAL, - sizeof(SavedTIMESTAMP_ISO8601_LOCAL), "\"%FT%T%z\"", time_local); + sizeof(SavedTIMESTAMP_ISO8601_LOCAL), "\"%FT%T%z\"", + time_local); + + const struct tm *time_utc = gmtime(&now); - struct tm *time_utc = gmtime(&now); strftime(SavedTIMESTAMP_ISO8601_UTC, - sizeof(SavedTIMESTAMP_ISO8601_UTC), "\"%FT%TZ\"", time_utc); + sizeof(SavedTIMESTAMP_ISO8601_UTC), "\"%FT%TZ\"", + time_utc); strftime(SavedDAY, sizeof(SavedDAY), "%d", time_utc); strftime(SavedMONTH, sizeof(SavedMONTH), "%m", time_utc); @@ -933,8 +942,10 @@ sym_Init(void) helper_RemoveLeadingZeros(SavedSECOND); } else { warnx("Couldn't determine current time."); - /* The '?' have to be escaped or they will be treated as - * trigraphs... */ + /* + * The '?' have to be escaped or they will be treated as + * trigraphs... + */ strcpy(SavedTIME, "\"\?\?:\?\?:\?\?\""); strcpy(SavedDATE, "\"\?\? \?\?\? \?\?\?\?\""); strcpy(SavedTIMESTAMP_ISO8601_LOCAL, "\"\?\?\?\?-\?\?-\?\?T\?\?:\?\?:\?\?+\?\?\?\?\""); @@ -961,5 +972,4 @@ sym_Init(void) pScope = NULL; math_DefinePI(); - }