The Sinclair ZX Spectrum BASIC compiler!

Overview

Boriel ZX Basic

Build Status Build Status license pyversions

ZX BASIC

Copyleft (K) 2008, Jose Rodriguez-Rosa (a.k.a. Boriel) http://www.boriel.com

All files in this project are covered under the GPLv3 LICENSE except those placed in directories library/ and library-asm. Those are licensed under MIT license unless otherwise specified in the files themselves (i.e. a different license). Anyway, all of the licenses for files under those directories allow binary closed-source (i.e. commercial) distribution of the files created with this compiler.

You can create closed-source programs (even commercial ones) with this compiler (a mention to this tool will be welcome, though). But you are not allowed to release the compiler itself as a closed source program.

If you modify this project (the compiler .py or anything licensed as GPLv3) in any way you MUST publish the changes you made and submit your contribution to the community under the same license.


DOCUMENTATION

This is a very little help file.

  • For DOCUMENTATION in English go to the ZX BASIC docs.

  • For help, support, updates meet the community at the forum.

INSTALLATION

Go to the ZXBasic download page and get the version most suitable for you.

There are, basically, two flavors (both with identical capabilities):

  • For Windows you can download de win32 executable (Windows .exe zip package) version. To install just uncompress it in a directory of your choice. The main executable is zxbc.exe (more on this later). With this toolchain also comes zxbasm.exe (the assembler) and zxbpp.exe (the preprocessor), but these are not needed when programming in BASIC.

  • For Linux and Mac OSX there is a python version, so you will need a python interpreter (available on many platforms, and usually already installed in Linux and Mac OSX). Just uncompress it in a directory of your choice and installation is done. :-) The main executables are zxbc.py (the compiler), zxbasm.py (the assembler) and zxbpp.py (the preprocessor). You can use this version in Windows, but will need to install a python interpreter first.

Examples
Eleuterio, el mono serio El Hobbit Knight & Demonds DX
An in-game screenshot of Eleuterio by @na_th_an Ingame screenshot of El Hobbit by @Wilco2000 Ingame screenshot of Knignt and Demonds DX by Einar Saukas

See more examples at the Relased Programs page.

QUICK START

For a quick start, just open a terminal in your PC in the same directory you uncompressed ZX Basic and type zxbc (on Windows) or zxbc.py (OSX, Linux). You should see a zxbasic message like this:

usage: zxbc [-h] [-d] [-O OPTIMIZE] [-o OUTPUT_FILE] [-T] [-t] [-B] [-a] [-A]
           [-S ORG] [-e STDERR] [--array-base ARRAY_BASE]
           [--string-base STRING_BASE] [-Z] [-H HEAP_SIZE] [--debug-memory]
           [--debug-array] [--strict-bool] [--enable-break] [-E] [--explicit]
           [-D DEFINES] [-M MEMORY_MAP] [-i] [-I INCLUDE_PATH] [--strict]
           [--version]
           PROGRAM
zxbc: error: the following arguments are required: PROGRAM

Create a text file with the following content:

10 CLS
20 PRINT "HELLO WORLD!"

Save it as hello.bas and finally compile it with:

zxbc -taB hello.bas

If everything went well, a file named hello.tap should be created. Open it with your favourite emulator (i.e. fuse) and see the result.

Congratulations! You're now ready to create compiled BASIC programs for your machine. Check and compile the examples included in the examples/ folder or go to the documentation page for further info.

ACKNOWLEDGEMENTS

These are some people who has contributed in a way or another. I consider some of them co-authors (Britlion, LCD) of this project.

Thanks to:

  • Andre Adrian [adrianandre AT compuserve.de] from which I ripped the 32 bits Z80 MULT and DIV routines. See: http://www.andreadrian.de/oldcpu/Z80_number_cruncher.html

  • Matthew Wilson [matthew AT mjwilson.demon.co.uk] and Andy [fract AT zx-81.co.uk] from comp.sys.sinclair for their help on ROM FP-CALC usage.

  • Mulder from World Of Spectrum for finding the nasty PRINT AT bug and the GTU8 bug. See: http://www.worldofspectrum.org/forums/showthread.php?p=278416&posted=1#post278416

  • Compiuter from Speccy.org for finding a bug in PRINT OVER 1 routine.

  • Britlion for his HUGE contribution (both in optimizations, ideas and libraries).

  • LCD Author of the BorIDE, which has also made many contributions to the project.

  • There are several more contributions (e.g. Thanks to them for their intensive testing!). And thank you all (the entire community) for your interest!

If you have contributed in some way to this project, please, tell me so I'll add you to this list.


ko-fi

Comments
  • ZXBasic fails to run as a console script

    ZXBasic fails to run as a console script

    The problem seems to be that the zxb.py in the root directory effectively imports itself on import zxb. Looks like either the script or the same-named package needs to be renamed? Or, you could just remove the script and let the package do its work.

    To reproduce:

    $ python3 setup.py develop --prefix ~/.local
    $ zxb
    Traceback (most recent call last):
      File "/home/kosarev/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2451, in resolve
        return functools.reduce(getattr, self.attrs, module)
    AttributeError: module 'zxb' has no attribute 'main'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/home/kosarev/.local/bin/zxb", line 11, in <module>
        load_entry_point('zxbasic', 'console_scripts', 'zxb')()
      File "/home/kosarev/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 489, in load_entry_point
        return get_distribution(dist).load_entry_point(group, name)
      File "/home/kosarev/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2852, in load_entry_point
        return ep.load()
      File "/home/kosarev/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2443, in load
        return self.resolve()
      File "/home/kosarev/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2453, in resolve
        raise ImportError(str(exc))
    ImportError: module 'zxb' has no attribute 'main'
    
    opened by kosarev 16
  • INPUT command not working

    INPUT command not working

    The INPUT command generates a flashing cursor but is otherwise unresponsive. Tested with the example file:

    #include <input.bas>
    
    print at 10, 5; "Type something: ";
    a$ = input(20)
    print
    print "You typed: "; a$
    

    Using Nextbuildv7, ZXbasic ver : 1.15.2

    The problem appears to be line 42 of input.bas: DO LOOP UNTIL LastK <> 0 The program gets stuck in this loop and pressing a key doesn't exit it, proven by inserting a BEEP command into the loop.

    Using labels and GOTO commands to replace both the DO...LOOPS in the INPUT function, I was able to create a ersatz version which works. Not sure if this is a bug or if I'm missing something obvious

    Thanks.

    opened by bwganblack 7
  • Incorrect opcode allowed

    Incorrect opcode allowed

    The following code compiles without an error but what happens is e is loaded with lsb of memory address ._c and d lsb of memory address ._c

    c=10
    b=20
    ASM 
     ld e,(._c)
     ld d,(._b)
    END ASM 
    

    While this works correctly

    c=10
    b=20
    ASM 
     ld de,(._c)  ; ._c and ._b are store as a byte next to each other
    END ASM 
    
    bug 
    opened by em00k 5
  • Differences with DEFINE

    Differences with DEFINE

    This in theory should work :

    #DEFINE SETREG(REG,VAL)\
    		LD A,REG \
    		LD BC,VAL \
    		OUT (C),A
    
    
    ASM 
    	STA:
    		LD C,7
    	REP:
    		LD A,C
    		SETREG(A,254)
    		DJNZ REP
    		LD C,7
    		JP STA
    END ASM
    

    In the same way this does :

    #DEFINE SETREG(REG,VAL)\
    	ASM \
    		LD A,REG \
    		LD BC,254 \
    		OUT (C),A \
    	END ASM
    
    SETREG(6,254)
    END
    
    
    
    
    bug 
    opened by em00k 5
  • Use the zx emulator to run zxbasic tests

    Use the zx emulator to run zxbasic tests

    @boriel Please see attached. The script merely loads the specified tape file and keeps the machine running until a breakpoint hit, which we expect at PC=0, provided the test source itself is amended as shown in the diff. Please let me know if there's something else needed. Thanks.

    use_zx_to_run_tests.zip.txt

    opened by kosarev 4
  • Command Documentation

    Command Documentation

    Hi,

    Thanks for Boriel, but is there anyway I can help with documentation?

    For example, I go to information about the Screen command at:

    https://zxbasic.readthedocs.io/en/latest/screen/

    At the bottom of the page there are links to:

    At the bottom of the page there is:

    See also CSRLIN POS AT

    None of these seem to work. I have the same with:

    https://zxbasic.readthedocs.io/en/lates ... er/attr.md

    If you have any rough notes, I'm happy to type them up for you in Git Flavoured MarkDown.

    Best wishes

    Peter

    opened by spectrumcomputing 4
  • ASM throws error when combining bytes and chars

    ASM throws error when combining bytes and chars

    This causes an error:

    string:
    			 ; at 21 , 31
    			 defb 22,21,31,"!"
    
    

    and has to be seperated like this:

    string:
    			 ; at 21 , 31
    			 defb 22,21,31
                             defb "!"
    

    Thanks!

    opened by em00k 4
  • Integer maths issue with result of VAL

    Integer maths issue with result of VAL

    I'm not sure how to even describe this strange issue. Here is some example code to expose it:

    DIM temp$ AS STRING = "-20"
    DIM intResult AS INTEGER
    
    CLS
    PRINT temp$
    PRINT VAL(temp$)
    PRINT INT(-20)
    PRINT INT(VAL(temp$))
    intResult=INT(VAL(temp$))
    PRINT intResult
    

    I would expect this to print -20 for each step (as confirmed in Sinclair BASIC), but far from it - the compiled code displays:

    -20
    -20
    -20
    -65516
    20
    

    I presume the 4th result is a variable type issue? (EDIT, confirmed - this matches the 5th result if using a CAST to Integer). But I don't understand how the sign is being lost after the INT function in the 5th example. Examples 1-3 show that in isolation all the component parts of this work fine, but putting them together is breaking my project. I see that the result of a VAL is a float, but converting that to an integer shouldn't affect the sign of the number as far as I understand.

    Even PRINT CAST(FLOAT,INT(VAL(temp$))) results in 20 not -20

    bug 
    opened by patters-syno 3
  • BUG: The --asm generates non-compiling output with codes where the HEAP SIZE is zero

    BUG: The --asm generates non-compiling output with codes where the HEAP SIZE is zero

    @boriel,

    I experienced that ZXB produces an invalid ASM output (--asm), provided the code's heap size is zero. Here is a very concise example:

    PRINT 12345
    

    As you can see in the attached file (Faulty.asm.txt), at its bottom is generates these labels:

    ZXBASIC_USER_DATA:
        ; Defines DATA END --> HEAP size is 0
    ZXBASIC_USER_DATA_END EQU ZXBASIC_MEM_HEAP
        ; Defines USER DATA Length in bytes
    ZXBASIC_USER_DATA_LEN EQU ZXBASIC_USER_DATA_END - ZXBASIC_USER_DATA
    

    Unfortunately, the ZXBASIC_MEM_HEAP symbol is undefined in the assembly output file.

    Should I use a program with non-zero heap size (Correct.asm.txt):

    PRINT 12345
    PRINT "HELLO"
    

    It generates all the necessary symbols. At the beginning of the code:

        org 32768
        ; Defines HEAP SIZE
    ZXBASIC_HEAP_SIZE EQU 4096
       ; ...
    

    And at the end of the code:

    ZXBASIC_USER_DATA:
    ZXBASIC_MEM_HEAP:
        ; Defines DATA END
    ZXBASIC_USER_DATA_END EQU ZXBASIC_MEM_HEAP + ZXBASIC_HEAP_SIZE
        ; Defines USER DATA Length in bytes
    ZXBASIC_USER_DATA_LEN EQU ZXBASIC_USER_DATA_END - ZXBASIC_USER_DATA
    

    I hope, you can fix this error soon.

    Istvan

    Correct.asm.txt Faulty.asm.txt

    bug 
    opened by Dotneteer 3
  • BUG: --asm creates assembly code that does not compile (v1.9.4)

    BUG: --asm creates assembly code that does not compile (v1.9.4)

    @boriel,

    While I was integrating ZX BASIC into SpectNetIDE, this simple code provided an assembly output that does not compile:

    print "Hello"
    

    I attached the .asm file this simple code generates with the --asm command line switch.

    The .asm file references five symbols that do not exist in the file:

    • __SET_ATTR2
    • INVERSE_TMP
    • OVER_TMP
    • BOLD_TMP
    • ITALIC_TMP

    Program.asm.txt

    opened by Dotneteer 3
  • Escape chars not being set

    Escape chars not being set

    GetFileSize("c:\\RBC.uue") should according to the docs send "c:\RBC.uue" as a string to the sub GetFileSize but it sends c:\.BC.uue

    image

    Should escape chars even be processed when not working with a print string?

    bug 
    opened by em00k 3
  • Removing inline IF functionality

    Removing inline IF functionality

    Say I wanted to remove the inline IF functionality, particularly through commenting out lines 1381-1389 in src/zxbc/zxbparser.py. How would I do this or something with the same effect without making Python throw errors like crazy?

    opened by MrKOSMOS 2
  • ZX Basic wiki error -  stack-check option

    ZX Basic wiki error - stack-check option

    In Docs » Reserved Words:

    WARNING: Using RETURN in global scope without a GOSUB will mostly crash your program.
    Use --stack-check if you suspect you have this bug, to detect it.
    
    

    That option doesn't exist (yet).

    opened by programadorhedonista 0
  • ZX computers support

    ZX computers support

    Does the compiler work on ZX Spectrum only? Does it support ZX80, ZX81 BASIC? if it's not, is there future projects to add compatibility for those machines?

    opened by qequ 1
  • Interested in testing

    Interested in testing

    And maybe in the future do some basic game :D But, I wonder, is there out there a repo of ZX basic ? That is, magazine games, book games, etc I am interested in software testing, fuzzy testing, etc. A compiler is a nice example, so. If someone has some pointers, I could try some testing. Other idea is testing it against repo of random generated basic programs, and seeing what it does 🗡️ Saludos, y genial tu charla en el canal de Javi!

    opened by bleuge 1
