Skip to content
HeavyNotFatPublic

About

A Turing Completeness Programming Language with Chinese PL. 一个带中文编程的图灵完备编程语言

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

22 Commits

Folders and files

Repository files navigation

EPScript

English · 简体中文

EPScript is a small scripting language implemented in pure Python: a hand-written lexer, a recursive-descent parser, and an evaluator that walks the resulting AST. The pipeline lives in core/ and imports nothing outside the standard library, so there is no install step and no dependency to manage.

The feature set stays close to the basics: values, arithmetic, logic, if, for, while, functions, classes, arrays, dictionaries, strings, cross-file imports, built-in libraries, pointers and memory, politeness markers (off by default) and Schrödinger values, and ten built-in functions. The one unusual trait is that every keyword and every bracket has a Chinese spelling next to the ASCII one, and both spellings go through the same parser. Files written the Chinese way use the .epsc extension, the ASCII dialect uses .eps. The libraries shipped with the interpreter live in core/libs; the ones written in Python come in through the core/bridge compatibility layer.

function fib(n) {
    if (n < 2) {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

for i from 0 to 10 {
    output(fib(i))
}

Numbers are stored as decimal.Decimal, so 0.1 + 0.2 prints 0.3 and 7 / 2 prints 3.5.

Requirements

  • Python 3.12 or newer. The lexer uses f-strings with nested quotes (PEP 701), which older versions reject.
  • No third-party packages.
  • No packaging yet; the repository itself is the EPScript package.

Getting started

Start the REPL from the repository root:

python __init__.py
>>> output("hi")
hi
>>> var n = 3
>>> 2 ** 10
1024
>>> output(n * n)
9

The REPL reads one line at a time, so multi-line programs belong in a file. Both keyword sets are active inside it.

To run one of the sample programs, use the run built-in:

>>> run("examples/01_hello.eps")
Hello, world!

run picks the tokenizer mode from the suffix: .epsc turns on the Chinese keyword set, anything else stays ASCII. The same function works inside a running program, so files can load other files.

From Python:

import EPScript

path = "examples/01_hello.eps"
source = open(path, encoding="utf-8").read()
result = EPScript.core.interpret(source, False, path, "<module>")

The four arguments are the source text, a flag for Chinese keywords, the file name and the module name used in error output. interpret returns a string when the program ends on an expression or fails, and None when there is nothing to report; printing is done by output() while the program runs. EPScript.run(source) is a thin wrapper that enables Chinese keywords and is what the REPL calls internally.

A program is a plain UTF-8 text file. There is no build step and no bytecode cache.

Sample programs

Each file in examples/ can be loaded with run("examples/<file>").

File What it shows
01_hello.eps the smallest program, a single output call
02_numbers.eps arithmetic, powers, decimal division
03_branch.eps if / else if / else, with and without parentheses
04_loops.eps for with a step, counting down, while, break and continue
05_fib.eps recursion inside a function
06_arrays.eps building an array, then reading it back by index and slice
07_input.eps readline plus Integer and String conversion
08_convert.eps formatting numbers, repeating strings
09_factorial.epsc the Chinese dialect end to end
10_text.eps string indexing, slicing and repetition
11_class.eps a class with a constructor and methods that read and write fields
12_class.epsc the same idea in the Chinese dialect
13_oop.eps inheritance, super, abstract methods, statics, private fields and toString
14_oop.epsc the same OOP pieces in the Chinese dialect
15_import.eps from ... import ... with two names, one of them renamed
16_import.epsc the same import in the Chinese dialect
17_library.eps names taken from the built-in math and from the Python-backed text
18_bridge.eps a function-only script for EPScript.load on the Python side
19_logic.eps and / or / not combining conditions, including short-circuit checks in a function
20_pointer.eps @ / $ and memory() reading and writing variables and memory cells
21_linked_list.eps a linked list whose nodes are memory(2) blocks and whose next is a pointer
22_dict.eps dictionary literals, reads and writes, methods, and a dictionary in a class field
23_polite.eps politeness markers choosing the loop-folding level (off by default)
24_schrodinger.eps superposition, collapse and returning ?(...)
25_cache.eps the set_cache switch, pure-loop state cache, and sharing across code
26_lru.eps automatic pure-function cache, the LRU limit, and recursive fib
mathlib.eps the module the two import examples above import

IDLE

The Tkinter editor lives in idle/ and starts from the repository root:

python -m idle

It follows the layout of toylang's IDLE: a line-number gutter on the left, Edit / View / Run menus, and a second window that collects the output of a run.

The editor, the completion popup and the run window

  • F5 runs the whole file, Alt+F5 runs the selection. The run window prints in blue, errors in red, and closes with Run finished with exit code 0 or -1; a failing run also highlights the reported line in the editor and puts the caret there.
  • Completion opens while you type (two characters is enough), after . or 。 for member lists, and on Ctrl+Space. Candidates are the keywords, the built-in functions, every name already in the file, and the methods defined in it.
  • Brackets and quotes close themselves. Typing the closing character steps over it, Backspace removes an empty pair, and typing an opener over a selection wraps the selection.
  • Enter between a pair opens the block and leaves the caret on the indented line; a closer typed on a blank line dedents first.
  • Tab expands snippets: if, while, for, function, class, var, from, and the Chinese 如果, 重复当, 循环, 函数, 类, 设置, 导入.
  • Ctrl+/ toggles # comments on the selected lines, and the bracket next to the caret is matched with its partner.
  • readline is served by an input row at the bottom of the run window, so the program keeps its own state while waiting.
  • Ctrl+Shift+P opens the preference dialog: font family, font size, and a live preview using the real highlighter.
  • Colours and the default font come from idle/settings.json; the dialog writes idle/config.json, which is what the next start reads.
  • The default font is JetBrains Mono at 10, in a portrait window (560x700). If the family is missing, the editor falls back to Consolas, Menlo, then the Tk fixed font.

Comments and layout

# starts a comment. It runs to the end of the line, or to the next # if there is one on the same line.

# a whole line
var a = 1    # trailing note

A newline ends a statement. A semicolon works too, which is how you fit two statements on one line:

var a = 1; var b = 2; output(a + b)

Indentation does not matter. Braces define blocks, and a block may hold a single statement written on the same line as its header.

Types

Type Literals Notes
Integer 0, 42, -7 Arbitrary precision, backed by Decimal.
Float 3.14, 0.5 Must contain a decimal point.
String "text", 'text' Escapes: \n, \t, \\, \", \'.
Boolean true, false Printed as true and false.
Null null Also the value of a statement that produces nothing.
Array [1, "two", [3]], [] Elements may mix types.
Dict {"a": 1}, {} Keys must be Strings; insertion order is kept.
Superposition ?(1, 2), ?(1,2) Holds several candidates until observed, then collapses to one.

Variables

var total = 0
total = total + 10
output(total)

var declares a name. Assigning without var updates an existing name and raises NameError when there is none, which is what catches typos like toatl.

Every function call gets a fresh scope whose parent is the scope that made the call. Parameters and var declarations in the body stay local. A bare assignment also writes into the current scope, so updating an outer variable from inside a function shadows it instead of changing it.

Operators

Binding Operators Notes
1, tightest ** % 2 ** 10 is 1024
2 * / / is exact decimal division: 7 / 2 is 3.5
3 + - + also joins strings and appends to arrays
4 == != < <= > >= comparisons
5 not ! negation; not a == b reads as not (a == b)
6 and & true only when both sides are true, short-circuits
7, loosest or | true when either side is true, short-circuits

Every group is left-associative; ( ) overrides the order.

A few rules are worth knowing up front:

  • + needs two strings. "a" + 1 is a TypeError; write "a" + String(1).
  • "ab" * 3 repeats a string.
  • array + value returns a new array with one more element; the left side is left alone. array + [value] adds the array itself, it does not concatenate.
  • <, <=, >, >= work on numbers only. == and != work on any two values of the same kind.
  • and / or treat both sides as conditions and always yield true or false; they short-circuit, so b is not evaluated in a and b when a is false, nor in a or b when a is true.
  • not is a prefix operator, looser than a comparison and tighter than and. &, | and ! are exact synonyms for and, or and not.

Conditionals

var score = 72

if (score >= 60) {
    output("pass")
} else {
    output("fail")
}

Parentheses around the condition are optional, so if score < 60 { ... } is valid as well. else has to sit on the same line as the closing brace. A body of one statement can stay on the header line:

function sign(n) {
    if (n < 0) { return "negative" }
    return "other"
}

Conditions chain with else if, and a one-line block works on both branches:

var points = 72

if (points >= 90) {
    output("excellent")
} else if (points >= 60) {
    output("pass")
} else {
    output("fail")
}

if (points >= 60) { output("passed") } else { output("failed") }

Conditions also take and / or / not (Chinese 并且 / 或者 / 非); they produce booleans and short-circuit:

var score = 72

if (score >= 60 and score < 90) {
    output("pass")
}

if (score < 60 or score >= 90) {
    output("need review")
}

if (not (score == 0)) {
    output("has score")
}

Loops

for i from 1 to 5 {
    output(i)
}

for i from 10 to 0 step -2 {
    output(i)
}

var n = 1
while (n <= 8) {
    output(n)
    n = n * 2
}

for counts from the first bound to the second, inclusive on both ends, and both bounds must be integers. step is optional and defaults to 1; a negative step counts down. while requires the parentheses around its condition.

break leaves the innermost loop, continue skips to its next iteration:

var total = 0

for i from 1 to 10 {
    if (i == 6) {
        break
    }
    if (i % 2 == 0) {
        continue
    }
    total = total + i
}

output(total)

Functions

function add(a, b) {
    return a + b
}

output(add(2, 3))

The argument count has to match the declaration exactly. A function that reaches its closing brace without return yields null. Recursion works, bounded by Python's own recursion limit because the evaluator recurses along the AST. Functions are always named: there are no anonymous functions and no default parameter values.

Classes

A class is a named block of methods. class takes a name and a body of function declarations; calling the class builds an instance, and a method named init runs as the constructor:

class Point {
    function init(x, y) {
        self.x = x
        self.y = y
    }

    function move(dx, dy) {
        self.x = self.x + dx
        self.y = self.y + dy
    }

    function show() {
        output("(" + String(self.x) + ", " + String(self.y) + ")")
    }
}

var p = Point(3, 4)
p.show()
p.move(10, -4)
p.show()
(3, 4)
(13, 0)

self is bound inside every method and points at the instance being called. Fields appear the first time a method assigns them: there is no declaration block, and reading a field that was never set reports NameError. A method that returns self can be chained, so bag.add(1).add(2) works, and anything that produces an instance can be used the same way: boxes[0].show(), make().show().

Constructor

A method named init (or 初始化) is the constructor and runs when the class is called. It is inherited: a child without its own init uses the parent's, and super.init(...) calls the parent's when it does have one. A class with no constructor accepts no arguments.

Inheritance

class Animal {
    function init(name) {
        self._name = name
    }

    function speak() {
        return "..."
    }

    function describe() {
        return self._name + " says " + self.speak()
    }
}

class Dog extends Animal {
    function init(name) {
        super.init(name)
    }

    function speak() {
        return "woof"
    }
}

var d = Dog("Rex")
output(d.describe())
Rex says woof

extends names the parent; the Chinese dialect writes 类 狗 继承 动物. super (Chinese 父类) starts at the parent of the class that defines the method, so a three-level chain still resolves one step at a time.

Polymorphism

describe lives in Animal, but self.speak() reaches Dog.speak: a method is looked up on the instance's own class first, then up the chain. isinstance(value, Class) (Chinese 属于) asks whether a value belongs to a class or to any of its parents:

class Animal {
    function speak() {
        return "..."
    }

    function describe() {
        return "it says " + self.speak()
    }
}

class Dog extends Animal {
    function speak() {
        return "woof"
    }
}

output(Animal().describe())
output(Dog().describe())
output(isinstance(Dog(), Animal))
it says ...
it says woof
true

Abstraction

abstract function declares a method without an implementation. A class that still has an unimplemented abstract method cannot be created:

class Shape {
    abstract function area() {
    }
}

class Square extends Shape {
    function init(side) {
        self._side = side
    }

    function area() {
        return self._side * self._side
    }
}

output(Square(3).area())
9

var s = Shape() would report 'Shape' is abstract, 'area' has no implementation.

Static methods

static function belongs to the class rather than the instance, so it is called as Class.method() and has no self:

class Unit {
    static function name() {
        return "cm2"
    }
}

output(Unit.name())
cm2

Calling a static method on an instance, or an instance method on the class, is an error.

Encapsulation

A member whose name starts with _ is private: only methods of the same class or of a subclass may read or write it. From outside it is a NameError.

class Counter {
    function init() {
        self._count = 0
    }

    function bump() {
        self._count = self._count + 1
        return self._count
    }
}

var c = Counter()
output(c.bump())

This prints 1. Reaching for c._count from outside reports '_count' is private to 'Counter'. The same rule covers methods, so _helper() can only be called from inside the class.

Printing

A method named toString (Chinese 转文本) decides how an instance prints, in output and in String alike:

class Point {
    function init(x, y) {
        self.x = x
        self.y = y
    }

    function toString() {
        return "(" + String(self.x) + ", " + String(self.y) + ")"
    }
}

output(Point(1, 2))
output(String(Point(3, 4)))
(1, 2)
(3, 4)

Without toString, an instance prints as <Point instance>.

A few rules:

  • Every instance keeps its own fields. Two instances share the method table and nothing else.
  • Calling a class that has no constructor with arguments is a TypeError.
  • == on two instances compares identity, so two separately built points are never equal.
  • Method names are ordinary identifiers, which means a keyword such as step, super or static cannot be used.

Arrays

var squares = []

for i from 1 to 5 {
    squares = squares + i * i
}

output(squares)
output(squares[0])
output(squares[1:3])
output(squares[-1])
output(squares + 36)
output(squares)
[1, 4, 9, 16, 25]
1
[4, 9]
25
[1, 4, 9, 16, 25, 36]
[1, 4, 9, 16, 25]

+ returns a new array and leaves the left side alone, which is why the last line still holds five elements. a.append(x) and a.添加(x) grow the array in place instead. array + [value] adds the array itself, not its contents.

One index returns an element, two or three return a slice, and a negative index counts from the end. An index outside the array reports ValueError. When printed, elements are separated by commas and strings lose their quotes, so [1, 2, "x"] comes out as [1, 2, x].

Dictionaries

A dictionary is written with braces; keys must be strings and insertion order is kept:

var user = {
    "name": "Ada",
    "age": 36
}

output(user["name"])      # Ada
user["age"] = 37
user["lang"] = "EPScript"
output(user)              # {"name": Ada, "age": 37, "lang": EPScript}
  • {} is the empty dictionary; d[key] reads and d[key] = value writes, adding the key when it is missing
  • reading a missing key raises NameError; a key that is not a String raises TypeError
  • dictionaries cannot be sliced, d["a":"b"] raises TypeError
  • == / != compare the entries
  • printing produces {"a": 1, "b": 2}: keys keep their quotes, values follow the output rules

Methods (English / Chinese):

Call What it does
d.set(key, value) / d.设置(key, value) write, same as d[key] = value
d.get(key) / d.get(key, default) / d.取(...) read; a missing key gives null or the default
d.has(key) / d.有(key) whether the key exists, as a Boolean
d.remove(key) / d.删除(key) remove and return the old value, null when missing
d.keys() / d.键() an array of keys in insertion order
d.values() / d.值() an array of values
d.length() / d.长度() number of keys
d.clear() / d.清空() remove everything

The example is 22_dict.eps.

Strings

Strings are immutable. They concatenate with +, repeat with *, compare with == / !=, and take the same subscripts as arrays:

var word = "EPScript"

output(word[0])
output(word[0:2])
output(word[0:8:2])
output("ab" * 3)
output("total: " + String(123))
E
EP
ESrp
ababab
total: 123

A subscript returns a one-character String or a String slice. Other types are converted first, usually with String.

Pointers and memory

@ takes the address of a variable, $ reads through a pointer, and $p = value writes through it. Both symbols stay ASCII in either dialect:

var value = 10
var pointer = @value

output($pointer)
$pointer = 42
output(value)

memory(n) allocates n cells and returns a pointer to the first one; p + k / p - k move inside the block, and going out of range raises ValueError:

var block = memory(3)
$block = "a"
$(block + 1) = "b"
output($block)
output($(block + 1))

Rules:

  • @ only works on variables; expressions, function results, array elements and fields are rejected
  • a pointer to a variable cannot be moved, p + 1 is a TypeError
  • a memory pointer has to stay in [0, size)
  • pointers print as <pointer 0> or <pointer to 'value'>
  • @ and $ are prefixes, but the postfix . / [] binds first: $self.pointer means $(self.pointer); $p + 1 still dereferences first, so write $(p + 1) to move first
  • @parameter points at the parameter cell, not the caller's variable; to keep a reference to the caller's variable, pass @x in and store that pointer directly

The example is 20_pointer.eps, printing 10, 42, a, b. The linked list in 21_linked_list.eps uses the same pieces: each node is a two-cell block and $(node + 1) holds the next node.

Politeness optimization

Politeness optimization is off by default. Turn it on first:

import core
core.set_politeness(True)   # True enables, False disables

A single call can override it: core.interpret(..., politeness_enabled=True), interpreter.run(..., politeness_enabled=True), EPScript.run(code, politeness_enabled=True). The switch itself is core.interpreter.POLITENESS_ENABLED, False by default; set_politeness just assigns it.

With it on, a statement can be prefixed with honorific words, which raises the optimization level for that piece of code:

please var note = "normal"

could you please kindly function count(n) {
    var total = 0
    for i from 1 to n {
        total = total + 1
    }
    return total
}

Writing or else! after a statement drops it back to the debug level:

var total = 0
for i from 1 to 100 {
    total = total + 1
} or else!

The honorific words are could, you, please, kindly, with 能否, 您, 请, 恳请 in Chinese mode. Each one raises the level by one:

Form Level Effect
please / 请 1 normal code
two or more honorific words >=2 optimized: simple counted loops fold immediately
or else! / 或者 否则! -1 debug: no folding, no caching

A function definition remembers the level of its prefix, and later calls run the body at that level. or else! follows the call into the callee, so counted loops in that function are not optimized either. The folding rules are in the next section.

When the switch is off, please, could you please kindly and or else! still parse, but everything runs at the normal level; the levels above only apply after the switch is on. Turning politeness off does not disable the ordinary counted-loop cache.

Schrödinger values

?(...) builds a value that holds several candidates at once:

var x = ?(1, 2, 3)

output(x)        # one of 1, 2, 3
output(x)        # the same one: it has collapsed

var y = x + 100  # arithmetic is an observation
output(y)

function pick() {
    return ?("red", "green", "blue")
}

output(pick())   # collapses on return
  • assignment and argument passing do not observe the value; printing, String(), arithmetic, comparison, if / while conditions and return do
  • after collapsing, the chosen value is fixed, so later observations agree
  • the candidate is chosen at random, with no weights; nested superpositions collapse recursively
  • Chinese mode writes ?(1,2)
  • the language declares with var; there is no let

Rate optimization

The interpreter recognizes a narrow kind of counted loop: the body is only x = x + constant or x = x - constant, and the bounds and step end up as integers. Such a loop is reduced to its final values instead of running iteration by iteration:

var x = 0
for i from 0 to 10000 {
    x = x + 1
}
output(x)   # 10001

Normal code still runs the loop once, then records the result for (start, end, step, initial value) on the loop node; the next execution of the same loop with the same parameters reuses that cache. This is most visible when a function is called repeatedly.

More generally, when the body only contains scalar variables, literals, arithmetic/logical operators, assignments, if, while and nested for, the interpreter caches the final state of the whole loop: the last values of every written variable and the loop variable, plus the values of every read variable before the loop. When the structure, bounds and inputs match, it restores that state and skips all iterations at once:

function sum(n) {
    var total = 0
    for i from 1 to n {
        total = total + i
    }
    return total
}

output(sum(1000))   # 500500
output(sum(1000))   # reads the cache

Variable names are normalized in the structural key, so differently named code with the same loop shape shares the entry. Both for and standalone while loops use this state cache; a while condition must follow the same pure-expression limits.

With the switch on, the could you please kindly level skips the first pass and folds by formula immediately; or else! neither folds nor caches.

Limits:

  • the accumulator fold only accepts x = x + constant and x = x - constant, and x cannot be the loop variable itself
  • the state cache only handles scalar reads and writes; the body cannot call functions or contain output, fields, subscripts, arrays/dictionaries, pointers, imports, break, continue or return
  • while, if and nested for are allowed inside the body as long as their conditions and branches follow the same limits
  • the initial value must be an integer; the evaluated bounds and step must be integers too
  • the loop variable keeps the value of the last iteration

Note that for i from 1 to 10000 currently runs 10000 times, so x starting at 0 ends at 10000; the example above starts at 0 to reach 10001.

Function cache

Pure functions cache their return value by arguments, much like lru_cache:

function fib(n) {
    if (n < 2) {
        return n
    }
    return fib(n - 1) + fib(n - 2)
}

output(fib(30))   # 832040
output(fib(30))   # reads the cache
  • detection is automatic: the function may only read parameters and local variables, not outside variables; it may call only itself for recursion
  • the body cannot contain output, readline, run, fields, subscripts, arrays/dictionaries, pointers, imports or class definitions
  • arguments and the return value must be scalars (integer/float/string/boolean/null); otherwise that call skips the cache
  • the function key is (function name, parameter names, body structure, argument values), so the same pure function hits across files and processes
  • function results and loop states share the same LRU cache file and work across processes
  • the default limit is 4096 entries; set_cache_size(n) changes it and set_cache(false) disables the cache

Offline cache

The offline cache is on by default; write set_cache(false) in the script to turn it off, and set_cache(true) to turn it back on:

var total = 0
for i from 1 to 1000 {
    total = total + i
}
output(total)   # 500500

set_cache(false)
  • the cache file is .epscript_cache.json in the working directory by default; EPSCRIPT_CACHE_PATH overrides it
  • since the cache is on by default, the file is loaded into memory on first use and a matching loop reuses the stored result
  • the cache is LRU: 4096 entries by default, hits refresh the order, and the least recently used entry is evicted when full; set_cache_size(n) changes the limit
  • the accumulator key is (delta, start, end, step, initial value)
  • for the loop-state cache, a for key is (body structure, start, end, step, initial read values), while a while key is (condition and body structure, initial read values); variable names are normalized
  • neither key contains variable names or file names, so different code with the same computation shares the entry
  • both the accumulator fold and the pure loop-state cache use it
  • set_cache(false) stops reads and writes but keeps the file; the switch is process-wide and does not reset when a script ends, so close it explicitly when needed
  • writes go through a temporary file; a bad version or broken content is ignored instead of breaking the script
  • an unwritable directory does not abort the script; the cache simply does not take effect

Built-in functions

Name Chinese Call Notes
output 输出 output(value) Prints the value followed by a newline.
readline 输入 readline(prompt) Prints the prompt, returns one line as a String.
Integer 整数 Integer(value) Parses integer text. Integer(3.9) fails.
Float 小数 Float(value) Parses a decimal number.
String 文本 String(value) Formats any value as text.
isinstance 属于 isinstance(value, Class) True when the value is an instance of that class or a subclass of it.
run 运行 run("file.eps") Runs another file; .epsc selects Chinese keywords.
memory 内存 memory(size) Allocates size cells and returns a pointer to the first one.
set_cache 设置缓存 set_cache(true/false) Turns the disk cache on or off; on by default.
set_cache_size 设置缓存大小 set_cache_size(size) Sets the LRU entry limit; 4096 by default.

A file loaded with run can read the variables of the caller, but the variables it declares stay inside it.

Imports

from pulls names out of a module file. import takes one name or a comma-separated list, and as renames one of them:

from mathlib import square, cube as volume

The module name is resolved as a file name: the importer's directory first, then the working directory. Without a suffix, .eps and .epsc are tried in that order; a module ending in .epsc runs with Chinese keywords. When nothing local matches, the lookup falls back to the built-in libraries in core/libs (next section). Put the path in a string when it needs directories:

from "lib/deep.eps" import shout

Importing runs the whole file, so top-level output calls print too; the names the module declares stay inside it, and only the ones named in the statement are bound in the current scope. A module can read the names that already exist in the importer, the same way run does. Functions declared in a module look names up in the table they were defined in, so helpers inside one module can call each other.

Every execution of a from statement reloads the module; nothing is cached. A failing module is reported as RuntimeError with its own traceback, and a circular import is stopped.

Built-in libraries

Libraries shipped with the interpreter live in core/libs. An import looks for a local file first and only then falls back to the built-in copy, so a file of the same name shadows the built-in one:

from math import max, min
File What it holds
math.eps abs, max, min, written in EPScript
text.py join, upper, lower, strip, written in Python
cdll.py load_dll(path) over ctypes; the DLL's functions can be called through it

.eps / .epsc libraries run like any other module; .py libraries come in through the compatibility layer below.

Talking to Python

core/bridge is that compatibility layer: it converts values both ways, wraps Python functions as PythonFunction so EPScript can call them, and turns their exceptions into RuntimeError.

EPScript Python
Integer int, or float when the value holds a decimal
Float float
String str
Boolean bool, null is None
Array list

Names in a .py library that do not start with _ are exported (or just the ones listed in __all__); functions are wrapped under library.name and constants are converted:

from text import join

output(join(["a", "b", "c"], "-"))
# core/libs/text.py
def join(items, separator):
    return separator.join(items)

Python values that do not fit the table above are wrapped in PythonObject instead of leaking a bare object into the evaluator. Their attributes can be read and their methods called, with the same conversions on arguments and results:

from cdll import load_dll

var dll = load_dll("path/to/SimpleFunction.dll")
output(dll.add(1, 2))

A missing attribute is a NameError, and exceptions raised by Python stay RuntimeError.

The other direction uses EPScript.load, and names defined by the script can be called as Python values:

import EPScript

script = EPScript.load("examples/18_bridge.eps")
print(script.call("double", 21))              # 42
print(script.call("describe", "EPScript"))    # hello, EPScript

load runs the whole file once and returns a Script; call converts arguments and the result, get reads a top-level name as a Python value (a function stays an EPScript Function, use call for it). Hosts that need the conversions directly can use to_python and to_epscript from the bridge.

Chinese keywords and punctuation

Chinese mode accepts English keywords as well, so both can appear in one file. ASCII mode is strict: a full-width bracket there is reported as a non-registered symbol. Identifiers may be Chinese in either mode.

ASCII Chinese Use
var 设置 declare or assign
true 真 boolean literal
false 假 boolean literal
null 空 null literal
if 如果 conditional
else 否则 else branch
function 函数 declare a function
for 循环 counted loop
from 从 loop start, source of an import
to 到 loop end
step 每次 loop step
while 重复当 conditional loop
break 停止 leave the innermost loop
continue 跳过 skip to the next iteration
return 返回 leave a function with a value
class 类 declare a class
self 自身 the instance inside a method
super 父类 the parent of the class that defines the method
abstract 抽象 declare a method without an implementation
static 静态 declare a method on the class, not the instance
extends 继承 name the parent class
import 导入 take names out of a module
as 作为 rename an imported name
and 并且 logical and, also &
or 或者 logical or, also |
not 非 logical not, also !
could 能否 honorific, see "Politeness optimization"
you 您 honorific, see "Politeness optimization"
please 请 honorific, see "Politeness optimization"
kindly 恳请 honorific, see "Politeness optimization"

Punctuation is mapped one to one:

ASCII Chinese ASCII Chinese
( ) ( ) [ ] 【 】
{ } 「 」 , ,
. 。 : :
; ; < > 《 》
" “ ” ' ‘ ’
! !

Operators such as =, +, -, *, /, % and &, | stay ASCII in both modes. 。 is the member-access dot, so 甲。添加(1) is the Chinese spelling of a.append(1). ? stays ? in both modes; Chinese mode also accepts the full-width ?, as in ?(1,2).

The example below is examples/09_factorial.epsc; it prints 1! = 1 through 5! = 120.

函数 阶乘(甲) 「
    如果 (甲 《= 2) 「
        返回 甲
    」
    返回 甲 * 阶乘(甲 - 1)
」

循环 已 从 1 到 5 「
    输出(文本(已) + “! = ” + 文本(阶乘(已)))
」

Errors

Failures are reported in the shape of a Python traceback, with the offending source line and a caret under the token that caused it:

TrackingException/s (the most recent call raised)
  File 'demo.eps', line 2, in '<module>'
        output(toatl)
                ^^^^^
NameError: 'toatl' is not defined

The output is coloured with ANSI escapes and follows East Asian character widths, so the caret stays aligned under Chinese source. The REPL switches the Windows console into VT mode before the first prompt.

Class Raised when
SyntaxError The parser cannot match the grammar.
RegistrationError The lexer meets a character it does not know.
TypeError An operand or argument has the wrong type.
ValueError Division or modulo by zero, or an index outside a value.
NameError Reading or reassigning an undeclared name.
OverflowError A number leaves the Decimal range.
FileNotFoundError run or from cannot find the file.
RuntimeError A file loaded by run or from failed, or a Python function raised.
ProgramInternalBugError The evaluator itself raised; that is a bug in EPScript, not in the program being run.

Project layout

EPScript/
├── __init__.py            REPL entry point and run() helper
├── core/
│   ├── __init__.py        interpret(): lex, parse, evaluate
│   ├── token/             lexer, token types, keyword tables
│   ├── parser/            recursive-descent parser and AST nodes
│   ├── interpreter/       evaluator, value types, built-ins
│   ├── cache.py           disk cache for rate optimization
│   ├── bridge/            the Python compatibility layer
│   ├── libs/              built-in libraries (EPScript and Python)
│   └── exception/         error classes and the traceback renderer
├── idle/
│   ├── __init__.py        editor window, menus, file handling
│   ├── editing/           auto pairs, snippets, comments, bracket match
│   ├── highlight/         token colouring and bracket colouring
│   ├── completion/        Ctrl+Space popup
│   ├── preference/        font and colour dialog
│   ├── run/               run window, isolated scope, readline
│   ├── settings.json      default colours, font and indent
│   └── config.json        what the preference dialog writes
├── examples/              the programs used in this README
├── bench/                 benchmark script (fib, loops, calls, imports)
└── TestUnits/             older scratch programs

Status

Everything documented above was run against the current source. What is left is design that has not been built, not defects:

Missing Notes
element assignment only dictionaries have d[key] = value; array elements still have no assignment syntax and grow with + and append
inheritance, class-level fields one parent per class; static covers methods, not fields
packages and module objects from only takes names out of one file; there are no package directories and no module value with members
Python containers and objects Python dicts are wrapped in PythonObject, so only attributes and methods work, not indexing; the language has its own dictionary type
pointers only variables and memory() cells can be addressed; array elements, fields and function results cannot
politeness switch off by default; enable with core.set_politeness(True) or politeness_enabled=True
offline cache on by default; turn it off with set_cache(false), file .epscript_cache.json in the working directory
function cache only automatically detected pure functions; calls with side effects, outside variables or non-scalar arguments/return values are not cached
cache LRU 4096 entries by default; use set_cache_size(n) to change the limit
rate optimization accumulator loops fold by formula; pure scalar loops cache their final state; normal code caches after the first run, polite code folds immediately, or else! does not optimize
Schrödinger values collapse is random, with no weights, seed or "keep the superposition" switch
open-ended subscript a[:3] needs a first index, a[0:3] works
command-line runner .eps files run through run() or core.interpret
test suite TestUnits/ holds two sample programs, not tests
packaging no pyproject.toml; the repository itself is the package

About

A Turing Completeness Programming Language with Chinese PL. 一个带中文编程的图灵完备编程语言

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages