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
This is a basic virtual quiz game using opencv-python

Basic Virtual-Quiz-Game This is a basic structure of a virtual quiz game using opencv-python. As the camera window opens up we can see the questions a

null 2 Dec 11, 2021
Basic Python physics library.

pythonPhysics Basic Python physics library. Must have pygame installed. How to: Sketon program is included. for p in env.particles: pygame.draw.circle

null 1 Jan 16, 2022
A chess engine with basic AI capabilities (search for best move using MinMax algorithm)

A chess engine with basic AI capabilities (search for best move using MinMax algorithm)

Ken Wu 1 Feb 2, 2022
ZX Spectrum Utilities: (zx-spectrum-utils)

Here are a few utility programs that can be used with the zx spectrum. The ZX Spectrum is one of the first home computers from the early 1980s.

Graham Oakes 4 Mar 7, 2022
Spectrum is an AI that uses machine learning to generate Rap song lyrics

Spectrum Spectrum is an AI that uses deep learning to generate rap song lyrics. View Demo Report Bug Request Feature Open In Colab About The Project S

null 39 Dec 16, 2022
Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns

Diffraction Simulations - Angular Spectrum Method Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns with arbitr

Rafael de la Fuente 276 Dec 30, 2022
Real-time audio visualizations (spectrum, spectrogram, etc.)

Friture Friture is an application to visualize and analyze live audio data in real-time. Friture displays audio data in several widgets, such as a sco

Timothée Lecomte 700 Dec 31, 2022
Implementation for the IJCAI2021 work "Beyond the Spectrum: Detecting Deepfakes via Re-synthesis"

Beyond the Spectrum Implementation for the IJCAI2021 work "Beyond the Spectrum: Detecting Deepfakes via Re-synthesis" by Yang He, Ning Yu, Margret Keu

Yang He 27 Jan 7, 2023
Data visualization electromagnetic spectrum

Datenvisualisierung-Elektromagnetischen-Spektrum Anhand des Moduls matplotlib sollen die Daten des elektromagnetischen Spektrums dargestellt werden. D

Pulsar 1 Sep 1, 2022
Use MATLAB to simulate the signal and extract features. Use PyTorch to build and train deep network to do spectrum sensing.

Deep-Learning-based-Spectrum-Sensing Use MATLAB to simulate the signal and extract features. Use PyTorch to build and train deep network to do spectru

null 10 Dec 14, 2022
This code is a near-infrared spectrum modeling method based on PCA and pls

Nirs-Pls-Corn This code is a near-infrared spectrum modeling method based on PCA and pls 近红外光谱分析技术属于交叉领域,需要化学、计算机科学、生物科学等多领域的合作。为此,在(北邮邮电大学杨辉华老师团队)指导下

Fu Pengyou 6 Dec 17, 2022
Full Spectrum Bioinformatics - a free online text designed to introduce key topics in Bioinformatics using the Python

Full Spectrum Bioinformatics is a free online text designed to introduce key topics in Bioinformatics using the Python programming language. The text is written in interactive Jupyter Notebooks, which allow you to try out and modify example code and analyses.

Jesse Zaneveld 33 Dec 28, 2022
Frequency Spectrum Augmentation Consistency for Domain Adaptive Object Detection

Frequency Spectrum Augmentation Consistency for Domain Adaptive Object Detection Main requirements torch >= 1.0 torchvision >= 0.2.0 Python 3 Environm

null 15 Apr 4, 2022
Separation of Mainlobes and Sidelobes in the Ultrasound Image Based on the Spatial Covariance (MIST) and Aperture-Domain Spectrum of Received Signals

Separation of Mainlobes and Sidelobes in the Ultrasound Image Based on the Spatial Covariance (MIST) and Aperture-Domain Spectrum of Received Signals

Rehman Ali 3 Jan 3, 2023
Aiming at the common training datsets split, spectrum preprocessing, wavelength select and calibration models algorithm involved in the spectral analysis process

Aiming at the common training datsets split, spectrum preprocessing, wavelength select and calibration models algorithm involved in the spectral analysis process, a complete algorithm library is established, which is named opensa (openspectrum analysis).

Fu Pengyou 50 Jan 7, 2023
A step-by-step tutorial for how to work with some of the most basic features of Nav2 using a Jupyter Notebook in a warehouse environment to create a basic application.

This project has a step-by-step tutorial for how to work with some of the most basic features of Nav2 using a Jupyter Notebook in a warehouse environment to create a basic application.

Steve Macenski 49 Dec 22, 2022
a basic code repository for basic task in CV(classification,detection,segmentation)

basic_cv a basic code repository for basic task in CV(classification,detection,segmentation,tracking) classification generate dataset train predict de

null 1 Oct 15, 2021
Nuitka Organization 8k Jan 7, 2023
Snowball compiler and stemming algorithms

Snowball is a small string processing language for creating stemming algorithms for use in Information Retrieval, plus a collection of stemming algori

Snowball Stemming language and algorithms 613 Jan 7, 2023
Snowball compiler and stemming algorithms

Snowball is a small string processing language for creating stemming algorithms for use in Information Retrieval, plus a collection of stemming algori

Snowball Stemming language and algorithms 471 Feb 9, 2021