Releases(v1.16.4)
  • v1.16.4(Oct 12, 2022)

  • v1.16.3(Oct 12, 2022)

  • v1.16.2(Jan 29, 2022)

    • Fixes bugs in drawing primitives (PLOT, DRAW, CIRCLE)
    • Fixes bug with ASM temporary labels
    • Does some optimizations on binary operations (+, *)
    Source code(tar.gz)
    Source code(zip)
  • v1.16.1(Jan 26, 2022)

  • v1.16.0(Oct 25, 2021)

    • Added optional parameters
    • Added keyword args
    • Allow temporary labels (1b, 1f) in the assembler
    • ! Fixed several bugs in the assembler and compiler
    • Produces better code for multiplications in ZX Next
    • zx0 compression library updated (thx to Einar Saukas)
    Source code(tar.gz)
    Source code(zip)
  • v1.15.2(Sep 20, 2021)

  • v1.15.1(Aug 16, 2021)

    • ! Fixed a bug in the peephole optimizer (-O4)
    • Implemented #include MACRO
    • Implemented library functions ltrim, rtrim, trim in <string.bas>
    • Some libraries rearranged.
    Source code(tar.gz)
    Source code(zip)
  • v1.15.0(Jul 19, 2021)

    • ! Fixed bugs and improved stability, specially with the optimizer
    • Variables and functions now allow underscore character
    • Peephole optimizer is now smarter
    • Compiler now allows config files to avoid repearing cmdline flags
    • Added #pragma once
    Source code(tar.gz)
    Source code(zip)
  • v1.14.1(Jan 18, 2021)

    • Fixed bugs and improved stability
    • Assembler will show a warning on DB truncated values
    • Input key taps will emit sound (mute then with a POKE)
    • Little optimizations
    Source code(tar.gz)
    Source code(zip)
  • v1.14.0(Jan 11, 2021)

    • Added token pasting ## and stringizing # operators to the preprocessor
    • Warnings and error messages improved with codes
    • Warnings can now be silenced with -Wxxx (i.e. -W150)
    • Improved error reporting (files and line numbers)
    • Improved code generation and optimization
    • Speed compilation increased by 100%!
    • ! Fixed many bugs and improved stability
    Source code(tar.gz)
    Source code(zip)
  • v1.13.2(Dec 11, 2020)

  • v1.13.1(Nov 4, 2020)

  • v1.13.0(Oct 27, 2020)

    • ! Fixes many bugs and improves stability
    • Added a new optimization recipe
    • New architecture backend parameter! From now on zxbasic will allow you to select the target machine.
    Source code(tar.gz)
    Source code(zip)
  • v1.12.1(Aug 17, 2020)

  • v1.11.1(Jul 6, 2020)

  • v1.11.0(Jul 2, 2020)

  • v1.10.3(Jun 7, 2020)

  • v1.10.2(Jun 4, 2020)

  • v1.10.1(May 29, 2020)

    • Deprecating zxb executable in favour of zxbc
    • ! Many bugs fixed (CODE, VAL, preprocessor...)
    • ! Improved stability
    • Can now hide LOAD messages using -D HIDE_LOAD_MSG
    • Improved Windows deployment
    • Fixes a Warning for python 3.8.x
    Source code(tar.gz)
    Source code(zip)
  • v1.10.0(May 17, 2020)

    • ! Fix warning in arrays boundaries checks
    • Added support for ZX Next extended ASM instruction set
    • Allow shifting SCREEN coordinates for drawing
    • Add mini-pacman example
    • Add tool for viewing .SCR files
    • Improved compatibility with Sinclair BASIC (--sinclair)
    • Updates testing and parsing tools
    • Code generation optimized
    • Many bugfixes and improves stability
    • Updates in online documentation
    Source code(tar.gz)
    Source code(zip)
  • v1.9.9(Apr 4, 2020)

  • v1.9.8(Nov 16, 2019)

  • v1.9.7(Nov 11, 2019)

    • Little bug fixes
    • Allow extra characters within ASM context for 3rd party assembler support
    • PRINT at the bottom of the screen now scrolls up like in Sinclair BASIC
    Source code(tar.gz)
    Source code(zip)
  • v1.9.6(Oct 20, 2019)

    Fix a bug with RESTORE / DATA (grammar refactorized). Also the assembler now parses ld (ix - 12 + 5), r as ld (ix + (-12) + 5), r which is the right way.

    Source code(tar.gz)
    Source code(zip)
  • v1.9.5(Oct 19, 2019)

  • v1.9.4(Oct 18, 2019)

  • v1.9.3(Oct 18, 2019)

  • v1.9.2(Jun 28, 2019)

  • v1.9.1(Jun 7, 2019)

Owner
Jose Rodriguez
Computer Scientist. Software Engineer. Opinions expressed here are solely my own and not necessarily those of my employer.
Jose Rodriguez
learn and have fun developing 2D retro games using python and pygame

Retro 2D Game Development Using Python + PyGame Skill up your programming skills with a walk down the memory lane. Learn how to create a retro 2D game

Marvin Trilles 1 Feb 23, 2022
A Game Engine Made in Python with the Pygame Module

MandawEngine A Game Engine Made in Python with the Pygame Module Discord: https://discord.gg/MPPqj9PNt3 Installation To Get The Latest Version of Mand

Mandaw 14 Jun 24, 2022
The Bowling Club (Facebook Game) get all strikes.

TheBowlingClubBot The Bowling Club (Facebook Game) get all strikes. FAQ Q: What is this? A: TheBowlingClubBot is a automation bot with 99.99% guarante

#~Rith 1 Jan 19, 2022
This is a python implementation of wordle, which uses the same set of available words as the hit game, Wordle

Wordle Game This is a python implementation of wordle, which uses the same set of available words as the hit game, Wordle. Play the game manually pyth

Pierre Theo Klein 11 Mar 04, 2022
Simple car game written in PyGame

Welcome to CarGame 👋 Car Game written in PyGame! NOTE: This is still new and there may be stuff broken... 🏠 Homepage Install install pygame by typin

