Initial PROTEL 2026 toolchain import

This commit is contained in:
2026-06-08 18:04:03 -05:00
commit 98a0bb329d
125 changed files with 12223 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
.venv/
__pycache__/
*.pyc
.pytest_cache/
build/
a.out
*.o
legacy/
*~
.*~
+84
View File
@@ -0,0 +1,84 @@
# AGENTS.md - PROTEL 2026 Project Instructions
You are an expert PROTEL language engineer and compiler developer assisting Vincente D'Ingianni with the **PROTEL 2026** revival project.
## Project Overview
- **Goal**: Modern revival of the PROTEL programming language (originally used in Nortel/DMS telecom switches).
- **Key Features**:
- Lark parser with OO (Object-Oriented) extensions.
- Transpiler to GCC-compatible C/C++ (or direct GCC integration).
- Case-sensitive identifiers by default.
- UPPERCASE keywords by default.
- `--classical` flag to support original legacy PROTEL syntax/behavior.
- Full language reference manual (Markdown, authored under Vincente's name).
- The new transpiler and all related tools should work on MacOS and UNIX / Linux with absolutely minimal dependencies.
- PROTEL integration with C/C++, Swift, and RUST should be supported, as well as any other language that uses the gcc compiler backend.
- Compiler and tool invocation should follow example in "PROTEL 2026 Development Tools" from the Introductory or Reference Manual.
- Implement the Protel Beautifier and EMACS PROTEL mode as per "PROTEL 2026 Development Tools" from the Introductory or Reference Manual.
## Core Responsibilities
- Maintain strict compatibility with historical PROTEL semantics where possible.
- Implement modern OO extensions cleanly without breaking legacy code.
- Generate high-quality, readable, and efficient C/C++ output suitable for GCC.
- Ensure the parser, transpiler, and runtime are robust, well-documented, and testable.
- Prioritize reproducibility and self-hosting (FOSS-friendly).
## Coding & Architecture Standards
- **Language**: Prefer modern C++ (C++20/23) for the toolchain itself.
- **Parser**: Lark (or equivalent modern parser generator). Keep grammar clean and extensible.
- **Transpiler**:
- Output clean, commented C/C++ code.
- Preserve original PROTEL structure where it aids debugging.
- Support modular compilation (dynamic linkable modules if applicable).
- **Style**:
- Use examples from PROTEL Introductory Manual 2026.pdf and PROTEL Reference Manual 2026.pdf
- Keywords should be in UPPERCASE (and BOLD where appropriate).
- Comprehensive error handling and diagnostics.
- Unit tests for parser rules, transpilation edge cases, and legacy compatibility.
- PROTEL example files should use the .protel extension (legacy Nortel sources may use .P or PLS edition suffixes .AA01 through .ZZ99).
- Indentation should be structured like Pascal.
- There should be no spaces between PROC and the first parenthesis - PROC(
- There should be no spaces between TABLE and the first brace - TABLE[
- There should be no spaces between DESC and the first brace - DESC[
- I/O should NOT be INTRINSIC. It should not use #include <iostream>. Output from the PROTEL transpiler should have extremely small memory requirements. Allow and demonstrate EXTERNAL C calls to I/O functions.
- **Project Structure** (suggested):
.
├── src/ # Core parser, transpiler, codegen
├── include/ # Headers
├── tests/ # Comprehensive test suite
├── examples/ # Legacy + modern PROTEL examples
├── docs/ # Reference manual (Markdown)
├── AGENTS.md # This file
├── README.md
└── CMakeLists.txt / Makefile (or equivalent build system)
## Build & Test Commands
- Build: `make` or `cmake --build build/`
- Test: Run full test suite (parser + transpiler validation)
- Classical mode: `./protel --classical example.ptl`
- Modern mode: `./protel example.ptl`
- Runnable sources: first line `#!/usr/bin/env protel-run`, `chmod +x`, project dir on `PATH` (`$PWD` or `$HOME/PROTEL`, not quoted `~/PROTEL`); preprocessor strips `#!` before parse (§7.0.5)
- Generate a test suite of PROTEL code covering all features and examples code in PROTEL Introductory Manual 2026.pdf and PROTEL Reference Manual 2026.pdf. Label test code so it can be correlated to sections of the Introductory Manual and Reference Manual.
- Compiler and tool invocation should follow example in "PROTEL 2026 Development Tools" from the Introductory or Reference Manual.
## Workflow Guidelines
1. Always review existing files before making changes.
2. Propose clear step-by-step plans for complex features.
3. Maintain backward compatibility unless explicitly instructed.
4. Document all new language features in the reference manual.
5. Use `--classical` flag to toggle legacy behavior.
6. Focus on telecom-grade reliability and performance.
## Additional Context from Grok Project
- This project was developed iteratively in Grok conversations.
- Emphasis on preserving Nortel/PROTEL heritage while adding modern capabilities.
- Target use cases: Legacy system maintenance, education, and potential new telecom/embedded applications.
Follow these instructions strictly in all interactions within this project directory. Ask for clarification only when necessary. Prioritize precision, historical fidelity, and clean modern engineering.
+63
View File
@@ -0,0 +1,63 @@
PYTHON ?= .venv/bin/python
PIP ?= .venv/bin/pip
.PHONY: all venv install test examples hello beautify interop-swift interop-rust interop-python interop-java clean
all: venv test
venv:
python3 -m venv .venv
$(PIP) install -q -r requirements.txt
$(PIP) install -q -r requirements-dev.txt
install: venv
chmod +x protel protel-run Pb examples/Hello.protel
@echo "PROTEL 2026 tools installed."
@echo " Compile/run: ./protel examples/Hello.protel --run"
@echo " Direct run: export PATH=\"$$(pwd):$$PATH\" && ./examples/Hello.protel"
@echo " (use \$$PWD or \$$HOME/PROTEL in PATH — quoted ~/PROTEL does not expand)"
test: venv
$(PYTHON) -m pytest tests/ -v
examples: venv
@for f in examples/*.protel; do \
echo "=== $$f ==="; \
$(PYTHON) protel "$$f" --emit-c -o "build/$$(basename $$f .protel).c"; \
done
hello: venv
chmod +x examples/Hello.protel
$(PYTHON) protel examples/Hello.protel -o build/Hello --run
hello-p: venv
$(PYTHON) protel examples/Hello.P -o build/Hello.P --run
hello-pls: venv
$(PYTHON) protel examples/Hello.aa01 -o build/Hello.aa01 --run
vdi: venv
$(PYTHON) protel vdi.aa01 -c -o build/vdi.aa01.o
beautify: venv
$(PYTHON) Pb examples/Hello.protel build/Hello.pretty.protel
interop-swift: venv
chmod +x examples/interop/build_interop.sh
examples/interop/build_interop.sh
interop-rust: venv
chmod +x examples/interop/build_interop_rust.sh
examples/interop/build_interop_rust.sh
interop-python: venv
chmod +x examples/interop/build_interop_python.sh
examples/interop/build_interop_python.sh
interop-java: venv
chmod +x examples/interop/build_interop_java.sh
examples/interop/build_interop_java.sh
clean:
rm -rf .venv __pycache__ src/__pycache__ tests/__pycache__ .pytest_cache build/a.out build/interop
find . -name '*.pyc' -delete
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
Executable
+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""
Pb - PROTEL Beautifier
A lexical beautifier for PROTEL (Procedure Oriented Type Enforcing Language)
originally created in the 1990s, then recreated in 2026, by Vincente D'Ingianni, vincente@binary-systems.com.
Reads PROTEL source from a file or standard input (supports redirection, pipes,
and explicit filename arguments for both input and output).
A first-line UNIX shebang (``#!...``) is preserved unchanged for runnable
``.protel`` programs (see Introductory Manual section 7.0.5).
Performs lexical analysis:
- Recognizes comments starting with % (to end of line). Keywords inside comments are ignored.
- Recognizes strings delimited by single quotes ('' for embedded quote). Keywords inside strings are ignored.
- All other text is tokenized.
- Any token that matches a reserved keyword (from the official list in the
PROTEL Reference Manual Appendix A) is forced to UPPERCASE.
- Lines that start with $LI (linker directives) are uppercased in full.
- Optionally, keywords can be wrapped in ANSI bold escapes (--bold).
Non-keyword identifiers, numbers, operators, and all formatting/whitespace are
preserved exactly.
The program attempts to determine whether the input "is PROTEL" by counting
recognized reserved keywords. If very few are found it emits a warning on stderr
but still outputs the (minimally modified) text.
Keyword list is derived directly from the Reference Manual (Appendix A) and
Introductory Manual + the original oflpr/oflpi sources.
Usage examples:
cat myprog.protel | Pb
Pb --bold < myprog.protel > pretty.protel
./Pb --bold < example.txt
Pb myprog.protel > pretty.protel
Pb myprog.protel pretty.protel
Pb < myprog.protel | less
Shebang makes it directly executable after chmod +x Pb
"""
import sys
import re
import argparse
# Official PROTEL Reserved Keywords (Reference Manual Appendix A / oflpr / oflpi)
PROTEL_KEYWORDS = {
"$EJECT",
"$LI",
"$OBJECT",
"$REFDESC",
"$TYPEDESC",
"$UNIVERSAL_PTR",
"$VARDESC",
"AREA",
"AS",
"BIND",
"BLOCK",
"BOOL",
"BY",
"CASE",
"CAST",
"CLASS",
"DCL",
"DEFINITIONS",
"DESC",
"DO",
"DOWN",
"ELSE",
"ENDAREA",
"ENDBLOCK",
"ENDCASE",
"ENDCLASS",
"ENDDO",
"ENDIF",
"ENDOVLY",
"ENDSELECT",
"ENDSTRUCT",
"ENTRY",
"EXIT",
"EXTERNAL",
"EXPORT",
"FALSE",
"FAST",
"FOR",
"FORWARD",
"FROM",
"IF",
"IN",
"INCL",
"INIT",
"INTERFACE",
"INTRINSIC",
"IS",
"LITERAL",
"METHOD",
"MOD",
"NIL",
"NONTRANSPARENT",
"NOTINCL",
"OF",
"OPERAND",
"OPERATIONS",
"OUT",
"OVER",
"OVLY",
"PACK",
"PERPROCESS",
"PRIVATE",
"PROC",
"PROTECTED",
"PTR",
"QUICK",
"REF",
"REFDESC",
"REFINES",
"RETURN",
"RETURNS",
"SECTION",
"SELECT",
"SELF",
"SET",
"SHARED",
"STRUCT",
"TABLE",
"TDSIZE",
"THEN",
"TO",
"TRUE",
"TYPE",
"TYPEDESC",
"UNRESTRICTED",
"UP",
"UPB",
"UPDATES",
"USES",
"VAL",
"VARDESC",
"VARIABLE",
"WHILE",
"WITH",
}
KEYWORD_RE = re.compile(
r'\b(' + '|'.join(sorted(PROTEL_KEYWORDS, key=len, reverse=True)) + r')\b',
re.IGNORECASE
)
ANSI_BOLD = '\033[1m'
ANSI_RESET = '\033[0m'
def is_likely_protel(keyword_count: int, total_ident_count: int) -> bool:
if keyword_count >= 2:
return True
if total_ident_count > 0 and (keyword_count / max(1, total_ident_count)) >= 0.1:
return True
return False
def is_dollar_li_line(line: str) -> bool:
"""True when line begins with a $LI linker directive (after optional indent)."""
stripped = line.lstrip()
return len(stripped) >= 3 and stripped[:3].upper() == "$LI"
def uppercase_dollar_li_line(line: str) -> str:
"""Uppercase an entire $LI linker directive line, preserving the line ending."""
ending = ""
body = line
if line.endswith("\r\n"):
ending = "\r\n"
body = line[:-2]
elif line.endswith("\n"):
ending = "\n"
body = line[:-1]
elif line.endswith("\r"):
ending = "\r"
body = line[:-1]
return body.upper() + ending
def find_comment_start(code_part: str) -> int:
"""
Find the position of the first % that starts a comment in 'code_part',
respecting strings (but we assume code_part has no outer strings here).
Very simple: first unquoted % .
"""
in_string = False
i = 0
while i < len(code_part):
c = code_part[i]
if c == "'":
in_string = not in_string
# handle '' escape
if in_string and i + 1 < len(code_part) and code_part[i+1] == "'":
i += 1
elif c == '%' and not in_string:
return i
i += 1
return -1
def beautify_protel(source: str, use_bold: bool = False) -> str:
output_parts = []
keyword_count = 0
ident_count = 0
# Process line by line so we can cleanly separate "code before %" from comments
lines = source.splitlines(keepends=True)
shebang_line = ""
if lines and lines[0].startswith("#!"):
shebang_line = lines[0]
lines = lines[1:]
for line in lines:
if is_dollar_li_line(line):
output_parts.append(uppercase_dollar_li_line(line))
keyword_count += 1
continue
# Find the first % that is not inside a string on this line
# We scan for strings and % manually per line (simple and reliable)
code_part = line
comment_part = ''
comment_pos = find_comment_start(line)
if comment_pos != -1:
code_part = line[:comment_pos]
comment_part = line[comment_pos:]
# Tokenize the code_part with the existing spec (no COMMENT now)
line_code_out = []
for match in TOKEN_RE.finditer(code_part):
kind = match.lastgroup
token = match.group()
if kind == 'STRING':
line_code_out.append(token)
elif kind == 'KEYWORD_ID':
ident_count += 1
upper = token.upper()
if upper in PROTEL_KEYWORDS:
keyword_count += 1
if use_bold:
line_code_out.append(f"{ANSI_BOLD}{upper}{ANSI_RESET}")
else:
line_code_out.append(upper)
else:
line_code_out.append(token)
else:
line_code_out.append(token)
output_parts.append(''.join(line_code_out) + comment_part)
result = ''.join(output_parts)
if shebang_line:
result = shebang_line + result
if not is_likely_protel(keyword_count, ident_count):
sys.stderr.write(
f"Pb: Warning - only {keyword_count} PROTEL keywords detected "
f"(out of ~{ident_count} identifiers). "
"Input may not be PROTEL source.\n"
)
return result
# Token spec (used only on the "code" portion after comment stripping)
TOKEN_SPEC = [
('STRING', r"'(?:''|[^'])*'"),
('KEYWORD_ID',r'[A-Za-z_$][A-Za-z0-9_$]*'),
('NUMBER', r'\d+(?:\.\d+)?(?:[eE][+-]?\d+)?'),
('OP_SYM', r'->|::=|[<>=!&|/*%+-]+|[\(\)\[\]\{\},;:\.\^]'),
('WHITESPACE',r'[ \t\r\n]+'),
('OTHER', r'.'),
]
TOKEN_RE = re.compile(
'|'.join(f'(?P<{name}>{pattern})' for name, pattern in TOKEN_SPEC),
re.IGNORECASE | re.DOTALL
)
def main():
parser = argparse.ArgumentParser(
description="Pb - PROTEL Beautifier. Uppercases reserved keywords in "
"PROTEL source. Supports stdin/stdout, redirection, and "
"file arguments for input/output. Optionally adds bold.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__
)
parser.add_argument('-b', '--bold', action='store_true',
help='Wrap keywords in ANSI bold (\\033[1m ... \\033[0m)')
parser.add_argument('--version', action='version',
version='Pb 1.0 (PROTEL Beautifier)')
parser.add_argument('input', nargs='?', default='-',
help='Input PROTEL file (default: read from stdin). '
'Use "-" to explicitly read from stdin.')
parser.add_argument('output', nargs='?', default='-',
help='Output file (default: write to stdout). '
'Use "-" to explicitly write to stdout.')
args = parser.parse_args()
# Read source
if args.input == '-':
try:
source = sys.stdin.read()
except (KeyboardInterrupt, BrokenPipeError):
sys.exit(0)
else:
try:
with open(args.input, 'r', encoding='utf-8', errors='replace') as f:
source = f.read()
except OSError as e:
sys.stderr.write(f"Pb: Error reading input file '{args.input}': {e}\n")
sys.exit(1)
if not source:
return
beautified = beautify_protel(source, use_bold=args.bold)
# Write output
if args.output == '-':
try:
sys.stdout.write(beautified)
sys.stdout.flush()
except BrokenPipeError:
sys.exit(0)
else:
try:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(beautified)
except OSError as e:
sys.stderr.write(f"Pb: Error writing output file '{args.output}': {e}\n")
sys.exit(1)
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
# 5.5.2 UNIX Command Line and Shell Exit Status
**PROTEL Introductory Manual 2026** — Vincente D'Ingianni
---
## 5.5.2 UNIX `argc` / `argv` and `RETURN` as Exit Status
On macOS and UNIX/Linux hosts, a standalone program's **IS ENTRY** procedure may receive the host command-line argument count and vector. A **RETURN** from an ENTRY body declared **RETURNS integer** becomes the process exit status observed by the shell (`echo $?`).
### Entry declaration
The **IS ENTRY** forward declaration may use the standard UNIX parameter list:
```protel
DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;
```
The procedure body must use the same parameter list. To propagate a status to the shell, declare **RETURNS integer** on the body:
```protel
DCL Start PROC(argc integer, argv PTR TO PTR TO char) RETURNS integer IS
BLOCK
...
RETURN status;
ENDBLOCK;
```
Programs without command-line arguments continue to use the classical form from §5.5.2:
```protel
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
...
ENDBLOCK;
```
### Generated host `main`
The C++ transpiler emits a POSIX `main` that forwards `argc` and `argv` and returns the ENTRY result:
```cpp
int main(int argc, char** argv) {
return protel_generated::ArgsExit::Start(argc, argv);
}
```
When the ENTRY body does not **RETURNS integer**, the wrapper calls the procedure and returns `0`.
### Example: `examples/intro_5_5_2_args_exit.protel`
This module prints each command-line argument (including the program name) and **RETURN**s `argc` as the exit status.
Build and run:
```bash
./protel examples/intro_5_5_2_args_exit.protel -o build/ArgsExit --run -- one two
echo $?
```
Arguments after `--` are forwarded to the compiled program when using **`--run`**.
Expected output:
```
build/ArgsExit
one
two
```
Expected exit status: `3` (program name plus two arguments).
### I/O
Command-line demonstration uses **EXTERNAL** C linkage to the minimal POSIX runtime (`writeln` in `src/runtime/protel_io.c`). I/O is not **INTRINSIC** and the transpiler does not emit `#include <iostream>`.
### See also
- §7.0 — **PROTEL 2026 Development Tools** (`protel` driver, `--run`)
- §7.0.5 — **Runnable `.protel` files (shebang)** — direct execution with `#!/usr/bin/env protel-run`
- Reference Manual §13 — **EXPORT** / **EXTERNAL** (ENTRY vs library procedures)
+139
View File
@@ -0,0 +1,139 @@
# 7.0 PROTEL 2026 Development Tools
**PROTEL Introductory Manual 2026** — Vincente D'Ingianni
---
## 7.0 PROTEL 2026 Development Tools
The PROTEL 2026 toolchain ships with a small set of command-line and editor tools intended for macOS and UNIX/Linux hosts with minimal dependencies.
| Tool | Section | Summary |
|------|---------|---------|
| **`protel`** | §7.1 | Parser, transpiler, and compiler driver |
| **`Pb`** | §7.0.1 | Source beautifier (keyword uppercasing) |
| **`protel-mode`** | §7.2 | GNU Emacs major mode for `.protel`, `.pt`, `.ptl`, legacy `.P`, and PLS `.AA01`–`.ZZ99` files |
---
## 7.0.1 Pb — PROTEL Beautifier
`Pb` uppercases PROTEL reserved keywords for readable, manual-style source. It is a filter-style tool:
```bash
Pb examples/Hello.protel build/Hello.pretty.protel
Pb --bold < myprog.protel > myprog.pretty.protel
```
Install with `make install` (marks `Pb` executable). See `Pb --help` for options.
In Emacs, run Pb on the current buffer with **`C-c C-f`** (`M-x protel-beautify`) — see Introductory Manual §7.2.
---
## 7.0.2 PLS edition modules (`.AA01` … `.ZZ99`)
Historical DMS/PLS modules use edition suffixes such as `vdi.aa01`. The `protel` driver **automatically enables classical preprocessing** for these names (keyword normalization, `$LI` / `$EJECT` linker directives stripped before parse).
```bash
protel vdi.aa01 -c -o build/vdi.aa01.o
make vdi
```
---
## 7.0.3 Type errors and `examples/errors/`
The transpiler performs **strong typing** checks (Reference Manual §11.3). Invalid assignments — such as storing an **integer** into **char** or a **PACK** byte — are rejected before code generation. See `docs/reference-error-messages.md` and `examples/errors/`.
```bash
./protel examples/errors/err_assign_integer_to_char.protel
./protel examples/errors/ok_assign_char_literal.protel -o build/ok_char
```
---
## 7.0.4 UNIX command line and exit status
Standalone programs may read **`argc`** and **`argv`** in the **IS ENTRY** procedure and **RETURN** an integer exit status to the shell. See Introductory Manual §5.5.2 (`docs/intro-5-5-2-entry-args-exit.md`) and `examples/intro_5_5_2_args_exit.protel`.
```bash
./protel examples/intro_5_5_2_args_exit.protel -o build/ArgsExit --run -- one two
echo $?
```
---
## 7.0.5 Runnable `.protel` files (shebang)
A PROTEL source file may be executed directly from the shell when:
1. **Line 1** is a UNIX shebang (`#!...`) naming **`protel-run`** (or `protel --run` via `env -S`).
2. The file is **executable** (`chmod +x`).
3. The PROTEL project directory is on your **`PATH`** so `protel-run` (or `protel`) is found.
The shebang is **not** PROTEL syntax. The preprocessor removes it before parse; **`Pb`** preserves it unchanged when beautifying.
`examples/Hello.protel` demonstrates the usual form:
```protel
#!/usr/bin/env protel-run
% Hello World — run with: ./Hello.protel
SECTION Hello;
...
```
**`protel-run`** is a small helper in the project root. The kernel runs `protel-run /path/to/script.protel [args]`; the helper invokes `protel script.protel --run -- [args]`.
### Setup
From the PROTEL project directory:
```bash
make install
export PATH="$PWD:$PATH"
./examples/Hello.protel
```
From any directory (replace with your checkout path):
```bash
export PATH="$HOME/PROTEL:$PATH"
~/PROTEL/examples/Hello.protel
```
`make install` marks `protel`, `protel-run`, `Pb`, and `examples/Hello.protel` executable.
**PATH pitfall:** `export PATH="~/PROTEL:$PATH"` does **not** work — the shell does not expand `~` inside double quotes, so `env` cannot find `protel-run`. Use **`$PWD`**, **`$HOME/PROTEL`**, or an absolute path instead.
### ENTRY programs with arguments
Add the same shebang to programs such as `examples/intro_5_5_2_args_exit.protel`, then:
```bash
chmod +x examples/intro_5_5_2_args_exit.protel
./examples/intro_5_5_2_args_exit.protel one two
```
The kernel invokes `protel --run -- script.protel one two`. The driver promotes the script path from after **`--`** to the input positional, then forwards **`one`** and **`two`** to the ENTRY procedure.
### Notes
| Topic | Detail |
|-------|--------|
| `%` comments | Cannot replace the shebang; the kernel only recognizes `#!` at the start of the file |
| **`Pb`** | Copies line 1 unchanged when it begins with `#!` |
| **`protel-mode`** | Displays the shebang line with `protel-comment-face` (§7.2) |
| **Parser** | `strip_shebang()` in `src/preprocess.py` runs before keyword normalization |
| **Output binary** | Default `a.out` in the current working directory (same as `protel … --run`) |
| `env: protel: No such file or directory` | **`PATH` wrong** — avoid quoted `~/PROTEL`; use `export PATH="$PWD:$PATH"` from the repo or `export PATH="$HOME/PROTEL:$PATH"` |
---
## See also
- §11.3 — **Type errors** (`docs/reference-error-messages.md`)
- §5.5.2 — **UNIX argc/argv and shell exit status**
- §7.0.5 — **Runnable `.protel` files (shebang)**
- §7.2 — **EMACS PROTEL mode** (`.emacs` setup; automatic `.protel`, `.P`, and PLS suffix detection)
- §7.3 — Foreign language interoperability
+237
View File
@@ -0,0 +1,237 @@
# 7.2 EMACS PROTEL Mode
**PROTEL Introductory Manual 2026** — Vincente D'Ingianni
---
## 7.2 EMACS PROTEL Mode
The PROTEL 2026 distribution includes **EMACS PROTEL mode** for GNU Emacs. It provides:
- **Keyword highlighting** for PROTEL 2026 reserved words (UPPERCASE keywords per the Reference Manual)
- **Comment** recognition (`%` to end of line)
- **String** highlighting (single-quoted PROTEL strings)
- **Pascal-style indentation** for `BLOCK` / `ENDBLOCK`, `IF` / `ENDIF`, and related structures
The mode file is `emacs/protel-mode.el` in the PROTEL project tree. It honors Bill Conn, original author of EMACS PROTEL mode at Nortel/BNR.
---
## 7.2.1 Enabling PROTEL mode in `.emacs`
The PROTEL tree includes a ready-made **`.emacs`**. You may use it in either of these ways:
**Option A — copy to `~/.emacs` (recommended)**
```bash
cp /path/to/PROTEL/.emacs ~/.emacs
```
Edit the copy once and set your checkout path (required when the file is not inside the PROTEL tree):
```elisp
(setq protel-user-root "/path/to/PROTEL")
```
The project `.emacs` also searches, in order: `PROTEL_ROOT` environment variable, the directory containing this init file (if it still lives inside PROTEL), the `protel` executable on your `PATH`, then `~/PROTEL`.
**Option B — load from the project directory**
```bash
cd /path/to/PROTEL
emacs -l .emacs
```
When `.emacs` remains inside the PROTEL tree, `protel-root` is discovered automatically.
After Emacs loads this block, `protel-mode` is available and **file-name detection is automatic** for:
| Extension | Mode started |
|-----------|--------------|
| `.protel` | `protel-mode` |
| `.pt` | `protel-mode` |
| `.ptl` | `protel-mode` |
| `.P` | `protel-mode` (legacy Nortel/BNR suffix; case-sensitive match) |
| `.AA01` … `.ZZ99` | `protel-mode` (PLS edition suffix: two letters + two digits) |
The PLS pattern matches any extension of the form **`.LLNN`** where `L` is a letter (`A`–`Z` or `a`–`z`) and `N` is a decimal digit. Examples: `vdi.aa01`, `module.AB18`, `Hello.aa01`.
No extra `auto-mode-alist` configuration is required in `.emacs`; `protel-mode.el` registers these extensions when it is loaded.
### Optional: user-wide install
To install the mode once under your home directory instead of pointing at the project tree:
```bash
mkdir -p ~/.emacs.d/lisp
cp /path/to/PROTEL/emacs/protel-mode.el ~/.emacs.d/lisp/
```
Then in `.emacs`:
```elisp
(add-to-list 'load-path "~/.emacs.d/lisp")
(require 'protel-mode)
```
---
## 7.2.2 Verifying automatic detection
1. Restart Emacs (or evaluate the `.emacs` block with `M-x eval-buffer`).
2. Open a PROTEL source file, for example `examples/Hello.protel`, legacy `examples/Hello.P`, or PLS `examples/Hello.aa01`.
3. Confirm the mode line shows **`PROTEL`** (not `Fundamental`).
4. Alternatively, run `M-x describe-mode` — it should report `protel-mode`.
To enable the mode manually on the current buffer (for example, a buffer without a recognized extension):
```
M-x protel-mode RET
```
---
## 7.2.3 Syntax highlighting and faces
`protel-mode` uses Emacs **Font Lock** to highlight keywords, comments, and strings. The mode does **not** hard-code RGB colors in the buffer; it assigns syntax classes to named **faces**, and Emacs (or your color theme) supplies the actual display attributes.
| Syntax | Face | Default appearance |
|--------|------|------------------|
| Reserved keywords | `protel-keyword-face` | **Bold white** (via `face-remap` from `font-lock-keyword-face`) |
| `%` comments | `protel-comment-face` | *Green italic* |
| `#!` shebang (line 1) | `protel-comment-face` | *Green italic* (runnable scripts, §7.0.5) |
| `'...'` strings | `protel-string-face` | Orange (inherits theme string color) |
Font Lock applies the standard `font-lock-*` faces; `protel-mode` **remaps** them to `protel-*` faces so highlighting works reliably and you can customize colors with `set-face-attribute` or `M-x customize-face`.
The project `.emacs` in the PROTEL distribution loads `protel-mode`, enables global Font Lock, and sets the `protel-*` face colors (bold keywords, green italic comments).
### Customizing colors in `.emacs`
Override any face after loading the mode:
```elisp
(with-eval-after-load 'protel-mode
;; Bold keywords (default)
(set-face-attribute 'protel-keyword-face nil :weight 'bold)
;; Green italic comments (default)
(set-face-attribute 'protel-comment-face nil
:foreground "green"
:slant 'italic)
;; Optional: softer green on dark backgrounds
;; (set-face-attribute 'protel-comment-face nil :foreground "dark olive green"))
```
Use `M-x customize-face RET protel-comment-face RET` to adjust interactively.
### Beautify with Pb
`protel-mode` pipes the buffer (or active region) through **Pb**, the PROTEL beautifier (keyword uppercasing per the Reference Manual).
| Key | Command | Action |
|-----|---------|--------|
| `C-c C-f` | `protel-beautify` | Beautify region, or whole buffer if no region |
| `C-c C-b` | `protel-beautify` | Same (mnemonic: **b**eautify / **P**b) |
| `TAB` | `protel-indent-line` | Indent current line (Pascal style) |
| `C-M-\` | `indent-region` | Indent active region (built-in) |
**Why `C-c C-f`?** In Emacs language modes, `C-c` is the standard mode-specific prefix. **`C-c C-f`** is widely used for *format* / *beautify*:
| Mode | `C-c C-f` |
|------|-----------|
| `go-mode` | `gofmt` |
| `rust-mode` | `rustfmt` |
| `csharp-mode` | reformat |
| Many `clang-format` setups | format buffer/region |
PROTEL follows that convention. `C-c C-b` is a secondary mnemonic binding for Pb.
Pb must be on your `PATH`, or set in `.emacs`:
```elisp
(setq protel-root "/path/to/PROTEL")
;; optional:
(setq protel-beautify-command "/path/to/PROTEL/Pb")
(setq protel-beautify-extra-args "--bold") ; ANSI bold keywords on stdout
```
### Other options
| Variable | Default | Purpose |
|----------|---------|---------|
| `protel-indent-offset` | `3` | Spaces to indent nested block bodies |
| `protel-beautify-command` | *(auto)* | Path to Pb |
| `protel-beautify-extra-args` | `""` | Extra Pb flags (e.g. `--bold`) |
Example:
```elisp
(with-eval-after-load 'protel-mode
(setq protel-indent-offset 3
protel-root "/path/to/PROTEL"))
```
---
## 7.2.4 Terminal Emacs (emacs-nox / `emacs -nw`)
**PROTEL mode works in terminal Emacs** — no GUI or X11 required. This includes **emacs-nox** on Linux and **`emacs -nw`** in macOS Terminal or iTerm.
| Feature | Terminal support |
|---------|------------------|
| `protel-mode` auto-detection | Yes |
| Pascal-style **indentation** (`TAB`, `protel-indent-offset`) | Yes |
| **Bold** keywords | Yes (terminal bold attribute; macOS Terminal and iTerm support this) |
| Comment **colors** | Yes (green foreground on tty) |
| Comment *italic* | Optional — many terminals ignore italic; color still applies |
| Strings / other faces | Yes (terminal color palette) |
From the PROTEL project directory:
```bash
emacs -nw -l .emacs examples/Hello.protel
```
On Linux with a separate nox build:
```bash
emacs-nox -l /path/to/PROTEL/.emacs /path/to/PROTEL/examples/Hello.protel
```
Ensure **Font Lock** is on (`M-x font-lock-mode` or `(global-font-lock-mode 1)` in `.emacs`, already set in the project file). If keywords are not bold, verify your terminal profile allows bold text (Terminal.app: Settings → Profiles → Text → “Use bold fonts”).
---
## 7.2.5 Requirements
- **GNU Emacs** 26.1 or later (lexical binding is enabled in `protel-mode.el`)
- **`cc-mode`** — included with standard Emacs and emacs-nox packages; `protel-mode` requires it for derived-mode support
---
## 7.2.6 Related development tools
| Tool | Manual section | Purpose |
|------|----------------|---------|
| `protel` | §7.1 | Transpile and compile PROTEL sources |
| `Pb` | §7.0 | Beautify / uppercase keywords |
| `protel-mode` | §7.2 (this section) | Emacs editing support |
For foreign-language linking from PROTEL, see §7.3.
---
## 7.2.7 Troubleshooting
| Symptom | Likely cause | Remedy |
|---------|--------------|--------|
| `Cannot open load file: protel-mode` | `load-path` does not include `emacs/` | In `~/.emacs`, set `(setq protel-user-root "/path/to/PROTEL")` |
| `PROTEL mode not loaded` warning at startup | Copied `~/.emacs` without checkout path | Set `protel-user-root` in `~/.emacs`, or add PROTEL `protel` to `PATH` |
| `Cannot find Pb` on beautify | Pb not on PATH | Set `protel-root` or `protel-beautify-command` after mode loads |
| Buffer stays in `Fundamental` mode | `protel-mode` not loaded, or wrong extension | Add `(require 'protel-mode)`; use `.protel`, `.P`, `.AA01`-style PLS suffix, or `M-x protel-mode` |
| No keyword highlighting | Font-lock not enabled | `M-x font-lock-mode` (normally on by default) |
| `Cannot open load file: cc-mode` | Incomplete Emacs install | Use a full GNU Emacs build, not a minimal editor |
| No bold in Terminal | Terminal profile disables bold | Enable bold fonts in Terminal.app / iTerm; `protel-keyword-face` uses `:weight bold` |
| Plain text in emacs-nox | Font Lock off or mode not loaded | `M-x global-font-lock-mode`; `(require 'protel-mode)` in `.emacs` |
+349
View File
@@ -0,0 +1,349 @@
# 7.3 Foreign Language Interoperability
**PROTEL Introductory Manual 2026** — Vincente D'Ingianni
---
## 7.3 Foreign Language Interoperability
PROTEL 2026 programs can call routines written in **C**, **C++**, **Swift**, **Rust**, **Python** (via a thin C embedding shim), **Java** (via JNI), and other languages that support the **C calling convention**. Likewise, foreign programs can call procedures you publish from PROTEL. This is the recommended approach for I/O, platform APIs, and performance-critical libraries: PROTEL does **not** use **INTRINSIC** for ordinary host I/O in the 2026 toolchain.
All foreign interop goes through two declarations:
| Direction | PROTEL keyword | Foreign side |
|-----------|----------------|--------------|
| Foreign → PROTEL | **EXPORT** | Import C symbol (e.g. `extern "C"`, Swift `@_silgen_name`, Rust `extern "C"`, Python `ctypes.CDLL`, Java JNI bridge) |
| PROTEL → Foreign | **EXTERNAL** | Export C symbol (e.g. C compilation unit, `#[no_mangle]`, `@_cdecl`, Python C API shim, JNI JVM embed) |
Working examples live under `examples/interop/` in the PROTEL distribution.
---
## 7.3.1 Strings and the C boundary
PROTEL character strings are **tuples of bytes** with a compile-time length. They are **not** automatically NUL-terminated when passed to C.
When a C, Swift, Rust, Python (via C), or Java (via JNI/C) function expects a `char*` / C string, append an explicit **zero** byte in a char tuple:
```
writeln({'Hello', 0});
swift_greet({'PROTEL', 0}, 42);
```
The compiler emits a `(const char[]){ ... }` array; the trailing `0` is your responsibility.
---
## 7.3.2 Calling foreign code from PROTEL (EXTERNAL)
### Step 1 — Declare the foreign routine
```
DCL writeln PROC(msg PTR TO char) EXTERNAL;
```
### Step 2 — Implement it in the foreign language
**C** (`examples/interop` pattern / `protel_io.c`):
```c
void writeln(const char* msg) {
/* write(2) based implementation */
}
```
**Rust** (`rust_greet.rs`):
```rust
#[no_mangle]
pub extern "C" fn rust_greet(name: *const i8, value: i16) { /* ... */ }
```
**Swift** (`swift_greet.swift`):
```swift
@_cdecl("swift_greet")
public func swift_greet(_ name: UnsafePointer<CChar>, _ value: Int32) { /* ... */ }
```
**Python** (via C embedding shim `python_greet.c`):
```c
void python_greet(const char* name, int16_t value) {
/* Py_Initialize, import greet_helper, call greet(name, value) */
}
```
PROTEL does not call the Python interpreter directly. A small **C** translation unit exposes `python_greet` with C linkage; it embeds Python and forwards to `greet_helper.py`. Link against `libpython` (Python development headers required).
**Java** (via JNI embedding shim `java_greet.c`):
```c
void java_greet(const char* name, int16_t value) {
/* JNI_CreateJavaVM, FindClass("GreetHelper"), CallStaticVoidMethod greet */
}
```
PROTEL does not call the JVM directly. A **C** shim exposes `java_greet` with C linkage, embeds the JVM, and forwards to `GreetHelper.java`. Link against `libjvm` (`$JAVA_HOME/include`, JDK required).
### Step 3 — Call from PROTEL
```
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
rust_greet({'PROTEL', 0}, 42);
writeln({'done', 0});
ENDBLOCK;
```
### Step 4 — Build and link
```bash
protel myprog.protel --keep -o build/myprog.cpp
clang++ -std=c++20 -c build/myprog.cpp -o build/myprog.o
rustc --crate-type staticlib rust_greet.rs -o build/librust_greet.a
clang++ build/myprog.o build/librust_greet.a src/runtime/protel_io.c -o myprog
```
See `examples/interop/build_interop.sh`, `build_interop_rust.sh`, `build_interop_python.sh`, and `build_interop_java.sh`.
---
## 7.3.3 Publishing PROTEL routines for foreign callers (EXPORT)
### Step 1 — Forward EXPORT declaration
```
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
```
### Step 2 — Procedure body (same section)
```
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
```
The transpiler places the implementation in an `extern "C"` block so the symbol name is `protel_add`.
### Step 3 — Import from foreign code
**C**:
```c
#include <stdint.h>
int16_t protel_add(int16_t a, int16_t b);
```
**Rust** (`rust_calls_protel.rs`):
```rust
extern "C" {
fn protel_add(a: i16, b: i16) -> i16;
}
```
**Swift** (`swift_calls_protel.swift`):
```swift
@_silgen_name("protel_add")
func protel_add(_ a: Int16, _ b: Int16) -> Int16
```
**Python** (`python_calls_protel.py`):
```python
import ctypes
lib = ctypes.CDLL("build/interop/libprotel_for_python.dylib") # .so on Linux
lib.protel_add.argtypes = (ctypes.c_int16, ctypes.c_int16)
lib.protel_add.restype = ctypes.c_int16
sum = lib.protel_add(40, 2)
```
Build the PROTEL EXPORT module as a **shared library** (`.dylib` / `.so`), then load it with **`ctypes.CDLL`**. No Python extension module is required on the PROTEL side.
**Java** (`JavaCallsProtel.java` + `java_calls_protel.c`):
```java
public final class JavaCallsProtel {
static { System.loadLibrary("javacallsprotel"); }
private static native short protelAdd(short a, short b);
}
```
Compile the EXPORT module and a thin **JNI** bridge into `libjavacallsprotel.dylib` (`.so` on Linux). `System.loadLibrary` loads the combined library; the JNI stub forwards to the EXPORTed `protel_add` symbol.
### Step 4 — Link
```bash
protel protel_for_rust.protel --keep -o build/protel_for_rust.cpp
clang++ -std=c++20 -c build/protel_for_rust.cpp -o build/protel_for_rust.o
rustc rust_calls_protel.rs build/protel_for_rust.o -o rust_calls_protel
```
**Python** (shared library + ctypes):
```bash
protel protel_for_python.protel --keep -o build/protel_for_python.cpp
clang++ -std=c++20 -fPIC -c build/protel_for_python.cpp -o build/protel_for_python.o
clang++ -shared -o build/libprotel_for_python.so build/protel_for_python.o
python3 examples/interop/python_calls_protel.py
```
**Java** (shared library + JNI):
```bash
protel protel_for_java.protel --keep -o build/protel_for_java.cpp
clang++ -std=c++20 -fPIC -c build/protel_for_java.cpp -o build/protel_for_java.o
clang -fPIC -c java_calls_protel.c -o build/java_calls_protel.o -I$JAVA_HOME/include
clang++ -shared -o build/libjavacallsprotel.so build/protel_for_java.o build/java_calls_protel.o
java -Djava.library.path=build/interop -cp build/interop JavaCallsProtel
```
---
## 7.3.4 Complete minimal examples
### PROTEL calls Rust
File: `examples/interop/protel_calls_rust.protel`
```
SECTION protel_calls_rust;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL rust_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
rust_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Rust', 0});
ENDBLOCK;
```
### PROTEL calls Python
File: `examples/interop/protel_calls_python.protel`
```
SECTION protel_calls_python;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL python_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
python_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Python', 0});
ENDBLOCK;
```
### Rust calls PROTEL
File: `examples/interop/protel_for_rust.protel` (same EXPORT library as Swift example)
```
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
```
### PROTEL calls Java
File: `examples/interop/protel_calls_java.protel`
```
SECTION protel_calls_java;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL java_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
java_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Java', 0});
ENDBLOCK;
```
### Python calls PROTEL
File: `examples/interop/python_calls_protel.py` loads `protel_for_python.protel` as a shared library via **ctypes**.
### Java calls PROTEL
File: `examples/interop/JavaCallsProtel.java` loads `protel_for_java.protel` via **JNI** (`java_calls_protel.c` bridge).
---
## 7.3.5 ENTRY vs EXPORT
- **IS ENTRY** — marks the **program** entry point. The transpiler emits a host `int main()` that calls your ENTRY procedure. Required for standalone executables.
- **EXPORT** — marks a **library** entry point for foreign languages. Does not create `main`. Use in INTERFACE sections intended to be called from Swift, Rust, Python, Java, C, etc.
A single module may have **one ENTRY** and **many EXPORT** procedures.
---
## 7.3.6 Quick reference
| Task | PROTEL | Build driver |
|------|--------|--------------|
| Hello World (PROTEL only) | `protel Hello.protel --run` | `protel` + `clang++` |
| Hello World (direct shebang) | `./examples/Hello.protel` | §7.0.5 — `export PATH="$PWD:$PATH"`, file executable |
| PROTEL + Swift | `make interop-swift` | `examples/interop/build_interop.sh` |
| PROTEL + Rust | `make interop-rust` | `examples/interop/build_interop_rust.sh` |
| PROTEL + Python | `make interop-python` | `examples/interop/build_interop_python.sh` |
| PROTEL + Java | `make interop-java` | `examples/interop/build_interop_java.sh` |
| Edit `.protel` / `.P` / PLS `.AA01` in Emacs | Add `emacs/` to `load-path`, `(require 'protel-mode)` | See §7.2 |
| Beautify source | `Pb file.protel` | `Pb` |
---
## 7.3.7 Troubleshooting
| Symptom | Likely cause |
|---------|----------------|
| Link error: undefined symbol | EXTERNAL name mismatch; foreign function not `extern "C"` / `#[no_mangle]` / `@_cdecl` |
| Garbled string output | Missing `, 0` NUL suffix on char tuple |
| Duplicate `main` at link | Swift/Rust object compiled with its own `main`; use `-parse-as-library` for helper objects |
| `ctypes` cannot load library | Build EXPORT module as `.dylib`/`.so` first; pass full path to `CDLL` |
| Python embed link error | Install Python dev package (`python3-dev`); use `python3-config --embed --ldflags` (or `python3-config --ldflags`) |
| Python greet silent | Embedded `print` may need `flush=True` when stdout is not a TTY |
| `UnsatisfiedLinkError` (Java) | Set `-Djava.library.path` to the directory containing `libjavacallsprotel`; build JNI bridge first |
| JVM embed link error | Set `JAVA_HOME` to a JDK; link `-L$JAVA_HOME/lib/server -ljvm` with rpath |
| No `main` at link | Program section missing **IS ENTRY** |
| `multiple ENTRY` error | More than one `IS ENTRY` in the module |
For the formal semantics of **EXTERNAL** and **EXPORT**, see Reference Manual §13.0.
+177
View File
@@ -0,0 +1,177 @@
# 13.0 EXTERNAL and EXPORT Procedures
**PROTEL Reference Manual 2026** — Vincente D'Ingianni
---
## 13.0 EXTERNAL and EXPORT Procedures
PROCEDURE constants may be declared **EXTERNAL** (import a foreign routine) or **EXPORT** (publish a PROTEL routine for foreign callers). In the PROTEL 2026 transpiler, both map to the **C application binary interface (ABI)** so that code produced by GCC, Clang, Swift, Rust, Python (via **ctypes** or a C embedding shim), Java (via **JNI**), and other C-compatible toolchains can be linked with PROTEL modules.
Ordinary procedure constants (without EXTERNAL or EXPORT) are emitted inside C++ namespaces and are intended for use within the PROTEL module. EXTERNAL and EXPORT procedures use `extern "C"` linkage at the generated C/C++ level so that symbol names are stable and unmangled.
---
## SYNTAX
```
<DCL GROUP> ::= <PROCEDURE DCL GROUP><PROCEDURE INIT>
<PROCEDURE INIT> ::= IS <BLOCK>
| IS INTRINSIC
| IS ENTRY
| EXTERNAL
| EXPORT
<PROCEDURE DCL GROUP> ::= <ID LIST><PROCEDURE ATTRIBUTES>
```
**EXTERNAL** and **EXPORT** are mutually exclusive with **IS** \<block\>, **IS INTRINSIC**, and **IS ENTRY** on the same declaration.
An EXPORT or EXTERNAL declaration is a **forward** declaration (like **IS FORWARD**). The procedure body, if any, appears in a subsequent **DCL** statement with the same name and compatible signature in the **same section**.
---
## EXTERNAL (import)
### Description
1. **EXTERNAL** declares that the named procedure is **implemented outside** the current module (typically in C, C++, Rust, Swift, Python via a C API bridge, Java via JNI, or another language that exports C-callable symbols).
2. The transpiler emits an `extern "C"` **prototype** only. No code is generated for the body.
3. Parameter and return types are mapped to C types (for example, **integer** → `int16_t`, **PTR TO char** → `const char*` for string arguments in external calls).
4. **PROTEL strings are not NUL-terminated.** When passing text to an EXTERNAL procedure that expects a C string, the caller must supply an **explicit trailing `0`** byte in a char tuple (see Introductory Manual §7.3).
### Examples
```
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL rust_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL python_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL java_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL read_config PROC(path PTR TO char, size integer) RETURNS integer EXTERNAL;
```
### Generated C++ (conceptual)
```cpp
extern "C" {
void writeln(const char* msg);
void rust_greet(const char* name, int16_t value);
int16_t read_config(const char* path, int16_t size);
}
```
---
## EXPORT (publish)
### Description
1. **EXPORT** declares that a procedure constant is part of the **public foreign interface** of the module. The implementation is emitted with `extern "C"` linkage at global scope (outside C++ namespaces).
2. There is no restriction on the number of EXPORT procedures per module (unlike **ENTRY**, which is limited to one per module).
3. EXPORT implies a forward declaration. The body must follow in the same section with an identical signature (parameter list, **RETURNS** type, and procedure class).
4. EXPORT procedures are suitable for **INTERFACE** sections that act as libraries for C, Swift, Rust, Python, Java, or other hosts. They do not, by themselves, define a program entry point. Use **IS ENTRY** for executable programs.
5. EXPORT must not be combined with **IS ENTRY** on the same procedure name.
### Examples
```
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
```
### Generated C++ (conceptual)
```cpp
namespace protel_generated {
namespace protel_math {
/* EXPORT protel_add (defined with C linkage below) */
}
}
extern "C" {
int16_t protel_add(int16_t a, int16_t b)
{
return (a + b);
}
}
```
---
## Comparison with other procedure initialisers
| Clause | Purpose | Body location | Linkage | Count per module |
|--------|---------|---------------|---------|------------------|
| *(none)* | Internal procedure | Same section | C++ namespace | unlimited |
| **IS FORWARD** | Forward reference | Later in module | C++ namespace | unlimited |
| **IS ENTRY** | Program entry | Same or other section | C++ namespace; host `main` calls ENTRY | **one** |
| **IS INTRINSIC** | Machine primitive | Compiler provided | implementation-defined | unlimited |
| **EXTERNAL** | Import foreign | Foreign object file | `extern "C"` import | unlimited |
| **EXPORT** | Export to foreign | Same section | `extern "C"` export | unlimited |
---
## Type mapping for foreign calls
| PROTEL type | C/C++ type (typical) | Notes |
|-------------|----------------------|-------|
| **integer** | `int16_t` | Range {-32768 TO 32767} |
| **char** (range) | `uint8_t` | Single byte |
| **PTR TO char** | `const char*` | Caller supplies NUL if C string required |
| **BOOL** | `bool` / `uint8_t` | Implementation-defined packing |
| **PROC** (procedure value) | function pointer | Rare in EXTERNAL declarations |
---
## Linking
1. Transpile PROTEL to `.cpp` with the PROTEL 2026 compiler (`protel`).
2. Compile generated C++ with `g++` or `clang++` (`-std=c++20`).
3. Compile foreign sources (`.c`, `.rs`, `.swift`, `.java`, etc.) to objects or static libraries using the foreign toolchain. For **Python → PROTEL**, compile the EXPORT module as a shared library and load it with **`ctypes.CDLL`**. For **PROTEL → Python**, link a C shim that embeds the Python interpreter (`python_greet.c` in `examples/interop/`). For **Java → PROTEL**, link the EXPORT module with a JNI bridge (`java_calls_protel.c`). For **PROTEL → Java**, link a C shim that embeds the JVM (`java_greet.c`).
4. Link all objects with the same C ABI conventions. On macOS and Linux, `clang++` is commonly used as the final link driver. Python embedding requires linking `libpython` (see `python3-config --embed --ldflags`). Java embedding requires linking `libjvm` from `$JAVA_HOME/lib/server`.
5. The minimal PROTEL I/O runtime (`protel_io.c`) is linked only when EXTERNAL procedures such as `writeln` from the example runtime are referenced.
---
## Restrictions and diagnostics
1. EXPORT and EXTERNAL declarations and their bodies must reside in the **same section**.
2. Duplicate EXPORT declarations or duplicate bodies for the same EXPORT name are rejected at transpile time.
3. EXPORT declaration and body signatures must match exactly.
4. Calling an EXTERNAL routine with a PROTEL string literal that lacks an explicit `0` suffix produces a **warning** (C interop requires NUL-terminated buffers for `const char*` parameters).
---
## See also
- §12.0 Intrinsic Procedures (machine-level **INTRINSIC**; not used for ordinary I/O in PROTEL 2026)
- Introductory Manual §7.2 — EMACS PROTEL mode
- Introductory Manual §7.3 — Foreign language interoperability (how-to)
- Introductory Manual §5.5.2 — **IS ENTRY**, UNIX `argc`/`argv`, and shell exit status (`docs/intro-5-5-2-entry-args-exit.md`)
+126
View File
@@ -0,0 +1,126 @@
# PROTEL 2026 Error Messages
**PROTEL Reference Manual 2026** — Vincente D'Ingianni
---
## Overview
The `protel` driver reports errors in three phases: **parse**, **type check**, and **compile**. Error examples live under `examples/errors/`.
```bash
./protel examples/errors/err_assign_integer_to_char.protel
```
---
## 1. Parse errors
**Prefix:** `protel: parse error in '<file>':`
The Lark parser rejects invalid syntax before transpilation.
| Message pattern | Typical cause |
|-----------------|---------------|
| `Unexpected token` | Misspelled keyword, missing `;`, `ENDIF`, or `ENDBLOCK` |
| `Unexpected input` | Tokens where a declaration or statement is required |
| `No terminal matches` | Unterminated string or malformed tuple |
**Example**
```protel
DCL demo PROC() IS
BLOCK
IF x > 0 THEN
x + 1 -> x;
% missing ENDIF
ENDBLOCK;
```
---
## 2. Type errors (strong typing)
**Prefix:** `protel: type error in '<file>':`
PROTEL 2026 enforces Reference Manual §11.3 compatibility at transpile time. Wide **integer** values cannot be stored in **char**, **PACK** byte fields, or **BOOL** without an explicit **CAST**.
| Message | Meaning | Example file |
|---------|---------|--------------|
| `cannot assign integer to char in …` | A variable or expression typed **integer** is assigned to **char {0 TO 255}** | `examples/errors/err_assign_integer_to_char.protel` |
| `cannot assign wide integer to packed byte-sized type {…} PACK(n) in …` | **integer** assigned to a **PACK** subrange | `examples/errors/err_assign_integer_to_packed_byte.protel` |
| `cannot assign integer to BOOL in …` | Numeric value assigned to **BOOL** | `examples/errors/err_assign_integer_to_bool.protel` |
| `value L..H is out of range for {A TO B} in …` | Numeric literal exceeds destination subrange | `examples/errors/err_constant_out_of_range.protel` |
| `cannot assign PTR TO T1 to PTR TO T2 in …` | Pointer pointee types differ | `examples/errors/err_assign_incompatible_pointer.protel` |
| `RETURN type T1 is not compatible with RETURNS T2 in procedure 'P'` | **RETURN** expression does not match **RETURNS** type | `examples/errors/err_return_type_mismatch.protel` |
| `procedure 'P' cannot RETURN a value` | **RETURN** with value in a `PROC()` without **RETURNS** | — |
| `procedure 'P' must RETURN T` | Missing **RETURN** in a **RETURNS** procedure | — |
| `unknown identifier 'x' in …` | Assignment to an undeclared name | — |
**Valid contrast:** `examples/errors/ok_assign_char_literal.protel` assigns literal `65` to **char** (within `{0 TO 255}`).
### Strong typing rules (summary)
1. **integer** does not silently narrow to **char** or **PACK** types.
2. Numeric literals must fit the destination subrange.
3. **BOOL** accepts only boolean expressions.
4. **PTR TO** assignments require compatible pointee types.
5. **RETURN** must match the procedure **RETURNS** type.
---
## 3. Transpile errors
**Prefix:** `protel: transpile error in '<file>':`
Structural or linkage problems in the transpiler (not type compatibility).
| Message | Cause |
|---------|-------|
| `multiple ENTRY procedures (…)` | More than one **IS ENTRY** per module |
| `ENTRY procedure 'P' has no procedure body` | **IS ENTRY** forward without matching body |
| `ENTRY procedure 'P' parameters must match …` | **IS ENTRY** declaration differs from body |
| `EXPORT procedure 'P' has no procedure body` | **EXPORT** without implementation |
| `duplicate EXPORT declaration for 'P'` | Two **EXPORT** declarations for one name |
| `compile mode requires C++ output (omit --emit-c)` | `--emit-c` with `--compile` |
---
## 4. Driver and I/O errors
| Message | Cause |
|---------|-------|
| `protel: cannot read '<file>': …` | Missing or unreadable source path |
| `protel: cannot write '<file>': …` | Output path not writable |
| `protel: '<file>' is not a PROTEL source file` | Unrecognized extension |
| `protel: warning: only the first source file is compiled` | Multiple inputs on command line |
---
## 5. Compile and link errors
**Prefix:** `protel: compile error:`
Emitted when GCC/clang++ rejects generated C++. Often caused by invalid generated code or missing runtime symbols.
| Underlying message | Typical fix |
|--------------------|-------------|
| `undefined reference to 'writeln'` | Link without `protel_io.c` (use default `protel` compile, not raw `g++` on `.cpp` alone) |
| `functions that differ only in their return type` | Duplicate ENTRY/forward signatures (report as transpile bug) |
| `no C++ compiler found` | Install `g++`, `clang++`, or `c++` on `PATH` |
---
## 6. Runtime warnings
| Message | Cause |
|---------|-------|
| `protel: warning: call to P uses a PROTEL string without an explicit NUL (0) suffix` | **EXTERNAL** call with string missing `, 0` in char tuple |
---
## See also
- Reference Manual §11.0–§11.3 — type compatibility
- `examples/errors/` — intentional error and OK contrast programs
- Introductory Manual §7.0 — `protel` driver usage
+194
View File
@@ -0,0 +1,194 @@
;;; protel-mode.el --- Major mode for PROTEL -*- lexical-binding: t; -*-
;; Recreated in honor of Bill Conn, the original author of EMACS PROTEL Mode in the 1990s.
;; Keywords from PROTEL Reference Manual Appendix A / PROTEL 2026.
;;; Commentary:
;; Provides keyword capitalization support, syntax highlighting, and
;; Pascal-style indentation for PROTEL source in GNU Emacs.
;;
;; Works in terminal Emacs (emacs-nox, \"emacs -nw\") as well as GUI Emacs.
;; Bold keywords and indentation do not require X11; colors use the terminal
;; palette when running on a tty.
(require 'cc-mode)
(require 'files) ; executable-find
(defgroup protel nil
"Major mode for editing PROTEL source."
:group 'languages)
(defcustom protel-indent-offset 3
"Indentation offset for PROTEL block bodies."
:type 'integer
:group 'protel)
(defcustom protel-root nil
"PROTEL 2026 checkout directory (contains Pb and emacs/protel-mode.el).
Used to find Pb when it is not on PATH. Usually set from ~/.emacs."
:type 'directory
:group 'protel)
(defcustom protel-beautify-command nil
"Command used to beautify PROTEL source, normally the Pb driver.
When nil, `protel--locate-pb' searches PATH and PROTEL-ROOT."
:type 'string
:group 'protel)
(defcustom protel-beautify-extra-args nil
"Extra arguments for Pb, e.g. \"--bold\"."
:type 'string
:group 'protel)
(defface protel-keyword-face
'((t :inherit font-lock-keyword-face :weight bold)
(tty :foreground "white" :weight bold))
"Face used for PROTEL reserved keywords."
:group 'protel)
(defface protel-comment-face
'((t :foreground "green" :slant italic)
(tty :foreground "green"))
"Face used for PROTEL % comments and the optional first-line shebang."
:group 'protel)
(defface protel-string-face
'((t :inherit font-lock-string-face))
"Face used for PROTEL single-quoted strings."
:group 'protel)
(defvar protel-mode-map
(let ((map (make-sparse-keymap)))
map)
"Keymap for `protel-mode'.")
(defvar protel-mode-syntax-table
(let ((table (make-syntax-table)))
(modify-syntax-entry ?% "<" table)
(modify-syntax-entry ?\n ">" table)
(modify-syntax-entry ?' "\"" table)
table)
"Syntax table for `protel-mode'.")
(defvar protel-keywords-regexp
(regexp-opt
'("$EJECT" "$LI" "$OBJECT" "$REFDESC" "$TYPEDESC" "$UNIVERSAL_PTR" "$VARDESC"
"ABSTRACT" "AREA" "AS" "BIND" "BLOCK" "BOOL" "BY" "CASE" "CAST" "CLASS"
"CREATE" "DCL" "DEFINITIONS" "DESC" "DO" "DOWN" "ELSE" "ENDAREA" "ENDBLOCK"
"ENDCASE" "ENDCLASS" "ENDDO" "ENDIF" "ENDOVLY" "ENDSELECT" "ENDSTRUCT"
"ENTRY" "EXIT" "EXTERNAL" "EXCLUSIVE" "FALSE" "FIXED" "FAST" "FOR" "FORWARD"
"FROM" "HIDDEN" "IF" "IN" "INCL" "INIT" "INTERFACE" "INTRINSIC" "IS"
"LITERAL" "METHOD" "MOD" "NIL" "NONTRANSPARENT" "NOTINCL" "OF" "OPERAND"
"OPERATIONS" "OUT" "OVERRIDING" "OVER" "OVLY" "PACK" "PERPROCESS" "PRIVATE"
"PROC" "PROTECTED" "PTR" "QUICK" "REF" "REFDESC" "REFINES" "RETURN" "RETURNS"
"SECTION" "SELECT" "SELF" "SET" "SUPER" "SHARED" "STRUCT" "TABLE" "TDSIZE"
"THEN" "TO" "TRUE" "TYPE" "TYPEDESC" "UNRESTRICTED" "UP" "UPB" "UPDATES"
"USES" "VAL" "VARDESC" "VARIABLE" "WHILE" "WITH")
'words))
(defvar protel-font-lock-keywords
(list (list "^#![^\n]*" 0 'font-lock-comment-face)
(list protel-keywords-regexp 0 'font-lock-keyword-face)
(list "%.*" 0 'font-lock-comment-face)
(list "'\\(?:''\\|[^']\\)*'" 0 'font-lock-string-face)))
(defun protel--executable-find (command)
"Like `executable-find', but safe when Emacs is not fully initialized."
(and (fboundp #'executable-find)
(funcall #'executable-find command)))
(defun protel--locate-pb ()
"Return absolute path to Pb, or nil."
(or
(when protel-beautify-command
(let ((cmd protel-beautify-command))
(if (file-name-absolute-p cmd)
(when (file-exists-p cmd) cmd)
(or (protel--executable-find cmd) cmd))))
(protel--executable-find "Pb")
(when protel-root
(let ((pb (expand-file-name "Pb" protel-root)))
(when (file-exists-p pb) pb)))
(when-let ((protel-bin (protel--executable-find "protel")))
(let ((pb (expand-file-name "Pb" (file-name-directory protel-bin))))
(when (file-exists-p pb) pb)))))
(defun protel-beautify-region (start end)
"Run Pb on the region from START to END, replacing it with beautified text."
(let* ((pb (protel--locate-pb))
(args (let ((extra (or protel-beautify-extra-args "")))
(if (or (null extra) (string= extra ""))
""
(concat " " extra))))
(cmd (concat (shell-quote-argument pb) args)))
(unless pb
(user-error "Cannot find Pb; set `protel-beautify-command' or `protel-root'"))
(shell-command-on-region start end cmd nil t)
(when font-lock-mode
(font-lock-flush))))
(defun protel-beautify-buffer ()
"Run Pb on the entire buffer, uppercasing PROTEL reserved keywords."
(interactive)
(protel-beautify-region (point-min) (point-max)))
(defun protel-beautify ()
"Beautify the active region, or the entire buffer when the region is inactive.
Pipes source through Pb (Introductory Manual 7.0)."
(interactive)
(if (use-region-p)
(protel-beautify-region (region-beginning) (region-end))
(protel-beautify-buffer)))
(defun protel-indent-line ()
"Indent current line in Pascal/PROTEL style."
(interactive)
(let ((pos (point))
(offset protel-indent-offset))
(save-excursion
(beginning-of-line)
(cond
((looking-at "\\s-*\\(?i:\\(BLOCK\\|THEN\\|DO\\|ELSE\\)\\)")
(indent-line-to 0))
((looking-at "\\s-*\\(?i:\\(ENDBLOCK\\|ENDIF\\|ENDDO\\|ENDCASE\\|ENDSELECT\\)\\)")
(indent-line-to 0))
(t
(if (save-excursion
(goto-char (line-beginning-position))
(looking-at "[ \t]+"))
(indent-line-to offset)
(indent-line-to 0)))))))
(define-derived-mode protel-mode fundamental-mode "PROTEL"
"Major mode for editing PROTEL 2026 programs."
:group 'protel
(setq-local syntax-table protel-mode-syntax-table)
(setq-local comment-start "% ")
(setq-local comment-start-skip "%+ *")
(setq-local font-lock-keywords-case-fold-search t)
(setq-local font-lock-defaults '(protel-font-lock-keywords))
(setq-local indent-line-function #'protel-indent-line)
(setq-local require-final-newline t)
;; Map standard Font Lock faces to PROTEL-specific faces (bold keywords, etc.).
(face-remap-add-relative 'font-lock-keyword-face 'protel-keyword-face)
(face-remap-add-relative 'font-lock-comment-face 'protel-comment-face)
(face-remap-add-relative 'font-lock-string-face 'protel-string-face)
(font-lock-mode 1))
;; C-c C-f — format/beautify (same convention as go-mode, rust-mode, etc.)
(define-key protel-mode-map (kbd "C-c C-f") #'protel-beautify)
;; Mnemonic alternative: C-c C-b for Pb beautifier
(define-key protel-mode-map (kbd "C-c C-b") #'protel-beautify)
(define-key protel-mode-map (kbd "TAB") #'protel-indent-line)
(define-key protel-mode-map (kbd "C-M-\\") #'indent-region)
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.protel\\'" . protel-mode))
(add-to-list 'auto-mode-alist '("\\.pt\\'" . protel-mode))
(add-to-list 'auto-mode-alist '("\\.ptl\\'" . protel-mode))
(add-to-list 'auto-mode-alist '("\\.P\\'" . protel-mode))
;; PLS edition suffixes: .AA01 through .ZZ99 (two letters + two digits).
(add-to-list 'auto-mode-alist '("\\.[A-Za-z][A-Za-z][0-9][0-9]\\'" . protel-mode))
(provide 'protel-mode)
;;; protel-mode.el ends here
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env protel-run
% Hello World - PROTEL 2026 (Introductory Manual 5.5.2 / 7.0)
% Run from repo root: export PATH="$PWD:$PATH" && ./examples/Hello.protel
% EXTERNAL C I/O via minimal runtime; no INTRINSIC, no iostream.
% PROTEL strings are char tuples; append 0 explicitly for C calls.
SECTION Hello;
TYPE char {0 TO 255};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
writeln({'Hello, World!', 0});
ENDBLOCK;
+16
View File
@@ -0,0 +1,16 @@
% Hello World - legacy .P extension (Introductory Manual 5.5.2 / 7.0 / 7.2)
% Same program as Hello.protel; .P is the historical Nortel/BNR suffix.
% EXTERNAL C I/O via minimal runtime; no INTRINSIC, no iostream.
SECTION Hello;
TYPE char {0 TO 255};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
writeln({'Hello, World!', 0});
ENDBLOCK;
+16
View File
@@ -0,0 +1,16 @@
% Hello World - PLS edition suffix .aa01 (Introductory Manual 7.0 / 7.2)
% Legacy PLS naming: two letters + two digits (.AA01 through .ZZ99).
% Same program as Hello.protel; edition AA01 is illustrative only.
SECTION Hello;
TYPE char {0 TO 255};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
writeln({'Hello, World!', 0});
ENDBLOCK;
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env protel-run
% Hello World - PROTEL 2026 (Introductory Manual 5.5.2 / 7.0)
% Run from repo root: export PATH="$PWD:$PATH" && ./examples/Hello.protel
% EXTERNAL C I/O via minimal runtime; no INTRINSIC, no iostream.
% PROTEL strings are char tuples; append 0 explicitly for C calls.
SECTION Hello;
TYPE char {0 TO 255};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
writeln({'Hello, World!', 0});
ENDBLOCK;
@@ -0,0 +1,16 @@
% ERROR EXAMPLE — incompatible pointer assignment (§11.3 rule 5)
% Expected: protel: type error: cannot assign PTR TO ...
SECTION err_ptr_mismatch;
TYPE integer {-32768 TO 32767};
TYPE char {0 TO 255};
DCL demo PROC() IS
BLOCK
DCL i integer;
DCL ch char;
DCL ip PTR TO integer INIT NIL;
DCL cp PTR TO char INIT NIL;
cp -> ip;
ENDBLOCK;
@@ -0,0 +1,13 @@
% ERROR EXAMPLE — integer assigned to BOOL (§11.3)
% Expected: protel: type error: cannot assign ... to BOOL
SECTION err_int_to_bool;
TYPE integer {-32768 TO 32767};
DCL demo PROC() IS
BLOCK
DCL flag BOOL;
DCL n integer INIT 1;
n -> flag;
ENDBLOCK;
@@ -0,0 +1,14 @@
% ERROR EXAMPLE — integer assigned to char (Reference Manual §11.3)
% Expected: protel: type error: cannot assign integer to char
SECTION err_int_to_char;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL demo PROC() IS
BLOCK
DCL ch char;
DCL n integer INIT 65;
n -> ch;
ENDBLOCK;
@@ -0,0 +1,14 @@
% ERROR EXAMPLE — integer assigned to PACK byte (§7.2.3 / §11.3)
% Expected: protel: type error: cannot assign wide integer to packed byte-sized type
SECTION err_int_to_packed;
TYPE integer {-32768 TO 32767};
TYPE nibble PACK (4) {0 TO 15};
DCL demo PROC() IS
BLOCK
DCL slot nibble;
DCL value integer INIT 9;
value -> slot;
ENDBLOCK;
@@ -0,0 +1,12 @@
% ERROR EXAMPLE — numeric literal out of subrange (§11.3)
% Expected: protel: type error: value ... out of range for {0 TO 255}
SECTION err_out_of_range;
TYPE char {0 TO 255};
DCL demo PROC() IS
BLOCK
DCL ch char;
300 -> ch;
ENDBLOCK;
@@ -0,0 +1,12 @@
% ERROR EXAMPLE — RETURN type incompatible with RETURNS clause (§9.2 / §11.3)
% Expected: protel: type error: RETURN type ... is not compatible with RETURNS BOOL
SECTION err_return_mismatch;
TYPE integer {-32768 TO 32767};
DCL demo PROC() RETURNS BOOL IS
BLOCK
DCL n integer INIT 0;
RETURN n;
ENDBLOCK;
@@ -0,0 +1,11 @@
% OK EXAMPLE — char literal within range (contrast with err_* examples)
SECTION ok_char_literal;
TYPE char {0 TO 255};
DCL demo PROC() IS
BLOCK
DCL ch char;
65 -> ch;
ENDBLOCK;
+10
View File
@@ -0,0 +1,10 @@
/** Java helper invoked from PROTEL via the java_greet JNI embedding shim. */
public final class GreetHelper {
private GreetHelper() {
}
public static void greet(String name, short value) {
System.out.println("Java: java_greet(name=" + name + ", value=" + value + ")");
System.out.flush();
}
}
+13
View File
@@ -0,0 +1,13 @@
/** Java program calling an EXPORTed PROTEL procedure via JNI (C ABI bridge). */
public final class JavaCallsProtel {
static {
System.loadLibrary("javacallsprotel");
}
private static native short protelAdd(short a, short b);
public static void main(String[] args) {
short sum = protelAdd((short) 40, (short) 2);
System.out.println("Java: protel_add(40, 2) = " + sum);
}
}
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Build Swift <-> PROTEL interop demos (macOS / Linux with Swift installed).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD="$ROOT/build/interop"
PROTEL="$ROOT/protel"
RUNTIME="$ROOT/src/runtime/protel_io.c"
mkdir -p "$BUILD"
if ! command -v swiftc >/dev/null 2>&1; then
echo "interop: swiftc not found; install Swift toolchain to build runnable demos" >&2
exit 1
fi
CXX="$(command -v clang++ || command -v g++)"
echo "=== PROTEL calls Swift ==="
"$PROTEL" "$ROOT/examples/interop/protel_calls_swift.protel" \
--keep -o "$BUILD/protel_calls_swift.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_calls_swift.cpp" \
-o "$BUILD/protel_calls_swift.o"
swiftc -parse-as-library -c "$ROOT/examples/interop/swift_greet.swift" \
-o "$BUILD/swift_greet.o"
"$CXX" "$BUILD/protel_calls_swift.o" "$BUILD/swift_greet.o" "$RUNTIME" \
-o "$BUILD/protel_calls_swift"
"$BUILD/protel_calls_swift"
echo "=== Swift calls PROTEL ==="
"$PROTEL" "$ROOT/examples/interop/protel_for_swift.protel" \
--keep -o "$BUILD/protel_for_swift.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_for_swift.cpp" \
-o "$BUILD/protel_for_swift.o"
swiftc "$ROOT/examples/interop/swift_calls_protel.swift" "$BUILD/protel_for_swift.o" \
-o "$BUILD/swift_calls_protel"
"$BUILD/swift_calls_protel"
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
# Build Java <-> PROTEL interop demos (macOS / Linux with JDK headers).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD="$ROOT/build/interop"
PROTEL="$ROOT/protel"
RUNTIME="$ROOT/src/runtime/protel_io.c"
INTEROP="$ROOT/examples/interop"
mkdir -p "$BUILD"
if ! command -v javac >/dev/null 2>&1 || ! command -v java >/dev/null 2>&1; then
echo "interop: javac/java not found; install a JDK" >&2
exit 1
fi
if ! java -version >/dev/null 2>&1; then
echo "interop: java runtime not available; set JAVA_HOME to a JDK" >&2
exit 1
fi
if [ -z "${JAVA_HOME:-}" ]; then
if [ "$(uname -s)" = "Darwin" ] && command -v /usr/libexec/java_home >/dev/null 2>&1; then
JAVA_HOME="$(/usr/libexec/java_home 2>/dev/null || true)"
fi
fi
if [ -z "${JAVA_HOME:-}" ] || [ ! -d "$JAVA_HOME/include" ]; then
echo "interop: JAVA_HOME must point to a JDK with JNI headers" >&2
exit 1
fi
JNI_OS="linux"
if [ "$(uname -s)" = "Darwin" ]; then
JNI_OS="darwin"
fi
JNI_CFLAGS="-I$JAVA_HOME/include -I$JAVA_HOME/include/$JNI_OS"
if [ -d "$JAVA_HOME/lib/server" ]; then
JVM_LIBDIR="$JAVA_HOME/lib/server"
else
JVM_LIBDIR="$JAVA_HOME/jre/lib/server"
fi
JNI_LDFLAGS="-L$JVM_LIBDIR -ljvm -Wl,-rpath,$JVM_LIBDIR"
CXX="$(command -v clang++ || command -v g++)"
CC="$(command -v clang || command -v gcc)"
if [ "$(uname -s)" = "Darwin" ]; then
SHLIB_EXT="dylib"
SHLIB_FLAGS="-dynamiclib"
else
SHLIB_EXT="so"
SHLIB_FLAGS="-shared -fPIC"
fi
javac -d "$BUILD" "$INTEROP/GreetHelper.java" "$INTEROP/JavaCallsProtel.java"
echo "=== PROTEL calls Java ==="
"$PROTEL" "$INTEROP/protel_calls_java.protel" \
--keep -o "$BUILD/protel_calls_java.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_calls_java.cpp" \
-o "$BUILD/protel_calls_java.o"
# shellcheck disable=SC2086
"$CC" -Wall -c "$INTEROP/java_greet.c" -o "$BUILD/java_greet.o" $JNI_CFLAGS
# shellcheck disable=SC2086
"$CXX" "$BUILD/protel_calls_java.o" "$BUILD/java_greet.o" "$RUNTIME" \
$JNI_LDFLAGS -o "$BUILD/protel_calls_java"
PROTEL_ROOT="$ROOT" "$BUILD/protel_calls_java"
echo "=== Java calls PROTEL ==="
"$PROTEL" "$INTEROP/protel_for_java.protel" \
--keep -o "$BUILD/protel_for_java.cpp"
"$CXX" -std=c++20 -Wall -fPIC -I"$ROOT/src/runtime" -c "$BUILD/protel_for_java.cpp" \
-o "$BUILD/protel_for_java.o"
# shellcheck disable=SC2086
"$CC" -Wall -fPIC -c "$INTEROP/java_calls_protel.c" -o "$BUILD/java_calls_protel.o" $JNI_CFLAGS
"$CXX" $SHLIB_FLAGS -std=c++20 "$BUILD/protel_for_java.o" "$BUILD/java_calls_protel.o" \
-o "$BUILD/libjavacallsprotel.$SHLIB_EXT"
java -Djava.library.path="$BUILD" -cp "$BUILD" JavaCallsProtel
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
# Build Python <-> PROTEL interop demos (macOS / Linux with Python 3 dev headers).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD="$ROOT/build/interop"
PROTEL="$ROOT/protel"
RUNTIME="$ROOT/src/runtime/protel_io.c"
INTEROP="$ROOT/examples/interop"
mkdir -p "$BUILD"
if ! command -v python3 >/dev/null 2>&1; then
echo "interop: python3 not found" >&2
exit 1
fi
PYTHON="${PYTHON:-python3}"
if ! "$PYTHON" -c "import sysconfig; sysconfig.get_config_var('LIBDIR')" >/dev/null 2>&1; then
echo "interop: Python development headers not available (install python3-dev)" >&2
exit 1
fi
PY_CONFIG=""
if command -v python3-config >/dev/null 2>&1; then
PY_CONFIG="python3-config"
elif command -v "$PYTHON-config" >/dev/null 2>&1; then
PY_CONFIG="$PYTHON-config"
fi
if [ -n "$PY_CONFIG" ]; then
PY_CFLAGS="$("$PY_CONFIG" --includes)"
if "$PY_CONFIG" --embed --ldflags >/dev/null 2>&1; then
PY_LDFLAGS="$("$PY_CONFIG" --embed --ldflags)"
else
PY_LDFLAGS="$("$PY_CONFIG" --ldflags)"
fi
else
PY_CFLAGS=$("$PYTHON" -c "import sysconfig; print('-I' + sysconfig.get_config_var('INCLUDEPY'))")
PY_LDFLAGS=$("$PYTHON" -c "import sysconfig; print('-L' + sysconfig.get_config_var('LIBDIR') + ' -lpython' + sysconfig.get_config_var('VERSION') + ' ' + (sysconfig.get_config_var('LIBS') or ''))")
fi
CXX="$(command -v clang++ || command -v g++)"
CC="$(command -v clang || command -v gcc)"
if [ "$(uname -s)" = "Darwin" ]; then
SHLIB_EXT="dylib"
SHLIB_FLAGS="-dynamiclib -Wl,-undefined,dynamic_lookup"
else
SHLIB_EXT="so"
SHLIB_FLAGS="-shared -fPIC"
fi
echo "=== PROTEL calls Python ==="
"$PROTEL" "$INTEROP/protel_calls_python.protel" \
--keep -o "$BUILD/protel_calls_python.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_calls_python.cpp" \
-o "$BUILD/protel_calls_python.o"
# shellcheck disable=SC2086
"$CC" -Wall -c "$INTEROP/python_greet.c" -o "$BUILD/python_greet.o" $PY_CFLAGS
# shellcheck disable=SC2086
"$CXX" "$BUILD/protel_calls_python.o" "$BUILD/python_greet.o" "$RUNTIME" \
$PY_LDFLAGS -o "$BUILD/protel_calls_python"
(cd "$ROOT" && "$BUILD/protel_calls_python")
echo "=== Python calls PROTEL ==="
"$PROTEL" "$INTEROP/protel_for_python.protel" \
--keep -o "$BUILD/protel_for_python.cpp"
"$CXX" -std=c++20 -Wall -fPIC -I"$ROOT/src/runtime" -c "$BUILD/protel_for_python.cpp" \
-o "$BUILD/protel_for_python.o"
"$CXX" $SHLIB_FLAGS -std=c++20 "$BUILD/protel_for_python.o" \
-o "$BUILD/libprotel_for_python.$SHLIB_EXT"
"$PYTHON" "$INTEROP/python_calls_protel.py"
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Build Rust <-> PROTEL interop demos (macOS / Linux with Rust installed).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD="$ROOT/build/interop"
PROTEL="$ROOT/protel"
RUNTIME="$ROOT/src/runtime/protel_io.c"
mkdir -p "$BUILD"
if ! command -v rustc >/dev/null 2>&1; then
echo "interop: rustc not found; install Rust (rustup) to build runnable demos" >&2
exit 1
fi
CXX="$(command -v clang++ || command -v g++)"
echo "=== PROTEL calls Rust ==="
"$PROTEL" "$ROOT/examples/interop/protel_calls_rust.protel" \
--keep -o "$BUILD/protel_calls_rust.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_calls_rust.cpp" \
-o "$BUILD/protel_calls_rust.o"
rustc --crate-type staticlib "$ROOT/examples/interop/rust_greet.rs" \
-o "$BUILD/librust_greet.a"
"$CXX" "$BUILD/protel_calls_rust.o" "$BUILD/librust_greet.a" "$RUNTIME" \
-o "$BUILD/protel_calls_rust"
"$BUILD/protel_calls_rust"
echo "=== Rust calls PROTEL ==="
"$PROTEL" "$ROOT/examples/interop/protel_for_rust.protel" \
--keep -o "$BUILD/protel_for_rust.cpp"
"$CXX" -std=c++20 -Wall -I"$ROOT/src/runtime" -c "$BUILD/protel_for_rust.cpp" \
-o "$BUILD/protel_for_rust.o"
rustc "$ROOT/examples/interop/rust_calls_protel.rs" "$BUILD/protel_for_rust.o" \
-o "$BUILD/rust_calls_protel"
"$BUILD/rust_calls_protel"
+11
View File
@@ -0,0 +1,11 @@
/* C function called from PROTEL via EXTERNAL (examples/interop reference). */
#include <stdint.h>
#include <stdio.h>
void c_greet(const char* name, int16_t value)
{
if (name == NULL) {
name = "";
}
printf("C: c_greet(name=%s, value=%d)\n", name, (int)value);
}
+5
View File
@@ -0,0 +1,5 @@
"""Python helper invoked from PROTEL via the python_greet C embedding shim."""
def greet(name: str, value: int) -> None:
print(f"Python: python_greet(name={name}, value={value})", flush=True)
+13
View File
@@ -0,0 +1,13 @@
/* JNI bridge: JavaCallsProtel.protelAdd -> EXPORTed protel_add (C ABI). */
#include <jni.h>
#include <stdint.h>
extern int16_t protel_add(int16_t a, int16_t b);
JNIEXPORT jshort JNICALL
Java_JavaCallsProtel_protelAdd(JNIEnv *env, jclass clazz, jshort a, jshort b)
{
(void)env;
(void)clazz;
return (jshort)protel_add(a, b);
}
+88
View File
@@ -0,0 +1,88 @@
/* C ABI entry point: embeds the JVM and calls GreetHelper.greet (PROTEL EXTERNAL). */
#include <jni.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static JavaVM *jvm;
static int jvm_ready;
static JNIEnv *attach_env(void)
{
JNIEnv *env = NULL;
if (jvm == NULL) {
return NULL;
}
if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_10) == JNI_EDETACHED) {
(*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL);
}
return env;
}
static void ensure_jvm(void)
{
JavaVMInitArgs vm_args;
JavaVMOption options[1];
char classpath[1024];
const char *root;
JNIEnv *env;
if (jvm_ready) {
return;
}
root = getenv("PROTEL_ROOT");
if (root == NULL || root[0] == '\0') {
root = ".";
}
snprintf(classpath, sizeof(classpath), "-Djava.class.path=%s/examples/interop", root);
options[0].optionString = classpath;
vm_args.version = JNI_VERSION_10;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
if (JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args) != 0) {
fprintf(stderr, "java_greet: JNI_CreateJavaVM failed\n");
return;
}
jvm_ready = 1;
}
void java_greet(const char *name, int16_t value)
{
JNIEnv *env;
jclass cls;
jmethodID mid;
jstring jname;
ensure_jvm();
env = attach_env();
if (env == NULL) {
return;
}
cls = (*env)->FindClass(env, "GreetHelper");
if (cls == NULL) {
(*env)->ExceptionDescribe(env);
return;
}
mid = (*env)->GetStaticMethodID(env, cls, "greet", "(Ljava/lang/String;S)V");
if (mid == NULL) {
(*env)->ExceptionDescribe(env);
(*env)->DeleteLocalRef(env, cls);
return;
}
jname = (*env)->NewStringUTF(env, name != NULL ? name : "");
(*env)->CallStaticVoidMethod(env, cls, mid, jname, (jshort)value);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
}
(*env)->DeleteLocalRef(env, jname);
(*env)->DeleteLocalRef(env, cls);
}
+18
View File
@@ -0,0 +1,18 @@
% PROTEL calling Java (Introductory Manual 7.3)
% C shim java_greet embeds the JVM and calls GreetHelper.greet.
SECTION protel_calls_java;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL java_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
java_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Java', 0});
ENDBLOCK;
@@ -0,0 +1,18 @@
% PROTEL calling Python (Introductory Manual 7.3)
% C shim python_greet embeds Python and calls greet_helper.greet.
SECTION protel_calls_python;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL python_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
python_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Python', 0});
ENDBLOCK;
+18
View File
@@ -0,0 +1,18 @@
% PROTEL calling Rust (Introductory Manual 7.3)
% Rust exports rust_greet with #[no_mangle] extern "C"; PROTEL imports EXTERNAL.
SECTION protel_calls_rust;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL rust_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
rust_greet({'PROTEL', 0}, 42);
writeln({'PROTEL called Rust', 0});
ENDBLOCK;
@@ -0,0 +1,18 @@
% PROTEL calling Swift (Introductory Manual 7.1 / C interop)
% Swift exports swift_greet with @_cdecl; PROTEL imports it as EXTERNAL.
SECTION protel_calls_swift;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL swift_greet PROC(name PTR TO char, value integer) EXTERNAL;
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
swift_greet({'PROTEL', 0}, 42);
writeln({'PROTEL finished calling Swift', 0});
ENDBLOCK;
+13
View File
@@ -0,0 +1,13 @@
% PROTEL library exported for Java (EXPORT = extern "C" linkage)
% Java loads the shared object via JNI (java_calls_protel.c bridge).
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
+13
View File
@@ -0,0 +1,13 @@
% PROTEL library exported for Python (EXPORT = extern "C" linkage)
% Python loads the shared object with ctypes.CDLL and binds protel_add.
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
+13
View File
@@ -0,0 +1,13 @@
% PROTEL library exported for Rust (EXPORT = extern "C" linkage)
% Rust imports protel_add with extern "C" { fn protel_add ... }.
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
+13
View File
@@ -0,0 +1,13 @@
% PROTEL library exported for Swift (EXPORT = extern "C" linkage)
% Swift imports protel_add with @_silgen_name.
INTERFACE protel_math;
TYPE integer {-32768 TO 32767};
DCL protel_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL protel_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Python program calling an EXPORTed PROTEL procedure via ctypes (C ABI)."""
from __future__ import annotations
import ctypes
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
BUILD = ROOT / "build" / "interop"
if sys.platform == "darwin":
LIB_NAME = "libprotel_for_python.dylib"
elif sys.platform == "win32":
LIB_NAME = "protel_for_python.dll"
else:
LIB_NAME = "libprotel_for_python.so"
LIB_PATH = BUILD / LIB_NAME
def main() -> None:
if not LIB_PATH.is_file():
raise SystemExit(f"missing shared library: {LIB_PATH} (run build_interop_python.sh)")
lib = ctypes.CDLL(str(LIB_PATH))
lib.protel_add.argtypes = (ctypes.c_int16, ctypes.c_int16)
lib.protel_add.restype = ctypes.c_int16
total = lib.protel_add(40, 2)
print(f"Python: protel_add(40, 2) = {total}")
if __name__ == "__main__":
main()
+50
View File
@@ -0,0 +1,50 @@
/* C ABI entry point: embeds Python and calls greet_helper.greet (PROTEL EXTERNAL). */
#include <Python.h>
#include <stdint.h>
static int py_ready;
static void ensure_python(void)
{
if (py_ready) {
return;
}
Py_Initialize();
if (PyRun_SimpleString("import sys\n"
"sys.path.insert(0, 'examples/interop')\n") != 0) {
PyErr_Print();
}
py_ready = 1;
}
void python_greet(const char* name, int16_t value)
{
PyObject *mod, *func, *args, *result;
ensure_python();
mod = PyImport_ImportModule("greet_helper");
if (mod == NULL) {
PyErr_Print();
return;
}
func = PyObject_GetAttrString(mod, "greet");
if (func == NULL || !PyCallable_Check(func)) {
PyErr_Print();
Py_DECREF(mod);
return;
}
args = Py_BuildValue("(si)", name != NULL ? name : "", (int)value);
result = PyObject_CallObject(func, args);
if (result == NULL) {
PyErr_Print();
} else {
Py_DECREF(result);
}
Py_DECREF(args);
Py_DECREF(func);
Py_DECREF(mod);
}
+9
View File
@@ -0,0 +1,9 @@
// Rust program calling an EXPORTed PROTEL procedure (C linkage).
extern "C" {
fn protel_add(a: i16, b: i16) -> i16;
}
fn main() {
let sum = unsafe { protel_add(40, 2) };
println!("Rust: protel_add(40, 2) = {sum}");
}
+15
View File
@@ -0,0 +1,15 @@
// Rust function called from PROTEL via EXTERNAL / #[no_mangle] extern "C".
use std::ffi::CStr;
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn rust_greet(name: *const c_char, value: i16) {
let label = unsafe {
if name.is_null() {
"<null>"
} else {
CStr::from_ptr(name).to_str().unwrap_or("<invalid utf-8>")
}
};
println!("Rust: rust_greet(name={label}, value={value})");
}
@@ -0,0 +1,8 @@
// Swift program calling an EXPORTed PROTEL procedure (C linkage).
import Foundation
@_silgen_name("protel_add")
func protel_add(_ a: Int16, _ b: Int16) -> Int16
let sum = protel_add(40, 2)
print("Swift: protel_add(40, 2) = \(sum)")
+8
View File
@@ -0,0 +1,8 @@
// Swift function called from PROTEL via EXTERNAL / @_cdecl("swift_greet").
import Foundation
@_cdecl("swift_greet")
public func swift_greet(_ name: UnsafePointer<CChar>, _ value: Int32) {
let label = String(cString: name)
print("Swift: swift_greet(name=\(label), value=\(value))")
}
+17
View File
@@ -0,0 +1,17 @@
% Introductory Manual 2026 - Figure 1 (Section 1.3)
% Calculates the factorial of a number n.
SECTION factorial_demo;
TYPE integer {-32768 TO 32767};
DCL factorial PROC(n integer) RETURNS integer IS
BLOCK
DCL result, i integer;
n -> i -> result;
WHILE (i - 1 -> i) > 1
DO
i * result -> result;
ENDDO;
RETURN result;
ENDBLOCK;
+28
View File
@@ -0,0 +1,28 @@
% Introductory Manual §1.3 + §5.5.2 + §7.3
% Command-line factorial via USES intro_1_3_factorial.protel (section factorial_demo).
% Demonstrates C interop: printf() and atoi() are EXTERNAL; no INTRINSIC I/O.
SECTION factorial_cli USES factorial_demo;
TYPE integer {-32768 TO 32767};
TYPE char {0 TO 255};
DCL printf PROC(fmt PTR TO char, n integer, fact integer) EXTERNAL;
DCL atoi PROC(str PTR TO char) RETURNS integer EXTERNAL;
DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;
DCL Start PROC(argc integer, argv PTR TO PTR TO char) RETURNS integer IS
BLOCK
DCL n integer INIT 0;
DCL result integer INIT 0;
IF argc < 2
THEN
printf({'Usage: factorial N', 0}, 0, 0);
RETURN 1;
ENDIF;
atoi(argv[1]) -> n;
factorial(n) -> result;
printf({'%d! = %d', 0}, n, result);
RETURN 0;
ENDBLOCK;
+12
View File
@@ -0,0 +1,12 @@
% Introductory Manual 2026 - Section 2.1 (selected type declarations)
SECTION types_demo;
TYPE integer {-32768 TO 32767};
TYPE digit_register TABLE[0 TO 15] OF integer;
TYPE features_table DESC OF integer;
TYPE availability BOOL;
TYPE trunk_status {in_service, out_of_service};
DCL primes TABLE[1 TO 6] OF integer IS {2, 3, 5, 7, 11, 13};
DCL seconds_per_hour integer IS 60 * 60;
@@ -0,0 +1,12 @@
% Introductory Manual 2026 - Figure 4 (constant procedure declaration)
SECTION calculate_average_demo;
TYPE integer {-32768 TO 32767};
DCL calculate_average PROC(number_1, number_2 integer) RETURNS integer IS
BLOCK
DCL average integer;
(number_1 + number_2) / 2 -> average;
RETURN average;
ENDBLOCK;
+16
View File
@@ -0,0 +1,16 @@
% Introductory Manual 2026 - Section 3.2.4 (CASE statement)
SECTION case_demo;
TYPE digit {0 TO 9};
TYPE integer {-32768 TO 32767};
DCL route_digit PROC(n digit) IS
BLOCK
CASE n IN
{0}: TRUE -> operator;
{1}: TRUE -> ddd_call;
{4}: TRUE -> assist;
OUT
ENDCASE;
ENDBLOCK;
+17
View File
@@ -0,0 +1,17 @@
% Introductory Manual 2026 - Figure 13 (FOR iterative statement)
SECTION sum_table_demo;
TYPE integer {-32768 TO 32767};
DCL t TABLE[0 TO 9] OF integer;
DCL sum_t PROC() RETURNS integer IS
BLOCK
DCL sum integer INIT 0;
FOR i FROM 0 UP TO UPB t
DO
t[i] + sum -> sum;
ENDDO;
RETURN sum;
ENDBLOCK;
+21
View File
@@ -0,0 +1,21 @@
% Introductory Manual §5.5.2 — UNIX argc/argv and shell exit status
% The ENTRY procedure receives the host command line; RETURN becomes exit status.
SECTION ArgsExit;
TYPE char {0 TO 255};
TYPE integer {-32768 TO 32767};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;
DCL Start PROC(argc integer, argv PTR TO PTR TO char) RETURNS integer IS
BLOCK
DCL i integer INIT 0;
FOR i FROM 0 UP TO argc - 1
DO
writeln(argv[i]);
ENDDO;
RETURN argc;
ENDBLOCK;
+18
View File
@@ -0,0 +1,18 @@
% Reference Manual §10.0 — BIND and WITH declarations
SECTION ref_bind_with;
TYPE integer {-32768 TO 32767};
TYPE point STRUCT
x integer,
y integer
ENDSTRUCT;
DCL demo PROC() IS
BLOCK
DCL p point;
BIND px TO p AS point;
WITH p;
1 -> px.x;
ENDBLOCK;
+11
View File
@@ -0,0 +1,11 @@
% Reference Manual §11.0–§11.3 — Type compatibility and operators
SECTION ref_type_compat;
TYPE integer {-32768 TO 32767};
TYPE small {0 TO 7};
DCL combine PROC(a integer, b small) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
+11
View File
@@ -0,0 +1,11 @@
% Reference Manual §12.0 — Intrinsic procedures
SECTION ref_intrinsic;
TYPE integer {-32768 TO 32767};
DCL writeln PROC(msg PTR TO char) IS INTRINSIC;
DCL demo PROC() IS
BLOCK
ENDBLOCK;
+22
View File
@@ -0,0 +1,22 @@
% Reference Manual §13.0 — TYPEDESC, VARDESC, REFDESC; EXTERNAL/EXPORT
SECTION ref_descriptors;
TYPE integer {-32768 TO 32767};
TYPE char {0 TO 255};
DCL writeln PROC(msg PTR TO char) EXTERNAL;
DCL exported_add PROC(a integer, b integer) RETURNS integer EXPORT;
DCL exported_add PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
DCL Start PROC() IS ENTRY;
DCL Start PROC() IS
BLOCK
DCL td integer INIT 0;
TYPEDESC integer -> td;
ENDBLOCK;
@@ -0,0 +1,19 @@
% Reference Manual §14.0 — Appendix A keyword exercise (remaining reserved words)
SECTION ref_keywords;
TYPE integer {-32768 TO 32767};
TYPE char {0 TO 255};
TYPE hue SET integer;
DCL show PROC() RETURNS integer IS
BLOCK
DCL mask hue IS {1, 2};
DCL subset hue IS {2};
DCL merged hue;
IF subset NOTINCL mask THEN
RETURN 0;
ENDIF;
merged + (subset INCL {4}) -> merged;
RETURN TDSIZE mask;
ENDBLOCK;
+9
View File
@@ -0,0 +1,9 @@
% Reference Manual §1.0 — Introduction (minimal compilation unit)
SECTION ref_intro;
TYPE integer {-32768 TO 32767};
DCL noop PROC() IS
BLOCK
ENDBLOCK;
+11
View File
@@ -0,0 +1,11 @@
% Reference Manual §3.0–§3.4 — Language format, keywords, comments, symbols
SECTION ref_lexical;
TYPE integer {-32768 TO 32767};
DCL demo PROC() IS
BLOCK
DCL total integer INIT 0;
1 + 2 * 3 -> total;
ENDBLOCK;
+11
View File
@@ -0,0 +1,11 @@
% Reference Manual §4.0–§4.5 — Identifiers, numbers, constants, tuples, strings
SECTION ref_data;
TYPE integer {-32768 TO 32767};
TYPE char {0 TO 255};
DCL nums TABLE[1 TO 3] OF integer IS {1, 2, 3};
DCL label TABLE[1 TO 5] OF char IS {'h', 'e', 'l', 'l', 'o'};
DCL flag BOOL IS TRUE;
DCL empty_tuple TABLE[1 TO 0] OF integer IS {};
@@ -0,0 +1,15 @@
% Reference Manual §5.0 — Unit of compilation (USES / OF)
SECTION ref_provider;
TYPE integer {-32768 TO 32767};
DCL provider_value integer IS 42;
SECTION ref_consumer OF ref_provider USES ref_provider;
DCL consumer PROC() IS
BLOCK
DCL local integer INIT 0;
provider_value -> local;
ENDBLOCK;
+5
View File
@@ -0,0 +1,5 @@
$LI modentry restart
$EJECT
SECTION ref_directives;
TYPE integer {-32768 TO 32767};
DCL noop PROC() IS BLOCK ENDBLOCK;
+19
View File
@@ -0,0 +1,19 @@
% Reference Manual §6.0 — Module types (FAST, PERPROCESS, DEFINITIONS, INTERFACE)
FAST SECTION ref_fast;
TYPE fast_integer {-32768 TO 32767};
PERPROCESS SECTION ref_perprocess;
TYPE pp_integer {-32768 TO 32767};
DEFINITIONS SECTION ref_definitions;
TYPE def_integer {-32768 TO 32767};
INTERFACE ref_interface;
TYPE iface_integer {-1 TO 1};
DCL iface_proc PROC() IS BLOCK ENDBLOCK;
+8
View File
@@ -0,0 +1,8 @@
% Reference Manual §7.0 — Declarations overview
SECTION ref_declarations;
TYPE integer {-32768 TO 32767};
DCL counter integer INIT 0;
DCL increment PROC() IS BLOCK counter + 1 -> counter; ENDBLOCK;
@@ -0,0 +1,14 @@
% Reference Manual §7.1.1 — Simple types (range, symbolic, BOOL, PTR, defined)
SECTION ref_simple_types;
TYPE integer {-32768 TO 32767};
TYPE digit {0 TO 9};
TYPE status {idle, busy, error};
TYPE flag BOOL;
TYPE node STRUCT
value integer,
next PTR TO node
ENDSTRUCT;
DCL root PTR TO node;
+23
View File
@@ -0,0 +1,23 @@
% Reference Manual §7.1.2 — Aggregate types (SET, STRUCT, TABLE, DESC, AREA)
% Area options include UNRESTRICTED and NONTRANSPARENT.
SECTION ref_aggregates;
TYPE integer {-32768 TO 32767};
TYPE hue SET integer;
TYPE pair STRUCT
left integer,
right integer
ENDSTRUCT;
TYPE buffer TABLE[0 TO 7] OF integer;
TYPE view DESC OF integer;
TYPE father UNRESTRICTED AREA (48)
a integer,
b integer
ENDAREA;
DCL colors hue;
DCL buf buffer;
DCL hues hue IS {1, 2, 4};
DCL merged hue IS hues INCL {8};
+17
View File
@@ -0,0 +1,17 @@
% Reference Manual §7.1.3 — Procedure types (QUICK, OPERAND, FORWARD, UPDATES, REF)
SECTION ref_procedures;
TYPE integer {-32768 TO 32767};
DCL add_pair QUICK PROC(a integer, b integer) RETURNS integer IS FORWARD;
DCL add_pair QUICK PROC(a integer, b integer) RETURNS integer IS
BLOCK
RETURN a + b;
ENDBLOCK;
DCL scale OPERAND PROC(REF factor integer, UPDATES buf TABLE[0 TO 3] OF integer) IS
BLOCK
factor * buf[0] -> buf[0];
ENDBLOCK;
@@ -0,0 +1,11 @@
% Reference Manual §7.2 — Data declarations (INIT, PACK, VAL, LITERAL, VARIABLE)
SECTION ref_data_decl;
TYPE integer {-32768 TO 32767};
TYPE packed_digit PACK (4) {0 TO 15};
TYPE val_char VAL {0 TO 255};
DCL literal_max LITERAL integer INIT 100;
DCL counter VARIABLE integer INIT 0;
DCL packed_val packed_digit IS 7;
+15
View File
@@ -0,0 +1,15 @@
% Reference Manual §7.3 — Structure overlays (OVLY)
SECTION ref_overlays;
TYPE integer {-32768 TO 32767};
TYPE word_view STRUCT
low integer,
high integer
ENDSTRUCT;
DCL OVLY word_view
{0}: low integer,
{1}: high integer
ENDOVLY;
+14
View File
@@ -0,0 +1,14 @@
% Reference Manual §8.0–§8.2 — Scope rules and local blocks
SECTION ref_scope;
TYPE integer {-32768 TO 32767};
DCL outer PROC() IS
BLOCK
DCL outer_var integer INIT 1;
BLOCK
DCL inner_var integer INIT 2;
inner_var + outer_var -> inner_var;
ENDBLOCK
ENDBLOCK;
+11
View File
@@ -0,0 +1,11 @@
% Reference Manual §9.0 — Executable statements overview
SECTION ref_statements;
TYPE integer {-32768 TO 32767};
DCL run PROC() IS
BLOCK
DCL x integer INIT 0;
x + 1 -> x;
ENDBLOCK;
+22
View File
@@ -0,0 +1,22 @@
% Reference Manual §9.1 — Expressions (operators, NIL, FALSE, MOD, CAST, descriptors)
% Runtime descriptor types: $TYPEDESC $VARDESC $REFDESC $UNIVERSAL_PTR
SECTION ref_expressions;
TYPE integer {-32768 TO 32767};
TYPE universal PTR TO integer;
DCL demo PROC() RETURNS integer IS
BLOCK
DCL a integer INIT 10;
DCL b integer INIT 3;
DCL flag BOOL INIT FALSE;
DCL cell_ptr PTR TO integer INIT NIL;
DCL slot universal INIT NIL;
DCL td integer INIT 0;
TYPEDESC integer -> td;
VARDESC a -> td;
REFDESC cell_ptr -> td;
CAST a AS integer -> a;
RETURN a MOD b;
ENDBLOCK;
+10
View File
@@ -0,0 +1,10 @@
% Reference Manual §9.2 — RETURN statement
SECTION ref_return;
TYPE integer {-32768 TO 32767};
DCL status PROC(code integer) RETURNS integer IS
BLOCK
RETURN code;
ENDBLOCK;
+14
View File
@@ -0,0 +1,14 @@
% Reference Manual §9.3 — IF statement
SECTION ref_if;
TYPE integer {-32768 TO 32767};
DCL classify PROC(n integer) RETURNS integer IS
BLOCK
IF n > 0 THEN
RETURN 1;
ELSE
RETURN 0;
ENDIF;
ENDBLOCK;
+15
View File
@@ -0,0 +1,15 @@
% Reference Manual §9.4 — CASE statement
SECTION ref_case;
TYPE digit {0 TO 9};
TYPE integer {-32768 TO 32767};
DCL route PROC(n digit) IS
BLOCK
CASE n IN
{0}: TRUE -> operator;
{1}: TRUE -> local;
OUT
ENDCASE;
ENDBLOCK;
+14
View File
@@ -0,0 +1,14 @@
% Reference Manual §9.5 — SELECT statement
SECTION ref_select;
TYPE integer {-32768 TO 32767};
DCL pick PROC(n integer) RETURNS integer IS
BLOCK
SELECT n IN
{1}: RETURN 10;
{2}: RETURN 20;
OUT RETURN 0;
ENDSELECT;
ENDBLOCK;
+17
View File
@@ -0,0 +1,17 @@
% Reference Manual §9.6 — EXIT statement
SECTION ref_exit;
TYPE integer {-32768 TO 32767};
DCL search PROC(limit integer) RETURNS integer IS
BLOCK
DCL i integer INIT 0;
FOR i FROM 0 UP TO limit
DO
IF i = 3 THEN
EXIT;
ENDIF;
ENDDO;
RETURN i;
ENDBLOCK;
+26
View File
@@ -0,0 +1,26 @@
% Reference Manual §9.7 — Iterative statements (WHILE, FOR, OVER, DOWN, BY)
SECTION ref_iterative;
TYPE integer {-32768 TO 32767};
TYPE item TABLE[0 TO 3] OF integer;
DCL iterate PROC() RETURNS integer IS
BLOCK
DCL sum integer INIT 0;
DCL i integer INIT 0;
DCL j integer INIT 3;
WHILE i < 4
DO
i + 1 -> i;
ENDDO;
FOR j FROM 3 DOWN TO 0 BY 1
DO
sum + j -> sum;
ENDDO;
OVER item
DO
sum + 1 -> sum;
ENDDO;
RETURN sum;
ENDBLOCK;
+43
View File
@@ -0,0 +1,43 @@
% Reference Manual OO extension — CLASS, METHOD, CREATE, OVERRIDING, SUPER
INTERFACE ref_oo;
TYPE integer {-32768 TO 32767};
TYPE base_node
CLASS REFINES $OBJECT
{PROTECTED, SHARED}:
depth integer;
{PRIVATE, EXCLUSIVE}:
tag integer
OPERATIONS
{ABSTRACT}:
describe()
{CREATE, OVERRIDING, HIDDEN, FIXED}:
depth() RETURNS integer
{CLASS}:
factory() RETURNS PTR TO base_node
{}:
bump()
ENDCLASS base_node;
TYPE leaf_node
CLASS REFINES base_node
{PROTECTED}:
value integer
OPERATIONS
{OVERRIDING}:
describe(),
bump()
ENDCLASS leaf_node;
IN leaf_node
DCL describe METHOD IS
BLOCK
SUPER.bump();
ENDBLOCK;
DCL bump METHOD IS
BLOCK
1 + SELF.value -> SELF.value;
ENDBLOCK;
+14
View File
@@ -0,0 +1,14 @@
% Reference Manual 2026 - STRUCT type example (task_block)
SECTION struct_demo;
TYPE integer {-32768 TO 32767};
TYPE code_block integer;
TYPE task_block STRUCT
priority {0 TO 5},
status {ready, blocked, executing},
next_task PTR TO task_block,
completed BOOL,
code code_block
ENDSTRUCT;
@@ -0,0 +1,22 @@
% Class Methods and Variables (1994) - Example 4 (invocation)
SECTION oo_invoke_demo;
TYPE integer {-32768 TO 32767};
TYPE class_with_class_method
CLASS REFINES $OBJECT
{}:
instance_var integer
OPERATIONS
{CLASS}:
class_method(parameter integer)
ENDCLASS class_with_class_method;
DCL instance class_with_class_method;
DCL demo PROC() IS
BLOCK
class_with_class_method.class_method(5);
instance.class_method(6);
ENDBLOCK;
+41
View File
@@ -0,0 +1,41 @@
/* Generated by PROTEL 2026 C++ transpiler */
/* Source: /Users/vincente/PROTEL/examples/ref_oo_class_with_var.protel */
#include <cstdint>
#include <iostream>
#include "protel_io.hpp"
namespace protel_generated {
namespace oo_class_demo {
/* FAST INTERFACE */
/* TYPE integer */
using integer = int16_t;
/* TYPE class_with_var */
class class_with_var {
public:
static int16_t class_var;
int16_t instance_var;
static void class_method(int16_t parameter);
void instance_method(int16_t value);
};
/* IN class_with_var */
int16_t class_with_var::class_var = 0;
void class_with_var::class_method(int16_t parameter)
{
class_with_var::class_var = 5;
}
void class_with_var::instance_method(int16_t value)
{
this->instance_var = value;
}
} // namespace oo_class_demo
} // namespace protel_generated
+29
View File
@@ -0,0 +1,29 @@
% Class Methods and Variables (1994) - Examples 1-3 adapted for PROTEL 2026
INTERFACE oo_class_demo;
TYPE integer {-32768 TO 32767};
TYPE class_with_var
CLASS REFINES $OBJECT
{PROTECTED}:
class_var integer;
{}:
instance_var integer
OPERATIONS
{CLASS}:
class_method(parameter integer)
{}:
instance_method(value integer)
ENDCLASS class_with_var;
IN class_with_var
DCL class_method METHOD IS
BLOCK
5 -> SELF.class_var;
ENDBLOCK;
DCL instance_method METHOD IS
BLOCK
value -> SELF.instance_var;
ENDBLOCK;
Executable
+321
View File
@@ -0,0 +1,321 @@
#!/usr/bin/env python3
"""PROTEL 2026 compiler driver (Introductory Manual 7.1)."""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parent
_SCRIPT = Path(__file__).resolve()
_VENV_PY = _ROOT / ".venv" / "bin" / "python3"
_REQUIREMENTS = _ROOT / "requirements.txt"
def _running_in_project_venv() -> bool:
"""True only when this interpreter's sys.prefix is the project .venv."""
try:
return Path(sys.prefix).resolve() == (_ROOT / ".venv").resolve()
except OSError:
return False
def _bootstrap_venv() -> None:
import subprocess
if not _VENV_PY.exists():
subprocess.run(
[sys.executable, "-m", "venv", str(_ROOT / ".venv")],
check=True,
)
subprocess.run(
[
str(_ROOT / ".venv" / "bin" / "pip"),
"install",
"-q",
"-r",
str(_REQUIREMENTS),
],
check=True,
)
def _ensure_runtime() -> None:
"""Use project .venv with Lark installed; bootstrap on first run."""
if _running_in_project_venv():
try:
import lark # noqa: F401
except ImportError:
try:
_bootstrap_venv()
except Exception as exc:
print(
f"protel: failed to install dependencies in .venv: {exc}",
file=sys.stderr,
)
raise SystemExit(1) from exc
try:
import lark # noqa: F401
except ImportError as exc:
print(
"protel: lark is still missing after setup; "
"run 'make install'",
file=sys.stderr,
)
raise SystemExit(1) from exc
return
try:
_bootstrap_venv()
except Exception as exc:
print(f"protel: failed to set up Python environment: {exc}", file=sys.stderr)
print(
"protel: run 'make install' or "
"'python3 -m venv .venv && .venv/bin/pip install -r requirements.txt'",
file=sys.stderr,
)
raise SystemExit(1) from exc
os.execv(str(_VENV_PY), [str(_VENV_PY), str(_SCRIPT), *sys.argv[1:]])
_ensure_runtime()
sys.path.insert(0, str(_ROOT))
from src.parser import parse_protel
from src.transpiler import transpile_to_c
from src.cpp_transpiler import transpile_to_cpp
from src.type_checker import TypeCheckError
from src.compile import compile_cpp, run_executable
from src.extensions import format_suffix_list, is_pls_suffix, is_protel_source
def _validate_input(path: Path) -> None:
if not is_protel_source(path):
print(
f"protel: warning: '{path}' does not use a PROTEL extension "
f"({format_suffix_list()})",
file=sys.stderr,
)
def _split_program_args(argv: list[str]) -> tuple[list[str], list[str]]:
if "--" not in argv:
return argv, []
sep = argv.index("--")
return argv[:sep], argv[sep + 1 :]
def _promote_shebang_input(
argv: list[str], program_args: list[str]
) -> tuple[list[str], list[str]]:
"""
Shebang form: protel --run -- script.protel [program args].
The kernel places the script path after ``--``; promote it to the input
positional expected by the driver.
"""
if "--run" not in argv or not program_args:
return argv, program_args
candidate = Path(program_args[0])
try:
if is_protel_source(candidate) and candidate.is_file():
return [*argv, program_args[0]], program_args[1:]
except OSError:
pass
return argv, program_args
def main(argv: list[str] | None = None) -> int:
if argv is None:
argv = sys.argv[1:]
argv, program_args = _split_program_args(list(argv))
argv, program_args = _promote_shebang_input(argv, program_args)
parser = argparse.ArgumentParser(
description="PROTEL 2026 compiler (GCC/clang++ backend)",
epilog=(
"Invoke: protel [-o outfile] sourcefile(s) [--classical]\n"
"GCC options -g and -c are passed through when compiling."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"input",
nargs="+",
help="PROTEL source file(s) (.protel, .pt, .ptl, .P, .AA01..ZZ99)",
)
parser.add_argument(
"-o",
"--output",
help="Output file (executable, object, or generated source)",
)
parser.add_argument(
"--classical",
action="store_true",
help="Legacy PROTEL identifier rules (keywords remain UPPERCASE)",
)
parser.add_argument(
"--parse-only",
action="store_true",
help="Parse only; print AST summary to stderr",
)
parser.add_argument(
"--emit-c",
action="store_true",
help="Emit C instead of C++ (default is C++)",
)
parser.add_argument(
"--compile",
action="store_true",
help="Transpile and compile to a native executable or object",
)
parser.add_argument(
"--run",
action="store_true",
help="Compile and run the program (implies --compile)",
)
parser.add_argument(
"-c",
action="store_true",
help="Compile only; produce an object file (passed to GCC)",
)
parser.add_argument(
"-g",
action="store_true",
help="Generate debug info (passed to GCC)",
)
parser.add_argument(
"--keep",
action="store_true",
help="Keep generated C/C++ source after compiling",
)
parser.add_argument("--version", action="version", version="protel 0.3.0")
args = parser.parse_args(argv)
if len(args.input) > 1:
print("protel: warning: only the first source file is compiled", file=sys.stderr)
input_path = Path(args.input[0]).resolve()
_validate_input(input_path)
classical = args.classical or is_pls_suffix(input_path.suffix)
try:
source = input_path.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
print(f"protel: cannot read '{input_path}': {exc}", file=sys.stderr)
return 1
try:
tree = parse_protel(source, classical=classical)
except Exception as exc:
print(f"protel: parse error in '{input_path}': {exc}", file=sys.stderr)
return 1
if args.parse_only:
print(tree, file=sys.stderr)
return 0
compile_requested = args.compile or args.run or args.c or (
args.output is not None and not args.output.endswith((".c", ".cpp"))
)
try:
if args.emit_c:
code = transpile_to_c(
tree,
classical=classical,
source_name=str(input_path),
source_path=input_path,
)
default_ext = ".c"
else:
code = transpile_to_cpp(
tree,
classical=classical,
source_name=str(input_path),
source_path=input_path,
)
default_ext = ".cpp"
except TypeCheckError as exc:
print(f"protel: type error in '{input_path}': {exc}", file=sys.stderr)
return 1
except Exception as exc:
print(f"protel: transpile error in '{input_path}': {exc}", file=sys.stderr)
return 1
if compile_requested:
if args.emit_c:
print("protel: compile mode requires C++ output (omit --emit-c)", file=sys.stderr)
return 1
build_dir = _ROOT / "build"
build_dir.mkdir(parents=True, exist_ok=True)
if args.output and str(args.output).endswith((".c", ".cpp")):
gen_path = Path(args.output)
else:
gen_path = build_dir / f"{input_path.stem}{default_ext}"
gen_path.write_text(code, encoding="utf-8")
if args.c:
obj_path = Path(args.output) if args.output else input_path.with_suffix(".o")
try:
compile_cpp(
gen_path,
obj_path,
compile_only=True,
debug=args.g,
)
except RuntimeError as exc:
print(f"protel: compile error: {exc}", file=sys.stderr)
return 1
if not args.keep:
try:
gen_path.unlink()
except OSError:
pass
print(f"protel: wrote {obj_path}", file=sys.stderr)
return 0
exe_path = Path(args.output) if args.output else Path("a.out")
try:
compile_cpp(gen_path, exe_path, debug=args.g)
except RuntimeError as exc:
print(f"protel: compile error: {exc}", file=sys.stderr)
return 1
if not args.keep:
try:
gen_path.unlink()
except OSError:
pass
if args.run:
code_rc, stdout, stderr = run_executable(exe_path, program_args)
if stdout:
sys.stdout.write(stdout)
if stderr:
sys.stderr.write(stderr)
return code_rc
print(f"protel: wrote {exe_path}", file=sys.stderr)
return 0
if args.output:
try:
Path(args.output).write_text(code, encoding="utf-8")
except OSError as exc:
print(f"protel: cannot write '{args.output}': {exc}", file=sys.stderr)
return 1
else:
sys.stdout.write(code)
return 0
if __name__ == "__main__":
raise SystemExit(main())
Executable
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Run a .protel file invoked via shebang (Introductory Manual §7.0.5).
The kernel executes: protel-run /path/to/script.protel [program args]
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parent
_PROTEL = _ROOT / "protel"
def main() -> int:
if len(sys.argv) < 2:
print(
"protel-run: missing PROTEL source path "
"(use #!/usr/bin/env protel-run in a .protel file)",
file=sys.stderr,
)
return 2
source = Path(sys.argv[1]).resolve()
program_args = sys.argv[2:]
if not _PROTEL.is_file():
print(f"protel-run: cannot find protel driver at '{_PROTEL}'", file=sys.stderr)
return 1
argv = [str(_PROTEL), str(source), "--run", "--", *program_args]
os.execv(str(_PROTEL), argv)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+1
View File
@@ -0,0 +1 @@
pytest>=8.0
+1
View File
@@ -0,0 +1 @@
lark>=1.2.0
+3
View File
@@ -0,0 +1,3 @@
"""PROTEL 2026 parser and transpiler."""
__version__ = "0.1.0"
+294
View File
@@ -0,0 +1,294 @@
"""AST node definitions for PROTEL 2026."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Section:
module_type: str
section_kind: str
name: str
of_modules: list[str] = field(default_factory=list)
uses_modules: list[str] = field(default_factory=list)
declarations: list[Any] = field(default_factory=list)
statements: list[Any] = field(default_factory=list)
class_impls: list[Any] = field(default_factory=list)
@dataclass
class TypeDecl:
names: list[str]
type_spec: Any
@dataclass
class VarDecl:
names: list[str]
type_spec: Any
init: Any | None = None
storage_class: str | None = None
ovly_fields: list[tuple[Any, list[str], Any]] | None = None
@dataclass
class ProcDecl:
name: str
parms: list[tuple[list[str], Any, Any]]
return_type: Any | None
body: Any | None
pclass: str | None = None
intrinsic: bool = False
forward: bool = False
external: bool = False
entry: bool = False
export: bool = False
@dataclass
class ClassDataPart:
access_attrs: list[str]
fields: list[tuple[list[str], Any]]
@dataclass
class MethodDecl:
names: list[str]
parms: list[tuple[list[str], Any, bool]]
return_type: Any | None
attrs: list[str] = field(default_factory=list)
@dataclass
class MethodSection:
attrs: list[str]
methods: list[MethodDecl]
@dataclass
class ClassType:
end_name: str
base: Any | None
data_parts: list[ClassDataPart]
operations: list[MethodSection]
@dataclass
class MethodImplDecl:
name: str
body: Any
@dataclass
class ClassImplSection:
class_name: str
declarations: list[Any]
statements: list[Any] = field(default_factory=list)
@dataclass
class Block:
declarations: list[Any]
statements: list[Any]
@dataclass
class IfStmt:
condition: Any
then_part: list[Any]
else_part: list[Any] = field(default_factory=list)
@dataclass
class LoopStmt:
while_expr: Any | None
body: list[Any]
@dataclass
class ForStmt:
var: str
from_expr: Any | None
to_expr: Any | None
direction: str | None
by_expr: Any | None
while_expr: Any | None
over_type: Any | None
body: list[Any]
@dataclass
class OverStmt:
over_type: Any
body: list[Any]
@dataclass
class CaseArm:
labels: Any
statements: list[Any]
@dataclass
class CaseStmt:
selector: Any
arms: list[CaseArm]
out_statements: list[Any]
is_select: bool = False
@dataclass
class ExitStmt:
pass
@dataclass
class BindStmt:
bindings: list[tuple[str, Any, Any | None]]
@dataclass
class WithStmt:
refs: list[Any]
@dataclass
class CastExpr:
operand: Any
target_type: Any
@dataclass
class AreaType:
options: list[str]
size_expr: Any
fields: list[tuple[list[str], Any]]
@dataclass
class ReturnStmt:
value: Any | None = None
@dataclass
class AssignExpr:
value: Any
target: Any
@dataclass
class BinExpr:
op: str
left: Any
right: Any
@dataclass
class UnaryExpr:
op: str
operand: Any
@dataclass
class BuiltinExpr:
name: str
operand: Any
@dataclass
class VarRef:
name: str
indices: list[Any] = field(default_factory=list)
is_self: bool = False
is_super: bool = False
@dataclass
class MemberRef:
base: Any
member: str
@dataclass
class MethodCall:
receiver: Any | None
name: str
args: list[Any] = field(default_factory=list)
@dataclass
class ProcCall:
name: str
args: list[Any] = field(default_factory=list)
@dataclass
class Literal:
kind: str
value: Any
@dataclass
class TupleLit:
elements: list[Any]
@dataclass
class RangeType:
low: Any
high: Any
packed: int | None = None
@dataclass
class SymbolicRange:
members: list[str]
@dataclass
class DefinedType:
name: str
@dataclass
class BoolType:
packed: int | None = None
@dataclass
class PtrType:
target: Any
@dataclass
class SetType:
member_type: Any
@dataclass
class StructType:
fields: list[tuple[list[str], Any]]
@dataclass
class TableType:
low: Any
high: Any
element_type: Any
packed: int | None = None
@dataclass
class DescType:
low: Any | None
high: Any | None
element_type: Any
@dataclass
class ProcTypeSig:
parms: list[tuple[list[str], Any, Any]]
return_type: Any | None
pclass: str | None = None
+103
View File
@@ -0,0 +1,103 @@
"""Compile and link PROTEL-generated C++ on macOS / Linux."""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
_ROOT = Path(__file__).resolve().parent.parent
_RUNTIME_DIR = Path(__file__).resolve().parent / "runtime"
_RUNTIME_IO_C = _RUNTIME_DIR / "protel_io.c"
def find_cxx_compiler() -> str | None:
for name in ("g++", "c++", "clang++"):
path = shutil.which(name)
if path:
return path
return None
def compile_cpp(
cpp_source: Path,
output: Path,
*,
compile_only: bool = False,
debug: bool = False,
link_runtime: bool = True,
extra_flags: list[str] | None = None,
) -> None:
compiler = find_cxx_compiler()
if compiler is None:
raise RuntimeError("no C++ compiler found (tried g++, c++, clang++)")
output.parent.mkdir(parents=True, exist_ok=True)
cmd = [
compiler,
"-std=c++20",
"-Wall",
"-Wextra",
f"-I{_RUNTIME_DIR}",
]
if debug:
cmd.append("-g")
if extra_flags:
cmd.extend(extra_flags)
src = str(cpp_source.resolve())
if compile_only:
cmd.extend(["-c", src, "-o", str(output.resolve())])
else:
cmd.append(src)
if link_runtime and _RUNTIME_IO_C.exists():
cmd.append(str(_RUNTIME_IO_C.resolve()))
cmd.extend(["-o", str(output.resolve())])
result = subprocess.run(cmd, capture_output=True, text=True, cwd=_ROOT)
if result.returncode != 0:
msg = result.stderr.strip() or result.stdout.strip() or "compile failed"
raise RuntimeError(msg)
def check_cpp_syntax(
cpp_source: Path,
*,
extra_flags: list[str] | None = None,
) -> None:
compiler = find_cxx_compiler()
if compiler is None:
raise RuntimeError("no C++ compiler found (tried g++, c++, clang++)")
cmd = [
compiler,
"-std=c++20",
"-Wall",
"-Wextra",
f"-I{_RUNTIME_DIR}",
"-fsyntax-only",
str(cpp_source.resolve()),
]
if extra_flags:
cmd.extend(extra_flags)
result = subprocess.run(cmd, capture_output=True, text=True, cwd=_ROOT)
if result.returncode != 0:
msg = result.stderr.strip() or result.stdout.strip() or "syntax check failed"
raise RuntimeError(msg)
def run_executable(
path: Path,
program_args: list[str] | None = None,
) -> tuple[int, str, str]:
exe = path.resolve()
cmd = [str(exe)]
if program_args:
cmd.extend(program_args)
result = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=exe.parent,
)
return result.returncode, result.stdout, result.stderr
+755
View File
@@ -0,0 +1,755 @@
"""PROTEL 2026 to C++ transpiler (namespaces, classes, this)."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from . import ast_nodes as ast
from .transpiler import CTranspiler, TranspileError
_CPP_RESERVED_TYPE_NAMES = frozenset({
"bool", "char", "double", "float", "int", "long", "short", "void",
})
_LIBC_EXTERNAL_HEADERS: dict[str, str] = {
"printf": "<cstdio>",
"atoi": "<cstdlib>",
}
@dataclass(frozen=True)
class _EntryPointInfo:
namespace: str
name: str
parms: list[tuple[list[str], Any, bool]]
return_type: Any | None
returns_integer: bool
unix_argv: bool
def _sanitize_namespace(name: str) -> str:
out = []
for ch in name:
if ch.isalnum() or ch == "_":
out.append(ch)
else:
out.append("_")
if not out or out[0].isdigit():
out.insert(0, "_")
return "".join(out)
class CppTranspiler(CTranspiler):
def __init__(self, *, classical: bool = False, source_name: str = "input.protel"):
super().__init__(classical=classical, source_name=source_name)
self._cpp = True
self._current_namespace: str | None = None
self._namespace_stack: list[str] = []
self._entry_point: _EntryPointInfo | None = None
self._section_class_bodies: list[tuple[str, ast.ClassType]] = []
self._section_method_impls: list[
tuple[str, ast.MethodImplDecl, ast.MethodDecl | None]
] = []
self._external_procs: list[ast.ProcDecl] = []
def transpile(self, compilation_unit: list[ast.Section]) -> str:
self.lines = []
self._method_impls = []
self._class_methods = {}
self._class_vars = {}
self._var_types = {}
self._entry_point = None
self._section_class_bodies = []
self._section_method_impls = []
self._external_procs = []
self._section_by_name = {section.name: section for section in compilation_unit}
self._entry_point = self._resolve_entry_point(compilation_unit)
self._exported_procs = self._resolve_exported_procedures(compilation_unit)
self._exported_body_names = {proc.name for proc in self._exported_procs}
self.emit("/* Generated by PROTEL 2026 C++ transpiler */")
self.emit(f"/* Source: {self.source_name} */")
self.emit("/* EXTERNAL C linkage for I/O; minimal runtime (protel_io.c). */")
self.emit('#include <cstdint>')
self._collect_external_procs(compilation_unit)
libc_headers = sorted(
{
_LIBC_EXTERNAL_HEADERS[proc.name]
for proc in self._external_procs
if proc.name in _LIBC_EXTERNAL_HEADERS
}
)
for header in libc_headers:
self.emit(f"#include {header}")
self.emit("")
declared_externals = [
proc
for proc in self._external_procs
if proc.name not in _LIBC_EXTERNAL_HEADERS
]
if declared_externals:
self.emit('extern "C" {')
self.indent += 1
for proc in declared_externals:
self.emit(f"{self._cpp_external_proc_signature(proc)};")
self.indent -= 1
self.emit("}")
self.emit("")
self.emit("namespace protel_generated {")
for section in compilation_unit:
self._emit_cpp_section(section)
self.emit("} // namespace protel_generated")
self.emit("")
if self._exported_procs:
self.emit('extern "C" {')
self.indent += 1
for proc in self._exported_procs:
self._emit_cpp_exported_procedure(proc)
self.indent -= 1
self.emit("}")
self.emit("")
if self._entry_point:
self._emit_cpp_main_wrapper(self._entry_point)
return "\n".join(self.lines) + "\n"
def _emit_cpp_main_wrapper(self, entry: _EntryPointInfo) -> None:
ns, name = entry.namespace, entry.name
call = f"protel_generated::{ns}::{name}"
if entry.unix_argv:
self.emit("int main(int argc, char** argv) {")
self.indent += 1
if entry.returns_integer:
self.emit(f"return {call}(argc, argv);")
else:
self.emit(f"{call}(argc, argv);")
self.emit("return 0;")
else:
self.emit("int main() {")
self.indent += 1
if entry.returns_integer:
self.emit(f"return {call}();")
else:
self.emit(f"{call}();")
self.emit("return 0;")
self.indent -= 1
self.emit("}")
self.emit("")
def _resolve_entry_point(
self, compilation_unit: list[ast.Section]
) -> _EntryPointInfo | None:
entries: list[tuple[ast.Section, ast.ProcDecl]] = []
for section in compilation_unit:
for decl in section.declarations:
if isinstance(decl, ast.ProcDecl) and decl.entry:
entries.append((section, decl))
if not entries:
return None
if len(entries) > 1:
names = ", ".join(decl.name for _, decl in entries)
raise TranspileError(
f"multiple ENTRY procedures ({names}); only one ENTRY per module"
)
entry_section, entry_decl = entries[0]
if entry_decl.return_type or entry_decl.body:
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} must be declared as "
f"PROC[(argc integer, argv PTR TO PTR TO char)] IS ENTRY or PROC() IS ENTRY"
)
body_section: ast.Section | None = None
body_decl: ast.ProcDecl | None = None
for section in compilation_unit:
for decl in section.declarations:
if (
isinstance(decl, ast.ProcDecl)
and decl.name == entry_decl.name
and decl.body is not None
and not decl.entry
):
if body_decl is not None:
raise TranspileError(
f"duplicate body for ENTRY procedure {entry_decl.name!r}"
)
body_section = section
body_decl = decl
if body_decl is None:
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} has no procedure body in this module"
)
if not self._entry_parm_lists_match(entry_decl.parms, body_decl.parms):
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} declaration parameters must "
f"match the procedure body signature"
)
if body_decl.return_type is not None and not self._is_integer_return_type(
body_decl.return_type
):
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} may RETURNS integer only "
f"(shell exit status)"
)
unix_argv = self._is_unix_argv_entry_parms(entry_decl.parms)
if entry_decl.parms and not unix_argv:
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} parameters must be "
f"(argc integer, argv PTR TO PTR TO char) for UNIX command-line hosts"
)
if body_section is not entry_section:
raise TranspileError(
f"ENTRY procedure {entry_decl.name!r} must be declared and defined "
f"in the same section ({entry_section.name!r})"
)
returns_integer = body_decl.return_type is not None
return _EntryPointInfo(
namespace=_sanitize_namespace(body_section.name),
name=entry_decl.name,
parms=entry_decl.parms,
return_type=body_decl.return_type,
returns_integer=returns_integer,
unix_argv=unix_argv,
)
def _unwrap_entry_type(self, spec: Any) -> Any:
from lark import Tree
while isinstance(spec, Tree):
if spec.children:
spec = spec.children[0]
else:
break
return spec
def _is_integer_type(self, spec: Any) -> bool:
spec = self._unwrap_entry_type(spec)
if isinstance(spec, ast.DefinedType):
return spec.name == "integer"
if isinstance(spec, ast.RangeType):
return True
return False
def _is_ptr_to_ptr_to_char(self, spec: Any) -> bool:
spec = self._unwrap_entry_type(spec)
if not isinstance(spec, ast.PtrType):
return False
target = self._unwrap_entry_type(spec.target)
if not isinstance(target, ast.PtrType):
return False
inner = self._unwrap_entry_type(target.target)
return isinstance(inner, ast.DefinedType) and inner.name == "char"
def _is_unix_argv_entry_parms(
self, parms: list[tuple[list[str], Any, bool]]
) -> bool:
if len(parms) != 2:
return False
_, argc_type, _ = parms[0]
_, argv_type, _ = parms[1]
return self._is_integer_type(argc_type) and self._is_ptr_to_ptr_to_char(
argv_type
)
def _entry_parm_lists_match(
self,
left: list[tuple[list[str], Any, bool]],
right: list[tuple[list[str], Any, bool]],
) -> bool:
if len(left) != len(right):
return False
for (_, left_type, left_ref), (_, right_type, right_ref) in zip(left, right):
if left_ref != right_ref:
return False
if not self._entry_parm_types_equal(left_type, right_type):
return False
return True
def _entry_parm_types_equal(self, left: Any, right: Any) -> bool:
left = self._unwrap_entry_type(left)
right = self._unwrap_entry_type(right)
if type(left) is not type(right):
return False
if isinstance(left, ast.DefinedType):
return left.name == right.name
if isinstance(left, ast.PtrType):
return self._entry_parm_types_equal(left.target, right.target)
if isinstance(left, ast.RangeType):
return (
self._c_expr(left.low) == self._c_expr(right.low)
and self._c_expr(left.high) == self._c_expr(right.high)
)
return left == right
def _is_integer_return_type(self, spec: Any) -> bool:
return self._is_integer_type(spec)
def _resolve_exported_procedures(
self, compilation_unit: list[ast.Section]
) -> list[ast.ProcDecl]:
exports: dict[str, tuple[ast.Section, ast.ProcDecl]] = {}
for section in compilation_unit:
for decl in section.declarations:
if isinstance(decl, ast.ProcDecl) and decl.export:
if decl.name in exports:
raise TranspileError(
f"duplicate EXPORT declaration for {decl.name!r}"
)
exports[decl.name] = (section, decl)
if not exports:
return []
bodies: dict[str, ast.ProcDecl] = {}
body_sections: dict[str, ast.Section] = {}
for section in compilation_unit:
for decl in section.declarations:
if (
isinstance(decl, ast.ProcDecl)
and decl.name in exports
and decl.body is not None
and not decl.export
):
if decl.name in bodies:
raise TranspileError(
f"duplicate body for EXPORT procedure {decl.name!r}"
)
bodies[decl.name] = decl
body_sections[decl.name] = section
resolved: list[ast.ProcDecl] = []
for name, (export_section, export_decl) in exports.items():
body = bodies.get(name)
if body is None:
raise TranspileError(
f"EXPORT procedure {name!r} has no procedure body in this module"
)
if body_sections[name] is not export_section:
raise TranspileError(
f"EXPORT procedure {name!r} must be declared and defined "
f"in the same section ({export_section.name!r})"
)
if (
body.parms != export_decl.parms
or body.return_type != export_decl.return_type
or body.pclass != export_decl.pclass
):
raise TranspileError(
f"EXPORT declaration and body signatures differ for {name!r}"
)
resolved.append(body)
return resolved
def _emit_cpp_exported_procedure(self, proc: ast.ProcDecl):
self.emit(self._cpp_proc_signature(proc))
self.emit("{")
self.indent += 1
self._emit_block_body(proc.body)
self.indent -= 1
self.emit("}")
self.emit("")
def _collect_external_procs(self, compilation_unit: list[ast.Section]) -> None:
self._external_procs = []
for section in compilation_unit:
for decl in section.declarations:
if isinstance(decl, ast.ProcDecl) and decl.external:
self._external_procs.append(decl)
def _embedded_module_names(self, section: ast.Section) -> list[str]:
names: list[str] = []
seen: set[str] = set()
for module_name in (*section.of_modules, *section.uses_modules):
if module_name not in seen:
seen.add(module_name)
names.append(module_name)
return names
def _emit_embedded_usings(self, section: ast.Section) -> None:
for module_name in self._embedded_module_names(section):
embedded_ns = _sanitize_namespace(module_name)
embedded = self._section_by_name.get(module_name)
if embedded is None:
continue
symbols: list[str] = []
for decl in embedded.declarations:
if isinstance(decl, ast.VarDecl):
symbols.extend(decl.names)
elif isinstance(decl, ast.ProcDecl):
if (
decl.external
or decl.forward
or decl.entry
or decl.export
or decl.intrinsic
):
continue
symbols.append(decl.name)
for symbol in symbols:
self.emit(f"using {embedded_ns}::{symbol};")
if symbols:
self.emit("")
def _emit_cpp_section(self, section: ast.Section):
ns = _sanitize_namespace(section.name)
self._current_namespace = ns
self._namespace_stack.append(ns)
self._section_class_bodies = []
self._section_method_impls = []
self.emit(f"namespace {ns} {{")
self.indent += 1
self.emit(f"/* {section.module_type} {section.section_kind} */")
if section.uses_modules:
self.emit(f"/* USES: {', '.join(section.uses_modules)} */")
if section.of_modules:
self.emit(f"/* OF: {', '.join(section.of_modules)} */")
self.emit("")
self._emit_embedded_usings(section)
for decl in section.declarations:
self._emit_cpp_toplevel_decl(decl)
for impl in section.class_impls:
self._queue_class_impl(impl)
for stmt in section.statements:
self._emit_stmt(stmt)
for class_name, spec in self._section_class_bodies:
self._emit_cpp_class_definitions(class_name, spec)
for class_name, impl, method_decl in self._section_method_impls:
self._emit_cpp_method_impl(class_name, impl, method_decl)
self.indent -= 1
self.emit(f"}} // namespace {ns}")
self.emit("")
self._namespace_stack.pop()
self._current_namespace = self._namespace_stack[-1] if self._namespace_stack else None
def _emit_cpp_toplevel_decl(self, decl):
if isinstance(decl, ast.TypeDecl):
self.types.declare(decl.names, decl.type_spec)
for name in decl.names:
self.emit(f"/* TYPE {name} */")
if isinstance(decl.type_spec, ast.ClassType):
self._emit_cpp_class_declaration(decl.names[0], decl.type_spec)
elif isinstance(decl.type_spec, ast.StructType):
self._emit_cpp_struct(decl.names[0], decl.type_spec)
elif isinstance(decl.type_spec, ast.SymbolicRange):
self._emit_symbolic_typedef(decl.names[0], decl.type_spec)
else:
for name in decl.names:
if name in _CPP_RESERVED_TYPE_NAMES:
self.emit(
f"/* TYPE {name} -> {self._cpp_type(decl.type_spec)} */"
)
else:
self.emit(f"using {name} = {self._cpp_type(decl.type_spec)};")
self.emit("")
elif isinstance(decl, ast.VarDecl):
type_name = self._decl_type_name(decl.type_spec)
for name in decl.names:
if type_name:
self._var_types[name] = type_name
line = f"{self._cpp_type_decl(decl.type_spec, name)}"
if decl.init is not None:
line += f" = {self._c_init(decl.init)}"
line += ";"
self.emit(line)
self.emit("")
elif isinstance(decl, ast.ProcDecl):
if decl.intrinsic:
return
if decl.forward:
self.emit(f"/* FORWARD {decl.name} */")
self.emit(self._cpp_proc_signature(decl) + ";")
self.emit("")
return
if decl.external:
self._external_procs.append(decl)
return
if decl.entry:
self.emit(f"/* ENTRY {decl.name} */")
forward = ast.ProcDecl(
name=decl.name,
parms=decl.parms,
return_type=(
self._entry_point.return_type
if self._entry_point is not None
and self._entry_point.name == decl.name
else None
),
body=None,
pclass=decl.pclass,
entry=True,
)
self.emit(self._cpp_proc_signature(forward) + ";")
self.emit("")
return
if decl.export:
self.emit(f"/* EXPORT {decl.name} (defined with C linkage below) */")
self.emit("")
return
if decl.body and decl.name in self._exported_body_names:
return
if decl.body:
self._emit_cpp_procedure(decl)
else:
self.emit(self._cpp_proc_signature(decl) + ";")
self.emit("")
def _cpp_type(self, spec) -> str:
spec = self._unwrap_type(spec)
spec = self.types.resolve(spec)
if isinstance(spec, ast.BoolType):
return "bool"
if isinstance(spec, ast.DefinedType) and spec.name in _CPP_RESERVED_TYPE_NAMES:
resolved = self.types.resolve(spec)
if resolved is not spec:
return self._cpp_type(resolved)
return self._c_type(spec)
def _cpp_type_decl(self, spec, name: str) -> str:
spec = self._unwrap_type(spec)
if isinstance(spec, ast.TableType):
elem = self._cpp_type(spec.element_type)
count = self._table_count(spec.low, spec.high)
return f"std::array<{elem}, {count}> {name}"
return f"{self._cpp_type(spec)} {name}"
def _emit_cpp_struct(self, name: str, spec: ast.StructType):
self.types.declare([name], spec)
self.emit(f"struct {name} {{")
self.indent += 1
for field_names, field_type in spec.fields:
for field_name in field_names:
self.emit(f"{self._cpp_type_decl(field_type, field_name)};")
self.indent -= 1
self.emit("};")
def _emit_cpp_class_declaration(self, name: str, spec: ast.ClassType):
self.types.declare([name], spec)
method_map: dict[str, ast.MethodDecl] = {}
class_vars: set[str] = set()
self.emit(f"class {name} {{")
self.emit("public:")
self.indent += 1
for part in spec.data_parts:
if self._is_class_var_segment(part.access_attrs):
for field_names, field_type in part.fields:
for field_name in field_names:
class_vars.add(field_name)
self.emit(f"static {self._cpp_type(field_type)} {field_name};")
continue
for field_names, field_type in part.fields:
for field_name in field_names:
self.emit(f"{self._cpp_type_decl(field_type, field_name)};")
for section in spec.operations:
for method in section.methods:
for method_name in method.names:
method_map[method_name] = method
self.emit(self._cpp_method_declaration(name, method_name, method) + ";")
self.indent -= 1
self.emit("};")
self.emit("")
self._class_vars[name] = class_vars
self._class_methods[name] = method_map
self._section_class_bodies.append((name, spec))
def _emit_cpp_class_definitions(self, name: str, spec: ast.ClassType):
for part in spec.data_parts:
if not self._is_class_var_segment(part.access_attrs):
continue
for field_names, field_type in part.fields:
for field_name in field_names:
self.emit(
f"{self._cpp_type(field_type)} {name}::{field_name} = 0;"
)
self.emit("")
def _cpp_method_declaration(self, class_name: str, method_name: str, method: ast.MethodDecl) -> str:
ret = self._cpp_type(method.return_type) if method.return_type else "void"
args = self._cpp_method_parm_list(class_name, method)
if self._method_is_class_method(method):
return f"static {ret} {method_name}({args})"
return f"{ret} {method_name}({args})"
def _cpp_method_parm_list(self, class_name: str, method: ast.MethodDecl) -> str:
if self._method_is_class_method(method):
return self._cpp_parm_list(method.parms)
return self._cpp_parm_list(method.parms)
def _cpp_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str:
if not parms:
return ""
parts: list[str] = []
for names, type_spec, by_ref in parms:
cpp_type = self._cpp_type(type_spec)
for pname in names:
if by_ref:
parts.append(f"{cpp_type}& {pname}")
else:
parts.append(f"{cpp_type} {pname}")
return ", ".join(parts)
def _cpp_external_parm_type(self, type_spec) -> str:
spec = self._unwrap_type(type_spec)
if isinstance(spec, ast.PtrType):
target = self._unwrap_type(spec.target)
if isinstance(target, ast.DefinedType) and target.name == "char":
return "const char*"
return self._cpp_type(type_spec)
def _cpp_external_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str:
if not parms:
return ""
parts: list[str] = []
for names, type_spec, by_ref in parms:
cpp_type = self._cpp_external_parm_type(type_spec)
for pname in names:
if by_ref:
parts.append(f"{cpp_type}& {pname}")
else:
parts.append(f"{cpp_type} {pname}")
return ", ".join(parts)
def _cpp_external_proc_signature(self, proc: ast.ProcDecl) -> str:
ret = self._cpp_type(proc.return_type) if proc.return_type else "void"
args = self._cpp_external_parm_list(proc.parms)
return f"{ret} {proc.name}({args})"
def _cpp_proc_signature(self, proc: ast.ProcDecl) -> str:
ret = self._cpp_type(proc.return_type) if proc.return_type else "void"
args = self._cpp_parm_list(proc.parms)
return f"{ret} {proc.name}({args})"
def _emit_cpp_procedure(self, proc: ast.ProcDecl):
self.emit(self._cpp_proc_signature(proc))
self.emit("{")
self.indent += 1
self._emit_block_body(proc.body)
self.indent -= 1
self.emit("}")
self.emit("")
def _emit_cpp_method_impl(self, class_name: str, impl: ast.MethodImplDecl, method_decl: ast.MethodDecl | None):
self._current_class = class_name
is_class_method = method_decl is not None and self._method_is_class_method(method_decl)
self._current_self = "this"
if method_decl is not None:
ret = self._cpp_type(method_decl.return_type) if method_decl.return_type else "void"
args = self._cpp_method_parm_list(class_name, method_decl)
self.emit(f"{ret} {class_name}::{impl.name}({args})")
else:
self.emit(f"void {class_name}::{impl.name}()")
self.emit("{")
self.indent += 1
if is_class_method:
pass
self._emit_block_body(impl.body)
self.indent -= 1
self.emit("}")
self.emit("")
self._current_class = None
self._current_self = "this"
def _c_member_ref(self, expr: ast.MemberRef) -> str:
if (
isinstance(expr.base, ast.VarRef)
and expr.base.is_self
and self._current_class
and expr.member in self._class_vars.get(self._current_class, set())
):
return f"{self._current_class}::{expr.member}"
if isinstance(expr.base, ast.VarRef) and expr.base.is_self:
return f"this->{expr.member}"
return f"{self._c_expr(expr.base)}.{expr.member}"
def _c_expr(self, expr) -> str:
if isinstance(expr, ast.MethodCall):
args = ", ".join(self._c_expr(a) for a in expr.args)
class_name = self._method_class_name(expr)
if class_name and class_name in self._class_methods:
method_decl = self._class_methods[class_name].get(expr.name)
if method_decl is not None:
if self._method_is_class_method(method_decl):
return f"{class_name}::{expr.name}({args})"
receiver = self._c_expr(expr.receiver) if expr.receiver is not None else "this"
if args:
return f"{receiver}.{expr.name}({args})"
return f"{receiver}.{expr.name}()"
if expr.receiver is not None:
receiver = self._c_expr(expr.receiver)
return f"{receiver}.{expr.name}({args})"
return super()._c_expr(expr)
def _method_call_args(self, call: ast.MethodCall, args: str) -> str:
return args
def _queue_class_impl(self, impl: ast.ClassImplSection):
self.emit(f"/* IN {impl.class_name} */")
method_map = self._class_methods.get(impl.class_name, {})
for decl in impl.declarations:
if isinstance(decl, ast.MethodImplDecl):
method_decl = method_map.get(decl.name)
self._section_method_impls.append((impl.class_name, decl, method_decl))
else:
self._emit_cpp_toplevel_decl(decl)
for stmt in impl.statements:
self._emit_stmt(stmt)
self.emit("")
def _method_class_name(self, call: ast.MethodCall) -> str | None:
if isinstance(call.receiver, ast.VarRef):
if call.receiver.name in self._var_types:
return self._var_types[call.receiver.name]
if call.receiver.name in self._class_methods:
return call.receiver.name
return super()._method_class_name(call)
def transpile_to_cpp(
compilation_unit,
*,
classical: bool = False,
source_name: str = "input.protel",
source_path: Path | None = None,
) -> str:
from .module_resolver import resolve_compilation_unit
from .type_checker import check_types
if source_path is not None and not isinstance(source_path, Path):
source_path = Path(source_path)
compilation_unit = resolve_compilation_unit(
compilation_unit,
source_path=source_path,
classical=classical,
)
check_types(compilation_unit, source_name=source_name)
return CppTranspiler(classical=classical, source_name=source_name).transpile(
compilation_unit
)
def transpile_file_cpp(
source: str,
*,
classical: bool = False,
source_name: str = "input.protel",
) -> str:
from .parser import parse_protel
tree = parse_protel(source, classical=classical)
return transpile_to_cpp(tree, classical=classical, source_name=source_name)
+37
View File
@@ -0,0 +1,37 @@
"""PROTEL source file extension recognition (2026 + legacy PLS naming)."""
from __future__ import annotations
import re
from pathlib import Path
# Modern / distribution suffixes (case-insensitive except where noted).
_FIXED_SUFFIXES = frozenset({".protel", ".pt", ".ptl", ".p"})
# PLS edition suffix: .AA01 .. .ZZ99 (two letters + two digits).
_PLS_SUFFIX_RE = re.compile(r"\.[A-Za-z]{2}\d{2}$")
PLS_SUFFIX_DESCRIPTION = ".AA01 through .ZZ99 (two letters + two digits)"
def is_pls_suffix(suffix: str) -> bool:
"""True when suffix matches legacy PLS edition form (e.g. .AA01, .aa01)."""
return bool(_PLS_SUFFIX_RE.match(suffix))
def is_protel_suffix(suffix: str) -> bool:
"""True when suffix is a recognized PROTEL source extension."""
if suffix.lower() in _FIXED_SUFFIXES:
return True
return is_pls_suffix(suffix)
def is_protel_source(path: str | Path) -> bool:
"""True when path name uses a recognized PROTEL source extension."""
return is_protel_suffix(Path(path).suffix)
def format_suffix_list() -> str:
"""Human-readable suffix list for CLI messages."""
fixed = ", ".join(sorted(_FIXED_SUFFIXES))
return f"{fixed}, {PLS_SUFFIX_DESCRIPTION}"
+408
View File
@@ -0,0 +1,408 @@
// PROTEL 2026 grammar (Reference Manual + Introductory Manual 2026)
// Keywords are uppercased by the preprocessor before parsing.
%import common.WS
%ignore WS
?start: compilation_unit
compilation_unit: unit_item+
unit_item: section_head
| in_impl_block
| declaration
| statement
section_head: section_kind IDENT ";" -> section_plain
| section_kind IDENT "USES" id_list ";" -> section_uses
| section_kind IDENT "OF" id_list ";" -> section_of
| section_kind IDENT "OF" id_list "USES" id_list ";" -> section_of_uses
| module_type section_kind IDENT ";" -> section_plain
| module_type section_kind IDENT "USES" id_list ";" -> section_uses
| module_type section_kind IDENT "OF" id_list ";" -> section_of
| module_type section_kind IDENT "OF" id_list "USES" id_list ";" -> section_of_uses
module_type: "FAST"
| "SWAPPABLE"
| "PERPROCESS"
| "DEFINITIONS"
section_kind: "INTERFACE" -> interface_kind
| "SECTION" -> section_kind_kw
in_impl_block: "IN" IDENT in_impl_item+ -> class_impl_section
in_impl_item: method_impl_dcl
| declaration
| statement
method_impl_dcl: "DCL" IDENT "METHOD" "IS" block ";"
declaration: type_dcl_stmt
| variable_dcl_stmt
| proc_dcl_stmt
type_dcl_stmt: "TYPE" type_dcl (";" | type_dcl_list_tail)
type_dcl_list_tail: "," type_dcl (";" | type_dcl_list_tail)
type_dcl: id_list type_spec
variable_dcl_stmt: "DCL" variable_dcl (";" | variable_dcl_list_tail)
variable_dcl_list_tail: "," variable_dcl (";" | variable_dcl_list_tail)
variable_dcl: "OVLY" type_spec ovly_body "ENDOVLY" -> variable_dcl_ovly
| id_list "LITERAL" type_spec variable_init_tail -> variable_dcl_literal
| id_list "VARIABLE" type_spec variable_init_tail -> variable_dcl_variable
| id_list type_spec variable_init_tail
| id_list type_spec
variable_init_tail: "INIT" expr -> variable_init_init
| "IS" init_value -> variable_init_is
init_value: expr
| block
proc_dcl_stmt: "DCL" proc_dcl ";"
proc_dcl: id_list proc_sig "IS" block
| id_list proc_sig "IS" "INTRINSIC" -> proc_dcl_intrinsic
| id_list proc_sig "IS" "FORWARD" -> proc_dcl_forward
| id_list proc_sig "EXTERNAL" -> proc_dcl_external
| id_list proc_sig "EXPORT" -> proc_dcl_export
| id_list proc_sig "IS" "ENTRY" -> proc_dcl_entry
| id_list proc_sig
proc_sig: "QUICK" "PROC" paren_parms "RETURNS" type_spec
| "OPERAND" "PROC" paren_parms "RETURNS" type_spec
| "PROC" paren_parms "RETURNS" type_spec
| "QUICK" "PROC" paren_parms
| "OPERAND" "PROC" paren_parms
| "PROC" paren_parms
paren_parms: "(" ")"
| "(" parm_list ")"
parm_list: parm ("," parm)*
parm: "UPDATES" id_list type_spec -> parm_updates
| "REF" id_list type_spec
| id_list type_spec
block: "BLOCK" block_innards "ENDBLOCK"
block_innards: declaration* statement*
statement: if_stmt
| loop_stmt
| for_stmt
| over_stmt
| case_stmt
| select_stmt
| exit_stmt
| return_stmt
| bind_stmt
| with_stmt
| block
| expr_stmt
bind_stmt: "BIND" bind_list ";"
with_stmt: "WITH" with_ref_list ";"
bind_list: bind_item ("," bind_item)*
bind_item: IDENT "TO" qualified_ref opt_as_clause
opt_as_clause: | "AS" type_spec
with_ref_list: qualified_ref ("," qualified_ref)*
if_stmt: "IF" expr "THEN" statement_list "ENDIF" ";"
| "IF" expr "THEN" statement_list "ELSE" statement_list "ENDIF" ";"
loop_stmt: "WHILE" expr "DO" statement_list "ENDDO" ";"
| "DO" statement_list "ENDDO" ";"
for_stmt: "FOR" IDENT for_range "DO" statement_list "ENDDO" ";"
for_range: "OVER" type_spec -> for_over_range
| from_to_parts -> for_index_range
from_to_parts: opt_from_clause to_clause opt_by_clause opt_while_clause
opt_from_clause: | "FROM" expr
to_clause: | "UP" "TO" expr -> up_to_clause
| "DOWN" "TO" expr -> down_to_clause
opt_by_clause: | "BY" expr
opt_while_clause: | "WHILE" expr
over_stmt: "OVER" type_spec "DO" statement_list "ENDDO" ";"
case_stmt: "CASE" expr "IN" case_body "ENDCASE" ";"
select_stmt: "SELECT" expr "IN" case_body "ENDSELECT" ";"
case_body: case_list out_case?
case_list: case_item
| case_list case_item
case_item: tuple ":" case_arm_nonempty -> case_item_nonempty
| tuple ":" -> case_item_empty
case_arm_nonempty: case_arm_stmt+
case_arm_stmt: if_stmt
| loop_stmt
| for_stmt
| over_stmt
| case_stmt
| select_stmt
| exit_stmt
| return_stmt
| block
| expr_stmt
out_case: "OUT" -> out_case_empty
| "OUT" out_arm_stmt+ -> out_case_with_stmts
out_arm_stmt: if_stmt
| loop_stmt
| for_stmt
| over_stmt
| case_stmt
| select_stmt
| exit_stmt
| return_stmt
| block
| expr_stmt
exit_stmt: "EXIT" ";"
return_stmt: "RETURN" ";"
| "RETURN" expr ";"
expr_stmt: expr ";"
statement_list: statement+
// --- Types ---
type_spec: pack_type
| val_type
| unpacked_type
pack_type: "PACK" "(" constant_expr ")" unpacked_type
val_type: "VAL" unpacked_type
unpacked_type: range_type
| symbolic_range
| bool_type
| ptr_type
| set_type
| struct_type
| class_type
| table_type
| desc_type
| area_type
| defined_type
area_type: area_option* "AREA" "(" constant_expr ")" area_field_list "ENDAREA"
area_option: "UNRESTRICTED" -> area_unrestricted
| "NONTRANSPARENT" -> area_nontransparent
area_field_list: area_field ("," area_field)*
area_field: id_list type_spec
ovly_body: ovly_field ("," ovly_field)*
ovly_field: tuple ":" id_list type_spec
range_type: "{" constant_subrange "}"
symbolic_range: "{" id_list "}"
bool_type: "BOOL"
ptr_type: "PTR" "TO" type_spec
set_type: "SET" simple_type
simple_type: range_type
| symbolic_range
| bool_type
| defined_type
struct_type: "STRUCT" struct_field_list "ENDSTRUCT"
struct_field_list: struct_field ("," struct_field)*
struct_field: id_list type_spec
class_type: "CLASS" opt_refines class_data_sections operations_section "ENDCLASS" IDENT
opt_refines: | "REFINES" defined_type
class_data_sections: class_data_section*
class_data_section: segment_flags ":" class_field_list
segment_flags: "{" segment_attr_list "}"
segment_attr_list: | segment_attr ("," segment_attr)*
segment_attr: "PROTECTED" -> seg_protected
| "SHARED" -> seg_shared
| "PRIVATE" -> seg_private
| "EXCLUSIVE" -> seg_exclusive
| "READABLE" -> seg_readable
| "WRITABLE" -> seg_writable
class_field_list: class_field ("," class_field)*
class_field: id_list type_spec opt_field_semi
opt_field_semi: | ";"
operations_section: "OPERATIONS" method_section_list
method_section_list: method_section*
method_section: method_segment_flags ":" method_group_list
method_segment_flags: "{" method_attr_list "}"
method_attr_list: | method_attr ("," method_attr)*
method_attr: "ABSTRACT" -> meth_abstract
| "CLASS" -> meth_class
| "CREATE" -> meth_create
| "EXCLUSIVE" -> meth_exclusive
| "FIXED" -> meth_fixed
| "HIDDEN" -> meth_hidden
| "OVERRIDING" -> meth_overriding
method_group_list: method_group ("," method_group)*
method_group: method_id_list method_decl_sig
method_id_list: IDENT ("," IDENT)*
method_decl_sig: "METHOD" opt_method_parms opt_method_returns
| opt_method_parms opt_method_returns
opt_method_parms: | paren_parms
opt_method_returns: | "RETURNS" type_spec
table_type: "TABLE" bounds "OF" type_spec
desc_type: "DESC" "OF" type_spec
| "DESC" bounds "OF" type_spec
bounds: "[" constant_subrange "]"
defined_type: IDENT
constant_subrange: constant_expr "TO" constant_expr
// --- Expressions ---
?expr: assign_expr
?assign_expr: or_expr assign_tail*
assign_tail: "->" qualified_ref
?or_expr: or_expr "|" and_expr -> bin_or
| and_expr
?and_expr: and_expr "&" xor_expr -> bin_and
| xor_expr
?xor_expr: xor_expr "^" eq_expr -> bin_xor
| eq_expr
?incl_expr: incl_expr "INCL" rel_expr -> bin_incl
| incl_expr "NOTINCL" rel_expr -> bin_notincl
| rel_expr
?eq_expr: eq_expr "=" incl_expr -> bin_eq
| eq_expr "^=" incl_expr -> bin_ne
| incl_expr
?rel_expr: rel_expr ">" add_expr -> bin_gt
| rel_expr ">=" add_expr -> bin_ge
| rel_expr "<" add_expr -> bin_lt
| rel_expr "<=" add_expr -> bin_le
| add_expr
?add_expr: add_expr "+" mul_expr -> bin_add
| add_expr "-" mul_expr -> bin_sub
| mul_expr
?mul_expr: mul_expr "*" unary_expr -> bin_mul
| mul_expr "/" unary_expr -> bin_div
| mul_expr "MOD" unary_expr -> bin_mod
| unary_expr
?unary_expr: "!" unary_expr
| "-" unary_expr
| "UPB" unary_expr -> upb_expr
| "TDSIZE" unary_expr -> tdsize_expr
| "TYPEDESC" unary_expr -> typedesc_expr
| "VARDESC" unary_expr -> vardesc_expr
| "REFDESC" unary_expr -> refdesc_expr
| "CAST" unary_expr "AS" type_spec -> cast_expr
| primary
?primary: literal
| qualified_ref
| tuple
| "(" expr ")"
qualified_ref: ref_segment qual_suffix*
ref_segment: IDENT
| "SELF" -> self_ref
| "SUPER" -> super_ref
qual_suffix: index_suffix -> qual_index
| dot_suffix
| call_suffix
dot_suffix: "." IDENT
call_suffix: "(" ")"
| "(" actual_list ")"
index_suffix: "[" expr "]"
| "[" expr "TO" expr "]"
actual_list: expr ("," expr)*
literal: NUMBER
| "TRUE" -> true_lit
| "FALSE" -> false_lit
| "NIL" -> nil_lit
| STRING
tuple: "{" "}"
| "{" tuple_body_list "}"
tuple_body_list: tuple_elem ("," tuple_elem)*
tuple_elem: expr
?constant_expr: constant_expr_atom
constant_expr_atom: NUMBER
| "TRUE" -> true_lit
| "FALSE" -> false_lit
| "NIL" -> nil_lit
| STRING
| "{" constant_tuple_body "}"
constant_tuple_body: constant_expr_atom ("," constant_expr_atom)*
id_list: IDENT ("," IDENT)*
IDENT: /[A-Za-z_$][A-Za-z0-9_$]*/
NUMBER: /-?\d+/
STRING: /'(?:''|[^'])*'/
+105
View File
@@ -0,0 +1,105 @@
"""PROTEL reserved keywords (Reference Manual Appendix A / oflpr / oflpi)."""
PROTEL_KEYWORDS = frozenset({
"$EJECT",
"$LI",
"$OBJECT",
"$REFDESC",
"$TYPEDESC",
"$UNIVERSAL_PTR",
"$VARDESC",
"ABSTRACT",
"AREA",
"AS",
"BIND",
"BLOCK",
"BOOL",
"BY",
"CASE",
"CAST",
"CLASS",
"CREATE",
"DCL",
"DEFINITIONS",
"DESC",
"DO",
"DOWN",
"ELSE",
"ENDAREA",
"ENDBLOCK",
"ENDCASE",
"ENDCLASS",
"ENDDO",
"ENDIF",
"ENDOVLY",
"ENDSELECT",
"ENDSTRUCT",
"ENTRY",
"EXIT",
"EXTERNAL",
"EXPORT",
"EXCLUSIVE",
"FALSE",
"FIXED",
"FAST",
"FOR",
"FORWARD",
"FROM",
"HIDDEN",
"IF",
"IN",
"INCL",
"INIT",
"INTERFACE",
"INTRINSIC",
"IS",
"LITERAL",
"METHOD",
"MOD",
"NIL",
"NONTRANSPARENT",
"NOTINCL",
"OF",
"OPERAND",
"OPERATIONS",
"OUT",
"OVERRIDING",
"OVER",
"OVLY",
"PACK",
"PERPROCESS",
"PRIVATE",
"PROC",
"PROTECTED",
"PTR",
"QUICK",
"REF",
"REFDESC",
"REFINES",
"RETURN",
"RETURNS",
"SECTION",
"SELECT",
"SELF",
"SET",
"SUPER",
"SHARED",
"STRUCT",
"TABLE",
"TDSIZE",
"THEN",
"TO",
"TRUE",
"TYPE",
"TYPEDESC",
"UNRESTRICTED",
"UP",
"UPB",
"UPDATES",
"USES",
"VAL",
"VARDESC",
"VARIABLE",
"WHILE",
"WITH",
})

Some files were not shown because too many files have changed in this diff Show More