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
Multiplayer 2D shooter made with Pygame

PyTanks This project started as a one day project with two goals: Create a simulated environment with as much logic as possible written in Numpy, to o

Felix Chippendale 1 Nov 07, 2021
Gamelib is a pure-Python single-file library/framework for writing simple games.

Gamelib is a pure-Python single-file library/framework for writing simple games. It is intended for educational purposes (e.g. to be used in b

Diego Essaya 15 Dec 22, 2022
Useful guides, tutorials, and FAQs related to LEGO Universe and Darkflame Universe.

Awesome Lego Universe A curated list of awesome things related to LEGO Universe. LEGO Universe was a kid-friendly massively-multiplayer online role pl

Eric Myllyoja 33 Dec 12, 2022
Running Chess Night results tabulation

Running Chess Night results tabulation

Mitch LeBlanc 2 Nov 20, 2021
A Simple 2048 Game Built Using Python

Game 2048_Python Dựa trên trò chơi nổi tiếng 2048 của Gabriele Cirulli. Mục tiêu của trò chơi là trượt các khối được đánh số trên một lưới để kết hợp

Le Phuong Anh 3 Dec 13, 2021
Jogo da velha escrito em python para 1 ou 2 jogadores

O Jogo da Velha Esse jogo da velha foi desenvolvido por mim em python, como um desafio de programar um jogo da velha em menos de 24 horas, no qual o c

Gabriel Castelo Branco 5 Jun 18, 2021
This is simple minesweeper-like Telegram game

This is simple minesweeper-like Telegram game. You need to open all "free" squares and put flags on squares with bombs on them. If you open a cell with a bomb, the game is over.

Aleksandr 32 Dec 31, 2022
PLVRA is a TUI (Terminal User Interface) implementation of wordle / termo in portuguese, written in Python

PLVRA is a TUI (Terminal User Interface) implementation of wordle / termo in portuguese, written in Python

Enzo Shiraishi 1 Feb 11, 2022
Pong is one of the first computer games that ever created, this simple

Pong-Game Pong is one of the first computer games that ever created, this simple "tennis like" game features two paddles and a ball, the goal is to de

Lateefah Ajadi 0 Jan 15, 2022
FlappyBird game with python and pygame

FlappyBird game with python and pygame

Mohammad Dori 4 Jul 15, 2022
Implementation of Conway's game of life in python.

👾 👨🏻‍💻 Conway's Game of Life 👨🏻‍💻 👾 by FranciscoCharles An interactive simulator that implements the standard Conway Game of Life with a simpl

3 Oct 01, 2021
A converter for the .BMR / .RLE bitmap files used in some Neversoft PS1 games.

Requirements python3 pyqt5 - can be installed with pip install PyQt5 pypng - Included Usage Instructions This program can be running py main.py in the

4 Jul 30, 2022
Visualizing and learning from games on chess.com

Better Your Chess What for? This project aims to help you learn from all the chess games you've played online, starting with a simple way to download

Luc d'Hauthuille 0 Apr 17, 2022
Made to help you create UI using pygame in python, gonna add way more to this project

Pygame visualizer Made to help you create UI using pygame in python, gonna add way more to this project. As of now, this is only hours worth of work.

Ayza 2 Feb 08, 2022
Made by Ashish and Avinash-sord12k. Powered by pygame

Spook_alle About -Made by Ashish (Github: Ashish-Github193) and Avinash-sord12k Version - BETA v_1.0 /1-11-2021/ (game is at its base version more ite

Ashish Kumar Jha 1 Nov 01, 2021
Racing Fire - A simple game made with pygame.

Racing Fire A simple game in the making. Using pygame, this game is made to feel like an old arcade game. I developed a simple controller for it with

Builder212 1 Nov 09, 2021
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
Flappy Bird clone utilizing facial recognition to move the

Flappy Face Flappy Bird clone utilizing facial recognition to move the "bird" How it works Flappy Face uses Facial Recognition to detect your face's p

Brady McDermott 1 Jan 11, 2022
Console 2D GameEngine {C2DGE} [0.1.0]

Console 2D GameEngine {C2DGE} [0.1.0] By Grosse pastèque#6705 The Project's Goal : This projects was just a challenge so if you have bad reviews, it's

Big watermelon 1 Nov 06, 2021
Jogo da velha com interface gráfica desenvolvida em Python utilizando pygame e IA(Inteligência Artificial)

Jogo-da-Velha Sobre o projeto Jogo da velha com interface gráfica desenvolvida em Python utilizando pygame e IA(Inteligência Artificial) Layout tela d

Matheus Maia Alvarez 6 Apr 09, 2022