2 // coded by Ketmar // Vamprile Avalon
15 #include <sys/types.h>
19 #include "liburasm/liburasm.h"
28 #define MAYBE_UNUSED __attribute__((unused))
30 ///////////////////////////////////////////////////////////////////////////////
33 static char *sysIncludeDir
= NULL
;
35 #define MAX_LINE_SIZE 16384
36 static char curLine
[MAX_LINE_SIZE
]; /* current processing line; can be freely modified */
39 ///////////////////////////////////////////////////////////////////////////////
42 static void initInclideDir (void) {
43 const char *id
= getenv("URASM_INCLUDE_DIR");
45 sysIncludeDir
= strdup(id
);
48 memset(myDir
, 0, sizeof(myDir
));
49 if (readlink("/proc/self/exe", myDir
, sizeof(myDir
)-1) < 0) strcpy(myDir
, ".");
51 char *p
= (char *)strrchr(myDir
, '/');
52 if (!p
) strcpy(myDir
, "."); else *p
= '\0';
54 strcat(myDir
, "/libs");
55 sysIncludeDir
= strdup(myDir
);
57 while (sysIncludeDir
[0] && sysIncludeDir
[strlen(sysIncludeDir
)-1] == '/') sysIncludeDir
[strlen(sysIncludeDir
)-1] = '\0';
58 if (!sysIncludeDir
[0]) strcpy(sysIncludeDir
, ".");
62 ///////////////////////////////////////////////////////////////////////////////
65 /*TODO: expression parser should understant escapes in strings!*/
66 /* trim trailing spaces and comments */
67 static void normalizeStr (char *s
) {
71 for (p
= s
; *p
; ++p
) {
76 case 'x': case 'X': // hex code
78 for (f
= 0; f
< 2; ++f
) if (!isxdigit(*p
)) break;
79 --p
; // last digit will be skiped by 'for'
81 case '0': // octal code
82 for (f
= 0; f
< 4; ++f
) if (!isdigit(*p
) || *p
> '7') break;
83 --p
; // last digit will be skiped by 'for'
85 case '1' ... '9': // decimal code
86 for (f
= 0; f
< 3; ++f
) if (!isdigit(*p
)) break;
87 --p
; // last digit will be skiped by 'for'
89 default: ; // other escapes, do nothing
92 if (*p
== inQ
) inQ
= 0;
98 case '"': case '\'': // string catched
101 case ';': // end of line, comment follows
102 *p
-- = '\0'; // strip it and quit
104 default: ; // do nothing
108 for (p
= s
+strlen(s
)-1; p
>= s
&& isspace(*p
); --p
) ;
113 /* returns NULL or pointer to args */
114 /* skips spaces after command if any */
115 static char *strIsCommand (const char *command
, char *str
) {
118 for (cnt
= 1; cnt
> 0; --cnt
) {
119 while (*str
&& isspace(*str
)) ++str
; // skip spaces
120 for (; *command
&& *str
; ++command
, ++str
) {
121 if (toupper(*command
) != toupper(*str
)) return NULL
; // alas
123 if (*command
) return NULL
; // alas
124 if (*str
&& isalnum(*str
)) return NULL
; // alas
125 while (*str
&& isspace(*str
)) ++str
; // skip spaces
126 if (*str
&& *str
== ':') break; // try again if we have a colon
133 /* don't free() result */
134 /* skips trailing spaces */
135 static char *parseStr (char **str
, char endQ
, int *lenp
) {
136 static char buf
[MAX_LINE_SIZE
];
137 int len
= 0, n
, f
, base
;
140 int xDigit (char ch
, int base
) {
141 if (ch
< '0') return -1;
143 if (ch
>= '0'+base
) return -1;
147 if (ch
<= '9') return ch
-'0';
148 if (ch
< 'A' || ch
> 'A'+base
-10) return -1;
150 return ch
<base
? ch
: -1;
153 memset(buf
, 0, sizeof(buf
));
159 case 'a': buf
[len
++] = '\a'; break;
160 case 'b': buf
[len
++] = '\b'; break;
161 case 'f': buf
[len
++] = '\f'; break;
162 case 'n': buf
[len
++] = '\n'; break;
163 case 'r': buf
[len
++] = '\r'; break;
164 case 't': buf
[len
++] = '\t'; break;
165 case 'v': buf
[len
++] = '\v'; break;
166 case 'z': buf
[len
++] = '\0'; break;
167 case 'x': case 'X': // hex
170 donum
: for (n
= 0; f
> 0; --f
) {
171 char ch
= xDigit(*a
++, base
);
172 if (ch
< 0) { --a
; break; }
177 --a
; // return to the last digit, 'for' will skip it
182 case '1' ... '9': // decimal
185 default: buf
[len
++] = a
[0]; break; // others
188 if (*a
== endQ
) { ++a
; break; }
192 while (*a
&& isspace(*a
)) ++a
; // skip trailing spaces
195 if (lenp
) *lenp
= len
;
200 ///////////////////////////////////////////////////////////////////////////////
201 // source file stack, reader, etc
203 typedef struct SourceLine SourceLine
;
211 static SourceLine
*asmText
= NULL
;
212 static SourceLine
*asmTextLast
= NULL
;
213 static SourceLine
*curSrcLine
= NULL
;
216 static void asmTextClear (void) {
218 SourceLine
*l
= asmText
;
220 asmText
= asmText
->next
;
225 asmTextLast
= curSrcLine
= NULL
;
229 static void normIncName (char *dest
, const char *fn
, int system
) {
232 if (system
) sprintf(dest
, "%s/%s", sysIncludeDir
, fn
); else sprintf(dest
, "%s", fn
);
233 if (stat(dest
, &st
)) return;
234 if (S_ISDIR(st
.st_mode
)) strcat(dest
, "/zzmain.zas");
238 static int asmTextLoad (const char *fname
) {
243 static int includeCount
= 0;
245 if (!(fl
= fopen(fname
, "r"))) {
246 fprintf(stderr
, "ERROR: can't open file: %s\n", fname
);
249 printf("loading: %s\n", fname
);
251 while (fgets(curLine
, sizeof(curLine
)-1, fl
)) {
253 curLine
[sizeof(curLine
)-1] = '\0';
254 normalizeStr(curLine
);
255 if (!curLine
[0]) continue; // don't store empty lines
256 // find specials, if any
257 if (isspace(curLine
[0])) {
258 if ((args
= strIsCommand("INCLUDE", curLine
)) != NULL
) {
265 fprintf(stderr
, "ERROR: file %s, line %d: invalid INCLUDE!\n", fname
, lineNo
);
268 if (args
[0] == '"' || args
[0] == '\'') qCh
= *args
++;
269 else if (args
[0] == '<') { qCh
= '>'; ++args
; system
= 1; }
270 char *fn
= parseStr(&args
, qCh
, NULL
); // i don't care about string length here
273 fprintf(stderr
, "ERROR: file %s, line %d: can't INCLUDE nothing!\n", fname
, lineNo
);
278 fprintf(stderr
, "ERROR: file %s, line %d: extra args after INCLUDE filename!\n", fname
, lineNo
);
281 if (includeCount
> 256) {
283 fprintf(stderr
, "ERROR: file %s, line %d: too many nested INCLUDEs!\n", fname
, lineNo
);
286 normIncName(curLine
, fn
, system
);
287 //if (system) sprintf(curLine, "%s/%s", sysIncludeDir, fn); else sprintf(curLine, "%s", fn);
288 fn
= strdup(curLine
); if (!fn
) abort();
290 system
= asmTextLoad(fn
);
293 if (system
) { fclose(fl
); return system
; }
298 s
= calloc(1, sizeof(SourceLine
));
301 s
->line
= strdup(curLine
); if (!s
->line
) abort();
302 s
->fname
= strdup(fname
); if (!s
->fname
) abort();
303 if (asmTextLast
) asmTextLast
->next
= s
; else asmText
= s
;
311 static inline void loadCurSrcLine (void) { if (curSrcLine
) strcpy(curLine
, (curSrcLine
!= NULL
? curSrcLine
->line
: "")); }
312 static inline SourceLine
*setCurSrcLine (SourceLine
*l
) { curSrcLine
= l
; loadCurSrcLine(); return l
; }
313 static inline SourceLine
*nextSrcLine (void) { return (curSrcLine
!= NULL
? setCurSrcLine(curSrcLine
->next
) : NULL
); }
316 ///////////////////////////////////////////////////////////////////////////////
319 static void processCurrentLine (void); // only one, will skip to next one
322 ///////////////////////////////////////////////////////////////////////////////
323 // error raisers, etc
325 static jmp_buf errJP
;
328 static void errorWriteFile (void) {
330 fprintf(stderr
, "at file %s, line %d\n%s\n*", curSrcLine
->fname
, curSrcLine
->lineNo
, curSrcLine
->line
);
332 fprintf(stderr
, "somewhere in time: ");
336 static void errorMsgV (const char *fmt
, va_list ap
) {
338 vfprintf(stderr
, fmt
, ap
);
345 static void __attribute__((format(printf
, 1, 2))) warningMsg (const char *fmt
, ...) {
347 fprintf(stderr
, "WARNING ");
353 static void __attribute__((format(printf
, 1, 2))) errorMsg (const char *fmt
, ...) {
355 fprintf(stderr
, "FATAL ");
361 static void __attribute__((noreturn
)) __attribute__((format(printf
, 1, 2))) fatal (const char *fmt
, ...) {
369 static void __attribute__((noreturn
)) fatalUrLib (int errcode
) {
370 errorMsg("%s", urErrorMessage(errcode
));
375 //////////////////////////////////////////////////////////////////////////////
376 // operator management
378 typedef int (*UrAsmOpFn
) (void);
380 typedef struct UrAsmOp
{
383 struct UrAsmOp
*next
;
386 static UrAsmOp
*oplist
= NULL
;
389 static UrAsmOp
*urAddOp (const char *name
, UrAsmOpFn fn
) {
390 UrAsmOp
*res
= calloc(1, sizeof(UrAsmOp
));
392 res
->name
= strdup(name
);
400 static UrAsmOp
*urFindOp (const char *name
) {
402 for (res
= oplist
; res
; res
= res
->next
) if (!strcasecmp(name
, res
->name
)) break;
407 static void urClearOps (void) {
410 c
= oplist
; oplist
= oplist
->next
;
417 ///////////////////////////////////////////////////////////////////////////////
420 typedef struct UrLabelInfo UrLabelInfo
;
424 int type
; /* -1: uknown (forward reference); 0: =; 1: equ; 2: code */
425 int known
; /* !0: label value already known */
426 int refLine
; /* first referenced line */
431 static UrLabelInfo
*labels
= NULL
;
433 static void urClearLabels (void) {
435 while ((c
= labels
)) {
436 labels
= labels
->next
;
437 if (c
->name
) free(c
->name
);
438 if (c
->refFile
) free(c
->refFile
);
444 static UrLabelInfo
*urFindLabel (const char *name
) {
446 for (c
= labels
; c
; c
= c
->next
) if (!strcmp(name
, c
->name
)) break;
451 static UrLabelInfo
*urAddLabel (const char *name
) {
452 UrLabelInfo
*c
= urFindLabel(name
);
455 for (p
= NULL
, c
= labels
; c
; p
= c
, c
= c
->next
) ;
456 c
= calloc(1, sizeof(UrLabelInfo
));
458 c
->name
= strdup(name
);
460 if (p
) p
->next
= c
; else labels
= c
;
467 ///////////////////////////////////////////////////////////////////////////////
468 // module list management
470 typedef struct ModuleInfo ModuleInfo
;
473 char *fname
; // opened in this file
474 int seen
; // !0: module already seen, skip other definitions from the same file
477 static ModuleInfo
*modules
= NULL
;
478 static ModuleInfo
*curModule
= NULL
;
481 static void modulesClear (void) {
484 ModuleInfo
*c
= modules
;
485 modules
= modules
->next
;
493 static void modulesResetSeen (void) {
495 for (c
= modules
; c
; c
= c
->next
) c
->seen
= 0;
499 static ModuleInfo
*moduleFind (const char *name
) {
501 if (!name
|| !name
[0]) return NULL
;
502 for (c
= modules
; c
; c
= c
->next
) if (!strcmp(c
->name
, name
)) break;
507 static ModuleInfo
*moduleAdd (const char *name
, const char *fname
) {
509 if (!name
|| !fname
|| !name
[0] || !fname
[0]) abort();
510 c
= calloc(1, sizeof(ModuleInfo
));
512 c
->name
= strdup(name
); if (!c
->name
) abort();
513 c
->fname
= strdup(fname
); if (!c
->fname
) abort();
520 ///////////////////////////////////////////////////////////////////////////////
521 // destination memory management
523 static uint8_t memory
[65536];
524 static char memused
[65536];
525 static char memresv
[65536];
526 static uint16_t pc
= 0; /* current position to write */
527 static uint16_t disp
= 0; /* current 'virtual PC' */
528 static uint16_t ent
= 0; /* starting address */
529 static uint16_t clrAddr
= 24999; /* address for CLEAR for cargador */
530 static int pass
= 0; /* 0: collect labels; 1: compiling; 2: compiling and fixing labels */
531 static int inTapeBlock
= 0;
532 static uint8_t tapeXorB
= 0;
535 static inline uint8_t getByte (uint16_t addr
) {
540 static inline __attribute__((unused
)) uint16_t getWord (uint16_t addr
) {
541 return ((uint16_t)memory
[addr
])|(((uint16_t)memory
[addr
+1])<<8);
545 static inline void putByte (uint16_t addr
, uint8_t b
) {
546 if (inTapeBlock
) tapeXorB
^= b
;
552 static inline MAYBE_UNUSED
void putWord (uint16_t addr
, uint16_t w
) {
553 putByte(addr
, w
&0xFFU
);
554 putByte(addr
+1, (w
>>8)&0xFFU
);
558 static inline void emitByte (uint8_t b
) {
565 static inline void emitWord (uint16_t w
) {
567 emitByte((w
>>8)&0xFFU
);
571 static inline void emitRWord (uint16_t w
) {
572 emitByte((w
>>8)&0xFFU
);
577 static void prepareMemory (void) {
578 memset(memory
, 0, sizeof(memory
));
579 memset(memused
, 0, sizeof(memused
));
580 memset(memresv
, 0, sizeof(memresv
));
584 ///////////////////////////////////////////////////////////////////////////////
585 // label getter and utilities
587 static char *lastSeenGlobalLabel
= NULL
; /* global */
590 static char *fixLocalLabel (const char *name
) {
591 static char newname
[MAX_LINE_SIZE
*2+1024];
593 memset(newname
, 0, sizeof(newname
));
594 if (!name
|| !name
[0]) newname
[0] = '\0';
595 else if (!lastSeenGlobalLabel
|| name
[0] != '.') strcpy(newname
, name
);
597 // this is local label, let's rename it
598 sprintf(newname
, "{%s%s}", lastSeenGlobalLabel
, name
);
604 static char *fixGlobalLabel (const char *name
) {
605 static char newname
[MAX_LINE_SIZE
*2+1024];
607 memset(newname
, 0, sizeof(newname
));
608 if (!name
|| !name
[0]) newname
[0] = '\0';
609 else if (!curModule
|| name
[0] == '.' || name
[0] == '{' || name
[0] == '@' || strchr(name
, '.')) {
610 if (name
[0] == '@' && name
[1]) ++name
;
611 strcpy(newname
, name
);
613 // this is global unqualified label and we have a module; let's rename it
614 sprintf(newname
, "%s.%s", curModule
->name
, name
);
616 //printf("%s --> %s\n", name, newname);
621 static int lblOptMakeU2
= 0;
622 static int32_t findLabelCB (const char *name
, uint16_t addr
, int *defined
, int *found
) {
626 nn
= fixGlobalLabel((ln
= fixLocalLabel(name
)));
627 lbl
= urFindLabel(nn
);
629 // try non-module label
630 lbl
= urFindLabel(ln
);
634 errorMsg("using undefined label %s", ln
);
639 lbl
= urAddLabel(nn
);
640 lbl
->type
= lblOptMakeU2
? -42 : -1;
642 lbl
->refLine
= curSrcLine
->lineNo
;
643 lbl
->refFile
= strdup(curSrcLine
->fname
);
644 //printf("new label: [%s]\n", lbl->name);
646 //printf("label reference: [%s]\n", lbl->name);
650 *defined
= lbl
->known
!=0;
666 static int isLabelDefinedOrKnown (const char *name
, uint16_t addr
, int qtype
) {
670 nn
= fixGlobalLabel((ln
= fixLocalLabel(name
)));
671 lbl
= urFindLabel(nn
);
673 // try non-module label
674 lbl
= urFindLabel(ln
);
677 case UR_QTYPE_DEFINED
: return lbl
? lbl
->known
!=0 : 0;
678 case UR_QTYPE_KNOWN
: return lbl
!=NULL
;
685 static int checkLabels (void) {
689 for (c
= labels
; c
; c
= c
->next
) {
691 fprintf(stderr
, "ERROR at file %s, line %d: referencing undefined label: %s\n", c
->refFile
, c
->refLine
, c
->name
);
694 if (c
->type
== 0) c
->known
= -1;
696 //if (wasError) longjmp(errJP, 667);
701 ///////////////////////////////////////////////////////////////////////////////
704 static int32_t getExprArg (int *defined
) {
710 while (*a
&& isspace(*a
)) ++a
;
711 if (!a
[0]) fatal("expression expected");
712 ee
= urExpression(&res
, a
, disp
, defined
, &error
);
713 if (error
) fatalUrLib(error
);
715 if (ee
[0] != ',' && ee
[0] != ':') fatal("bad expression");
716 memmove(curLine
, ee
, strlen(ee
)+1);
724 static int32_t getOneExprArg (int *defined
) {
725 int32_t res
= getExprArg(defined
);
727 if (curLine
[0] && curLine
[0] != ':') fatal("too many expressions");
732 static int isStrArg (void) { return (curLine
[0] == '"' || curLine
[0] == '\''); }
735 static char *getStrArg (int *lenp
) {
739 while (*a
&& isspace(*a
)) ++a
;
741 if (qCh
!= '"' && qCh
!= '\'') fatal("string expected");
742 res
= parseStr(&a
, qCh
, lenp
);
744 if (a
[0] != ',' && a
[0] != ':') fatal("bad string expression");
745 memmove(curLine
, a
, strlen(a
)+1);
753 static MAYBE_UNUSED
char *getOneStrArg (int *lenp
) {
754 char *res
= getStrArg(lenp
);
756 if (curLine
[0] && curLine
[0] != ':') fatal("too many expressions");
761 static char *getLabelArg (void) {
762 static char res
[MAX_LINE_SIZE
+128], *p
;
765 memset(res
, 0, sizeof(res
));
766 while (*a
&& isspace(*a
)) ++a
;
767 if (!a
[0]) fatal("label expected");
768 for (p
= res
; *a
&& *a
!= ','; ++a
, ++p
) *p
= *a
;
769 for (; p
> res
&& isspace(p
[-1]); --p
) ;
771 if (p
-res
> 120) fatal("label name too long: %s", res
);
772 while (*a
&& isspace(*a
)) ++a
;
774 if (a
[0] != ',' && a
[0] != ':') fatal("bad string expression");
775 memmove(curLine
, a
, strlen(a
)+1);
783 static char *getOneLabelArg (void) {
784 char *res
= getLabelArg();
786 if (curLine
[0] && curLine
[0] != ':') fatal("too many expressions");
791 /* res == 0: end of expression */
792 static int skipComma (void) {
795 for (a
= curLine
; *a
&& isspace(*a
); ++a
) ;
796 if (!a
[0]) { curLine
[0] = '\0'; return 0; }
798 while (a
[0] && (a
[0] == ':' || isspace(a
[0]))) ++a
;
799 if (!a
[0]) { curLine
[0] = '\0'; return 0; }
800 memmove(curLine
, a
, strlen(a
)+1);
803 if (a
[0] != ',') fatal("invalid expression: ',' expected");
804 for (++a
; *a
&& isspace(*a
); ++a
) ;
805 if (!a
[0]) { curLine
[0] = '\0'; return 0; }
806 memmove(curLine
, a
, strlen(a
)+1);
811 static void skipInstruction (void) {
815 for (cnt
= 1; cnt
> 0; --cnt
) {
816 while (*str
&& isspace(*str
)) ++str
; // skip spaces
817 while (*str
&& !isspace(*str
)) ++str
; // skip non-spaces
818 while (*str
&& isspace(*str
)) ++str
; // skip spaces
819 if (!str
[0] || *str
!= ':') break;
820 // try again if we have a colon
822 memmove(curLine
, str
, strlen(str
)+1);
826 ///////////////////////////////////////////////////////////////////////////////
829 static MAYBE_UNUSED
void removeSpacesAndColons (void) {
832 while (*ep
&& (isspace(*ep
) || *ep
== ':')) ++ep
;
833 memmove(curLine
, ep
, strlen(ep
)+1);
837 static void checkExprEnd (void) {
840 while (*ep
&& isspace(*ep
)) ++ep
;
841 memmove(curLine
, ep
, strlen(ep
)+1);
842 if (curLine
[0] && curLine
[0] != ':') fatal("end of expression expected");
846 /* remove label from curLine */
847 static void removeLabel (void) {
850 if (ep
[0] && !isspace(ep
[0])) for (ep
= curLine
; *ep
&& !isspace(*ep
) && *ep
!= ':'; ++ep
) ; // skip text
851 // skip spaces and colons
852 while (*ep
&& (isspace(*ep
) || *ep
== ':')) ++ep
;
853 memmove(curLine
, ep
, strlen(ep
)+1);
857 static void processLabel (void) {
862 int noLocAff
= 0, doEQU
= 0;
864 memset(n2
, 0, sizeof(n2
));
865 if (!curLine
[0] || isspace(curLine
[0]) || curLine
[0] == ':') { removeLabel(); return; } // removeLabel() removes any spaces, etc
867 for (ep
= curLine
; *ep
&& !isspace(*ep
) && *ep
!= ':'; ++ep
) ;
868 if (ep
-curLine
> 120) fatal("label too long");
870 memset(n2
, 0, sizeof(n2
));
871 memmove(n2
, curLine
, ep
-curLine
);
872 if (!urIsValidLabelName(n2
)) return; // this is not a valid label, get out of here
873 // check if this can be instruction
874 while (*ep
&& isspace(*ep
)) ++ep
;
875 if (*ep
!= ':' && urFindOp(n2
)) return; // this must be and instruction, process it
876 // ok, we got a good label
878 if (n2
[0] == '@' && n2
[1]) { noLocAff
= 1; memmove(n2
, n2
+1, strlen(n2
)); }
879 nn
= fixGlobalLabel((ln
= fixLocalLabel(n2
)));
880 lbl
= urAddLabel(nn
);
882 lbl
->refLine
= curSrcLine
->lineNo
;
883 lbl
->refFile
= strdup(curSrcLine
->fname
);
885 //printf("new: [%s]\n", lbl->name);
887 if (curLine
[0] == '=') {
889 argstart
= curLine
+1;
892 argstart
= strIsCommand("EQU", curLine
);
894 if (!argstart
|| doEQU
) {
895 if (pass
== 0 && lbl
->type
!= -1) fatal("duplicate label %s", lbl
->name
);
899 memmove(curLine
, argstart
, strlen(argstart
)+1);
901 if (lbl
->type
!= -1 && lbl
->type
!= 0) fatal("duplicate label %s", lbl
->name
);
904 int32_t res
= getOneExprArg(&defined
);
910 if (pass
!= 0) fatal("can't calculate label %s", lbl
->name
);
916 if (lbl
->name
[0] != '{' && !noLocAff
) {
917 if (lastSeenGlobalLabel
) free(lastSeenGlobalLabel
);
918 lastSeenGlobalLabel
= strdup(lbl
->name
);
926 ///////////////////////////////////////////////////////////////////////////////
927 // instruction finder (in source)
929 /* array ends with NULL */
930 /* returns line or NULL */
931 /* iidx will be set to found instruction number */
932 static SourceLine
*findNextInstructionFromList (int *iidx
, ...) {
933 if (iidx
) *iidx
= -1;
934 for (SourceLine
*cur
= curSrcLine
; cur
; cur
= cur
->next
) {
938 //if (!isspace(cur->line[0])) continue; // fuck labeled strings
941 const char *name
= va_arg(ap
, const char *);
944 if (strIsCommand(name
, cur
->line
)) {
956 static MAYBE_UNUSED SourceLine
*findNextInstruction (const char *name
) {
957 return findNextInstructionFromList(NULL
, name
, NULL
);
961 ///////////////////////////////////////////////////////////////////////////////
964 static int optRunSNA
= 1;
965 static int optRunTape
= 1;
966 static int optRunDMB
= 1;
967 static int optTapExt
= 0; /* set '.tap' extension (but don't write tape; this for inline tape blocks) */
970 /* return 'found' flag */
971 static int findChunkFrom (int addr
, int *start
, int *len
) {
972 if (addr
< 0) addr
= 0;
973 for (; addr
<= 65535 && !memused
[addr
]; ++addr
) ;
974 if (addr
> 65535) return 0;
976 for (; addr
<= 65535 && memused
[addr
]; ++addr
) ;
977 *len
= addr
-(*start
);
982 static void rleUnpack (uint16_t addr
, const uint8_t *buf
, int buflen
) {
983 for (; buflen
>= 2; buflen
-= 2) {
985 uint8_t byte
= *buf
++;
986 //printf("%d %u %u\n", cnt+1, byte, addr);
987 for (; cnt
>= 0; --cnt
, ++addr
) if (!memused
[addr
]) putByte(addr
, byte
);
992 static int fWriteByte (FILE *fo
, uint8_t b
, uint8_t *bxor
) {
993 if (fwrite(&b
, 1, 1, fo
) != 1) return -1;
994 if (bxor
) *bxor
= (*bxor
)^b
;
999 static int fWriteWord (FILE *fo
, uint16_t w
, uint8_t *bxor
) {
1000 if (fWriteByte(fo
, w
&0xFFU
, bxor
)) return -1;
1001 if (fWriteByte(fo
, (w
>>8)&0xFFU
, bxor
)) return -1;
1006 ///////////////////////////////////////////////////////////////////////////////
1009 static int saveSna (const char *fname
) {
1010 char *fn
= malloc(strlen(fname
)+16);
1014 sprintf(fn
, "%s.sna", fname
);
1015 fo
= fopen(fn
, "wb");
1017 if (!fo
) { fprintf(stderr
, "ERROR: can't write SNA file: %s.sna\n", fname
); return -1; }
1018 printf("out: %s.sna\n", fname
);
1019 memmove(regs
, ursna48
, 27);
1021 /* push new address */
1022 uint16_t sp
= (uint16_t)regs
[23]+(((uint16_t)regs
[24])<<8);
1024 putByte(sp
, ent
&0xFFU
);
1025 putByte(sp
+1, (ent
>>8)&0xFFU
);
1026 regs
[23] = sp
&0xFFU
;
1027 regs
[24] = (sp
>>8)&0xFFU
;
1029 fwrite(regs
, 27, 1, fo
);
1030 rleUnpack(16384, ursna48
+27, sizeof(ursna48
)-27);
1031 fwrite(memory
+16384, 49152, 1, fo
);
1037 ///////////////////////////////////////////////////////////////////////////////
1040 static void saveRaw (const char *basename
) {
1041 char *fname
= malloc(strlen(basename
)+16);
1045 while (findChunkFrom(start
, &start
, &len
)) {
1046 sprintf(fname
, "%s_%04X.%s", basename
, start
, optTapExt
?"tap":"bin");
1047 fo
= fopen(fname
, "wb");
1049 fprintf(stderr
, "ERROR: can't write file %s!\n", fname
);
1051 printf("out: %s\n", fname
);
1052 if (fwrite(memory
+start
, len
, 1, fo
) != 1) {
1053 fprintf(stderr
, "ERROR: error writing file %s!\n", fname
);
1066 ///////////////////////////////////////////////////////////////////////////////
1069 static int fwriteW16 (FILE *fo
, uint16_t w
) {
1072 if (fwrite(&b
, 1, 1, fo
) != 1) return -1;
1074 if (fwrite(&b
, 1, 1, fo
) != 1) return -1;
1079 static int saveDMB (const char *fname
) {
1080 char *fn
= malloc(strlen(fname
)+16);
1085 sprintf(fn
, "%s.dmb", fname
);
1086 fo
= fopen(fn
, "wb");
1088 if (!fo
) { fprintf(stderr
, "ERROR: can't write DMB file: %s.dmb\n", fname
); return -1; }
1090 while (findChunkFrom(start
, &start
, &len
)) { ++pcnt
; start
+= len
; }
1092 printf("out: %s.dmb\n", fname
);
1093 if (fwrite("DMB1", 4, 1, fo
) != 1) goto error
;
1094 if (fwriteW16(fo
, (optRunDMB
? ent
: 0)) != 0) goto error
;
1095 if (fwriteW16(fo
, (optRunDMB
? clrAddr
: 0)) != 0) goto error
;
1096 if (fwriteW16(fo
, pcnt
) != 0) goto error
;
1099 while (findChunkFrom(start
, &start
, &len
)) {
1100 if (fwriteW16(fo
, len
) != 0) goto error
;
1101 if (fwriteW16(fo
, start
) != 0) goto error
;
1102 if (fwrite(memory
+start
, len
, 1, fo
) != 1) goto error
;
1110 fprintf(stderr
, "ERROR: error writing file %s.dmb!\n", fname
);
1115 ///////////////////////////////////////////////////////////////////////////////
1118 static char tapeLoaderName
[16];
1121 static void saveTapCargador (FILE *fo
) {
1123 static uint8_t cargador
[16384]; // should be enough for everyone
1124 int start
= 0, len
, pos
, f
;
1128 void putStr (const char *s
) {
1129 for (; *s
; ++s
) cargador
[pos
++] = *s
;
1132 void putNum (int num
) {
1134 sprintf(buf
, "%d", num
);
1141 cargador
[0] = 0; cargador
[1] = 10;
1142 // size (will be fixed later)
1143 putStr("\xfd\xb0\""); putNum(clrAddr
); putStr("\""); // CLEAR VAL "xxx"
1145 while (findChunkFrom(start
, &start
, &len
)) {
1147 putStr(":\xef\"\"\xaf");
1151 // :RANDOMIZE USR VAL "xxx"
1152 putStr(":\xf9\xc0\xb0\""); putNum(ent
); putStr("\"\r");
1154 cargador
[2] = (pos
-4)&0xff;
1155 cargador
[3] = ((pos
-4)>>8)&0xff;
1157 fWriteWord(fo
, 19, NULL
); // length of header
1159 fWriteByte(fo
, 0, &bxor
); // header block
1160 fWriteByte(fo
, 0, &bxor
); // 'basic' flag
1161 if (tapeLoaderName
[0]) {
1162 for (int f
= 0; f
< 10; ++f
) fWriteByte(fo
, tapeLoaderName
[f
], &bxor
);
1164 fWriteByte(fo
, 'c', &bxor
);
1165 fWriteByte(fo
, 'a', &bxor
);
1166 fWriteByte(fo
, 'r', &bxor
);
1167 fWriteByte(fo
, 'g', &bxor
);
1168 fWriteByte(fo
, 'a', &bxor
);
1169 fWriteByte(fo
, 'd', &bxor
);
1170 fWriteByte(fo
, 'o', &bxor
);
1171 fWriteByte(fo
, 'r', &bxor
);
1172 fWriteByte(fo
, ' ', &bxor
);
1173 fWriteByte(fo
, ' ', &bxor
);
1175 fWriteWord(fo
, pos
, &bxor
); // length
1176 fWriteWord(fo
, 10, &bxor
); // start
1177 fWriteWord(fo
, pos
, &bxor
); // length2
1178 fWriteByte(fo
, bxor
, NULL
);
1180 fWriteWord(fo
, pos
+2, NULL
); // plus type and checkbyte
1182 fWriteByte(fo
, 0xFFU
, &bxor
); // data block
1183 for (f
= 0; f
< pos
; ++f
) fWriteByte(fo
, cargador
[f
], &bxor
);
1184 fWriteByte(fo
, bxor
, NULL
);
1188 static void saveTap (const char *basename
) {
1189 char *fname
= malloc(strlen(basename
)+16);
1191 int start
= 0, len
, f
;
1195 sprintf(fname
, "%s.tap", basename
);
1196 fo
= fopen(fname
, "wb");
1198 if (!fo
) { fprintf(stderr
, "ERROR: can't write file %s.tap!\n", basename
); return; }
1199 printf("out: %s.tap\n", basename
);
1200 if (optRunTape
) saveTapCargador(fo
);
1201 while (findChunkFrom(start
, &start
, &len
)) {
1203 if (tapeLoaderName
[0]) {
1204 //for (int f = 0; f < 10; ++f) fWriteByte(fo, tapeLoaderName[f], &bxor);
1205 memcpy(blkname
, tapeLoaderName
, 10);
1207 sprintf(blkname
, "c%04X:%04X", start
, len
);
1209 //printf(" block: %s\n", blkname);
1210 fWriteWord(fo
, 19, NULL
); // length of header
1212 fWriteByte(fo
, 0, &bxor
); // header block
1213 fWriteByte(fo
, 3, &bxor
); // 'code' flag
1214 for (f
= 0; f
< 10; ++f
) fWriteByte(fo
, blkname
[f
], &bxor
);
1215 fWriteWord(fo
, len
, &bxor
);
1216 fWriteWord(fo
, start
, &bxor
);
1217 fWriteWord(fo
, 32768, &bxor
);
1218 fWriteByte(fo
, bxor
, NULL
);
1220 fWriteWord(fo
, len
+2, NULL
); // plus type and checkbyte
1222 fWriteByte(fo
, 0xFFU
, &bxor
); // data block
1223 for (f
= 0; f
< len
; ++f
) fWriteByte(fo
, memory
[start
+f
], &bxor
);
1224 fWriteByte(fo
, bxor
, NULL
);
1231 ///////////////////////////////////////////////////////////////////////////////
1232 // pseudoinstructions
1234 // note that processCurrentLine() will NOT skip to the next line before
1235 // calling pseudoinstruction handler!
1236 // note that processCurrentLine() will skip current line after calling
1237 // pseudoinstruction handler!
1239 static int wasOrg
= 0;
1240 static int wasClr
= 0;
1243 ///////////////////////////////////////////////////////////////////////////////
1246 static int piDISPLAYX (int passNo
, int asHex
) {
1250 char *res
= getStrArg(&len
);
1252 if (passNo
< 0 || pass
== passNo
) printf("%s", res
);
1255 int32_t v
= getExprArg(&defined
);
1257 if (passNo
< 0 || pass
== passNo
) {
1258 if (asHex
) printf("%04X", (unsigned int)v
);
1259 else printf("%d", v
);
1262 if (!skipComma()) break;
1268 static int piDISPLAY (void) { return piDISPLAYX(1, 0); }
1269 static int piDISPLAY0 (void) { return piDISPLAYX(0, 0); }
1270 static int piDISPLAYA (void) { return piDISPLAYX(-1, 0); }
1271 static int piDISPHEX (void) { return piDISPLAYX(1, 1); }
1272 static int piDISPHEX0 (void) { return piDISPLAYX(0, 1); }
1273 static int piDISPHEXA (void) { return piDISPLAYX(-1, 1); }
1276 ///////////////////////////////////////////////////////////////////////////////
1279 static int piORG (void) {
1281 int32_t res
= getOneExprArg(&defined
);
1283 if (!defined
) fatal("sorry, ORG operand value must be known here");
1284 if (res
< 0 || res
> 65535) fatal("invalid ORG operand value: %d", res
);
1285 if (inTapeBlock
) fatal("sorry, no ORGs in TAPEDATA allowed");
1290 if (!wasClr
&& res
> 0) clrAddr
= res
-1;
1296 static int piDISP (void) {
1298 int32_t res
= getOneExprArg(&defined
);
1300 if (!defined
) fatal("sorry, DISP operand value must be known here");
1301 if (res
< 0 || res
> 65535) fatal("invalid DISP operand value: %d", res
);
1302 //printf("DISP=%d\n", res);
1308 static int piENDDISP (void) {
1309 if (inTapeBlock
) fatal("sorry, no ENDDISPs in TAPEDATA allowed");
1316 static int piENT (void) {
1318 int32_t res
= getOneExprArg(&defined
);
1320 //if (!defined) fatal("sorry, ENT operand value must be known here");
1321 if (res
< 0 || res
> 65535) fatal("invalid ENT operand value: %d", res
);
1327 static int piCLR (void) {
1329 int32_t res
= getOneExprArg(&defined
);
1331 //if (!defined) fatal("sorry, CLR operand value must be known here");
1332 if (res
< 0 || res
> 65535) fatal("invalid CLR operand value: %d", res
);
1339 static int piRESERVE (void) {
1341 int defined = 1, start;
1342 int32_t res = getExprArg(&defined);
1343 if (!defined) fatal("sorry, RESERVE operand values must be known here");
1344 if (res < 0 || res > 65535) fatal("invalid RESERVE operand value: %d", res);
1346 if (!skipComma()) fatal("RESERVE needs 2 args");
1347 res = getOneExprArg(&defined);
1348 if (!defined) fatal("sorry, RESERVE operand values must be known here");
1349 if (res < 0 || res > 65535) fatal("invalid RESERVE operand value: %d", res);
1350 for (; len > 0; --len, start = (start+1)&0xffff) memresv[start] = 1;
1352 fatal("RESERVE: not yet!");
1357 static int piALIGN (void) {
1361 if (inTapeBlock
) fatal("sorry, no ALIGNs in TAPEDATA allowed");
1362 res
= getOneExprArg(&defined
);
1363 if (!defined
) fatal("sorry, ALIGN operand value must be known here");
1364 if (res
< 0 || res
> 65535) fatal("invalid ALIGN operand value: %d", res
);
1365 if (pc
!= disp
) fatal("sorry, no ALIGNs in desynced blocks allowed");
1366 if (res
> 0 && pc
%res
!= 0) {
1376 static int piDISPALIGN (void) {
1378 int32_t res
= getOneExprArg(&defined
);
1380 if (!defined
) fatal("sorry, DISPALIGN operand value must be known here");
1381 if (res
< 0 || res
> 65535) fatal("invalid DISPALIGN operand value: %d", res
);
1382 if (res
> 0 && disp
%res
!= 0) {
1391 ///////////////////////////////////////////////////////////////////////////////
1394 static int defIncr
= 0;
1397 static int piDEFINCR (void) {
1399 int32_t cnt
= getOneExprArg(&defined
);
1401 if (!defined
) fatal("DEFINCR: increment must be defined");
1407 static int piDEFBW (int isWord
) {
1413 char *res
= getStrArg(&len
);
1415 for (f
= 0; f
< len
; ++f
) {
1416 int32_t b
= (uint8_t)res
[f
];
1418 if (b
< -128 || b
> 255) fatal("invalid operand value: %d", b
);
1419 if (b
< 0) b
+= 256;
1423 int32_t res
= getExprArg(&defined
);
1425 if (pass
> 0 && !defined
) fatal("undefined operand");
1428 if (res
< -32768 || res
> 65535) fatal("invalid operand value: %d", res
);
1429 if (res
< 0) res
+= 65536;
1430 if (isWord
== 1) emitWord(res
); else emitRWord(res
);
1432 if (res
< -128 || res
> 255) fatal("invalid operand value: %d", res
);
1433 if (res
< 0) res
+= 256;
1437 if (!skipComma()) break;
1442 static int piDEFB (void) { return piDEFBW(0); }
1443 static int piDEFW (void) { return piDEFBW(1); }
1444 static int piDEFR (void) { return piDEFBW(2); }
1447 static int piDEFS (void) {
1451 int32_t res
= getExprArg(&defined
);
1453 if (pass
> 0 && !defined
) fatal("undefined operand");
1454 if (res
< 1 || res
> 65535) fatal("invalid number of repetitions: %d", res
);
1455 if (*curLine
&& curLine
[0] == ',') {
1457 bt
= getExprArg(&defined
);
1458 if (pass
> 0 && !defined
) fatal("undefined operand");
1460 if (bt
< -128 || bt
> 255) fatal("invalid operand value: %d", res
);
1461 if (bt
< 0) bt
+= 256;
1462 for (f
= 0; f
< res
; ++f
) emitByte(bt
);
1464 pc
+= res
; disp
+= res
;
1466 if (!skipComma()) break;
1472 /* bit 0: put '\0' */
1473 /* bit 1: set bit 7 of last byte */
1474 /* bit 2: put length */
1475 static int piDEFSTR (int type
) {
1479 char *res
= getStrArg(&len
);
1482 if (len
> 255) fatal("string too long");
1485 for (f
= 0; f
< len
; ++f
) {
1486 uint8_t b
= (uint8_t)res
[f
];
1488 if ((type
&0x02) && f
== len
-1) b
|= 0x80;
1491 if (type
&0x01) emitByte(0);
1494 int32_t v
= getExprArg(&defined
);
1496 if (pass
> 0 && !defined
) fatal("undefined expression");
1497 if (!defined
) v
= 0; else v
+= defIncr
;
1498 if (v
< -128 || v
> 255) fatal("invalid operand value: %d", v
);
1499 if (v
< 0) v
+= 256;
1502 if (!skipComma()) break;
1508 static int piDEFM (void) { return piDEFSTR(0x00); }
1509 static int piDEFZ (void) { return piDEFSTR(0x01); }
1510 static int piDEFX (void) { return piDEFSTR(0x02); }
1511 static int piDEFC (void) { return piDEFSTR(0x04); }
1514 ///////////////////////////////////////////////////////////////////////////////
1517 /* INCBIN "name"[,maxlen] */
1518 static int piINCBIN (void) {
1524 char *args
= curLine
;
1526 if (!curLine
[0]) fatal("INCBIN without file name");
1530 } else if (curLine
[0] == '<') {
1537 fn
= parseStr(&args
, qCh
, NULL
); // i don't care about string length here
1538 if (!fn
[0]) fatal("INCBIN: empty file name");
1539 memmove(curLine
, args
, strlen(args
)+1);
1541 if (curLine
[0] == ',') {
1545 maxlen
= getOneExprArg(&defined
);
1546 if (!defined
) fatal("INCBIN: undefined maxlen");
1547 if (maxlen
< 1) return 1; // nothing to do
1551 sprintf(curLine
, "%s/%s", sysIncludeDir
, fn
);
1553 sprintf(curLine
, "%s", fn
);
1556 fl
= fopen(curLine
, "rb");
1557 if (!fl
) fatal("INCBIN: file not found: %s", curLine
);
1558 while (maxlen
-- > 0) {
1559 int res
= fread(&bt
, 1, 1, fl
);
1562 if (res
!= 1) { fclose(fl
); fatal("INCBIN: error reading file: %s", curLine
); }
1570 ///////////////////////////////////////////////////////////////////////////////
1571 // MODULE, ENDMODULE
1573 static int piENDMODULE (void) {
1574 if (!curModule
) fatal("ENDMODULE without MODULE");
1576 char *mn
= getOneLabelArg();
1578 if (strcmp(mn
, curModule
->name
)) fatal("invalid module name in ENDMODULE: %s", mn
);
1585 static int piMODULE (void) {
1588 SourceLine
*ol
= curSrcLine
;
1591 if (curModule
) fatal("no nested modules allowed");
1592 mn
= getOneLabelArg();
1593 if (!urIsValidLabelName(mn
)) fatal("invalid module name: %s", mn
);
1594 mi
= moduleFind(mn
);
1595 //printf("[%s] %p\n", mn, mi);
1598 if (strcmp(mi
->fname
, curSrcLine
->fname
)) fatal("duplicate module definition; previous was in %s", mi
->fname
);
1600 nextSrcLine(); // skip ourself
1601 if (!setCurSrcLine(findNextInstructionFromList(&inum
, "MODULE", "ENDMODULE", NULL
))) {
1603 fatal("no ENDMODULE");
1605 if (inum
== 0) fatal("no nested modules allowed");
1612 mi
= moduleAdd(mn
, curSrcLine
->fname
);
1620 ///////////////////////////////////////////////////////////////////////////////
1623 static int piEDUP (void) {
1624 fatal("EDUP without DUP");
1630 static int piDUP (void) {
1631 int defined
= 1, dupCnt
= 1, inum
;
1632 SourceLine
*stline
, *eline
= NULL
;
1633 int32_t cnt
= getOneExprArg(&defined
);
1635 if (!defined
) fatal("DUP: counter must be defined");
1636 if (cnt
> 65535) fatal("DUP: counter too big: %d", cnt
);
1637 if (cnt
< 0) warningMsg("DUP: counter too small: %d", cnt
);
1638 // now find corresponding EDUP
1639 // note that we should skip nested DUPs
1640 nextSrcLine(); // skip ourself
1641 stline
= curSrcLine
;
1642 while (curSrcLine
) {
1643 if (!setCurSrcLine(findNextInstructionFromList(&inum
, "DUP", "EDUP", NULL
))) break;
1644 // ok, we found something; what is it?
1648 nextSrcLine(); // skip DUP
1651 if (--dupCnt
== 0) {
1656 nextSrcLine(); // skip EDUP
1659 if (!eline
) { setCurSrcLine(stline
); fatal("no EDUP"); }
1660 // now repeat that lines
1662 setCurSrcLine(stline
);
1663 while (curSrcLine
!= eline
) processCurrentLine();
1669 ///////////////////////////////////////////////////////////////////////////////
1672 static int ifCount
= 0;
1675 static int ifSkipToEndIfOrElse (int wholeBody
) {
1676 int inum
, wasElse
= 0;
1679 while (curSrcLine
) {
1680 if (!setCurSrcLine(findNextInstructionFromList(&inum
, "IF", "ELSE", "ENDIF", "ELSEIF", "MACRO", "ENDM", "IFX", "ELSEIFX", NULL
))) break;
1684 nextSrcLine(); // skip IF
1685 ifSkipToEndIfOrElse(1); // and recurse
1686 nextSrcLine(); // skip ENDIF
1689 if (wasElse
) fatal("duplicate ELSE");
1690 if (!wholeBody
) return 1;
1692 nextSrcLine(); // skip ELSE
1693 break; // and continue
1695 return 0; // and exit
1698 if (wasElse
) fatal("ELSEIF in ELSE");
1699 if (!wholeBody
) return 2;
1700 nextSrcLine(); // skip ELSEIF
1701 break; // and continue
1703 // skip it as a whole
1704 nextSrcLine(); // skip MACRO
1707 if (!setCurSrcLine(findNextInstructionFromList(&inum
, "MACRO", "ENDM", NULL
))) { setCurSrcLine(oline
); fatal("invalid MACRO"); }
1708 if (inum
== 1) break;
1709 fatal("invalid nested MACRO");
1711 nextSrcLine(); // skip ENDM
1714 fatal("unexpected ENDM");
1717 fatal("IF without ENDIF");
1722 static int piENDIF (void) {
1723 if (--ifCount
< 0) fatal("ENDIF without IF");
1729 static int piELSE (void) {
1730 if (--ifCount
< 0) fatal("ELSE without IF");
1731 nextSrcLine(); // skip ELSE
1732 ifSkipToEndIfOrElse(1);
1737 static int piELSEIF (void) {
1738 if (--ifCount
< 0) fatal("ELSEIF without IF");
1739 nextSrcLine(); // skip ELSEIF
1740 ifSkipToEndIfOrElse(1);
1745 static int piIFAll (int isIfX
) {
1747 int ooo
= lblOptMakeU2
;
1748 lblOptMakeU2
= isIfX
? 1 : 0;
1749 int32_t cond
= getOneExprArg(&defined
);
1753 if (!isIfX
) fatal("IF: condition must be defined");
1754 cond
= 0; // for IFX: 0 is there is any undefined label
1757 // ok, do it until ELSE/ELSEIF/ENDIF
1765 nextSrcLine(); // skip last instruction
1766 // skip until ELSE/ELSEIF/ENDIF
1767 r
= ifSkipToEndIfOrElse(0);
1768 if (r
== 0) break; // ENDIF
1769 if (r
== 1) { ++ifCount
; break; } // ELSE
1770 // ELSEIF, do condition
1771 if ((args
= strIsCommand("ELSEIF", curLine
)) == NULL
) fatal("internal error in conditionals"); // the thing that should not be
1772 memmove(curLine
, args
, strlen(args
)+1);
1773 cond
= getOneExprArg(&defined
);
1774 if (!defined
) fatal("ELSEIF: condition must be defined");
1775 if (cond
) { ++ifCount
; break; } // condition is true
1781 static int piIF (void) { return piIFAll(0); }
1782 static int piIFX (void) { return piIFAll(1); }
1785 ///////////////////////////////////////////////////////////////////////////////
1788 * what i did with MACRO is the brain-damaged cheating all the way.
1789 * first, i will collect the MACRO body and remember it.
1790 * second, when the macro is used, i will:
1791 * * create unique labels for all supplied macro args, each with
1792 * number (so IFARG/IFNARG can check the existance)
1793 * * insert the whole macro body in place, fixing argument refs
1794 * * let the asm play with it
1795 * another tricky part is 'local labels': i have to change all
1796 * '..lbl' references -- generate new label name for it and
1797 * replace all refs. and be careful to not touch the strings.
1798 * this is not the best scheme, but it is fairly simple and it wokrs.
1800 static int piMACRO (void) {
1801 fatal("sorry, no MACRO yet");
1806 static int piENDM (void) {
1807 fatal("ENDM withoud MACRO");
1812 ///////////////////////////////////////////////////////////////////////////////
1814 static int optWriteType
= 't';
1815 static int optWTChanged
= 0;
1818 static void piTapParseLoaderName (void) {
1823 if (!isStrArg()) fatal("loader name expected");
1824 fn
= getStrArg(&len
);
1825 if (len
> 10) fatal("loader name too long");
1826 memset(tapeLoaderName
, ' ', 10);
1827 for (int f
= 0; f
< len
; ++f
) tapeLoaderName
[f
] = fn
[f
];
1832 static int piDEFFMT (void) {
1838 name
= getStrArg(&len
);
1840 name
= getLabelArg();
1842 if (optWTChanged
) return 1;
1843 if (!strcasecmp(name
, "SNA") || !strcasecmp(name
, "RUNSNA")) {
1845 optRunSNA
= (toupper(name
[0]) == 'R');
1847 if (curLine
[0]) fatal("too many expressions");
1850 if (!strcasecmp(name
, "TAP") || !strcasecmp(name
, "TAPE")) {
1854 piTapParseLoaderName();
1857 if (!strcasecmp(name
, "RUNTAP") || !strcasecmp(name
, "RUNTAPE")) {
1861 piTapParseLoaderName();
1864 if (!strcasecmp(name
, "BIN") || !strcasecmp(name
, "RAW")) {
1868 if (curLine
[0]) fatal("too many expressions");
1871 if (!strcasecmp(name
, "DMB") || !strcasecmp(name
, "RUNDMB")) {
1874 optRunDMB
= (toupper(name
[0]) == 'R');
1876 if (curLine
[0]) fatal("too many expressions");
1879 if (!strcasecmp(name
, "NONE") || !strcasecmp(name
, "NOTHING")) {
1883 if (curLine
[0]) fatal("too many expressions");
1886 fatal("invalid default output type: %s", name
);
1890 ///////////////////////////////////////////////////////////////////////////////
1893 static void processCurrentLine (void) {
1894 if (!curSrcLine
) return; // do nothing
1898 char *str
, *ee
, name
[66];
1903 removeSpacesAndColons();
1904 // skip spaces and ':'
1905 if (!curLine
[0]) { nextSrcLine(); break; }
1906 // try to find and process command
1907 str
= curLine
; //while (*str && isspace(*str)) ++str; // skip spaces
1909 for (ee
= str
; *ee
&& !isspace(*ee
) && *ee
!= '"' && *ee
!= '\''; ++ee
) ;
1910 // get command, if any
1911 if (ee
!= str
&& ee
-str
<= 64) {
1912 memset(name
, 0, sizeof(name
));
1913 memmove(name
, str
, ee
-str
);
1915 op
= urFindOp(name
);
1918 str
= ee
; while (*str
&& isspace(*str
)) ++str
; // skip spaces
1919 memmove(curLine
, str
, strlen(str
)+1);
1921 nextSrcLine(); // skip it
1927 len
= urAssembleOne(curLine
, pc
, disp
, &errpos
);
1928 if (len
< 0) fatalUrLib(len
);
1929 pc
+= len
; disp
+= len
;
1930 if (len
>= 0 && errpos
) {
1931 memmove(curLine
, errpos
+1, strlen(errpos
));
1933 nextSrcLine(); // skip it
1940 ///////////////////////////////////////////////////////////////////////////////
1941 // setup instructions
1943 static void registerInstructions (void) {
1944 urAddOp("DISPLAY", piDISPLAY
);
1945 urAddOp("DISPLAY0", piDISPLAY0
);
1946 urAddOp("DISPLAYA", piDISPLAYA
);
1947 urAddOp("DISPHEX", piDISPHEX
);
1948 urAddOp("DISPHEX0", piDISPHEX0
);
1949 urAddOp("DISPHEXA", piDISPHEXA
);
1951 urAddOp("DEFFMT", piDEFFMT
);
1953 urAddOp("MACRO", piMACRO
);
1954 urAddOp("ENDM", piENDM
);
1956 urAddOp("ORG", piORG
);
1957 urAddOp("DISP", piDISP
);
1958 urAddOp("ENDDISP", piENDDISP
);
1959 urAddOp("PHASE", piDISP
);
1960 urAddOp("DEPHASE", piENDDISP
);
1961 urAddOp("UNPHASE", piENDDISP
);
1962 urAddOp("ALIGN", piALIGN
);
1963 urAddOp("DISPALIGN", piDISPALIGN
);
1964 urAddOp("PHASEALIGN", piDISPALIGN
);
1965 urAddOp("ENT", piENT
);
1966 urAddOp("CLR", piCLR
);
1967 urAddOp("RESERVE", piRESERVE
);
1969 urAddOp("INCBIN", piINCBIN
);
1971 urAddOp("MODULE", piMODULE
);
1972 urAddOp("ENDMODULE", piENDMODULE
);
1974 urAddOp("DUP", piDUP
);
1975 urAddOp("EDUP", piEDUP
);
1977 urAddOp("IF", piIF
);
1978 urAddOp("IFX", piIFX
);
1979 urAddOp("ELSE", piELSE
);
1980 urAddOp("ELSEIF", piELSEIF
);
1981 urAddOp("ELSEIFX", piELSEIF
);
1982 urAddOp("ENDIF", piENDIF
);
1984 urAddOp("DEFINCR", piDEFINCR
);
1985 urAddOp("DEFB", piDEFB
); urAddOp("DB", piDEFB
);
1986 urAddOp("DEFW", piDEFW
); urAddOp("DW", piDEFW
);
1987 urAddOp("DEFR", piDEFR
); urAddOp("DR", piDEFR
);
1988 urAddOp("DEFS", piDEFS
); urAddOp("DS", piDEFS
);
1989 urAddOp("DEFM", piDEFM
); urAddOp("DM", piDEFM
);
1990 urAddOp("DEFZ", piDEFZ
); urAddOp("DZ", piDEFZ
);
1991 urAddOp("DEFX", piDEFX
); urAddOp("DX", piDEFX
);
1992 urAddOp("DEFC", piDEFC
); urAddOp("DC", piDEFC
);
1996 ///////////////////////////////////////////////////////////////////////////////
1997 // !0: invalid label
1999 static inline void fnSkipSpaces (const char *expr) {
2000 while (*expr && isspace(*expr)) ++expr;
2006 static inline char fnNextChar (const char *expr
) {
2007 while (*expr
&& isspace(*expr
)) ++expr
;
2012 #define FN_CHECK_END do { \
2013 while (*expr && isspace(*expr)) ++expr; \
2014 if (expr[0] != ')') { *error = UR_EXPRERR_FUNC; return expr; } \
2019 #define FN_CHECK_COMMA do { \
2020 while (*expr && isspace(*expr)) ++expr; \
2021 if (expr[0] != ',') { *error = UR_EXPRERR_FUNC; return expr; } \
2026 static const char *readLabelName (char *buf
, const char *expr
) {
2029 while (*expr
&& isspace(*expr
)) ++expr
;
2033 if (pos
>= 128) return NULL
;
2035 if (isalnum(ch
) || ch
== '$' || ch
== '.' || ch
== '_' || ch
== '@') {
2041 if (pos
< 1) return NULL
;
2043 if (!urIsValidLabelName(buf
)) return NULL
;
2048 static const char *fnDefKn (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
, int qtype
) {
2051 if ((expr
= readLabelName(lbl
, expr
)) == NULL
) { *error
= UR_EXPRERR_LABEL
; return NULL
; }
2053 if (!donteval
) res
->val
= (isLabelDefinedOrKnown(lbl
, addr
, qtype
) != 0);
2057 static const char *fnDefined (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
) { return fnDefKn(res
, expr
, addr
, donteval
, defined
, error
, UR_QTYPE_DEFINED
); }
2058 static const char *fnKnown (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
) { return fnDefKn(res
, expr
, addr
, donteval
, defined
, error
, UR_QTYPE_KNOWN
); }
2061 static const char *fnAligned256 (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
) {
2062 expr
= urExpressionEx(res
, expr
, addr
, &donteval
, defined
, error
);
2064 if (!donteval
) res
->val
= (res
->val
%256 ? 0 : 1);
2069 static const char *fnSameSeg (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
) {
2072 urInitExprValue(&v0
);
2073 urInitExprValue(&v1
);
2074 expr
= urExpressionEx(&v0
, expr
, addr
, &donteval
, defined
, error
);
2076 expr
= urExpressionEx(&v1
, expr
, addr
, &donteval
, defined
, error
);
2078 if (!donteval
) res
->val
= (v0
.val
/256 == v1
.val
/256);
2083 static const char *fnAlign (URExprValue
*res
, const char *expr
, uint16_t addr
, int donteval
, int *defined
, int *error
) {
2086 urInitExprValue(&v0
);
2087 urInitExprValue(&v1
);
2088 expr
= urExpressionEx(&v0
, expr
, addr
, &donteval
, defined
, error
);
2089 if (fnNextChar(expr
) == ',') {
2091 expr
= urExpressionEx(&v1
, expr
, addr
, &donteval
, defined
, error
);
2097 if (v1
.val
< 1) { *error
= UR_EXPRERR_FUNC
; return NULL
; }
2098 res
->val
= (v0
.val
+v1
.val
-1)/v1
.val
*v1
.val
;
2104 static void registerFunctions (void) {
2105 urExpressionRegisterFunction("defined", fnDefined
);
2106 urExpressionRegisterFunction("known", fnKnown
);
2107 urExpressionRegisterFunction("aligned256", fnAligned256
);
2108 urExpressionRegisterFunction("align", fnAlign
);
2109 urExpressionRegisterFunction("sameseg", fnSameSeg
);
2113 ///////////////////////////////////////////////////////////////////////////////
2114 // preparing another pass
2116 static void initPass (void) {
2117 curSrcLine
= asmText
;
2119 pc
= disp
= ent
= 0x100; // viva CP/M!
2127 lastSeenGlobalLabel
= strdup(" [MAIN] ");
2133 static int posstPass (void) {
2134 if (lastSeenGlobalLabel
) free(lastSeenGlobalLabel
); lastSeenGlobalLabel
= NULL
;
2135 if (checkLabels()) return -1;
2136 if (ifCount
!= 0) fatal("unbalanced IFs");
2141 ///////////////////////////////////////////////////////////////////////////////
2144 static struct option longOpts
[] = {
2145 {"sna", 0, NULL
, 's'},
2146 {"autosna", 0, NULL
, 'S'},
2147 {"tap", 0, NULL
, 't'},
2148 {"autotap", 0, NULL
, 'T'},
2149 /*{"rawtap", 0, NULL, 'T'},*/
2150 {"raw", 0, NULL
, 'r'},
2151 {"autodmb", 0, NULL
, 'B'},
2152 {"dmb", 0, NULL
, 'b'},
2153 {"none", 0, NULL
, 'n'},
2154 {"help", 0, NULL
, 'h'},
2159 static const char *defInFiles
[] = {"main.zas", "main.a80", "main.asm", NULL
};
2162 static void usage (const char *pname
) {
2164 "usage: %s [options] infile\n"
2165 "default infiles:", pname
);
2166 for (int f
= 0; defInFiles
[f
]; ++f
) printf(" %s", defInFiles
[f
]);
2169 " -s --sna write 48K .SNA file\n"
2170 " -S --autosna write 48K .SNA file with autostart\n"
2171 " -t --tap write .tap file\n"
2172 " -T --autotap write .tap file with basic loader (CLR to set CLEAR)\n"
2173 " -r --raw write raw file(s)\n"
2174 " -b --dmb write DMB file\n"
2175 " -B --autodmb write DMB file with autostart\n"
2176 " -n --none write nothing\n"
2177 " -h --help this help\n");
2181 ///////////////////////////////////////////////////////////////////////////////
2184 int main (int argc
, char *argv
[]) {
2186 const char *pname
= argv
[0];
2187 char *inFile
= NULL
;
2190 urGetByteFn
= getByte
;
2191 urPutByteFn
= putByte
;
2192 urFindLabelByNameFn
= findLabelCB
;
2193 //urIsLabelDefinedOrKnownFn = isLabelDefinedOrKnown;
2195 //strcpy(tapeLoaderName, "cargador ");
2196 tapeLoaderName
[0] = 0;
2198 printf("urasm v%d.%d.%d, compile date: %s %s\n", VERSION_HI
, VERSION_MID
, VERSION_LO
, __DATE__
, __TIME__
);
2199 while ((c
= getopt_long(argc
, argv
, "sStTbBrnh", longOpts
, NULL
)) >= 0) {
2201 case 'S': optRunSNA
= 1; optWriteType
= 's'; optWTChanged
= 1; break;
2202 case 's': optRunSNA
= 0; optWriteType
= 's'; optWTChanged
= 1; break;
2203 case 'T': optRunTape
= 1; optWriteType
= 't'; optWTChanged
= 1; break;
2204 case 't': optRunTape
= 0; optWriteType
= 't'; optWTChanged
= 1; break;
2205 case 'b': optRunTape
= 0; optRunDMB
= 0; optWriteType
= 'd'; optWTChanged
= 1; break;
2206 case 'B': optRunTape
= 0; optRunDMB
= 1; optWriteType
= 'd'; optWTChanged
= 1; break;
2207 case 'r': case 'n': optWriteType
= c
; optWTChanged
= 1; break;
2208 case 'h': usage(pname
); res
= 0; goto earlyerrquit
;
2212 if (optind
>= argc
) {
2213 // try to find default input file
2215 for (f
= 0; defInFiles
[f
]; ++f
) {
2216 if (!access(defInFiles
[f
], R_OK
)) {
2217 inFile
= strdup(defInFiles
[f
]);
2222 inFile
= strdup(argv
[optind
]);
2224 if (!inFile
|| !inFile
[0]) {
2226 fprintf(stderr
, "ERROR: no input file!\n");
2230 registerInstructions();
2231 registerFunctions();
2233 res
= asmTextLoad(inFile
);
2236 printf("dumping...\n");
2237 FILE *fo = fopen("z000.out", "w");
2240 for (c = asmText; c; c = c->next) fprintf(fo, "%s ; %s: %d\n", c->line, c->fname, c->lineNo);
2244 for (pass
= 0; pass
<= 1; ++pass
) {
2246 printf("pass %d\n", pass
);
2247 setCurSrcLine(asmText
);
2248 if (setjmp(errJP
)) { res
= 1; break; }
2249 while (curSrcLine
) processCurrentLine();
2250 if (posstPass()) { res
= 1; break; }
2254 char *oc
= strdup(inFile
);
2255 char *pd
= strrchr(oc
, '.');
2256 if (pd
&& !strchr(oc
, '/')) *pd
= '\0';
2257 switch (optWriteType
) {
2258 case 's': saveSna(oc
); break;
2259 case 't': saveTap(oc
); break;
2260 case 'r': saveRaw(oc
); break;
2261 case 'd': saveDMB(oc
); break;
2266 fprintf(stderr
, "ERROR: loading error!\n");
2269 if (lastSeenGlobalLabel
) free(lastSeenGlobalLabel
);
2275 if (inFile
) free(inFile
);
2276 if (sysIncludeDir
) free(sysIncludeDir
);