John 1 Oct 29, 2021
Multi minecraft server helper for python

呐 Yuki 您的群组服操作小助手。 使用Python3编写。使用 .yaml 配置文件记录子服,配合Screen管理Linux系统上的Minecraft子服,支持MCDR子服与非MCDR子服。 功能: 开启所有子服 关闭所有子服 重载所有子服MCDR 重载所有子服ChatBridge 使用方法:

3 Mar 17, 2022
Rudimentary CMD based implementation of the Tic Tac Toe game

Packages used: questionary random os (Requires Python 3.8 as walrus operators are used in the script) Contains the .py file (tictactoe.py) and an exe

Ashwin 1 Oct 15, 2021
A zombie game using Kinetic. You can control players using fingers

This is Eden Park's portpolio: Works, projects and practices This repository can be used to show the potential employers to check my works, code and p

Eden Park 4 May 16, 2022
A simple pygame implementation of the LOGO programming language.

LOGO-py A simple pygame implementation of the LOGO programming language. Latest Version Notes Fixed a bug where penup/pendown would not work properly.

Ethan Evans 1 Dec 05, 2021
An open-world game made in Python.

Dragon Realms Notes Windows OS only Contributors This project follows the all-contributors specification (emoji key, command Issue). See what you can

Dragon Realms 2 Jul 28, 2022
Blender Game Engine Game Type Templates Logic Bricks (and Python script) based Game Templates for Blender

