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
Email guesser - Guessing BF email based on emailGuesser by WhiteHatInspector

email_guesser Guessing BF email based on emailGuesser by WhiteHatInspector (http

4 Dec 25, 2022
Open source translation for the Tsukihime Remake game

Tsukihime-Translation Open source translation for the Tsukihime Remake game prepared by Clovermoon and Tsukihimates. Copyright Disclaimer under Sectio

118 Jan 01, 2023
A full featured game of falling pieces using python's pygame library.

A full featured game of falling shapes using python's pygame library. Key Features • How To Play • Download • Contributing • License Key Features Sing

Giovani Rodriguez 7 Dec 14, 2022
Wordle-Python - A simple low-key clone of the popular game WORDLE made with python and a 2D Graphics module Pygame

Wordle-Python A simple low-key clone of the popular game WORDLE made with python

Showmick Kar 7 Feb 10, 2022
Turn NY Times crosswords into Across Lite files

NYT Crossword to Puz A windows program to convert NY Times crosswords from the web to Across Lite compatible files. To run this, first download and de

31 Oct 11, 2022
Bingo game now in python play as much you want :) no need to give me credit it's open as fuck

Bingo-py-game A game coded with Python Introduction This is a Terminal-based game currently in its initial stage. I am working on adding more efficien

Frey 5 Aug 12, 2021
Simple python program to simulate Conway's game of life with custom variables.

ConwaysGameOfLife Simple python program to simulate Conway's game of life with custom variables. Custom Variables Grid-size : Change the size of the p

davidgasinski 1 Oct 28, 2021
WordleHelper suggests words to help players better enjoy the hit game Wordle

WordleHelper Introduction WordleHelper suggests words to help players better enjoy the hit game Wordle. Both the general mode and the hard mode are su

Shao-Yu, Chu 5 Jun 02, 2022
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
Abandoned plan for a clone of the old Flash game Star Relic

space-grid When I was in middle school, I was a fan of the Flash game Star Relic (no longer playable in modern browsers, but it works alright in Flash

Radon Rosborough 3 Aug 23, 2021
An easy to use game engine/framework for python.

A game engine powered by python and panda3d.

Petter Amland 1.6k Jan 05, 2023
Krieg is a Python package for a general game framework.

Krieg Krieg is a Python package for a general game framework. It provides base classes for implementing simple games. Some example games are already i

Juho Kim 2 Jan 06, 2022
Logo hitting the corner == best feeling ever!

Bouncing DVD logo - Pygame A little ride back to the 90s. Ah good ol' time! Didn't we all wait for the logo to hit the corners? Best feeling ever!! I

Hoang Nguyen 3 May 25, 2022
A networking library for multiplayer games.

Aerics A networking library for multiplayer games. Getting Started Install Python Open cmd/terminal and type: pip install Aerics Examples Creating a

Yusuf Rençber 3 Jan 04, 2023
Memory game in Python

Concentration - Memory Game Concentration is a memory game written in Python, inspired by memory-game. Description As stated in the introduction of th

Marco Colonna 0 Jul 21, 2022
We tried to recreate this classic game using python physics libraries.

We tried to recreate this classic game using python physics libraries. The result is certainly hilarious but enjoyable. One of my very first physics application.

Delwys Glokpor 2 Dec 12, 2021
Official PyTorch implementation of NAC from the paper: Neural Auto-Curricula in Two-Player Zero-Sum Games.

NAC Official PyTorch implementation of NAC from the paper: Neural Auto-Curricula in Two-Player Zero-Sum Games. We release code for: Gradient based ora

Xidong Feng 19 Nov 11, 2022
A didactic GUI chess game made in Python3 using pygame.

Chess A didactic GUI chess game made in Python3 using pygame. At the moment, there is no AI. The only way you can test the game is by playing against

Leonardo Delfino 1 Dec 22, 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
Chess-commandline - Chess in the Command Line using the Chess Module Can detect Checkmates

chess-commandline Chess in the Command Line using the Chess Module Can detect Ch

Harry Hopkinson 1 Jan 10, 2022