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
Track your favorite minecraft servers' (too bee too tee) queue at any time at your own convenience!

2b2t Queue Monitor Track your favorite minecraft servers' (too bee too tee) queue at any time at your own convenience! Compiled Usage go to https://gi

Addi 1 Feb 05, 2022
This is a 2D Link to the Past-esque game made using Python 3.2.5 and pygame 1.9.2

Queen-s-Demise Queen's Demise This is a 2D Link to the Past-esque game made using Python 3.2.5 and pygame 1.9.2 I made this for a game development cla

Zoey 1 Dec 15, 2021
WORDLE Helper and Solver

WORDLE Helper and Solver There is a pupular game around WORDLE The game could be hard for non-English speaking people so I started to think of a helpe

1 Jan 24, 2022
Open source Brawl Stars server emulator for version 29 of the game!

Welcome to Classic-Brawl v29 Remake 👋 Open source Brawl Stars server emulator for version 29 of the game! (Remake) What's working ? Battles Trophies

CrossFire 4 Jan 19, 2022
Tekken-python-ml - A project of playing tekken game using python

Tekken Python Description Hi this is new project of playing tekken game using py

Programminghut 13 Dec 30, 2022
A "finish the lyrics" game using Spotify, YouTube Transcript, and YouTube Search APIs, coupled with visual machine learning

Singify Introducing Singify, the party game! Challenge your friend to who knows songs better. Play random songs from your very own Spotify playlist an

Josh Wong 4 Nov 19, 2021
Open source Board Games Like Tic Tac Toe, Connect 4, Ludo, Snakes and Ladder etc...

Board-Games What to do... Add Board games like Tic Tac Toe, Connect 4, Ludo, Snakes and Ladder etc... How to do... Fork the repo Clone the repo git cl

Bit By Bit 1 Oct 10, 2022
pygame is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

pygame is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

pygame 5.6k Jan 01, 2023
SpiderArcadeGame - A game where the player controls a little spider who is trying to protect herself from other invasive bugs

SpiderArcadeGame - A game where the player controls a little spider who is trying to protect herself from other invasive bugs

Matheus Farias de Oliveira Matsumoto 1 Mar 17, 2022
DOTD - A murder mystery game made in Python

DOTD This repo holds the files for my video game project from ENG101, Disaster o

Ben Bruzewski 1 Jan 13, 2022
A fun discord bot for music, mini games, admin controls, economy, ai chatbot and levelling system

A fun discord bot for music, mini games, admin controls, economy, ai chatbot and levelling system. This bot was specially made for Dspark discord server.

2 Aug 30, 2022
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
Game code for Evennia servers designed for use with ALPACASclient.

ALPACASgame Game code for Evennia servers designed for use with ALPACASclient. This code is meant to be a type of "compatability layer" between the AL

FreeDelete Software 1 Nov 07, 2021
狼人杀,线下面杀用,服务端语音播报,浏览器操作,移动端友好。不再需要真人法官~

Wolf 狼人杀面杀法官系统 Preview 如何使用 安装 Python 3.5.2 版本及以上(PyWebIO 要求) pip install -r requirements.txt python main.py 所有玩家访问 Web 服务 TODO,欢迎PR TTS 目前仅支持 macOS 未

Lake Chan 33 Nov 11, 2022
View your VALORANT performance in different areas of every map in the game!

Valorant-Zone-Stats Inspired by Leetify's awesome Map Zones Tool for CS:GO A simple desktop program to view your VALORANT performance in different are

Louis 76 Jan 01, 2023
Flappy-Bird AI - Flappy Bird game with AI

FLAPPY BIRD AI Flappy Bird game solved with neat-python, a Python module based o

1 Jan 07, 2022
AI based assitant for minecarft

Minecraft_AI_assistant AI-based assistant for Minecraft There are 4 steps to build 1-I'm using collecting_data.png as a structure to take shots with c

Murat Ali Avcu 13 Oct 16, 2022
BritishTrainsDepartureBoard - A pygame program that immitates the dot matrix departure screens found at National Rail stations

BritishTrainsDepartureBoard - A pygame program that immitates the dot matrix departure screens found at National Rail stations

Finn O'Neill 3 Aug 10, 2022
Pyxel is a retro game engine for Python.

Pyxel is open source and free to use. Let's start making a retro game with Pyxel!

Takashi Kitao 11.2k Jan 09, 2023
Nerdle - a nerd's approach to solving Wordle

Nerdle - a nerd's approach to solving Wordle

4 Nov 28, 2022