cj68_asm.html


001| '''CJ68 Virtual CPU Assembler.
001| 
001| Functions:
001|     assembler           (stmnts, base, show, raw)   - assemble a list of statements
001|     compile_statement   (linenum, opname, parts)    - compile a statement
001|     tokenize_statement  (linenum, text)             - split string into tokens
001| 
001| '''

002| ####################################################################################################
003| from os import path
004| from logger import logger
005| from files import SPC, EOL, CR,LF, linefile
006| from goodies import KWARG
007| from cj68_opcodes import OpIndex, OpCodes
008| ####################################################################################################
009| BasePath = r'C:\CJS\prj\Python\app\sims\cj68'
010| TextPath = path.join(BasePath, 'src')
011| DocsPath = path.join(BasePath, 'doc')
012| Log = logger('cj68asm')
013| 
014| SQUOTE      = "'"   # single quote
015| DQUOTE      = '"'   # double quote
016| REMCHAR     = ';'
017| COMMA       = ','
018| 
019| SpecialChars = {'CR':ord(CR), 'LF':ord(LF), 'EOL':ord(EOL), 'SPC':ord(SPC)}
020| 
021| bs2v = lambda b0,b1,b2,b3:b0+(b1<<8)+(b2<<16)+(b3<<24)
022| v2bs = lambda v:((v&0xff),((v>>8)&0xff),((v>>16)&0xff),((v>>24)&0xff))
023| 
024| list2str = lambda lst: ''.join(lst)
025| list2strs = lambda lst: [str(x) for x in lst]
026| 
027| 
028| ##================================================================================================##
029| def tokenize_statement (linenbr:int, text:str) -> list:
030|     '''Split statement text into space-separated tokens, but recognize characters and strings.'''
031|     Log.trace(f'tokenize({linenbr}, {text})')
032| 
033|     def convert_token (tokenchars:list) -> str:
034|         token = list2str(tokenchars)
035|         if token in SpecialChars:
036|             return SpecialChars[token]
037|         return token.lower()
038| 
039|     in_char = False
040|     in_string = False
041|     tokens = []
042|     curr = []
043|     for ch in text:
044|         # If we're in character mode...
045|         if in_char:
046|             if ch == SQUOTE:
047|                 # End of quoted text...
048|                 tokens.append(ord(list2str(curr)))
049|                 curr = []
050|                 in_char = False
051|                 continue
052|             # Add to quoted text...
053|             curr.append(ch)
054|             continue
055| 
056|         # If we're in string mode...
057|         if in_string:
058|             if ch == DQUOTE:
059|                 # End of quoted text...
060|                 for t in curr:
061|                     tokens.append(ord(t))
062|                 curr = []
063|                 in_string = False
064|                 continue
065|             # Add to quoted text...
066|             curr.append(ch)
067|             continue
068| 
069|         # If in token mode...
070|         if 0 < len(curr):
071|             # A comment means no more to process...
072|             if ch == REMCHAR:
073|                 break
074|             # A space or comma ends a text token...
075|             if ch.isspace() or (ch == COMMA):
076|                 # End of token text...
077|                 tokens.append(convert_token(curr))
078|                 curr = []
079|                 continue
080|             # Add to token text...
081|             curr.append(ch)
082|             continue
083| 
084|         # Not in quote or token mode...
085|         if ch == REMCHAR:
086|             break
087|         if ch.isspace() or (ch == COMMA):
088|             continue
089|         if ch == SQUOTE:
090|             in_char = ch
091|             continue
092|         if ch == DQUOTE:
093|             in_string = ch
094|             continue
095|         # Start new token...
096|         curr.append(ch)
097| 
098|     assert not in_char, SyntaxError(f'[{linenbr+1}] Unclosed character: {text}.')
099|     assert not in_string, SyntaxError(f'[{linenbr+1}] Unclosed string: {text}')
100| 
101|     if 0 < len(curr):
102|         tokens.append(convert_token(curr))
103|     return tokens
104| 
105| ##================================================================================================##
106| def compile_statement (linenbr:int, opname:str, parts:list) -> list:
107|     '''Compile a single statement.'''
108|     Log.trace('compile-statement(%04d, %s, %s)' % (linenbr+1, opname,'|'.join(list2strs(parts))))
109|     wholeline = SPC.join([opname]+[str(p) for p in parts])
110|     statement = []
111| 
112|     def parse_part (p):
113|         if isinstance(p, str):
114|             # Hex Number...
115|             if p.startswith('0x') or p.startswith('-0x'):
116|                 return int(p, base=16)
117|             # Decimal Number...
118|             if p.isnumeric() or (p.startswith('-') and p[1:].isnumeric()):
119|                 return int(p)
120|         # Not a number, just return it...
121|         return p
122| 
123|     if opname == 'DATA':
124|         # Painted myself into a corner [..,#,'*n',..] ...
125|         pbuf = []
126|         plst = list(reversed(parts))
127|         while 0 < len(plst):
128|             p = plst.pop()
129|             if isinstance(p,str) and p.startswith('*'):
130|                 repeat_value = pbuf.pop()
131|                 repeat_count = int(p[1:], base=0)
132|                 for _ in range(repeat_count):
133|                     pbuf.append(repeat_value)
134|                 continue
135|             pbuf.append(p)
136|         parts = pbuf
137| 
138|         for part in parts:
139|             # Handle ch*n tokens...
140|             if isinstance(part,str) and ('*' in part):
141|                 pair = part.split('*')
142|                 assert len(pair)==2, SyntaxError(f'[{linenbr+1}] Illegal DATA spec: {wholeline}')
143|                 val = int(pair[0], base=0)
144|                 num = int(pair[1], base=0)
145|                 for _ in range(num):
146|                     statement.append(val)
147|                 continue
148| 
149|             b = parse_part(part)
150|             assert b < 256, SyntaxError(f'[{linenbr+1}] Data value too large: {wholeline}')
151|             statement.append(b)
152|         return statement
153| 
154|     if opname == 'WORD':
155|         for part in parts:
156|             # Handle ch*n tokens...
157|             if isinstance(part,str) and ('*' in part):
158|                 pair = part.split('*')
159|                 assert len(pair)==2, SyntaxError(f'[{linenbr+1}] Illegal DATA spec: {wholeline}')
160|                 val = int(pair[0], base=0)
161|                 num = int(pair[1], base=0)
162|                 b0,b1,b2,b3 = v2bs(val)
163|                 for _ in range(num):
164|                     statement.append(b0)
165|                     statement.append(b1)
166|                     statement.append(b2)
167|                     statement.append(b3)
168|                 continue
169| 
170|             if part.startswith('@'):
171|                 statement.append(part)
172|                 statement.append('#')
173|                 statement.append('#')
174|                 statement.append('#')
175|                 continue
176| 
177|             val = parse_part(part)
178|             b0,b1,b2,b3 = v2bs(val)
179|             statement.append(b0)
180|             statement.append(b1)
181|             statement.append(b2)
182|             statement.append(b3)
183|         return statement
184| 
185|     opindx = OpIndex[opname]
186|     opcode = OpCodes[opindx]
187|     opsize = int(opcode[2])
188|     opcues = opcode[4].split()
189|     statement.append(opcode[0])
190| 
191|     for operand in opcues:
192|         Log.trace(f'operand={operand}')
193|         if len(parts) == 0:
194|             raise SyntaxError(f'[{linenbr+1}] Missing operand: {wholeline}')
195|         part = parts.pop(0)
196|         # Register spec...
197|         if operand.startswith('reg'):
198|             assert part.startswith('r'), SyntaxError(f'[{linenbr+1}] Register expected: {wholeline}')
199|             statement.append(int(part[1:]))
200|             continue
201| 
202|         # Channel spec...
203|         if operand == 'chn':
204|             assert part.startswith('c'), SyntaxError(f'[{linenbr+1}] Channel expected: {wholeline}')
205|             statement.append(int(part[1:]))
206|             continue
207| 
208|         # Address...
209|         if operand in ['address', 'number']:
210|             if isinstance(part,str) and part.startswith('@'):
211|                 statement.append(part)
212|                 statement.append('#')
213|                 statement.append('#')
214|                 statement.append('#')
215|                 continue
216| 
217|             val = parse_part(part)
218|             b0,b1,b2,b3 = v2bs(val)
219|             statement.append(b0)
220|             statement.append(b1)
221|             statement.append(b2)
222|             statement.append(b3)
223|             continue
224| 
225|         # Number...
226|         if operand.startswith('num') or operand in ['len','id','ver','int']:
227|             statement.append(parse_part(part))
228|             continue
229| 
230|         if operand == 'b1...blen':
231|             statement.append(parse_part(part))
232|             while 0 < len(parts):
233|                 statement.append(parse_part(parts.pop(0)))
234|             continue
235| 
236|         raise SyntaxError(f'[{linenbr+1}] Unknown operand: "{operand}"')
237| 
238|     assert len(parts)==0, SyntaxError(f'[{linenbr+1}] Unexpected operands: {wholeline}')
239|     if 0 < opsize:
240|         assert len(statement)==opsize, SyntaxError(f'[{linenbr+1}] Invalid Op: {wholeline}')
241|     return statement
242| 
243| ##================================================================================================##
244| def assembler (statements:list, baseaddr:int, savefile='', show=0, raw=0) -> list:
245|     '''CJ68 Assembler. Expects list of source code statements.'''
246|     Log.info(f'assembler: {len(statements)} statements (base={baseaddr:08x})')
247| 
248|     codeseg = baseaddr
249|     dataseg = baseaddr #ATTN!
250|     names = {}
251|     pgm = []
252| 
253|     # For each line in the source...
254|     for linenbr,text in enumerate(statements):
255|         # Strip and force to UC...
256|         stmt = text.strip()
257| 
258|         # Ignore blank and comment lines...
259|         if (len(stmt)==0) or stmt.startswith(REMCHAR):
260|             continue
261| 
262|         # Split line into tokens...
263|         parts = tokenize_statement(linenbr, stmt)
264| 
265|         # If first token starts with '@', it's an address marker...
266|         if parts[0].startswith('@'):
267|             nm = parts.pop(0)
268|             assert nm not in names, SyntaxError(f'[{linenbr+1}] Duplicate name: "{nm}"')
269|             names[nm] = codeseg + len(pgm)
270|             # Statement is just an address marker, no code...
271|             if len(parts) == 0:
272|                 continue
273| 
274|         # Tokens remain, so assemble them...
275|         opname = parts.pop(0).upper()
276|         if opname == 'END':
277|             Log.debug(f'End assemble. ({len(pgm)} bytes)')
278|             break
279| 
280|         if opname == 'CODESEG':
281|             assert len(parts)==1, SyntaxError(f'[{linenbr+1}] Unexpected text: "{stmt}"')
282|             codeseg = int(parts.pop(0), base=0)
283|             continue
284|         if opname == 'DATASEG':
285|             assert len(parts)==1, SyntaxError(f'[{linenbr+1}] Unexpected text: "{stmt}"')
286|             dataseg = int(parts.pop(0), base=0)
287|             continue
288| 
289|         # Compile statement...
290|         bs = compile_statement(linenbr, opname, parts)
291|         Log.trace(f'statement: {bs}')
292|         pgm.extend(bs)
293| 
294|     Log.debug()
295|     # If RAW, dump pre-address fixup program codes...
296|     if raw:
297|         Log.info(pgm)
298|         Log.info()
299| 
300|     # Fix fixed addresses...
301|     addr_indexes = [px for px,p in enumerate(pgm) if isinstance(p,str) and p.startswith('@')]
302|     while 0 < len(addr_indexes):
303|         ax = addr_indexes.pop()
304|         nam = pgm[ax]
305|         off = 0
306|         # Adjust address by offset...
307|         if '+' in nam:
308|             nam,offs = nam.split('+')
309|             off = int(offs, base=0)
310|         elif '-' in nam:
311|             nam,offs = nam.split('-')
312|             off = -int(offs, base=0)
313| 
314|         addr = names[nam] + off
315|         pgm[ax:ax+4] = v2bs(addr)
316|         Log.trace(f'address fixup: @{ax:04x} {nam}=0x{addr:08x}')
317| 
318|     # Fix relative addresses...
319|     addr_indexes = [px for px,p in enumerate(pgm) if isinstance(p,str) and p.startswith('$')]
320|     while 0 < len(addr_indexes):
321|         ax = addr_indexes.pop()
322|         nam = pgm[ax].replace('$','@')
323|         leap = names[nam]-(codeseg+ax+1)
324|         pgm[ax] = leap
325|         Log.trace(f'relative address fixup: @{ax:04x} {nam} {leap=}')
326| 
327|     # If SHOW or RAW, list Names and Codebytes to the Log...
328|     if show or raw:
329|         # If RAW, dump post-address fixup program codes...
330|         if raw:
331|             Log.info(pgm)
332| 
333|         Log.info()
334|         for nm,addr in sorted(names.items(), key=lambda x:x[1]):
335|             Log.info(f'{nm:<24s}: {addr:08x}')
336|         Log.info()
337| 
338|         width = 16
339|         for bx in range(0, len(pgm)+width, width):
340|             bs = [f'{b:02x}' for b in pgm[bx:bx+width]]
341|             st = f'[{bx+codeseg:08x}] {SPC.join(bs)}'
342|             Log.info(st)
343|         Log.info()
344| 
345|     if 0 < len(savefile):
346|         '''Save loadable listing file.'''
347|         ntab = sorted(names.items(), key=lambda x:x[1])
348|         nams = [f'name:{nm}={addr:08x}' for nm,addr in ntab]
349|         cods = [f'code:{baseaddr+bx:08x}={0xff & b:02x}' for bx,b in enumerate(pgm)]
350| 
351|         # Save output...
352|         fo = linefile(savefile)
353|         fo.data.append(f'base:{baseaddr:08x}')
354|         fo.data.append(f'size:{len(pgm)}')
355|         if 0 < len(nams):
356|             fo.data.append(LF.join(nams))
357|         fo.data.append(LF.join(cods))
358|         fo.save()
359| 
360|     Log.info(f'program: {len(pgm)} bytes')
361|     Log.info()
362|     return (pgm, names)
363| 
364| 
365| ####################################################################################################
366| if __name__ == '__main__':
367|     print()
368|     Log.start()
369|     baseaddr = 0xffff0000
370|     statements = [
371|         'PGM 99, 1',
372|         'CALL @main',
373|         'RET',
374|         '@args WORD 0*10',
375|         '@main PUTM c1,14,"Hello, World!" EOL',
376|         'LOADA r1,@args+0x00',
377|         'LOADA r2,@args+0x04',
378|         'LOADA r3,@args+0x08',
379|         'PUSH r3',
380|         'PUSH r2',
381|         'PUSH r1',
382|         'CALL @user',
383|         'POP r1',
384|         'POP r2',
385|         'POP r3',
386|         'RET',
387|         '@user spbpi 16',
388|         'LOADSF r31,0',
389|         'LOADSF r30,4',
390|         'LOADSF r29,8',
391|         'RET',
392|     ]
393|     print()
394|     pgm,names = assembler(statements, baseaddr, show=False, raw=False)
395|     Log.end()
396| ####################################################################################################
397| '''eof'''
398|