misc/kforth: Initial import.

This commit is contained in:
Kyle Isom 2018-02-22 11:38:27 -08:00
parent 0fb6dce050
commit c4d78e17ff
13 changed files with 1083 additions and 0 deletions

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
CXXSTD := c++11
CXXFLAGS := -std=$(CXXSTD) -Wall -Werror -g -O0
OBJS := linux/io.o \
kforth.o
TARGET := kforth
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) $(CFLAGS) -o $@ $(OBJS)
clean:
rm -f $(OBJS) $(TARGET)

9
defs.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef __KF_DEFS_H__
#define __KF_DEFS_H__
#ifdef __linux__
#include "linux/defs.h"
#endif
#endif // __KF_DEFS_H__

216
doc/Makefile Normal file
View File

@ -0,0 +1,216 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/WriteYouaForth.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/WriteYouaForth.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/WriteYouaForth"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/WriteYouaForth"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

283
doc/conf.py Normal file
View File

@ -0,0 +1,283 @@
# -*- coding: utf-8 -*-
#
# Write You a Forth documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 22 08:15:32 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Write You a Forth'
copyright = u'2018, K. Isom'
author = u'K. Isom'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'0.0.1'
# The full version, including alpha/beta/rc tags.
release = u'0.0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'WriteYouaForthdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'WriteYouaForth.tex', u'Write You a Forth Documentation',
u'K. Isom', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'writeyouaforth', u'Write You a Forth Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'WriteYouaForth', u'Write You a Forth Documentation',
author, 'WriteYouaForth', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

18
doc/index.rst Normal file
View File

@ -0,0 +1,18 @@
Write You a Forth
=================
Contents:
.. toctree::
:maxdepth: 2
part-0x01
part-0x02
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

91
doc/part-0x01.rst Normal file
View File

@ -0,0 +1,91 @@
Write You a Forth, 0x01
-----------------------
:date: 2018-02-21 23:17
:tags: wyaf, forth
Following on from the `last post`_ I've decided to frame this as a Write You an
X-type series where I'll write up my thinking and planning as I go.
.. _last post: https://dl.kyleisom.net/posts/2018/02/21/2018-02-21-revisiting-forth/
The basics
^^^^^^^^^^
Let's start with the basics: what are the characteristics of a Forth? First,
it's a stack-based language, so it'll need a stack. Actually, it'll need at
least two stacks --- the data stack and the return stack (where return addresses
are normally stored). Modern Forths also have a floating point stack.
Forth calls functions *words*, and the FORTH-83 standard defines a set of
required words for an implementation. Note that there is an ANS Forth, but I'll
target FORTH-83 first for simplicity. The `required words`_ are:
.. _required words: http://forth.sourceforge.net/standard/fst83/fst83-12.htm)
**Nucleus layer**::
! * */ */MOD + +! - / /MOD 0< 0= 0> 1+ 1- 2+
2- 2/ < = > >R ?DUP @ ABS AND C! C@ CMOVE
CMOVE> COUNT D+ D< DEPTH DNEGATE DROP DUP EXECUTE
EXIT FILL I J MAX MIN MOD NEGATE NOT OR OVER PICK
R> R@ ROLL ROT SWAP U< UM* UM/MOD XOR
**Device layer**::
BLOCK BUFFER CR EMIT EXPECT FLUSH KEY SAVE-BUFFERS
SPACE SPACES TYPE UPDATE
**Interpreter layer**::
# #> #S #TIB ' ( -TRAILING . .( <# >BODY >IN
ABORT BASE BLK CONVERT DECIMAL DEFINITIONS FIND
FORGET FORTH FORTH-83 HERE HOLD LOAD PAD QUIT SIGN
SPAN TIB U. WORD
**Compiler layer**::
+LOOP , ." : ; ABORT" ALLOT BEGIN COMPILE CONSTANT
CREATE DO DOES> ELSE IF IMMEDIATE LEAVE LITERAL LOOP
REPEAT STATE THEN UNTIL VARIABLE VOCABULARY WHILE
['] [COMPILE] ]
In a lot of cases, Forth is also the operating system for the device. This
won't be a target at first, but something to keep in mind as I progress.
Eventually, I'd like to build a zero-allocation Forth that can run on an
STM-32 or an MSP430, but the first goal is going to get a minimal Forth
working. I'll define the stages as
Stage 1
~~~~~~~
1. Runs on Linux (that's what my Pixelbook runs, more or less).
2. Implements the nucleus layer.
3. Has a REPL that works in a terminal.
4. Explicit non-goal: performance. I'll build a working minimal Forth to get a
baseline experience.
Stage 2
~~~~~~~
1. Implement the compiler and interpreter layers.
Stage 3
~~~~~~~~
1. Define a block layer interface.
2. Implement a Linux block layer interface.
Stage 4
~~~~~~~~
1. Build a memory management system.
2. Replace all managed memory with the homebrew memory management system.
3. Switch to a JPL rule #3 (no heap allocation) implementation.
Next steps
^^^^^^^^^^
I don't really know what I'm doing, so in the next section, I'll build out the
basic framework and set up the build.

274
doc/part-0x02.rst Normal file
View File

@ -0,0 +1,274 @@
Write You a Forth, 0x02
-----------------------
:date: 2018-02-22 10:48
:tags: wyaf, forth
The basic framework will consist of two main parts:
1. A modular I/O subsystem: on Linux, it makes sense to use the operating
system's terminal I/O features. On the MSP430, there won't be the luxury
of any operating system and I'll have to build out the I/O facilities. The
I/O interface will be defined in ``io.h``; the build system will eventually
have to decide which interface implementation to bring in.
2. A toplevel function (the C++ ``main`` function, for example) that will
handle starting up the Forth system and bring us into an interpreter. We'll
put this in ``kforth.cc``.
The project will also need a build system. For simplicity, I'll at least start
with a basic Makefile::
# Makefile
CXXSTD := c++11
CXXFLAGS := -std=$(CXXSTD) -Werror -Wall -g -O0
OBJS := linux/io.o \
kforth.o
TARGET := kforth
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) $(CFLAGS) -o $@ $(OBJS)
clean:
rm -f $(OBJS) $(TARGET)
A simple frontend
^^^^^^^^^^^^^^^^^
Starting out with the most basic front end; we'll first want to include our I/O
interface::
#include "io.h"
If kforth is running on Linux, and it will be for the first stage, the
frontend should pull in Linux specific pieces. ``linux.h`` is the place
to set up the Linux-specific pieces::
#ifdef __linux__
#include "linux.h"
#endif // __linux__
The interpreter function takes an I/O interface instance, and reads lines in
an infinite loop, printing "ok" after each line is read. I'll go over the
methods called on the ``interface`` instance when I get to the I/O subsystem.
Printing the line buffer right now helps to verify that the I/O subsystem is
working correctly::
static char ok[] = "ok.\n";
static void
interpreter(IO &interface)
{
static size_t buflen = 0;
static char linebuf[81];
while (true) {
buflen = interface.rdbuf(linebuf, 80, true, '\n');
interface.wrln(linebuf, buflen);
interface.wrbuf(ok, 4);
}
}
The main function, for right now, can just instantiate a new I/O interface and
then call the interpreter::
static char banner[] = "kforth interpreter\n";
const size_t bannerlen = 19;
int
main(void)
{
#ifdef __linux__
Console interface;
#endif
interface.wrbuf(banner, bannerlen);
interpreter(interface);
return 0;
}
That gives a good interactive test framework that I can use to start playing
with the system. I'm trying to avoid bringing in ``iostream`` directly in order
to force writing and building useful tooling built around the I/O interface.
This is, after all, the Forth ideal: start with a core system, then build your
world on top of that.
The I/O interface
^^^^^^^^^^^^^^^^^
In the truest of C++ fashions, the I/O interface is defined with the ``IO``
abstract base class::
#ifndef __KF_IO_H__
#define __KF_IO_H__
#include "defs.h"
class IO {
public:
// Virtual destructor is required in all ABCs.
virtual ~IO() {};
The two building block methods are the lowest-level. My original plan was to
include these in the interface, but there's one snag with that: line endings.
But, we'll get to that.
::
// Building block methods.
virtual char rdch(void) = 0;
virtual void wrch(char c) = 0;
I could have just made the buffer I/O methods functions inside the ``io.h``
header, but it seems easy to just include them here. I may move them outside
the class later, though.
::
// Buffer I/O.
virtual size_t rdbuf(char *buf, size_t len, bool stopat, char stopch) = 0;
virtual void wrbuf(char *buf, size_t len) = 0;
Line I/O presents some challenges. On a serial console, it's the sequence 0x0d
0x0a; on the Linux terminal, it's 0x0a. Therefore, reading a line is
platform-dependent, and I can't just make this a generic function unless I want
to handle all the cases. And, *surprise surprise*, right now I don't.
::
// Line I/O
virtual bool rdln(char *buf, size_t len, size_t *readlen) = 0;
virtual void wrln(char *buf, size_t len) = 0;
};
#endif // __KF_IO_H__
The Linux implementation is the ``Console`` (as seen in ``main``). The header
file isn't interesting; it's basically a copy of ``io.h`` in ``linux/io.h``.
::
#include <iostream>
#include "../io.h"
#include "io.h"
The building blocks flush I/O. ``getchar`` is used instead of ``cin`` because
the latter skips whitespace. Later, flushing may be removed but it's not a
performance concern yet.
::
char
Console::rdch()
{
std::cout.flush();
return getchar();
}
void
Console::wrch(char c)
{
std::cout.flush();
std::cout << c;
}
The buffer read and write functions are straightforward, and are just built on
top of the character read and write methods.
::
size_t
Console::rdbuf(char *buf, size_t len, bool stopat, char stopch)
{
size_t n = 0;
char ch;
while (n < len) {
ch = this->rdch();
if (stopat && stopch == ch) {
break;
}
buf[n++] = ch;
}
return n;
}
void
Console::wrbuf(char *buf, size_t len)
{
for (size_t n = 0; n < len; n++) {
this->wrch(buf[n]);
}
}
Line reading doesn't reuse the buffer I/O functions, because the latter
doesn't indicate whether the buffer ran out or the line has ended. I could add
length checks and whatnot, but this is straightforward and gives me something
to work with now. Again, the mantra is dumb and works rather than clever. For
now.
::
bool
Console::rdln(char *buf, size_t len, size_t *readlen) {
size_t n = 0;
char ch;
bool line = false;
while (n < len) {
ch = this->rdch();
if (ch == '\n') {
line = true;
break;
}
buf[n++] = ch;
}
if (nullptr != readlen) {
*readlen = n;
}
return line;
}
Line writing, however, can absolutely reuse the buffer and character I/O
methods.
::
void
Console::wrln(char *buf, size_t len)
{
this->wrbuf(buf, len);
this->wrch(0x0a);
}
``defs.h``
^^^^^^^^^^
The common definition file ``defs.h`` is just a front for the actual platform
definitions::
#ifndef __KF_DEFS_H__
#define __KF_DEFS_H__
#ifdef __linux__
#include "linux/defs.h"
#endif
#endif // __KF_DEFS_H__
The Linux definitions in ``linux/defs.h`` just bring in the standard
definitions from the standard library::
#ifndef __KF_LINUX_DEFS_H__
#define __KF_LINUX_DEFS_H__
#include <stddef.h>
#endif
Next steps
^^^^^^^^^^
I guess the next thing to do will be to start parsing.

24
io.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef __KF_IO_H__
#define __KF_IO_H__
#include "defs.h"
class IO {
public:
// Virtual destructor is required in all ABCs.
virtual ~IO() {};
// Building block methods.
virtual char rdch(void) = 0;
virtual void wrch(char c) = 0;
// Buffer I/O.
virtual size_t rdbuf(char *buf, size_t len, bool stopat, char stopch) = 0;
virtual void wrbuf(char *buf, size_t len) = 0;
// Line I/O
virtual bool rdln(char *buf, size_t len, size_t *readlen) = 0;
virtual void wrln(char *buf, size_t len) = 0;
};
#endif // __KF_IO_H__

34
kforth.cc Normal file
View File

@ -0,0 +1,34 @@
#include "io.h"
#ifdef __linux__
#include "linux.h"
#endif // __linux__
static char ok[] = "ok.\n";
static void
interpreter(IO &interface)
{
static size_t buflen = 0;
static char linebuf[81];
while (true) {
buflen = interface.rdbuf(linebuf, 80, true, '\n');
interface.wrln(linebuf, buflen);
interface.wrbuf(ok, 4);
}
}
static char banner[] = "kforth interpreter\n";
const size_t bannerlen = 19;
int
main(void)
{
#ifdef __linux__
Console interface;
#endif
interface.wrbuf(banner, bannerlen);
interpreter(interface);
return 0;
}

12
linux.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef __KF_LINUX_H__
#define __KF_LINUX_H__
#include <stdint.h>
// build support for linux
#include "linux/io.h"
constexpr uint8_t STACK_SIZE = 128;
#endif // __KF_LINUX_H__

7
linux/defs.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef __KF_LINUX_DEFS_H__
#define __KF_LINUX_DEFS_H__
#include <stddef.h>
#endif

79
linux/io.cc Normal file
View File

@ -0,0 +1,79 @@
#include <iostream>
#include "../io.h"
#include "io.h"
char
Console::rdch()
{
std::cout.flush();
return getchar();
}
void
Console::wrch(char c)
{
std::cout << c;
}
size_t
Console::rdbuf(char *buf, size_t len, bool stopat, char stopch)
{
size_t n = 0;
char ch;
while (n < len) {
ch = this->rdch();
if (stopat && stopch == ch) {
break;
}
buf[n++] = ch;
}
return n;
}
void
Console::wrbuf(char *buf, size_t len)
{
for (size_t n = 0; n < len; n++) {
this->wrch(buf[n]);
}
}
// Line I/O
bool
Console::rdln(char *buf, size_t len, size_t *readlen) {
size_t n = 0;
char ch;
bool line = false;
while (n < len) {
ch = this->rdch();
if (ch == '\n') {
line = true;
break;
}
buf[n++] = ch;
}
if (nullptr != readlen) {
*readlen = n;
}
return line;
}
void
Console::wrln(char *buf, size_t len)
{
this->wrbuf(buf, len);
this->wrch(0x0a);
}

23
linux/io.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef __KF_IO_LINUX_H__
#define __KF_IO_LINUX_H__
#include "io.h"
#include "defs.h"
class Console : public IO {
public:
~Console() {};
char rdch(void);
void wrch(char c);
// Buffer I/O.
size_t rdbuf(char *buf, size_t len, bool stopat, char stopch);
void wrbuf(char *buf, size_t len);
// Line I/O
bool rdln(char *buf, size_t len, size_t *readlen);
void wrln(char *buf, size_t len);
private:
};
#endif // __KF_IO_LINUX_H__