Blender-Game-Engine-Templates Blender Game Engine Game Type Templates Logic Bric

3 Oct 25, 2022
Sukoku-solver Python About Sudoku is one of the most popular puzzle games of all time

Sukoku-solver Python About Sudoku is one of the most popular puzzle games of all time. As a logic puzzle, Sudoku is also an excellent brain game. Bein

Harshith VH 1 Nov 20, 2021
2DMC is an abrrieviation for 2 Dimensional Minecraft.

2DMC 2DMC is an abrrieviation for 2 Dimensional Minecraft. This idea is originally created and implemented by Griffpatch on Scratch. This is a persona

DaNub 5 Nov 06, 2022
A very bad wordle solver to help me solve the daily wordle

Wordle Solver A very bad wordle solver to help me solve the daily wordle on https://www.powerlanguage.co.uk/wordle/ TODO list take into account letter

Logan Anderson 4 Feb 03, 2022
🍦 Cheat for cs:go written in Python.

Cs::Fuck 🍦 Cheat for cs:go written in Python. You can show a video here: https://vimeo.com/642730650 Feature. TriggerBot Glow Esp NoFlash Setup. 0. p

Ѵιcнч 10 Sep 23, 2022
Hagia is a 2D game engine and toolset for Python.

HAGIA What is Hagia? Hagia is a 2D game engine and toolset for Python. Hagia has

star 3 Jun 01, 2022
AI Games and its programming solution with Python.

Problem: Save the princess: Problem defination on Hackerrank: https://www.hackerrank.com/challenges/saveprincess About problem: Princess Peach is trap

Hasit Parmar 1 Feb 19, 2022
Bingo game with python

bingo-game-with-python type of plays possible player vs computer player vs player computer vs computer game is built with 4 objects classes 1.game 2.b

1 Nov 27, 2021
A game based on Motus, to be played on Unix terminals.

Motus python game A game based on Motus, to be played on Unix terminals. How to play? Before playing, you need to install all the requirements needed

Arthur Molia 1 Feb 02, 2022
This is a python bot to automate BombCrypto game

This is a python bot to automate BombCrypto game. Logs in to the game, reconnects when needed, closes error warnings, sends heroes to work or home automatically, has Telegram integration and lets you

AFKAPP 39 Sep 28, 2022