commit 98a0bb329debbb5464a7bda5c6be8ae4858b80f7 Author: vincente Date: Mon Jun 8 18:04:03 2026 -0500 Initial PROTEL 2026 toolchain import diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..037f97f --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ +build/ +a.out +*.o +legacy/ +*~ +.*~ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b7d8fcf --- /dev/null +++ b/AGENTS.md @@ -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 . 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. + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ae1fac9 --- /dev/null +++ b/Makefile @@ -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 \ No newline at end of file diff --git a/PROTEL Introductory Manual 2026.pages b/PROTEL Introductory Manual 2026.pages new file mode 100644 index 0000000..379c4cc Binary files /dev/null and b/PROTEL Introductory Manual 2026.pages differ diff --git a/PROTEL Introductory Manual 2026.pdf b/PROTEL Introductory Manual 2026.pdf new file mode 100644 index 0000000..7a8168b Binary files /dev/null and b/PROTEL Introductory Manual 2026.pdf differ diff --git a/PROTEL Introductory Manual.rtf b/PROTEL Introductory Manual.rtf new file mode 100644 index 0000000..478dcec --- /dev/null +++ b/PROTEL Introductory Manual.rtf @@ -0,0 +1,3169 @@ +{\rtf1\ansi\ansicpg1252\cocoartf2822 +\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;\f1\fnil\fcharset0 HelveticaNeue-Bold;\f2\fmodern\fcharset0 CourierNewPSMT;\f3\fmodern\fcharset0 CourierNewPS-BoldMT; +} +{\colortbl;\red255\green255\blue255;\red0\green0\blue0;} +{\*\expandedcolortbl;;\cssrgb\c0\c0\c0;} +{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid1\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid1} +{\list\listtemplateid2\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid101\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid2} +{\list\listtemplateid3\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid201\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid3} +{\list\listtemplateid4\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid301\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid4} +{\list\listtemplateid5\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid401\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid5} +{\list\listtemplateid6\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid501\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid6} +{\list\listtemplateid7\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid601\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid7} +{\list\listtemplateid8\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid701\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid8} +{\list\listtemplateid9\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid801\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid9} +{\list\listtemplateid10\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid901\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid10} +{\list\listtemplateid11\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1001\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid11} +{\list\listtemplateid12\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{disc\}}{\leveltext\leveltemplateid1101\'01\uc0\u8226 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid12} +{\list\listtemplateid13\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1201\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid13} +{\list\listtemplateid14\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat2\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1301\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid14} +{\list\listtemplateid15\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat3\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1401\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid15} +{\list\listtemplateid16\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat4\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1501\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid16} +{\list\listtemplateid17\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat5\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1601\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid17} +{\list\listtemplateid18\listhybrid{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{decimal\}.}{\leveltext\leveltemplateid1701\'02\'00.;}{\levelnumbers\'01;}\fi-360\li720\lin720 }{\listname ;}\listid18}} +{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}{\listoverride\listid2\listoverridecount0\ls2}{\listoverride\listid3\listoverridecount0\ls3}{\listoverride\listid4\listoverridecount0\ls4}{\listoverride\listid5\listoverridecount0\ls5}{\listoverride\listid6\listoverridecount0\ls6}{\listoverride\listid7\listoverridecount0\ls7}{\listoverride\listid8\listoverridecount0\ls8}{\listoverride\listid9\listoverridecount0\ls9}{\listoverride\listid10\listoverridecount0\ls10}{\listoverride\listid11\listoverridecount0\ls11}{\listoverride\listid12\listoverridecount0\ls12}{\listoverride\listid13\listoverridecount0\ls13}{\listoverride\listid14\listoverridecount0\ls14}{\listoverride\listid15\listoverridecount0\ls15}{\listoverride\listid16\listoverridecount0\ls16}{\listoverride\listid17\listoverridecount0\ls17}{\listoverride\listid18\listoverridecount0\ls18}} +\margl1440\margr1440 +\deftab720 +\pard\pardeftab720\partightenfactor0 + +\f0\fs22 \cf2 \up0 \nosupersub \ulnone \ +\ + \ +\pard\pardeftab720\qc\partightenfactor0 + +\f1\b\fs60 \cf2 PROTEL\ +\pard\pardeftab720\qc\partightenfactor0 + +\fs28 \cf2 Procedure Oriented \f1\b TYPE\f0\b0 Enforcing Language\ +\pard\pardeftab720\qc\partightenfactor0 + +\fs38 \cf2 \ +Introductory Manual\ +\pard\pardeftab720\qc\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\qc\partightenfactor0 + +\f1\b \cf2 Version 2026\ +\pard\pardeftab720\qc\partightenfactor0 + +\f0\b0 \cf2 \ +\ +Derived from the April 1987 revision\ +\ +Resurrected and enhanced for the 21st century\ +\ +by\ +\ +\pard\pardeftab720\qc\partightenfactor0 + +\fs32 \cf2 Vincente D\'92Ingianni\ +\pard\pardeftab720\qc\partightenfactor0 + +\f2\fs16 \cf2 vincente@binary-systems.com\ +\pard\pardeftab720\qc\partightenfactor0 + +\f0 \cf2 \ +former Advisor and Manager,\ +Nortel/BNR DMS-500 Development \ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \ + \ +\ +\ + \page \pard\tqr\tx9360\pardeftab720\sa160\partightenfactor0 + +\fs28 \cf2 \ +1.0 INTRODUCTION \ +PART I: BASIC STRUCTURE OF THE LANGUAGE \ +PART II: RULES OF THE LANGUAGE. \ +APPENDIX A. KEYWORDS \ +\pard\tqr\tx9360\pardeftab720\partightenfactor0 +\cf2 APPENDIX B. SPECIAL SYMBOLS +\fs22 \ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +\ +TABLE OF CONTENTS\ + _________________\ + \ + \ + \ + 1.0 INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . 1\ + \ + PART I: BASIC STRUCTURE OF THE LANGUAGE . . . . . . . . . . . 2\ + 1.1 Input Format . . . . . . . . . . . . . . . . . . . . . . 2\ + 1.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . 2\ + 1.3 Types of Symbols . . . . . . . . . . . . . . . . . . . . 2\ + 1.3.1 Keywords . . . . . . . . . . . . . . . . . . . . . . 2\ + 1.3.2 Special Symbols . . . . . . . . . . . . . . . . . . 3\ + 1.3.3 Identifiers . . . . . . . . . . . . . . . . . . . . 4\ + 1.3.4 Numbers . . . . . . . . . . . . . . . . . . . . . . 4\ + 1.4 Constants . . . . . . . . . . . . . . . . . . . . . . . 5\ + 1.4.1 Simple Constant Expressions . . . . . . . . . . . . 5\ + 1.4.2 Aggregate Constants (Tuples) . . . . . . . . . . . . 5\ + 1.4.3 Character Strings . . . . . . . . . . . . . . . . . 6\ + \ + PART II: RULES OF THE LANGUAGE. . . . . . . . . . . . . . . . 7\ + 1.5 General Overview . . . . . . . . . . . . . . . . . . . . 7\ + \ + 2.0 DECLARATIONS . . . . . . . . . . . . . . . . . . . . . . 9\ + 2.1 Type declarations . . . . . . . . . . . . . . . . . . . 9\ + 2.1.1 Numeric range . . . . . . . . . . . . . . . . . . . 10\ + 2.1.2 Symbolic Range . . . . . . . . . . . . . . . . . . . 12\ + 2.1.3 Boolean . . . . . . . . . . . . . . . . . . . . . . 12\ + 2.1.4 Pointer . . . . . . . . . . . . . . . . . . . . . . 12\ + 2.1.5 Sets . . . . . . . . . . . . . . . . . . . . . . . . 13\ + 2.1.6 Tables . . . . . . . . . . . . . . . . . . . . . . . 14\ + 2.1.7 Structures . . . . . . . . . . . . . . . . . . . . . 15\ + 2.1.8 Areas . . . . . . . . . . . . . . . . . . . . . . . 16\ + 2.1.9 Descriptors . . . . . . . . . . . . . . . . . . . . 17\ + 2.1.10 Procedures . . . . . . . . . . . . . . . . . . . . 19\ + 2.1.11 PACK Attribute . . . . . . . . . . . . . . . . . . 20\ + 2.2 Data Declarations . . . . . . . . . . . . . . . . . . . 20\ + 2.2.1 Variable Declarations . . . . . . . . . . . . . . . 21\ + 2.2.2 Constant Declarations . . . . . . . . . . . . . . . 22\ + \ + 3.0 EXECUTABLE STATEMENTS . . . . . . . . . . . . . . . . . 25\ + 3.1 Expressions . . . . . . . . . . . . . . . . . . . . . . 25\ + 3.1.1 Operators . . . . . . . . . . . . . . . . . . . . . 27\ + 3.1.1.1 Assignment Operator . . . . . . . . . . . . . . 27\ + 3.1.1.2 Arithmetic Operators . . . . . . . . . . . . . . 27\ + 3.1.1.3 Comparison Operators . . . . . . . . . . . . . . 28\ + 3.1.1.4 Logical Operators . . . . . . . . . . . . . . . 29\ + 3.1.1.5 Unary Operators . . . . . . . . . . . . . . . . 30\ + 3.1.2 Operands . . . . . . . . . . . . . . . . . . . . . . 31\ + 3.1.2.1 Identifiers . . . . . . . . . . . . . . . . . . 33\ + 3.1.2.2 Selection . . . . . . . . . . . . . . . . . . . 33\ + 3.1.2.3 Indexing . . . . . . . . . . . . . . . . . . . . 33\ + 3.1.2.4 Multiple . . . . . . . . . . . . . . . . . . . . 34\ + 3.1.2.5 Dereference . . . . . . . . . . . . . . . . . . 34\ + 3.2 Control Statements . . . . . . . . . . . . . . . . . . . 35\ + 3.2.1 RETURN Statement . . . . . . . . . . . . . . . . . . 35\ + 3.2.2 IF Statement . . . . . . . . . . . . . . . . . . . . 36\ + 3.2.3 Nested IF Statements . . . . . . . . . . . . . . . . 37\ + 3.2.4 CASE Statement . . . . . . . . . . . . . . . . . . . 39\ + 3.2.5 SELECT Statement . . . . . . . . . . . . . . . . . . 40\ + 3.2.6 Iterative Statement . . . . . . . . . . . . . . . . 41\ + 3.2.7 The OVER Specification . . . . . . . . . . . . . . . 43\ + 3.2.8 Iterative Statement with the WHILE Condition . . . . 45\ + 3.2.9 EXIT Statement . . . . . . . . . . . . . . . . . . . 46\ + \ + 4.0 PARAMETER PASSING MECHANISMS . . . . . . . . . . . . . . 47\ + 4.1.1 Formal and Actual Parameters . . . . . . . . . . . . 47\ + 4.1.2 The VAL Attribute . . . . . . . . . . . . . . . . . 50\ + 4.1.2.1 Common Errors . . . . . . . . . . . . . . . . . 51\ + \ + 5.0 PROTEL PROGRAM ORGANISATION . . . . . . . . . . . . . . 52\ + 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . 52\ + 5.1.1 Declaration versus Definition . . . . . . . . . . . 52\ + 5.2 Sections, Modules, and Programs . . . . . . . . . . . . 53\ + 5.2.1 Sections . . . . . . . . . . . . . . . . . . . . . . 53\ + 5.2.2 Imbedding and Outbedding . . . . . . . . . . . . . . 54\ + 5.2.3 Modules . . . . . . . . . . . . . . . . . . . . . . 54\ + 5.2.4 Programs . . . . . . . . . . . . . . . . . . . . . . 54\ + 5.3 Compilation Order . . . . . . . . . . . . . . . . . . . 55\ + 5.3.1 Compilation Order for Programs . . . . . . . . . . . 56\ + 5.3.2 Compilation Order for Modules . . . . . . . . . . . 57\ + 5.4 Imbedding . . . . . . . . . . . . . . . . . . . . . . . 59\ + 5.4.1 Differences between USES and OF Imbedding . . . . . 59\ + 5.4.2 Imbedding of Non-top-level Sections . . . . . . . . 61\ + 5.4.3 Private Interfaces . . . . . . . . . . . . . . . . . 61\ + 5.5 PROTEL Language . . . . . . . . . . . . . . . . . . . . 61\ + 5.5.1 Design Goals . . . . . . . . . . . . . . . . . . . . 61\ + 5.5.2 A Sample Program . . . . . . . . . . . . . . . . . . 64\ + 5.5.3 Program Organization: Points to remember . . . . . . 65\ + \ + 6.0 SUMMARY . . . . . . . . . . . . . . . . . . . . . . . . 66\ + \ + APPENDIX A. KEYWORDS . . . . . . . . . . . . . . . . . . . . 67\ + \ + APPENDIX B. SPECIAL SYMBOLS . . . . . . . . . . . . . . . . . 68\ +\ + \ + \ + \ + \ +\page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs36 \cf2 1.0 INTRODUCTION\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +PROTEL is a high level language developed specifically for use in switching systems. This manual is an introduction to PROTEL. It provides an overview of the language and is designed to be read in conjunction with the PROTEL Reference Manual.\ + \ +In particular, the following aspects of PROTEL are not discussed in this document\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls1\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone The special declarative keywords \f1\b PROTECTED\f0\b0 , \f1\b SHARED\f0\b0 and \f1\b PRIVATE\f0\b0 \ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone The scope rules\ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone The type compatibility rules\ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone Overlays\ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone The CAST construct\ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone BIND and WITH declarations\ +\ls1\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone Module types\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +The manual is divided into two parts. The first of these describes the basic structure of the language while the second details the language rules. The latter section is divided into subsections corresponding to different types of PROTEL statements. Program examples are provided to illustrate the points being discussed.\ + \ + \ +\ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs36 \cf2 PART I: BASIC STRUCTURE \f1\b OF\f0\b0 THE LANGUAGE\ +\pard\pardeftab720\partightenfactor0 + +\fs32 \cf2 \ +1.1 INPUT FORMAT\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +The language source is free form input between columns 1 and 110 (inclusive) of the input record. Embedded blanks are permitted anywhere except within numbers, identifiers, special symbols or keywords. Character strings may span several input records, although this is not recommended.\ +\ +Compiler directives are denoted by a dollar sign ($) in column one followed by a command word (e.g., $EJECT). Therefore identifiers which begin with a dollar sign must not occur beginning on column one.\ + \ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 1.2 COMMENTS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +Comments are prefixed by a percent sign (%) and extend to the end of the input record. They may begin anywhere in the record and may be preceded by source text on the same line.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 1.3 TYPES \f1\b OF\f0\b0 SYMBOLS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +Four basic types of symbols are used in PROTEL. They are:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls2\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone Keywords\ +\ls2\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Special Symbols\ +\ls2\ilvl0\up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone Identifiers\ +\ls2\ilvl0\up0 \nosupersub \ulnone {\listtext 4. }\up0 \nosupersub \ulnone Numbers\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.3.1 KEYWORDS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The keywords of the language are reserved, and may not be used as identifiers. Each keyword must be delimited by non-alphanumeric characters.\ +\ +Some examples of keywords are:\ + \ + \f1\b BLOCK\f0\b0 \ + \f1\b BOOL\f0\b0 (Boolean)\ + \f1\b DCL\f0\b0 (Declare)\ + \f1\b DO\f0\b0 \ + \f1\b IF\f0\b0 \ + \f1\b INIT\f0\b0 (Initialise)\ + \f1\b STRUCT\f0\b0 (Structure)\ + \f1\b TRUE\f0\b0 \ + \ +Figure 24 on page 67 contains a complete list of PROTEL keywords. Keywords will be introduced as required while discussing various features of the PROTEL language. Throughout the rest of this manual keywords will appear in \f1\b UPPERCASE BOLD\f0\b0 . This makes the programs easier to read and does not imply that keywords must be entered in upper case. PROTEL is indifferent to case, except within character strings.\ + \ +In the following PROTEL statement, keywords are shown in \f1\b BOLD UPPERCASE\f0\b0 :\ + \ + \f1\b DCL\f0\b0 factorial \f1\b PROC\f0\b0 (i integer) \f1\b RETURNS\f0\b0 integer \f1\b IS\f0\b0 \ + \f1\b BLOCK\f0\b0 \ + :\ + :\ + :\ + \f1\b ENDBLOCK\f0\b0 ;\ +\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.3.2 SPECIAL SYMBOLS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +An alphanumeric character is either a letter or a digit. The alphanumeric characters in PROTEL are:\ + \ + A, B, C, ..., Z, 0, 1, 2, ..., 9.\ + \ +Sequences of one or more non-alphanumeric characters constitute the special symbols of the language.\ +\ +The following are examples of special symbols.\ + \ + < less than\ + = equals\ + ; semicolon\ + | or\ + -> assignment\ + \ +A complete list of special symbols can be found in Figure 25. The use of these symbols will become clear as various aspects of the language are discussed.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.3.3 IDENTIFIERS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +An identifier is a sequence of characters used to name a data type, constant, variable, procedure, statement label, or section. Identifiers consist of a letter, the dollar sign ($), or the underscore character (_) followed by up to 31 alphanumeric characters, dollar signs, or underscore characters.\ + \ +Some examples of identifiers are:\ + \ + \ + weekday\ + n\ + AMOUNT_IN_$\ + NUMBER_35\ + end_of_file\ + $AMOUNT\ + \ + In the following PROTEL statement, identifiers (e.g. factorial, i) are shown in plain lower case for illustration:\ + \ + DCL factorial PROC (i integer) RETURNS integer IS\ + BLOCK\ + :\ + :\ + :\ + ENDBLOCK;\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.3.4 NUMBERS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Decimal numbers are represented by a string of decimal digits. Hexadecimal numbers are denoted by the symbol # followed by a string of hexadecimal digits (digits 0 to 9, letters A to F). Negative numbers are prefixed by a minus sign.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b \cf2 EXAMPLES\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0 \cf2 \ + 1. #41 % hexadecimal number equal to decimal 65.\ + \ + 2.\ + 65 % decimal number.\ + \ + 3. -17 % negative decimal number.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 \page 1.4 CONSTANTS\ +\pard\pardeftab720\sa360\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 + 1.4.1 SIMPLE CONSTANT EXPRESSIONS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A simple constant expression is an expression, as described in "Expressions" on page 25, which can be evaluated at compile time and which results in a single value.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. 5\ + \ + 2. TRUE\ + \ + 3. 2 * (size - 1) % size is a constant\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.4.2 AGGREGATE CONSTANTS (TUPLES)\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Tuples are used to represent structured constants which include several values. A constant tuple consists of a sequence of constant expressions enclosed by braces. The constant expressions may themselves be tuples; thus nesting of tuples is allowed.\ + \ +A tuple may be preceded by a repetition factor which must be a numeric compile time constant. Such a factor indicates that what follows is to be treated as a single tuple where the elements are repeated the given number of times.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. \{1, 3, 5, 7, 9\}\ + \ + 2. \{size, 3 * size, length - 1\}\ + \ + 3. 3\{2, 4\} % Equivalent to \{2, 4, 2, 4, 2, 4\}\ + \ + 4. \{2, \{3,4\}\} % Outer tuple has two elements;\ + % inner tuple has two elements.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +1.4.3 CHARACTER STRINGS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A character string is a sequence of characters enclosed in single quotes (apostrophes). A single quote within a character string is represented as a pair of adjacent single quotes. A number preceding a character string indicates that the string is to be repeated a given number of times.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. 'error'\ + \ + 2. 'out of range'\ + \ + 3. 'don''t' % The string is "don't".\ + \ + 4. 2 'ab' % Equivalent to 'abab'.\ + \ +A character string is treated as a tuple of numeric values corresponding to the characters of the string.\ + \ +For example, on a machine which uses the ASCII character set, the following three tuples are identical:\ + \ + 'AB' % ASCII\ + \{#41, #42\} % hex\ + \{65,66\} % decimal\ + \ + \ +\ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs36 \cf2 \page PART II: RULES \f1\b OF\f0\b0 THE LANGUAGE.\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 1.5 GENERAL OVERVIEW\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +A PROTEL program consists of a number of statements constructed from the basic symbols described previously.\ + \ +The program in Figure 1 on page 8 illustrates some of the statement types used in PROTEL. Each statement type will be discussed in more detail in subsequent sections.\ + \ +NOTE: The numbers preceding the statements are for reference purposes only and are not part of the PROTEL program.\ + \ +The types and variables used in the program are defined in statements 1,5 and 7. The procedure for calculating the factorial of a number is defined in statements 5 through 16.\ + \ +In statement 9, the initial value of n is assigned to variables i and result.\ + \ +The value of i is decremented by one and the new value assigned to i (statement 10). The new value is compared with 1. If it is greater, then the variable i is multiplied by the variable result and the new value assigned to result (statement 13).\ + \ +Statements 10 through 14 are repeated as long as the value of i-1 is greater than 1 (statement 10). When the value of i-1 is no longer greater than 1, the value of result (i.e., the factorial of n) is returned to the point of invocation of the procedure (statement 15).\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 TYPE integer \{-32768 TO 32767\}; |\ + | 2 |\ + | 3 % calculates the factorial of a number n |\ + | 4 |\ + | 5 DCL factorial PROC (n integer) RETURNS integer IS |\ + | 6 BLOCK |\ + | 7 DCL result, i integer; |\ + | 8 |\ + | 9 n -> i -> result; |\ + | 10 WHILE (i - 1 -> i) > 1 |\ + | 12 DO |\ + | 13 i * result -> result; |\ + | 14 ENDDO; |\ + | 15 RETURN result; |\ + | 16 ENDBLOCK; |\ + | |\ + | Figure 1. Simple Program |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 \page 2.0 DECLARATIONS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +A PROTEL program consists of type declarations and data declarations Since every datum has a type, we call a datum an instance of its type.\ +\ +Named types are declared using TYPE statements. Named data are declared using DCL statements.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 2.1 \f1\b TYPE\f0\b0 DECLARATIONS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\partightenfactor0 + +\f1\b \cf2 EXAMPLES\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0 \cf2 \ + TYPE byte \{0 TO 255\};\ + \ + TYPE integer \{-32768 TO 32767\};\ + \ + TYPE line_status \{on_hook, off_hook\};\ + \ + TYPE end_of_file BOOL;\ + \ + TYPE time_interval\ + STRUCT\ + value \{0 TO 255\},\ + unit \{tenms, sec, mins, hours\}\ + ENDSTRUCT;\ + \ + TYPE line_table TABLE [0 TO 99] OF BOOL;\ + \ + TYPE small_non_negative_number byte; % a defined type\ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b \cf2 DESCRIPTION +\f0\b0 \ + \ +Type declarations are used to describe the characteristics of data. The fundamental characteristic of a type is a definition of the set of values which an instance of the type may assume. We refer to this as the value-set of the type. Other characteristics include the amount of storage it requires and whether its value may be updated.\ + \ +Types can be defined in terms of existing primitive types in the language or in terms of other types defined by the programmer. The primitive types consist of the simple types, the aggregate types and the procedure type.\ +\ + \ +small_non_negative_number is defined in terms of user-defined types, not in terms of primitive types. It is an example of a defined type.\ +\ +Once a type is declared, it can be used in any context where a type is required. The declaration of data in terms of types allows the compiler to do extensive type checking at compile time.\ + \ +The simple types are used to declare data representing "atomic", or single values.\ +\ +The simple types are:\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls3\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone numeric range\ +\ls3\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone symbolic range\ +\ls3\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone Boolean\ +\ls3\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone pointer\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + \ +Aggregate types are used to define data constructs representing collections of data values which can be treated as a single named object.\ + \ +The aggregate types are:\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls4\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone sets\ +\ls4\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone structures\ +\ls4\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone areas\ +\ls4\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone tables\ +\ls4\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone descriptors\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.1 NUMERIC RANGE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A numeric range type defines a range of numeric values within which instances of the type may assume. The range is used to determine the amount of storage required by an instance of the type.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1. TYPE positive_integer \{0 TO 32767\};\ + % Defines the type positive_integer as\ + % a number in the range 0 to 32767.\ + \ + 2. TYPE integer \{-32768 to 32767\};\ + % Defines integer as a number in the\ + % range -32768 to 32767. Note that\ + % integer is not a built-in type.\ + \ + 3. TYPE digit \{0 TO 9\};\ + % Defines the type digit as a number in\ + % the range 0 to 9.\ + \ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.2 SYMBOLIC RANGE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 A symbolic range \f1\b TYPE\f0\b0 specifies \f1\b BY\f0\b0 enumeration the allowable constant values that may be assumed \f1\b BY\f0\b0 an instance \f1\b OF\f0\b0 that \f1\b TYPE\f0\b0 . That \f1\b IS\f0\b0 , the value-\f1\b SET\f0\b0 \f1\b OF\f0\b0 a symbolic range \f1\b TYPE\f0\b0 \f1\b IS\f0\b0 "enumerated".\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1. TYPE digit_protocol \{mf, dp, dt\};\ + % Specifies that the type digit_protocol\ + % consists of the values mf, dp, or dt.\ + \ + 2. TYPE weekday \{mon, tues, wed, thurs, fri\} ;\ + % Specifies that the type weekday is comprised\ + % of the values mon, tues, wed, thurs, or fri.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.3 BOOLEAN\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The value-set of type Boolean contains two values: TRUE and FALSE. These correspond to truth values, and are the result of evaluating any Boolean expression.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 1. TYPE can_be_serviced BOOL;\ + % Specifies that a variable of type\ + % can_be_serviced may be either TRUE or FALSE.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.4 POINTER\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +An item of type pointer contains an absolute address and is used to indirectly reference data.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1. TYPE pntr PTR TO digit_protocol;\ + % Defines pntr as a pointer to instances\ + % of type digit_protocol.\ + \ + 2. TYPE ptr_day PTR TO weekday;\ + % Defines ptr_day as a pointer to instances\ + % of type weekday.\ + \ +Pointers to storage references may be obtained by using the PTR operator as described in "Unary Operators" on page 30. To access the storage reference pointed to by a pointer, one dereferences the pointer. Dereferencing of pointers is described in "Dereference".\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.5 SETS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A set is used to define a data type whose value-set consists of any subset of the values from a specified symbolic or numeric range. Within an instance of a set, one bit is associated with each element of the base symbolic or numeric range.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1. TYPE bit_word SET \{0 TO 15\};\ + % Specifies that an instance of the type\ + % bit_word may be used to represent any\ + %\ + % 16\ + % of the 2 (two to the sixteen) subsets of\ + % the set \{0,1,2,...,15\}.\ + % Each of the 16 bits in the set is associated\ + % with one of the values in the numeric range.\ + \ + 2. TYPE special_features SET \{abbreviated_dial,\ + add_on,\ + call_transfer,\ + digitone\};\ + % Specifies that an instance of the type\ + % special_features can assume any of the\ + %\ + % 4\ + % 2 (two to the four) subsets of the\ + % set \{abbreviated_dial, add_on, call_transfer,\ + % digitone\}.\ + \ + 3. TYPE feature \{abbreviated_dial,\ + add_on,\ + call_transfer,\ + digitone\};\ + \ + TYPE special_features SET feature;\ + % Same as example 2. An instance of type\ + % special_features can assume any subset\ + % of the set of feature.\ + \ + +\f1\b DISCUSSION +\f0\b0 \ + \ +The type special_features has a storage requirement of 4 bits. Each bit is associated with an element in the symbolic range.\ +For example, in any subset of type feature, the element call_transfer is either in the subset or it is not. We represent these two conditions by setting the bit corresponding to call_transfer to one or zero, respectively.\ + \ +The maximum number of elements in a set is the number of bits in a word (16 in PROTEL/DMS, 32 in PROTEL/370).\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.6 TABLES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A table type is used to build a named collection of homogeneous items, i.e., elements of the same type.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1. TYPE digit_register TABLE [0 TO 15] OF digit;\ +\ + | |\ + | |\ + bounds type of entries\ + \ + 2. TYPE boc_type \{boc1, boc2, boc3, boc4\};\ + \ + TYPE switch_count TABLE [boc_type] of integer;\ + \ +The type declaration in example 1 specifies that digit_register is a table of 16 elements, the elements of which are of type digit. An index range specifies the legitimate set of indices into the table. Informally, we think of the index range as specifying the "bounds" of the table. In example 1, the "lower bound" of a digit_register table is 0, and the "upper bound" is 15.\ + \ +The bounds specification of a table can be a numeric or symbolic range. It may also be a defined type, if the base type of the defined type is either numeric or symbolic range. In example 2, a table of type switch_count has 4 elements, one for each value in its index type (boc_type).\ + \ +In all cases, the number of elements in the table is equal to the number of elements in the index range.\ + \ +The type of entries in a table may be any type, including table types. Thus, a two dimensional table may be declared as a TABLE OF TABLE.\ + \ +An item within a table is referenced by suffixing the name of the table instance with a subscript expression in square brackets. The value (as described in "Indexing") of the subscript expression corresponds to the desired table element.\ + \ +\ +\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.7 STRUCTURES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A structured type is used to build a named collection of non-homogeneous elements, i.e., elements of different types.\ + \ + +\f1\b Examples +\f0\b0 \ + \ + 1. TYPE terminal_id\ + STRUCT\ + terminal_controller \{0 TO 4095\},\ + terminal_number \{0 TO 255\}\ + ENDSTRUCT;\ + \ + % Specifies that the type terminal_id is made\ + % up of two fields, a terminal_controller in\ + % the numeric range 0 to 4095 and a terminal_number\ + % in the numeric range 0 to 255.\ + \ + 2. TYPE time_interval\ + STRUCT\ + value \{0 TO 255\},\ + units \{tenms, secs, mins, hrs\}\ + ENDSTRUCT;\ + \ + % Type time_interval has two fields,\ + % value in the numeric range 0 to 255,\ + % and units in the symbolic range\ + % \{tenms, secs, mins, hrs\}.\ + \ + DCL call_time time_interval;\ + % An instance of time_interval.\ + \ + 3. TYPE experiment_results\ + STRUCT\ + runs integer,\ + time time_interval\ + ENDSTRUCT;\ + \ + DCL\ + exp1 experiment_results,\ + exps TABLE [1 TO 10] OF experiment_results;\ + \ +Each element of a structure has a name, e.g., "value" and "units" in type time_interval (example 2). Each element of a structure is called a field of the structure. "value" is a field of type time_interval. A field specification consists of a name and a type. To reference the field value of an instance of type time_interval, say call_time, we use the name of the instance and the name of the field, joined by a period.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + call_time.value\ + call_time.units\ + \ +Fields within a structure may be of any type, including structure types. Thus, structures may be nested. In example 2 above, a variable of type experiment_results has a field "time", which is a structure of type time_interval.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + exp1.runs\ + exp1.time.value\ + exp1.time.units\ + \ +A field within a structure is referenced by specifying the name of the structure instance and the name of the field itself, as described in "Selection".\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.8 AREAS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The area type is used to build collections of items similar to those built by the structure type. Areas, however, provide a facility to postpone declaration of fields in the structure to a later time.\ + \ + An area type is either:\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls5\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone a father \f1\b AREA\f0\b0 . This \f1\b IS\f0\b0 an initial \f1\b TYPE\f0\b0 declaration \f1\b FOR\f0\b0 an \f1\b AREA\f0\b0 ; or\ +\ls5\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone a refinement of a father area.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +A father area declaration indicates the amount of storage required for the area and may specify some of the fields in the area. A refinement specifies the names and types of one or more fields in the area.\ + \ +Several refinements may be associated with the same father area. In such cases, the refinements are overlayed in storage.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1.\ + TYPE father AREA (3 * 16)\ + i integer\ + ENDAREA;\ + \ + % Specifies that father is an area 48 bits in width.\ + % father's first field is i, an integer. There are\ + % 32 bits unallocated in the type declaration for\ + % father.\ + \ + 2.\ + TYPE son1 AREA REFINES father\ + t TABLE[0 TO 15] OF BOOL\ + ENDAREA;\ + \ + % Specifies that son1 is a refinement of father. The\ + % table t is allocated storage, after i, in the space\ + % reserved for father.\ + \ + 3.\ + TYPE son2 AREA REFINES father\ + j int,\ + k colour\ + ENDAREA;\ + \ + % Specifies that son2 is a refinement of father. The\ + % integer j and k of type colour are both allocated\ + % storage, after i, in the space reserved for father.\ + % Note that j and t share the same storage.\ + \ +Area types exist to allow for information hiding and data abstraction. These concepts are discussed in "Using PROTEL in DMS" in the section on AREAS (DIS OFLPA).\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.9 DESCRIPTORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Descriptors are used to indirectly reference tables. Conceptually, a descriptor consists of two parts: A descriptor part and a table part. The descriptor part contains the number of elements in the table, the size of these elements and a pointer to the base of the table. The table part contains the elements of the table.\ + \ +At run time, the information in the descriptor part is modified to reflect changes in the table pointed to.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b \cf2 EXAMPLE +\f0\b0 \ + \ + 1. TYPE features_table DESC OF integer;\ + \ + % Defines features_table as a descriptor which\ + % points to a table whose elements are integers.\ + \ +An item within a descriptor is referenced in the same manner as an item within a table. The lower bound of a descriptor is assumed to be zero.\ + \ +The TDSIZE and UPB descriptor operators are described in "Unary Operators".\ + \ +There are two primary uses of descriptors:\ + \ + 1. To allow the implementation of generalized code which can deal with tables of arbitrary size.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 2. \f1\b TO\f0\b0 allow dynamic allocation \f1\b OF\f0\b0 tables. A descriptor can be "filled \f1\b IN\f0\b0 " \f1\b BY\f0\b0 some storage allocator at run-time; conversely, storage pointed \f1\b TO\f0\b0 \f1\b BY\f0\b0 a descriptor can be reclaimed dynamically, at which point the descriptor would be \f1\b SET\f0\b0 \f1\b TO\f0\b0 \f1\b NIL\f0\b0 , thus disconnecting it \f1\b FROM\f0\b0 the storage it previously pointed \f1\b TO\f0\b0 . \f1\b IN\f0\b0 PROTEL all local descriptors are initialized \f1\b TO\f0\b0 \f1\b NIL\f0\b0 .\ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.10 PROCEDURES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The procedure type is used to define the formal parameters and return type for a procedure.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 1. TYPE get_channel_proc PROC (terminal terminal_id)\ + RETURNS integer;\ + \ + DCL new_get_channel get_channel_proc;\ + \ +The name of the type is get_channel_proc. An instance of get_channel_proc is a procedure; new_get_channel is an instance of get_channel_proc. It has one parameter, terminal, of type terminal_id. It returns a value of type integer. The RETURNS clause is omitted for procedures which do not return a value.\ + \ +The parameter is passed by value for parameters defined as terminal is in example 1. This means that the value of the actual parameter will be copied into the formal parameter on procedure entry. A value parameter may be altered within the procedure, but doing so will not change the value of the corresponding argument in the calling routine.\ + \ +The REF keyword may be associated with a parameter. When REF is specified, the address of the actual parameter will be passed to the called procedure. This can be used, for example, when the parameter is a large aggregate which should not be copied. REF parameters are read-only.\ + \ +Alternatively, keyword UPDATES may be associated with a parameter. In this case the parameter is passed in the same way as a REF parameter but updating is allowed and will cause the actual parameter in the calling procedure to change.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 2. TYPE data_table TABLE [1 TO 50] OF BOOL;\ + \ + TYPE transfer_data PROC (REF features_table_1 data_table,\ + UPDATES features_table_2 data_table);\ + \ +The name of the procedure type in example 2 is transfer_data. It has two parameters, features_table_1 and features_table_2. Each is a table containing fifty entries of type BOOL. The addresses of both parameters are passed to the called procedure. Updating of features_table_2 is allowed; features_table_1 cannot be altered.\ + \ +A detailed discussion of parameter passing mechanisms is given in "Parameter Passing Mechanisms".\ + \ + \ + \ + \page \pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.1.11 PACK ATTRIBUTE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The width in bits of a data item is determined from the item's type. In the definition of a type, the PACK attribute can be used to specify a different width. It can be used, for example, to align fields on byte boundaries.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 1. TYPE card_number\ + STRUCT\ + card_in_shelf PACK (8) \{0 TO 15\},\ + shelf_number PACK (16) \{0 TO 4095\}\ + ENDSTRUCT;\ + \ +Normally, the field card_in_shelf would be allocated only 4 bits. The PACK(8) specification overrides this, and forces 8 bits to be allocated. Similarly the field shelf_number requires only 12 bits. However, 16 bits are allocated, since PACK(16) is specified.\ + \ +A PACK attribute can specify a bit width greater than or equal to the default width for a type; it cannot force a type to occupy less space than it would otherwise. Its effect, therefore, is to pad the width normally allocated for a type.\ + \ +Scalar types have maximum allowed packing widths. Aggregate types can be packed to arbitrary widths.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 2. TYPE line_table TABLE [0 TO 99] OF PACK(8) BOOL;\ + \ +An instance of type BOOL only requires 1 bit. However, since PACK(8) is specified, 8 bits are allocated for each element of line_table.\ + \ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 \page 2.2 DATA DECLARATIONS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. DCL remote_make_busy BOOL;\ + \ + 2. DCL inter_digit_time time_interval;\ + \ + 3. DCL calculate_checksum PROC (start_address store_address)\ + RETURNS integer IS\ + BLOCK\ + :\ + :\ + :\ + ENDBLOCK;\ + \ +Data declarations are used to define the data accessible to a program. They can be divided into two categories:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls6\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone \f1\b VARIABLE\f0\b0 declarations;\ +\ls6\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Constant declarations.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.2.1 VARIABLE DECLARATIONS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Figure 2 gives examples of data declaration statements being used to declare variables.\ + \ +The DCL statement declares one or more variables and their type. The type used in a variable declaration can be a defined type created with a type definition or a primitive type. For example, the variable "result" is defined in terms of the type integer. \ +\ + integer is a defined type. In the first three declarations the variables are defined in terms of the primitive types, numeric range, Boolean, and symbolic range.\ + \ +The value following the keyword INIT specifies the initial value to be assumed by a variable at the time of its allocation to storage. In the last example the variable result is initialized to i. The INIT clause is optional.(1)\ +\ + ----------------\ + \ + 1 In the DMS implementation, variables declared within a procedure can be initialized using an INIT clause. Global variables cannot generally (there are exceptions) be initialized in this fashion. The IBM/370 implementation allows global variables to be initialised as well.\ + \ + \ + \page \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | DCL i, j \{0 TO 127\}; |\ + | ____ ________ |\ + | | | |\ + | | | |\ + | variables | |\ + | type |\ + | |\ + | |\ + | DCL availability BOOL; |\ + | ____________ ____ |\ + | | | |\ + | | type |\ + | variable |\ + | |\ + | |\ + | DCL trunk_status \{in_service, out_of_service\}; |\ + | ____________ __________________________ |\ + | | | |\ + | variable type |\ + | |\ + | |\ + | DCL result integer INIT i; |\ + | ______ _______ _ |\ + | | | | |\ + | variable type initial value |\ + | |\ + | |\ + | |\ + | Figure 2. Variable Declarations |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +2.2.2 CONSTANT DECLARATIONS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The data declaration statement can be used to define symbolic names for scalar, aggregate, or procedure constants. The value of a declared constant is fixed at compile time and may not be modified during program execution.\ + \ +The value(s) following the keyword IS in the declaration specifies the constant value(s).\ + \ +In Figure 3 the value of the constant seconds_per_hour is fixed at 60 * 60, and the primes table contains the entries 2, 3, 5, 7, 11, and 13.\ + \ + \ + +\f2 +---------------------------------------------------------------+\ + | |\ + | DCL seconds_per_hour integer IS 60 * 60; |\ + | _______________ _______ ____ |\ + | | | | |\ + | | | | |\ + | symbolic name for defined constant |\ + | constant type value |\ + | |\ + | |\ + | DCL primes TABLE [1 TO 6] OF integer IS \{2,3,5,7,11,13\}; |\ + | ______ _________________________ _______________ |\ + | | | | |\ + | | | | |\ + | | type constant value |\ + | symbolic name |\ + | for constant |\ + | |\ + | Figure 3. Constant Declarations: Definitions of symbolic |\ + | constants |\ + +---------------------------------------------------------------+\ + +\f0 \ + Constant declarations can also be used to define the type and body of a procedure. As an example, consider Figure 4. Statements 1 through 8 comprise the constant declaration statement. The name of the procedure, the parameters, and the return value are specified in statements 1 through 2. Calculate_average is the procedure name. This is followed by the keyword PROC and the procedure parameters and their types enclosed in parentheses. In the example the parameters are number_1 and number_2, each of type integer.\ + \ +The portion of the statement\ + \ + RETURNS integer\ + \ +is called the "returns clause". It specifies that the procedure returns a value of type integer.\ + \ +The block statement following IS and delimited by the BLOCK and ENDBLOCK keywords defines the body of the procedure calculate_average. We call the DCL statement, up to the IS keyword, the declaration of procedure "calculate_average". We call the body of a procedure its definition, or its implementation.\ +\ +Data declarations local to the procedure may follow the keyword BLOCK. In this example, the local variable "average" is declared in statement 4.\ + \ +Executable statements (statements 6 and 7) related to the procedure are located between the local variable data declaration(s) and the keyword ENDBLOCK.\ + \ +\ +\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 DCL calculate_average PROC (number_1, number_2 integer) |\ + | 2 RETURNS integer IS |\ + | 3 BLOCK |\ + | 4 DCL average integer; |\ + | 5 |\ + | 6 (number_1 + number_2) / 2 -> average; |\ + | 7 RETURN average; |\ + | 8 ENDBLOCK; |\ + | |\ + | Figure 4. Constant Procedure Declaration |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 \page 3.0 EXECUTABLE STATEMENTS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +Executable statements operate on the data defined in the declaration statements. We think of executable statements as "doing things" or manipulating objects. Formally, executable statements are those PROTEL statements which cause sequences of machine language instructions to be generated.\ + \ +Executable statements can be divided into two basic categories:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls7\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone Expressions;\ +\ls7\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Control Statements.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 3.1 EXPRESSIONS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. i * result -> result;\ + \ + 2. get_idle_trunk ();\ + \ +Expressions are executable statements which create new data values from existing ones. Expressions can be categorized by those which evaluate to a value, and those which do not. An expression which does not evaluate to a value is a procedure call. An expression is a statement if it is either an assignment statement, or a procedure call.\ +\ +The assignment operator in PROTEL is "->".(2) \ +\ +The value of the expression\ + \ + 23 -> x\ + \ +is 23.\ + \ +To see that an assignment statement is an expression, one must understand that the assignment operator is a binary operator which causes a side-effect.\ +\ +Consider the following assignment statement:\ + \ + 23 + 1 -> x / 2 -> y;\ + \ + ----------------\ + 2 '->' is pronounced "guzinta", a derivative of "goes into". Thus a -> b reads "a goes into b".\ + \ + \ +\page Evaluation of arithmetic operators in PROTEL is left-to-right. The value of "23 + 1 -> x" is 24, with the side-effect that x has been assigned the value 24. 24 / 2 is then evaluated and the right-most assignment operator is evaluated, causing y to be assigned the value 12. The order of evaluation of operators in this example is +, ->, /, ->.\ + \ +Assignment expressions contain the assignment operator in the expression. However, an assignment expression is a statement only if the assignment operator is the last evaluated operator in the expression.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 3. i + 1 -> i; % legal assignment statement.\ + \ + 4. (i + 1 -> i); % legal assignment statement.\ + \ + 5. (i -> i + 1); % not legal; -> not the last operator.\ + \ + 6. p(i + 1 -> i); % legal if p does not return a value.\ + \ +Procedure calls may be used either by themselves or as a component of an assignment statement. When used as part of an assignment statement, a procedure must have been declared with a RETURNS clause, indicating the type of the value to be returned. When used by itself the procedure must have been defined without the RETURNS clause. A procedure call consists of the procedure name followed by the procedure parameters enclosed in parentheses.\ + \ +In example 1 above, the value of i is multiplied by the value of result and the new value assigned to result.\ + \ +In example 2 the procedure get_idle_trunk is called. Note that this procedure has no parameters as is indicated by the empty parentheses.\ + \ +The basic components of an \ul expression\ulnone are \ul operators\ulnone , \ul operands\ulnone , and \ul parentheses\ulnone .\ +\ +The operands and operators are indicated in the statement in Figure 5.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | ( number_1 + number_2 ) / 2 -> average ; |\ + | ________ _ ________ _ _ __ _______ |\ + | | | | | | | | |\ + | | | | | | | operand |\ + | | | | | | operator |\ + | | | | | operand |\ + | | | | operator |\ + | | | operand |\ + | | operator |\ + | operand |\ + | |\ + | Figure 5. Operators and Operands |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1 OPERATORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The types of operators used in PROTEL are:\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls8\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone assignment operator\ +\ls8\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone arithmetic operators\ +\ls8\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone comparison operators\ +\ls8\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone logical operators\ +\ls8\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone unary operators\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1.1 ASSIGNMENT OPERATOR\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The assignment operator -> causes the value on the left of the operator to be assigned to the variable on the right. The operands and the result of an assignment statement must be type-compatible. The type compatibility rules are discussed in detail in the PROTEL Reference Manual.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1.2 ARITHMETIC OPERATORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The PROTEL arithmetic operators are:\ + \ + * multiplication\ + \ + / integer division\ + \ + + addition\ + \ + - subtraction\ + \ + MOD a MOD b gives the integer remainder of a divided by b\ + \ + << shift left\ + \ + >> shift right\ + \ + Arithmetic operators operate on and produce values of type numeric range.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1.3 COMPARISON OPERATORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ + The PROTEL comparison operators are:\ + \ + a < b % a is less than b\ + \ + a > b % a is greater than b\ + \ + a <= b % a is less than or equal to b\ + \ + a >= b % a is greater than or equal to b\ + \ + a = b % a is equal to b\ + \ + a ^= b % a is not equal to b\ + \ +These operators compare (algebraically) the relative magnitudes of their two operands and yield a Boolean (true or false) value as a result. The valid operand types for the <, >, <=, and >= operators are the types numeric range and symbolic range. For the = and ^= operators, any type of operand is valid. The result of these operators is of type BOOL.\ +\ +Tables or structures of identical type may also be compared. This is not a good idea with structures, because there may be unused bits with random values inside a structure. The detailed rules for allowable comparisons are given in the PROTEL Reference Manual.\ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1.4 LOGICAL OPERATORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The logical operators used in PROTEL are:\ + \ + \ul Symbol\ulnone \ul Meaning\ulnone \ + \ + & AND\ + \ + | OR\ + \ + ! Exclusive OR\ + \ + ^ NOT\ + \ + INCL Set inclusion ("is included in")\ + \ + NOTINCL Set exclusion ("is not included in")\ + \ +The valid operand types and result types for the &, |, and ! operators are BOOL, numeric range, and SET.\ +\ +The function of the logical operators depends on their operands. When both operands are of type BOOL, they perform the logical operations. When both operands are of type SET or numeric range, they perform the bitwise AND, OR, and exclusive OR functions (set intersection, set union, and exclusive OR). For these cases, the result is of the same type as the operands.\ + \ +For example, the set s is defined in the statement\ + \ + DCL s SET \{x, y, z\};\ + \ +The OR operator can be used to set the x bit in the set s.\ + \ + \{x\} | s -> s;\ + \ +Similarly, the AND operator can be used to clear the x bit in the set s.\ + \ + ^ \{x\} & s -> s;\ + \ +The operand type for the INCL and NOTINCL operators is the type SET. The result is of type BOOL.\ + \ + \{y,x\} INCL \{x,z,w,y\} % TRUE. \{y,x\} is included in \{x,z,w,y\}.\ +\ +Compound Boolean expressions can be formed from one or more Boolean expression through the use of logical operators. Consider, for example, the Boolean expressions:\ + \ + a >= 2\ + \ + a = 1\ + \ + b <= 3\ + \ +A compound Boolean expression composed from these three expressions is shown in Figure 6.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | yields TRUE only if |\ + | both conditions are true. |\ + | | |\ + | -------------------- |\ + | |\ + | (a >= 2) | ((a = 1) & (b >= 3)) |\ + | |\ + | __________________________________ |\ + | | |\ + | yields TRUE value if either condition |\ + | on opposite sides of the OR operator is true. |\ + | |\ + | Figure 6. Compound Boolean Expression |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.1.5 UNARY OPERATORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The unary operators used in PROTEL are:\ + \ + \ul Symbol\ulnone \ul Meaning\ulnone \ +\ + - negation (arithmetic)\ + \ + ^ NOT (logical)\ + \ + UPB upper bound\ + \ + TDSIZE Size ("Table or Descriptor SIZE")\ + \ + DESC Descriptor\ + \ + PTR Pointer\ + \ +The valid operand and result type for the minus operator ('-') is numeric range.\ + \ +For the NOT operator ('^'), the operand type must be one of BOOL, numeric range, or SET. The result is of the same type as the operand.\ + \ +The operand type for the UPB and TDSIZE operators must be either DESC or TABLE. UPB returns the highest value in the bounds of the table; TDSIZE returns the number of elements in the table. The result type for the UPB operator is the type of the bounds; for TDSIZE, it is numeric range.(3)\ + \ +The DESC operator requires a table or descriptor as an operand and returns a descriptor to that table. The PTR operator accepts a storage reference as an operand and returns a pointer to the storage location where the reference is contained.\ + \ +Expressions are evaluated from left to right. However, parentheses can be used to change the order of evaluation. For example,\ + \ + sum_1 + sum_2 / sum_3\ + \ + sum_1 is added to sum_2 and the result is divided by sum_3. However, in the expression\ + \ + sum_1 + (sum_2 / sum_3)\ + \ + sum_1 is added to the result of dividing sum_2 by sum_3.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + DCL t TABLE [0 TO 10] OF integer;\ + \ + UPB t % value is 10.\ + \ + TDSIZE t % value is 11.\ + \ + ----------------\ + 3 Actually, TDSIZE yields a result of type unsignedint, a positive subset of numeric range.\ + \ +\ + \page \pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2 OPERANDS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The operands in an expression are the objects operated on by the operators.\ + \ +Operands in an expression can be of three types:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls9\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone constants\ +\ls9\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone storage references\ +\ls9\ilvl0\up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone procedure calls\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +Examples of each of these operand types are illustrated in Figure 7.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | (a + b) / 2 -> average; |\ + | _ _ _ _______ |\ + | | | | | |\ + | | | | storage reference to average |\ + | | | constant |\ + | | storage reference to variable b |\ + | storage reference to variable a |\ + | |\ + | |\ + | i * factorial(i) -> result; |\ + | _ ____________ ______ |\ + | | | | |\ + | | | storage reference to variable result |\ + | | | |\ + | | procedure call |\ + | | |\ + | storage reference to variable i |\ + | |\ + | |\ + | collect_digits(); |\ + | ________________ |\ + | | |\ + | procedure call |\ + | |\ + | Figure 7. Types of Operands |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +"Constants" may be either self-defining or user-defined. A self-defining constant is a number, tuple or string occurring in an expression. A user-defined constant is an identifier denoting a constant declared in a constant declaration (i.e., a DCL statement).\ + \ +Storage references may be of five types:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls10\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone Identifiers\ +\ls10\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Selection\ +\ls10\ilvl0\up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone Indexing\ +\ls10\ilvl0\up0 \nosupersub \ulnone {\listtext 4. }\up0 \nosupersub \ulnone Multiples\ +\ls10\ilvl0\up0 \nosupersub \ulnone {\listtext 5. }\up0 \nosupersub \ulnone Dereferences\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2.1 IDENTIFIERS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ +The "identifier" form of a storage reference may be applied when dealing with variables of a simple type or all of the fields of a structured type. The effect of such a reference is to yield the value of the variable associated with the identifier.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2.2 SELECTION\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Selection is used to specify a field of a structure or area. A "selection" consists of a storage reference to the structure followed by a dot, followed by the name of the selected field.\ + \ +For example, consider the data declaration statement\ + \ + DCL trunk_id terminal_id;\ + \ +It specifies that the variable trunk_id is of the type terminal_id (as defined in example 1 in \'93Structures\'94.) \ +\ +The field terminal_number of the structure is accessed in the following way:\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 trunk_id . terminal_number\ + -------- ---------------\ + | |\ + | |\ + | field referenced\ + |\ + an instance of type terminal_id\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2.3 INDEXING\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ +Indexing is used to select an element of a table or descriptor. An "indexing" consists of a storage reference to the table or descriptor followed by a square bracketed expression. The expression should be of the same type as the table bounds and its result indicates the position of the desired element within the table.\ + \ +For example, a reference to the 4th value in an instance\ + digit_register_x of type digit_register would be written\ + \ + digit_register_x[3]\ + \ + (Remember that digit_register is indexed from zero.)\ + \ + \ + \ +\ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2.4 MULTIPLE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ +The multiple form of a storage reference is used to index more than one element of a table, or even a whole table, simultaneously. A "multiple" consists of a storage reference to the table followed by a square bracketed subrange expression. The subrange expression indicates, by specifying its first and last elements, the portion of the table to be referenced.\ + \ +The subrange expression is optional. If omitted, the whole table is referenced.\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + digit_register_x[0 TO 4]\ + % specifies the first 5 elements of digit_register_x.\ + \ + digit_register_x[11 TO 15]\ + % specifies the last 5 elements of digit_register_x.\ + \ + digit_register_x[]\ + % specifies the whole table digit_register_x.\ + \ + digit_register_x[0 TO UPB digit_register_x]\ + % specifies the whole table digit_register_x.\ + \ +Note that brackets are required when specifying all elements in a table.\ + \ +Forming a descriptor over only part of a table is sometimes referred to as taking a "slice" of the table.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.1.2.5 DEREFERENCE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ +Dereferences denote items pointed to by pointer variables. A "dereference" consists of a storage reference to a pointer followed by an at ("@") symbol.\ + \ +For example, consider the following declarations\ + \ + DCL p PTR TO \{0 TO 255\};\ + \ + DCL i, j \{0 TO 255\};\ + \ + The following two-statement sequence causes the value of i to be assigned to j\ + \ + PTR i -> p;\ + p@ -> j;\ + \ + \page \pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 3.2 CONTROL STATEMENTS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + \ + 1.\ + RETURN result;\ + \ + 2.\ + IF a > 0 THEN\ + b + 1 -> b;\ + ENDIF;\ + \ + 3.\ + WHILE (i - 1 -> i) > 1\ + DO\ + i * result -> result;\ + ENDDO;\ + \ +These examples illustrate three types of control statements:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls11\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone the \f1\b RETURN\f0\b0 statement;\ +\ls11\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone the IF statement;\ +\ls11\ilvl0\up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone the ITERATIVE statement.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +Control statements are used to modify the normal sequential execution of statements. PROTEL has different types of control statements. These are:\ + \ +\pard\tx20\tx180\pardeftab720\li180\fi-180\partightenfactor0 +\ls12\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone \f1\b RETURN\f0\b0 statement;\ +\ls12\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone IF statement;\ +\ls12\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone CASE statement;\ +\ls12\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone SELECT statement;\ +\ls12\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone ITERATIVE statement;\ +\ls12\ilvl0\up0 \nosupersub \ulnone {\listtext \uc0\u8226 }\up0 \nosupersub \ulnone EXIT statement.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +Each of these will be discussed in detail in the following sections.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.1 RETURN STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + RETURN result;\ + \ + \ +The RETURN statement, when used in a procedure, causes control to be returned to the point of invocation of the procedure.\ + \ +Procedures defined with a RETURNS clause must specify after the keyword RETURN the expression whose value is to be returned.\ + \ + Consider the statements in Figure 8.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | DCL factorial PROC (i integer) RETURNS integer IS |\ + | --------------- |\ + | | |\ + | RETURNS clause |\ + | specifies the type |\ + | of the value returned |\ + | |\ + | BLOCK |\ + | DCL result integer INIT i; |\ + | : |\ + | : |\ + | : |\ + | : |\ + | RETURN result; |\ + | ------ |\ + | | |\ + | expression to be returned |\ + | ENDBLOCK; |\ + | |\ + | Figure 8. Return Statement: A PROTEL procedure may return a |\ + | value of any type. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + Note that result is of the type integer as defined in the procedure declaration.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \page \pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.2 IF STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The \f1\b IF\f0\b0 statement is used in PROTEL when a test or a decision is to be made between alternatives. The \f1\b IF\f0\b0 statement has the following format:\ + \ + IF expression_1\ + THEN\ + statement_list_1;\ + ELSE\ + statement_list_2;\ + ENDIF;\ + Next_Statement;\ + \ +The expression following the keyword IF must always yield a value of type BOOL. If this value is TRUE, the statement list following THEN is executed. If the value is FALSE, the statement list following ELSE is executed. The ELSE clause of the IF statement is optional. If it is not present and the value of the expression following IF is FALSE the statement following ENDIF is executed.\ + \ +Both statement_list_1 and statement_list_2 are optional.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 1. IF x > y\ + THEN\ + x - y -> x;\ + ELSE\ + y - x -> x;\ + ENDIF;\ + Next_ statement;\ + \ +In example 1 above one of the expressions\ + \ + x - y -> x\ + \ +or\ + \ + y - x -> x\ + \ +will be executed. The choice depends on the values of x and y. If x is greater than y, x - y is assigned to x. If, however, x is not greater than y, then y - x assigned to x.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.3 NESTED IF STATEMENTS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The THEN and ELSE clauses of the IF statement can be expanded to govern the execution of any number of alternative statements. This type of statement contains IF statements within IF statements and is referred to as a nested IF statement.\ + \ +The general form of such statements is shown in Figure 9. Note that each IF has a corresponding ENDIF.\ + \ +\ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | IF expression_1 |\ + | THEN |\ + | IF expression_2 |\ + | THEN |\ + | statement_list_1; |\ + | ELSE |\ + | statement_list_2 ; |\ + | ENDIF; |\ + | |\ + | ELSE |\ + | IF expression_3 |\ + | THEN |\ + | statement_list_3 ; |\ + | ELSE |\ + | statement_list_4 ; |\ + | ENDIF; |\ + | ENDIF; |\ + | Next Statement; |\ + | |\ + | Figure 9. IF Statement: general form. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +In Figure 10 on page 39 only one of the three statements\ + \ + x -> biggest_number;\ + \ + y -> biggest_number;\ + \ + z -> biggest_number;\ + \ +will be executed. Statement 12 logically follows statements 3, 7, and 9.\ + \ +If x is greater than both y and z then statement 3 is executed. If, however, x is less than or equal to either y or z, control is transferred to statement 5. Now if y is greater than z, then statement 7 is executed. If, however, y is not greater than z, then statement 9 is executed.\ + \ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 IF (x > y) & (x > z) |\ + | 2 THEN |\ + | 3 x -> biggest_number; |\ + | 4 ELSE |\ + | 5 IF y > z |\ + | 6 THEN |\ + | 7 y -> biggest_number; |\ + | 8 ELSE |\ + | 9 z -> biggest_number; |\ + | 10 ENDIF; |\ + | 11 ENDIF; |\ + | 12 next_statement_1; |\ + | |\ + | Figure 10. IF Statement Example |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.4 CASE STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The \f1\b CASE\f0\b0 statement is another type of control statement. It is used to selectively transfer control to one group of statements out of several.\ + \ +The general form of the CASE statement is:\ + \ + CASE expression IN\ + \{expression_value_1\}: statement_list_1;\ + \{expression_value_2\}: statement_list_2;\ + .\ + .\ + .\ + \{expression_value_n\}: statement_list_n;\ + OUT statement_list_n_plus_1;\ + ENDCASE;\ + \ +Each group of statements is uniquely labelled with one or more of the values in the range of the expression following the keyword CASE. The value of expression must be of type numeric range, symbolic range, SET, or BOOL. When the CASE statement is executed control is transferred to the group of statements whose label matches the value of expression. If no match is found, control is transferred to the group of statements following OUT.\ + \ +When the last statement in a group has been executed control passes to the statement following the keyword ENDCASE, providing that no statement in the group transfers control out of the CASE statement (e.g., RETURN or EXIT).\ + \ + +\f2 +---------------------------------------------------------------+\ + | |\ + | TYPE digit \{0 TO 9\}; |\ + | |\ + | DCL n digit; |\ + | |\ + | CASE n IN % n is first digit dialled |\ + | \{0\} : TRUE -> operator; |\ + | |\ + | \{1\} : TRUE -> ddd_call; |\ + | set_area (); |\ + | |\ + | \{4\} : TRUE -> assist; |\ + | check_11 (); |\ + | |\ + | \{2,6\} : TRUE -> wrong_number; % sorry, ... |\ + | |\ + | OUT TRUE -> local_call; |\ + | ENDCASE; |\ + | |\ + | Next_statement; |\ + | |\ + | Figure 11. Case Statement |\ + +---------------------------------------------------------------+\ + +\f0 \ +In Figure 11 n lies in the range 0 to 9. Values in this range are used to label statements enclosed by CASE, ENDCASE keywords.\ +\ +Note that not all possible values for n (0 to 9) occur as case selector labels.\ + \ +When the CASE statement is executed, control is transferred to the group of statements whose label matches or includes the value of the expression. For example, if n is 0, control is transferred to the statement\ + \ + \{0\} : TRUE -> operator;\ + \ +If n does not equal 0, 1, 2, 4 or 6, control is transferred to the statement following OUT. In all cases, execution will resume at next_statement.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.5 SELECT STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The SELECT statement is similar to the CASE statement. Their syntax is identical except that SELECT and ENDSELECT are substituted for CASE and ENDCASE.\ + \ +The action of CASE and SELECT are the same. The difference is in efficiency. CASE is usually faster than SELECT but may require more space. This is particularly true if the range of the label values is large but the actual labels are sparse within that range.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.6 ITERATIVE STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Another type of control statement is the "iterative" statement.\ + \ + FOR i FROM initial UP TO limit BY modification\ + DO\ + statement_1;\ + :\ + :\ + :\ + statement_n;\ + ENDDO;\ + \ +The iterative statement facilitates the definition and control of repetitions of a group of statements.\ + \ +The statements which perform these repetitions are collectively called an iterative statement or loop.\ + \ +The FOR statement defines the number of times the iterative statement will be executed.\ + \ +The components of this statement are:\ + \ + o the control variable. It is implicitly declared by the FOR\ + statement and is not accessible outside the loop. It is read-\ + only.\ + \ + o the initial value.\ + It is optional; if omitted, FROM 0 is assumed.\ + \ + o the limit value.\ + It is optional; if omitted, DOWN TO 0 is assumed.\ + \ + o the modification value.\ + It is optional; if omitted, BY 1 is assumed.\ + \ +They are labelled in the statement in Figure 12.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | FOR i FROM 0 UP TO 10 BY 1 |\ + | _ _ __ _ |\ + | | | | | |\ + | | | | modification |\ + | | | limit value |\ + | | | value |\ + | | initial |\ + | | value |\ + | | |\ + | control |\ + | variable |\ + | |\ + | Figure 12. FOR Loop |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +The sequence of events involved in executing the iterative statement is:\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls13\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone Initialize the control \f1\b VARIABLE\f0\b0 .\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +This variable (i in our example) will be set equal to the initial value (0 in our example). It cannot be modified within the loop.\ +\ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls14\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Test the control \f1\b VARIABLE\f0\b0 .\ +\pard\pardeftab720\partightenfactor0 +\cf2 \f1\b IF\f0\b0 the control \f1\b VARIABLE\f0\b0 \f1\b IS\f0\b0 less than or equal \f1\b TO\f0\b0 the limit value, the statements following \f1\b DO\f0\b0 will be executed. Otherwise a transfer \f1\b TO\f0\b0 the statement following \f1\b ENDDO\f0\b0 \f1\b IS\f0\b0 effected and the iteration terminated. \f1\b IN\f0\b0 the example, \f1\b AS\f0\b0 long \f1\b AS\f0\b0 I \f1\b IS\f0\b0 less than or equal \f1\b TO\f0\b0 10 the statements following \f1\b DO\f0\b0 will be executed.\ +\ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls15\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone Execute the statements following \f1\b DO\f0\b0 .\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ + The statements headed by the DO and terminated by the ENDDO are executed.\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls16\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 4. }\up0 \nosupersub \ulnone Modify the control \f1\b VARIABLE\f0\b0 .\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +The modification value is added to the control variable. In the example above the constant 1 is added to the contents of the control variable i.\ +\ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls17\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 5. }\up0 \nosupersub \ulnone \f1\b RETURN\f0\b0 \f1\b TO\f0\b0 step 2.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +Consider the following example\ +\ + FOR i FROM 2 UP TO 10 BY 3\ + DO\ + :\ + :\ + :\ + ENDDO;\ + \ +The first time through the loop, i will have value 2. The second time through i will have value 5. Recall that the modification value, in this case 3, is added to the control variable (2 + 3 = 5). The third time through the loop, i will have value 8. On the fourth test of "i <= 10", i will have value 11, the test will fail, and the body of the loop will not be executed.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.7 THE OVER SPECIFICATION\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Another way of specifying the number of times the iteration is to be performed is by using the OVER keyword.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + TYPE weekday \{mon, tues, wed, thurs, fri\};\ + \ + 1. FOR i OVER weekday\ + DO\ + :\ + :\ + :\ + ENDDO;\ + \ +The number of elements in the symbolic range weekday is 5. Therefore, the above FOR statement performs the same number of iterations as\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 2. FOR j FROM 0 UP TO 4\ + DO\ + :\ + :\ + :\ + ENDDO;\ + \ +The two loops differ in the type of the control variable. i has type weekday, while j has type "numeric range".\ + \ +In example 2 the control variable j is initialised to 0 and the loop is repeated until j is greater than 4. Each time the value of j is incremented by 1.\ + \ +In example 1 the control variable i is initialised to mon, and increments through the values tues, wed, thurs, and fri.\ + \ +The program in Figure 13 sums the elements of a table.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 DCL t TABLE [0 TO 9] OF integer; |\ + | 2 |\ + | 3 DCL sum_t PROC () RETURNS integer IS |\ + | 4 BLOCK |\ + | 5 DCL sum integer INIT 0; |\ + | 6 |\ + | 7 FOR i FROM 0 UP TO UPB t |\ + | 8 DO |\ + | 9 t[i] + sum -> sum; |\ + | 10 ENDDO; |\ + | 11 RETURN sum; |\ + | 12 ENDBLOCK; |\ + | |\ + | Figure 13. Iterative Statement: This program sums the |\ + | elements in a table. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +The table t, the elements of which are to be summed, has 10 entries all of type integer.\ + \ +Note that no parameters are required for the sum_t PROC. This is indicated by the empty parenthesis in statement 3.\ + \ +Statements 7 through 10 form the iterative statement, or loop. Note that in statement 7 the limit value is UPB t, meaning the upper bound of table t. Thus the loop is repeated until i is greater than 9. The preceding examples show loops with positive modification values. It is possible to specify a negatively incremented loop, in which case a 'count down' operation is effected. This is down by specifying DOWN TO instead of UP TO in the iteration statement.\ +\ +Note that the modification value is still positive.\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 3. FOR k FROM 5 DOWN TO 0 BY 1\ + DO\ + :\ + :\ + :\ + ENDDO;\ + \ + Each time through the loop the value of k is decremented by 1.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +3.2.8 ITERATIVE STATEMENT WITH THE WHILE CONDITION\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The WHILE condition is a modification of the iterative statement. This form of iterative statement specifies that the body of the loop is to be repeated as long as a specified 'condition' is true. The condition is evaluated prior to each pass through the loop.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 0 -> a; |\ + | 2 1 -> i; |\ + | 3 |\ + | 4 WHILE (i <= 10) |\ + | 5 DO |\ + | 6 a + 1 -> a; |\ + | 7 i + 1 -> i; |\ + | 8 ENDDO; |\ + | |\ + | Figure 14. WHILE Loop |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +In this case as long as i is less than or equal to 10 the loop is repeated.\ + \ +The first time through the loop statement 7 assigns 2 (= i + 1) into i, since i was initialised to value 1 in statement 2.\ + \ +On each iteration through the loop i is incremented by 1 until i = 11. At this point execution of the loop is terminated.\ + \ +The program for calculating the factorial of a number in Figure 1 on page 8 uses an iterative statement with the WHILE condition.\ + \ +Both WHILE and FOR clauses may be mixed in the same statement.\ +\ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 1. FOR i FROM 0 UP TO 20 BY 1 WHILE (a < b) DO\ + :\ + :\ + :\ + ENDDO;\ + \ + A result of the default values for all clauses yields\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 2. FOR i FROM 0 DOWN TO 0 BY 1 WHILE TRUE DO\ + :\ + :\ + :\ + ENDDO;\ + \ + \ +\ +Example 2 describes an infinite loop. Therefore, with all optional fields removed, a loop-forever construct in PROTEL reduces to:\ + \ + +\f1\b EXAMPLE +\f0\b0 \ + \ + 3. DO\ + :\ + :\ + :\ + ENDDO;\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 + 3.2.9 EXIT STATEMENT\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The EXIT Statement is another type of control statement. It is used to branch out of a sequence of statements within a labelled BLOCK, DO, CASE, SELECT or IF statement.\ + \ +The general format of the EXIT statement is:\ + \ + e : DO\ + statement_1;\ + IF expression_1 THEN\ + EXIT e;\ + ENDIF;\ + statement_2;\ + ENDDO e;\ + Next_statement;\ + \ +Note in the example the DO statement is labelled e. The identifier e following the EXIT statement matches this label. If expression_1 is true then the EXIT is executed. This transfers control to the statement following the terminating keyword of the block whose label matches the identifier. In this case, control is transferred to the statement following ENDDO e;\ + \ + If expression_1 is false, statement_2 is executed, and control\ + returns to the statement labelled e.\ +\ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 4.0 PARAMETER PASSING MECHANISMS\ +\pard\pardeftab720\sa360\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +4.1.1 FORMAL AND ACTUAL PARAMETERS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A parameter declared in a procedure declaration is called a formal parameter. In Figure 15, f is a formal parameter of p.\ +\ +The parameter in a procedure call which matches a formal parameter is called an actual parameter. On line 11 of Figure 15, i is an actual parameter for f. Actual parameters are referred to colloquially as "arguments".\ + \ + +\f2 +---------------------------------------------------------------+\ + | |\ + | 1 | DCL p PROC (f int) IS |\ + | 2 | BLOCK |\ + | 3 | 23 -> f; |\ + | 4 | ENDBLOCK; |\ + | 5 | |\ + | 6 | DCL alpha PROC () IS |\ + | 7 | BLOCK |\ + | 8 | DCL i int; |\ + | 9 | |\ + | 10 | 75 -> i; |\ + | 11 | p(i); |\ + | 12 | typeint ('i = ', i); |\ + | 13 | ENDBLOCK; |\ + | |\ + | Figure 15. Parameter Passing: calling by value |\ + +---------------------------------------------------------------+\ + +\f0 \ +There are numerous methods of matching actual and formal parameters. Only two are generally used in PROTEL. The first is called call-by-value. This involves evaluating the actual parameter, and passing its value to the formal parameter. The formal parameter is a stack variable which is initialised to the value of its actual parameter. It disappears when the procedure finishes executing. Inside of the procedure it is a read-write variable like all of the other variables local to that procedure. The only way it is distinguished is that it has an initial value supplied by the caller. Because the argument is a value, we consider the argument to be an expression, which is evaluated at run-time.\ + \ +In Figure 15, the value of i at line 12 is 75. Note that procedure p cannot change the value of any argument to a call-by-value formal parameter. We may think of a call-by-value actual parameter as an initial value. Call-by-value is the default parameter passing mechanism in PROTEL.\ + \ +The second parameter passing mechanism is called call-by-reference. Here a pointer to the argument is generated by the compiler as the actual parameter. The formal parameter is implemented as a pointer to the actual parameter. All accesses to the value of the formal parameter are indirect. The compiler must generate the indirect addressing modes required, even though the references inside the procedure look as though they are direct.\ +\ +For example, if the formal parameter is a table t, then t[i] is an indirect reference through the table pointer t.\ + \ +Note that for a call-by-reference parameter, the argument must be a storage reference.(4)\ +\ +\ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 | DCL h PROC (UPDATES t TABLE [1 TO 5] OF int) IS |\ + | 2 | BLOCK |\ + | 3 | 78 -> t[3]; |\ + | 4 | ENDBLOCK; |\ + | 5 | |\ + | 6 | DCL k PROC () IS |\ + | 7 | BLOCK |\ + | 8 | DCL w TABLE [1 TO 5] OF int; |\ + | 9 | |\ + | 10 | \{10,20,30,40,50\} -> w[]; |\ + | 11 | h(w); |\ + | 12 | typeint ('w[3] = ', w[3]); |\ + | 13 | ENDBLOCK; |\ + | |\ + | Figure 16. Parameter Passing: call by reference (efficient) |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +The value of t[3] in statement 12 is 78, not 30.\ + \ + \ + ----------------\ + \ + 4 A storage reference is generally a variable, but may also be a constant. A self-defining tuple, such as 'Quebec', is both a constant an a storage reference. If this is confusing, the reader is directed to the reference manual for an explanation of storage reference.\ + \ +\page \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 | DCL g PROC (UPDATES x int) IS |\ + | 2 | BLOCK |\ + | 3 | 123 -> x; |\ + | 4 | ENDBLOCK; |\ + | 5 | |\ + | 6 | DCL k PROC () IS |\ + | 7 | BLOCK |\ + | 8 | DCL v int; |\ + | 9 | |\ + | 10 | 67 -> v; |\ + | 11 | g(v); |\ + | 12 | typeint ('v = ', v); |\ + | 13 | ENDBLOCK; |\ + | |\ + | Figure 17. Parameter Passing: call by reference (ineffi- |\ + | cient) |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +Using procedure g in Figure 17, a call such as g(i+67) is illegal, since one cannot take a pointer to the value of 'i+67'. The argument to a call-by-reference formal parameter must be a storage reference. A storage reference is a data object which is stored in memory, and therefore has an address.\ + \ +When a procedure intends to alter the value is an argument, the formal parameter must be call-by-reference. In PROTEL, we invoke call-by-reference by the keyword UPDATES. In line 12 of Figure 17, the value of v is 123, not 67.\ + \ +Now we look at the 'work' involved in each of these parameter passing mechanisms. The number of bytes of data which must be copied to match an argument to a call-by-value parameter is equal to the width of the formal parameter. Hence, when f (Figure 15 on page 47) gets an initial value, one word is passed. If the formal parameter is a table of 5 ints (such as f in Figure 16 on page 48) then 5 words will be copied as the initial value.\ + \ +A pointer, however, is always the same width. In PROTEL/DMS a pointer is two words. A call-by-reference parameter always requires two words to be passed. Obviously it is inefficient to pass an int or byte by reference. However, it is even less desirable to pass a large table by value. If we don't wish to have read-write access to an argument, we should use call-by-value.\ + \ +For the sake of efficiency, PROTEL allows us to invoke call-by-reference through two different keywords. One, UPDATES, asks for the usual call-by-reference, i.e., is a demand for read-write capability. REF, on the other hand, says "this should be a call-by-value parameter, but because the bit width of the value is large, use call-by-reference with read-only capability.". Both REF and UPDATES generate identical object code, however a REF parameter cannot be used as the target of an assignment.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +4.1.2 THE VAL ATTRIBUTE\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The keyword VAL may also be used in formal parameter declarations. This is used when a level of indirection to data is passed, and the data itself is to be considered, but is not subject to modification by the procedure.\ + \ +Consider parameter d3 of procedure pv in Figure 18. d3 is passed call-by-value, so pv gets a local copy of the argument. d3 is not a constant; pv is free to change the value of its local copy (though this would likely be unwise). However, pv is not permitted to modify the storage pointed to by d3. Hence line 7 is an error, since within procedure pv, the int type which d3 points to has been redeclared to be a read-only type.\ + \ +Similarly p1 points to a read-only int type. p1 is not, itself, read-only, but again changing the value of p1, i.e., causing it to point somewhere other than its initial value would likely be a programming error, since no updated value can be returned through p1.\ + \ + +\f2 +---------------------------------------------------------------+\ + | |\ + | 1 |DCL pv PROC (d3 DESC OF VAL char, p1 PTR TO VAL char) IS |\ + | 2 |BLOCK |\ + | 3 | DCL |\ + | 4 | c char, |\ + | 5 | capital DESC OF CHAR is 'Ottawa'; |\ + | 6 | |\ + | 7 | 'G' -> d3[1]; % illegal. d3[1] is read-only. |\ + | 8 | 'G' -> p1@; % illegal. p1@ is read-only. |\ + | 9 | capital -> d3; % legal. d3 is read-write. |\ + | 10 | PTR c -> p1; % legal. p1 is read-write. |\ + | 11 |ENDBLOCK; |\ + | |\ + | ERROR LINE 7 |\ + | *** ERROR: ATTEMPT TO ASSIGN VIA READ ONLY TYPE INT ON LINE 1 |\ + | ERROR LINE 8 |\ + | *** ERROR: ATTEMPT TO ASSIGN VIA READ ONLY TYPE INT ON LINE 1 |\ + | |\ + | Figure 18. Parameter Passing: use of VAL attribute |\ + +---------------------------------------------------------------+\ + +\f0 \ +One last remark on procedure pv: being a two-word object, p1 should not be passed by REF for reasons of efficiency. It rarely makes sense to pass a pointer by passing a pointer to it. d3, on the other hand, is an object larger than two words, but since it contains a pointer it is also sensible to pass it by value.\ +\ +Otherwise all references through d3 will require double dereferencing.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \page \pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +4.1.2.1 COMMON ERRORS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ + \ +One sometimes finds formal parameter declarations such as\ + \ + DCL px PROC (REF d4 DESC OF char) IS FORWARD;\ + \ +where the author believes that REF protects the data pointed to by d4. It does not. d4 would, of course, have to be passed as an UPDATES parameter to allow it to be modified, so d4 itself is read-only. Inside the body of procedure px, the statement\ + \ + 'Canada' -> d4;\ + \ +would be illegal; however, the statement\ + \ + 'Canada' -> d4[];\ + \ +would be quite legitimate.\ + \ + If px were called\ + \ + :\ + px (some_desc);\ + :\ + \ +then the caller can rest assured that some_desc has not been modfied, i.e., it still points to the same table, and that table still contains the same number of elements. There is no guarantee that the values of the elements have been unaltered.\ +\ +The correct declaration to protect the table pointed to by d4 is:\ + \ + DCL px PROC (d4 DESC OF VAL int) IS FORWARD;\ + \ + \ +\page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 5.0 PROTEL PROGRAM ORGANIZATION\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 5.1 INTRODUCTION\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +No explanation of PROTEL program organization would be complete without a discussion of the design goals of the language - nor would it be easily understood. It also requires a firm understanding of the terms, declaration and definition, especially with respect to procedures.\ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.1.1 DECLARATION VERSUS DEFINITION\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +In general, a declaration declares the type of an object, while the definition gives the object a value. The declaration statement below declares variable I. The assignment statement is a definition of I. The last two statements both declare and define J and K, respectively. In every case, the declaration part of the statement ends after the type. The definition parts of the last two statements follow the keyword INIT or IS.\ + \ + DCL I Int;\ + 28 -> I;\ + DCL J Int INIT 29;\ + DCL K Int IS 30;\ + \ +We say that a procedure is declared when it is first encountered in a DCL statement.\ + \ +A declaration of a procedure defines the name of the procedure, its formal parameters (if any), and its return type (if any).\ +\ +A definition specifies the "value" of the procedure, i.e., the executable statements which will be executed when the procedure is invoked. The value of a procedure is called its body.\ +\ + +\f1\b EXAMPLES +\f0\b0 \ + \ + 1. DCL P1 PROC () IS FORWARD;\ + \ + 2. DCL Get_status PROC (P Port) RETURNS Status IS ...\ + \ + 3. DCL Init_device PROC (D Device);\ + \ + 4. TYPE Cc_partitioned_proc PROC () RETURNS BOOL;\ + DCL Gated_use_partitioned_cc_translations\ + Cc_partitioned_proc;\ + \ + 5. DCL Nil_partitioned_translations Cc_partitioned_proc IS\ + RETURN FALSE;\ + \ + 6. TYPE Cibincom PROC (\ + UPDATES Pv Parval, % result of evaluation\ + UPDATES Pstr String, % result if string type\ + UPDATES Pd Did, % dir containing name\ + UPDATES Pn Parname, % name of evaluated par\ + UPDATES Rc Ciretcode); % result of the proc.\ + \ + \ +Example 1 declares P1 to be a procedure with no parameters and no return value. Example 2 declares Get_status as a procedure; the declaration ends with the identifier Status.\ + \ +Examples 3 and 4 both declare procedure variables. Their definitions will come through assignment statements. Example 3 declares procedure variable Init_device having a formal parameter D of type Device, and having no return type.\ + \ +Example 5 illustrates a procedure declaration and definition, where the definition is a single statement.\ + \ +In example 6, a procedure type is declared. Any procedure declared of type Ccibincom will have the parameter list in the Cibincom type declaration.\ + \ + \ + \page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 5.2 SECTIONS, MODULES, AND PROGRAMS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +Let us begin our discussion of program structure by defining the objects with which we are dealing. We shall define the terms section, module, and program.\ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.2.1 SECTIONS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A section is the smallest compilable unit. It is stored in a file. The name of the section is the name of the file which contains it. The first statement of every section is called the imbed statement. The imbed statement contains the section name, which must be the same as the file name. It also indicates other section-type and module-type information. We will consider only INTERFACE and SECTION section types. The imbed statement contains imbedding information if it contains either of the keywords\ +\ + USES or OF.\ +\ + \ + +\f1\b EXAMPLES +\f0\b0 \ + \ + SECTION Prog1ui USES Mydefs, Formato;\ + SECTION Prog1imp OF Prog1ui;\ + INTERFACE Formato USES Mydefs, Myio;\ + INTERFACE Mydefs;\ + INTERFACE Myio;\ + \ + Prog1ui, Prog1imp and Formato are all sections. Formato is an interface section.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.2.2 IMBEDDING AND OUTBEDDING\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Imbedding a section means opening the object file for that section, and reading the "imbed data". The imbed data for a section consists of the symbols for all data types, and data objects which are global to that section. When the object file for a section y contains such data, we say that y outbeds these symbols. If section x imbeds section y, it can imbed any subset of the symbols outbed by y.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.2.3 MODULES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A module is a collection of one or more sections, connected by OF links. The name of a module is the name of its top-most section.\ +\ +The top-most section is the only section in a module which is not OF another section. In the above example, Prog1ui is a module consisting of the sections Prog1ui and Prog1imp.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 + 5.2.4 PROGRAMS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Let us now examine the USES graph for Prog1ui (see Figure 19). When module x uses module y, we draw an arrow from x to y. Prog1ui uses Mydefs and Formato. Formato also uses Mydefs.(5)\ + \ +The USES list for Prog1ui is \{Formato, Mydefs\}, represented by directed edges from Prog1ui to Formato and Mydefs. The USES list for Formato is \{Myio, Mydefs\}, and is represented by directed edges from Formato to Myio and Mydefs.\ + \ +Note that Prog1ui uses Formato directly, while it uses Myio indirectly. It uses Myio by virtue of the fact that it uses Formato, which uses Myio. We say that Prog1ui uses Myio transitively.\ +\ +Prog1ui uses Mydefs both directly and transitively.\ + \ +The set of all modules used by Prog1ui, either directly or transitively, is called the "transitive closure of its USES list." The definition of a PROTEL program is a module, an entry point (i.e., an ENTRY procedure), and the transitive closure of the USES list of the module.(6)\ + \ +It is not required that the top-most section of every module be an interface. Of course no module without an interface can be used by any other module. A module which contains an entry point, and thus defines a program, does not generally have an interface.\ + \ +Note that Prog1ui is such a module. Note also that the lack of an interface in Prog1ui does not prevent it from using other modules.\ + \ + ----------------\ + \ + 5 For the mathematically inclined, a USES graph is a \'93directed acyclic graph" (DAG). There exist no cycles in the directed edges.\ + \ + 6 It is not required that the entry point be within the module whose transitive closure defines the program. In CC software, however, SOS does require that this be so.\ +\page \pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.3 COMPILATION ORDER\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +A compilation order for PROTEL is an ordering of the sections to be compiled, such that all sections are compiled before they are imbedded.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | Prog1ui |\ + | / \\ |\ + | / \\ |\ + | / \\ |\ + | | | |\ + | | | |\ + | \\!/ | |\ + | V | |\ + | Formato | |\ + | / \\ | |\ + | / \\ | |\ + | / \\ | |\ + | / \\ | |\ + | | \\| |\ + | | | |\ + | \\!/ \\!/ |\ + | V V |\ + | Myio Mydefs |\ + | |\ + | |\ + | Figure 19. USES Graph for program Prog1ui: a USES graph is |\ + | a directed acyclic graph. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.3.1 COMPILATION ORDER FOR PROGRAMS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Suppose we wish to compile Prog1ui. To do so requires that the object code for Formato and Mydefs be available, so they must both have been compiled before Prog1ui. Furthermore, Mydefs must have been compiled before Formato, since Formato uses Mydefs. Myio must have been compiled before Formato, as well. Furthermore, every module used by Myio, if any, must have been compiled before Myio.\ + \ +One can see that determining a correct compilation order can be difficult. The derivation of a compilation order is recursive. As a first attempt at its definition, let us say that "for every module to be compiled, the modules in its USES list must first be compiled."\ + \ +The above definition is not quite correct. Imbedding is performed not on a per-module basis, but on a per-section basis. The USES list of a module contains a section list. The restriction on the sections occurring in a USES list is that they must be INTERFACE sections. Therefore, a second attempt at defining compile order might be: "for every module to be compiled, the sections in its USES list must first be compiled."\ + \ +This means, for example, that even though module Prog1ui may use module Formato, only the interface section, Formato, must be compiled before Prog1ui is compiled.\ + \ +A glance at Figure 20 should make the reason for this clear. Module Prog1ui uses the identifiers Int and Typeint, which are not declared in Prog1ui. In order to check that identifiers are used correctly, the declaration of all identifiers must be available when they are used. Typeint is declared in Formato, and Int is declared in Mydefs.\ + \ +Typeint is a FORWARD procedure, which means it is implemented somewhere in module Formato.(7) The purpose of imbedding is to permit full compile-time type checking. The USES list of a given module X specifies those sections which define all of the external symbols used in module X. Since the USES list is composed only of interface sections, only the interface section of each used module needs to be previously compiled.\ + \ +To type check the use of a procedure, we need to know only the number and types of its formal parameters, and the type of its RETURN value, if any. This information is provided by a FORWARD declaration. Thus a forward declaration generally appears in an interface section, while the body of the procedure occurs in an implementation section. By implementation section, we generally mean a section which is not an INTERFACE section, and which contains the bodies of forward-declared procedures.\ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \page \pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.3.2 COMPILATION ORDER FOR MODULES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +The compilation order for the sections of a module must satisfy the same rule as those for a program: for every section to be compiled, all of its imbedded sections must have been previously compiled.\ + \ +A section imbeds every section which it is OF or USES, either directly or transitively. Thus Prog1imp imbeds Prog1ui directly, and imbeds indirectly those sections in the USES list of Prog1ui. By definition, the USES list for every section in a module is the USES list of the top-level section. This is sensible since only the top-level section can have a USES list.\ + \ +As a concrete example, consider the module X in Figure 21.\ + \ +Section X must be compiled first, followed by X1. For the remaining sections any compile order is valid, as long as X2 is compiled before X3. There are no compile order dependencies between X2, X4, and X5, since they are neither OF each other, nor USE each other.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | +-----------------------------------------------------+ |\ + | | SECTION Prog1ui USES Mydefs, Formato; | |\ + | | | |\ + | | DCL Print_and_reset PROC (UPDATES i Int) IS FORWARD;| |\ + | +-----------------------------------------------------+ |\ + | |\ + | +-----------------------------------------------------+ |\ + | | SECTION Prog1imp OF Prog1ui; | |\ + | | | |\ + | | DCL Print_and_reset PROC (UPDATES i Int) IS | |\ + | | BLOCK | |\ + | | | |\ + | | Typeint ('Previous value of i was', i); | |\ + | | 0 -> i; | |\ + | | ENDBLOCK; | |\ + | +-----------------------------------------------------+ |\ + | |\ + | +-----------------------------------------------------+ |\ + | | INTERFACE Formato USES Mydefs, Myio; | |\ + | | | |\ + | | DCL Typeint PROC (format DESC OF VAL Char, | |\ + | | data Int) IS FORWARD; | |\ + | +-----------------------------------------------------+ |\ + | |\ + | +-----------------------------------------------------+ |\ + | | INTERFACE Mydefs; | |\ + | | | |\ + | | DCL | |\ + | | Wordsize \{16 TO 16\} IS 16; | |\ + | | | |\ + | | TYPE | |\ + | | Int PACK(Wordsize) \{-32768 TO 32767\}, | |\ + | | Unsignedint PACK(Wordsize) \{0 TO #FFFF\}, | |\ + | | Byte PACK(Bytesize) \{0 TO #FF\}, | |\ + | | Char Byte; | |\ + | +-----------------------------------------------------+ |\ + | |\ + | Figure 20. Imbedding for Prog1ui: module Prog1ui imbeds |\ + | interfaces Formato and Mydefs. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +To use our previously defined terminology, we call X the "interface", and X2, X3, X4 and X5 the "implementation" sections.\ + \ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | INTERFACE X; X |\ + | SECTION X1 OF X; | |\ + | SECTION X2 OF X1; | |\ + | SECTION X3 OF X2; X1 |\ + | SECTION X4 OF X1; /| \\ |\ + | SECTION X5 OF X1; / | \\ |\ + | / | \\ |\ + | | | \\ |\ + | X2 X4 X5 |\ + | | |\ + | | |\ + | X3 |\ + | |\ + | Figure 21. Hierarchy for module X: The OF relationship |\ + | yields a tree structure. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + ----------------\ + \ + 7 Since Typeint is not implemented in section Formato, it must be implemented in some section OF Formato.\page \ +\pard\pardeftab720\sa360\partightenfactor0 + +\f1\b\fs32 \cf2 5.4 IMBEDDING\ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\f0\b0\fs28 \cf2 \kerning1\expnd1\expndtw5 + 5.4.1 DIFFERENCES BETWEEN USES AND OF IMBEDDING\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +When a section X3 OF X2 imbeds X2, it gains access to all global identifiers in X2. This includes types, variables, and constants.(8) We say then, that all global identifiers within the parent section are within the scope of the OF section. This scope rule holds true for sections imbedding through all OF relations, whether direct or transitive.\ + \ +For example, consider the module X in Figure 21. X3 has access to all global identifiers declared in X2, X1 and X. X3 can alter any global variable declared in X1 or X2.\ + \ +With USES imbedding, there are slightly different scope rules between direct and transitive imbedding. Constants and variables imbed only directly; types imbed both directly and transitively.\ + \ +Consider Figure 22 on page 60. Procedure Update_counter in module Zed updates variable Counter in module Alpha. It is not reasonable that any module which uses Zed should have direct access to Counter through Zed. Note, however, that module Zed does not use module Beta, so the type of Counter (Smallint), is imbedded transitively through Alpha. Suppose Zedimp declared a variable of type Hexdigit. \ +\ +Would the type Hexdigit be transitively imbedded into Zed? No, there is a catch to transitively imbedding types. Zed imbeds the type Smallint only because it was attached to the variable Counter. Alpha did not reference type Hexdigit, so it did not outbed it.\ + \ +The next question is, if the type of Counter in Alpha were changed to Posint, would Zedimp still compile? The answer is no, because it would no longer imbed type Smallint. This is not a particularly safe situation. The problem arose because Zed imbedded Smallint "for free." Since the identifier Smallint was referenced inside of module Zed, Zed should have had Beta in its USES list.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | +----------------------------------------------------+ |\ + | | INTERFACE Zed USES Alpha; | |\ + | | | |\ + | | DCL Update_counter PROC () IS FORWARD; | |\ + | +----------------------------------------------------+ |\ + | |\ + | +----------------------------------------------------+ |\ + | | SECTION Zedimp OF Zed; | |\ + | | | |\ + | | DCL Local_counter Smallint; | |\ + | | | |\ + | | DCL Update_counter PROC () IS | |\ + | | BLOCK | |\ + | | Counter + 1 -> Counter; | |\ + | | Local_counter + 1 -> Local_counter; | |\ + | | ENDBLOCK; | |\ + | +----------------------------------------------------+ |\ + | |\ + | +----------------------------------------------------+ |\ + | | INTERFACE Alpha USES Beta; | |\ + | | | |\ + | | SHARED Counter Smallint; | |\ + | +----------------------------------------------------+ |\ + | |\ + | +----------------------------------------------------+ |\ + | | INTERFACE Beta; | |\ + | | | |\ + | | DCL | |\ + | | Wordsize \{16 TO 16\} IS 16; | |\ + | | | |\ + | | TYPE | |\ + | | Smallint \{0 TO 4095\}, | |\ + | | Posint \{0 TO 32767\}, | |\ + | | Hexdigit \{0 TO #F\}; | |\ + | +----------------------------------------------------+ |\ + | |\ + | Figure 22. Imbedding for module Zed: type Smallint is |\ + | transitively imbedded. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ +\ + ----------------\ + \ +8 This includes procedures as well. Remember that in PROTEL a procedure is either a constant or a variable. A procedure implementation a always a constant.\ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \page \pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.4.2 IMBEDDING OF NON-TOP-LEVEL SECTIONS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 __________________________________________\ + \ + \ +It is possible for an interface to be OF an interface. Such a section may then appear in the USES list of some other module. Suppose section X1 in Figure 21 on page 59 had been declared as\ + \ + INTERFACE X1 OF X;\ + \ +Now consider a module Y which uses X1.\ + \ + INTERFACE Y USES X1;\ + \ +Since X1 is OF X, Y transitively imbeds X. Furthermore, Y imbeds X as though it were OF X, so it imbeds not only types, but variables, and constants as well. The presence of both X, and X1 in the uses list for Y is equivalent to the presence of X1 alone.\ + \ +Similarly, had X2 in Figure 21 on page 59 been declared an INTERFACE, Y could have used X2, and would have imbedded X2, X1, and X. In general, when a used interface is not the top-most section in a module, a user of the interface will imbed all sections of the module from the used interface up to the top.\ + \ + \ +\pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.4.3 PRIVATE INTERFACES\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +It often happens that an interface is required within a module, for the purpose of sharing types, variables, and constants within the module. X1 in Figure 21 on page 59 is such a section. In general, whenever a section has more than one section OF itself, it is an interface for the sections below it. If no other modules are to be permitted to use this private interface, it will be declared as a SECTION, not as an INTERFACE.\ + \ +There is no keyword in PROTEL to denote an interface which is not usable by all other modules.\ + \ +\page \pard\pardeftab720\sa360\partightenfactor0 + +\f1\b\fs32 \cf2 5.5 PROTEL LANGUAGE\ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\f0\b0\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.5.1 DESIGN GOALS\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +PROTEL is designed to support large-scale programming projects. The term "embedded systems" applies well to the types of programs implemented in PROTEL. Some of the requirements of such systems are: modularity, re-usability, and safety. We will discuss each of these concepts drawing examples from PROTEL.\ + \ +Modularity refers to the ability to localise software features. A PROTEL module should provide some well-defined set of features. The interface to a module should provide documentation of the features, and should contain only those types and procedures which a user of the module must have access to. The procedures should be forward-declared, and the bodies of the forward-declared procedures should not appear in the interface. A user of the procedures need not have access to the implementation of the procedures.\ + \ +Consider the compilation order of module Figure 21, and a module Y which uses X.\ + \ + INTERFACE Y USES X;\ + \ +To compile all of modules X and Y, one possible compilation order is \{X,X1,X2,X3,X4,X5,Y\}. Another possible compilation order is \{X,Y,X1,X2,X3,X4,X5\}. \ +\ +We now ask the question: if section X3 were modified, which sections would need to be recompiled? The answer is, only section X3. \ +\ +The reason is that no section imbeds X3, so no section requires recompilation because of a change to X3. In general, the implementation of a procedure is modified more often than its declaration. If a procedure p were implemented in interface section X, and the body of p required modification, then the sections requiring recompilation would be all those sections which imbed X. In our current example, this would be \{X,X1,X2,X3,X4,X5,Y\}.\ + \ +The restriction of procedure bodies to implementation sections has implications on the replacability of modules, an issue we shall not discuss further. We point out, however, that it is desirable that the number of sections requiring recompilation due to a change in a given module be kept as small as possible.\ + \ +In this context, our module also becomes reusable. When the use of a module depends only upon the interface it presents, and not upon its implementation, it is highly likely that the module will be used by many other modules. That it, it will appear in many USES lists.(9) Consider the modules Myio, Mydefs and Formato, of Figure 19. Prog1ui is some program which requires formatted I/O. Mydefs provides some basic types, Myio implements an I/O package, and Formato provides a facility for performing formatted I/O of these types.\ + \ +The likelyhood is high that a second program will be written which requires formatted I/O of the types in Mydefs. If Formato appears in the USES graph of a second program, say Prog2ui, it is reused. If Formato has implementation sections which require modification even due to hardware changes, the users of Formato will not even require recompilation.\ + \ +Safety, in terms of program organisation, involves structuring the modules of a program in such a way as to minimise the effects of changes to USED modules on one's own modules. We saw earlier(10) how a module X can reference an imbedded type from module Y without having the module Y in its USES list. This exposes module X to effects from modifications to module Y which are irrelevant to the facilities provided by Y.\ + \ +Using a private interface is not a safe technique, since private interfaces tend to be implementation-dependent. An important use of private interfaces is to declare procedure variables, otherwise known as aspects, a topic discussed in DIS OFLPI, Using PROTEL in DMS.\ + \ +One rule of imbedding is that an INTERFACE may only be OF another INTERFACE. This prevents an interface from being hung from an implementation and thus allowing another module to imbed the implementation section. In this respect implementation sections are safe from extra-modular imbedding (i.e., being imbedded from outside the module).\ + \ +An interface module provides either (a) a set of functions, such as Formato, or (b) a set of types. There exist DEFINITIONS modules, which are interface modules which contain nothing but type declarations.\ + \ +Imbedding statements provide static means of communication between modules and programs, via shared variables and procedures; they also privide a consistent environment via shared types.(11)\ + \ +\ + ----------------\ + \ + 9 When a module appears in the transitive closure of different modules which contain entry procedures, it has become imbedded in each of these programs. This is a nice example of reusable software.\ +\ + 10 See "Differences between USES and OF Imbedding" on page 59.\ + \ + 11 dynamic communication is not provided by the PROTEL language, as it is in some other languages. In the DMS context, it is provided by the operating system.\ +\page \pard\pardeftab720\sa360\partightenfactor0 +\cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 + 5.5.2 A SAMPLE PROGRAM\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +Prog3ui Figure 23 is a module with an entry procedure. Together with its USES list it defines a program. Prog3ui prints out a list of the primes less than 100. An explanation of the statements in section Prog3ui follows.\ + \ +Statement and Meaning\ + \ +\pard\tx20\tx360\pardeftab720\li360\fi-360\partightenfactor0 +\ls18\ilvl0\cf2 \up0 \nosupersub \ulnone {\listtext 1. }\up0 \nosupersub \ulnone Imbed statement. Prog3ui \f1\b IS\f0\b0 a program (no \f1\b INTERFACE\f0\b0 ) which \f1\b USES\f0\b0 modules Mydefs and Formato.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 2. }\up0 \nosupersub \ulnone Comment.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 3. }\up0 \nosupersub \ulnone Declares Start as the entry procedure and as forward.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 4. }\up0 \nosupersub \ulnone Declares Start procedure body.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 5. }\up0 \nosupersub \ulnone Begins the block defining the procedure body.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 6. }\up0 \nosupersub \ulnone Begins a local declaration statement.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 7. }\up0 \nosupersub \ulnone Declares an Int constant with value 100. Since Int is not declared in Prog3ui, it must be declared in either Mydefs or Formato.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 8. }\up0 \nosupersub \ulnone Declares an table variable of 100 BOOL elements.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 9. }\up0 \nosupersub \ulnone Initialises all elements of prime to TRUE.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 10. }\up0 \nosupersub \ulnone A loop which will iterate 99 times.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 11. }\up0 \nosupersub \ulnone An if statement which is entered if prime[i] is TRUE.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 12. }\up0 \nosupersub \ulnone A print statement which outputs i. Since Typeint is not declared in Prog3ui, it must be declared in either Mydefs or Formato.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 13. }\up0 \nosupersub \ulnone An if statement which iterates over all multiples of i less than or equal to limit.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 14. }\up0 \nosupersub \ulnone Assignment statement sets prime[multiple_of_i] to FALSE.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 15. }\up0 \nosupersub \ulnone Ends the loop begun on statement 16.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 16. }\up0 \nosupersub \ulnone Ends the if statement begun on statement 14.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 17. }\up0 \nosupersub \ulnone Ends the loop begun on statement 13.\ +\ls18\ilvl0\up0 \nosupersub \ulnone {\listtext 18. }\up0 \nosupersub \ulnone Ends the block begun on statement 6.\ +\pard\pardeftab720\partightenfactor0 +\cf2 \ +There is no ambiguity when we say that statement 3 declares Start as both the entry procedure and as a forward procedure. An entry procedure must de defined in the module in which it is declared. \ +\ +An entry procedure, as well, may not have either a formal parameter list or a RETURNS type; hence the IS ENTRY declaration fixes the procedure's type as "PROC ();" and serves as the FORWARD declaration as well.\ + \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | |\ + | 1 |SECTION Prog3ui USES Mydefs, Formato; |\ + | 2 |% print out prime numbers. |\ + | 3 |DCL Start PROC () IS ENTRY; |\ + | 4 | |\ + | 5 |DCL Start PROC () IS |\ + | 6 |BLOCK |\ + | 7 | DCL |\ + | 8 | limit Int IS 100, |\ + | 9 | prime TABLE [1 TO limit] OF BOOL; |\ + | 10 | |\ + | 11 | limit \{TRUE\} -> prime[]; |\ + | 12 | |\ + | 13 | FOR i FROM 2 UP TO limit DO |\ + | 14 | IF prime[i] THEN |\ + | 15 | Typeint ('next prime = ', i); |\ + | 16 | FOR multiple_of_i FROM i UP TO limit BY i DO |\ + | 17 | FALSE -> prime[multiple_of_i]; |\ + | 18 | ENDDO; |\ + | 19 | ENDIF; |\ + | 20 | ENDDO; |\ + | 21 | |\ + | 22 |ENDBLOCK; |\ + | |\ + | |\ + | Figure 23. Prog3ui: This program prints the primes less |\ + | than 100. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\sa360\partightenfactor0 + +\f0 \cf2 \ +\pard\pardeftab720\sl288\slmult1\sa40\partightenfactor0 + +\fs28 \cf2 \kerning1\expnd1\expndtw5 +5.5.3 PROGRAM ORGANIZATION: POINTS TO REMEMBER\ +\pard\pardeftab720\partightenfactor0 + +\fs22 \cf2 \kerning1\expnd0\expndtw0 \ +\ + 1. Imbedding is done on a per-section basis. A section imbeds sections, not modules.\ + \ + 2. Previous to compiling a section, every section which it imbeds, either directly or transitively, must have been compiled.\ + \ + 3. There is no PROTEL construct which tells a section which sections are OF it. Therefore, no section in a module can imbed from below itself.\ + \ + 4. Only INTERFACE sections can appear in a USES list.\ + \ + 5. The name of a section is the name of the file in which it is stored.\ + \ + 6. The name of a module is the name of its top-most section.\ + \ + 7. Types imbed transitively. Variables, constants, and procedures can only be imbedded directly. Types referenced within a module should be imbedded directly.\ +\ +\ + \ + \ + \ +\page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs32 \cf2 6.0 SUMMARY\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +Identifiers are used in PROTEL to allow the programmer to name data types, constants, variables, procedures, statement labels, and sections.\ + \ +PROTEL allows the definition of types in terms of existing primitive types in the language or in terms of other types defined by the programmer. Once a type is defined, it can be used in any context where a type is required. All data used in PROTEL programs must be defined in terms of a type. This allows the compiler to perform extensive type checking at compile time.\ + \ +PROTEL provides single-entry, single-exit control structures. This enables good structured programming techniques, which yield programs which are more easily implemented, understood, and maintained.\ + \ + \page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs36 \cf2 APPENDIX A. KEYWORDS\ +\pard\pardeftab720\partightenfactor0 + +\f2\b0\fs22 \cf2 \ + +---------------------------------------------------------------+\ + | AREA NONTRANSPARENT |\ + | AS NOTINCL |\ + | BIND OF |\ + | BLOCK OPERAND |\ + | BOOL OUT |\ + | BY OVER |\ + | CASE OVLY |\ + | CAST PACK |\ + | DCL PERPROCESS |\ + | DEFINITIONS PRIVATE |\ + | DESC PROC |\ + | DO PROTECTED |\ + | DOWN PTR |\ + | ELSE QUICK |\ + | ENDAREA REF |\ + | ENDBLOCK REFINES |\ + | ENDCASE RETURN |\ + | ENDDO RETURNS |\ + | ENDIF SECTION |\ + | ENDOVLY SELECT |\ + | ENDSELECT SET |\ + | ENDSTRUCT SHARED |\ + | ENTRY STRUCT |\ + | EXIT TABLE |\ + | FALSE TDSIZE |\ + | FAST THEN |\ + | FOR TO |\ + | FORWARD TRUE |\ + | FROM TYPE |\ + | IF UNRESTRICTED |\ + | IN UP |\ + | INCL UPB |\ + | INIT UPDATES |\ + | INTERFACE USES |\ + | INTRINSIC VAL |\ + | IS VARIABLE |\ + | LITERAL WHILE |\ + | MOD WITH |\ + | NIL |\ + | |\ + | Figure 24. Reserved Words: These keywords are reserved and |\ + | may not be used as identifiers. |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ + \ + \page \ +\pard\pardeftab720\partightenfactor0 + +\f1\b\fs36 \cf2 APPENDIX B. SPECIAL SYMBOLS\ +\pard\pardeftab720\partightenfactor0 + +\f0\b0\fs22 \cf2 \ +\pard\pardeftab720\partightenfactor0 + +\f2 \cf2 +---------------------------------------------------------------+\ + | = . |\ + | ( ^ |\ + | ) < |\ + | ; > |\ + | , & |\ + | : | |\ + | @ ! |\ + | \{ + |\ + | \} - |\ + | [ * |\ + | ] / |\ + | $ # |\ + | _ % |\ + | (* << |\ + | *) >> |\ + | (| -> |\ + | |) |\ + | |\ + | Figure 25. Special Symbols |\ + +---------------------------------------------------------------+\ +\pard\pardeftab720\partightenfactor0 + +\f0 \cf2 \ +} \ No newline at end of file diff --git a/PROTEL Reference Manual 2026.pages b/PROTEL Reference Manual 2026.pages new file mode 100644 index 0000000..8eb9231 Binary files /dev/null and b/PROTEL Reference Manual 2026.pages differ diff --git a/PROTEL Reference Manual 2026.pdf b/PROTEL Reference Manual 2026.pdf new file mode 100644 index 0000000..bfaf41f Binary files /dev/null and b/PROTEL Reference Manual 2026.pdf differ diff --git a/Pb b/Pb new file mode 100755 index 0000000..b045996 --- /dev/null +++ b/Pb @@ -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() diff --git a/docs/intro-5-5-2-entry-args-exit.md b/docs/intro-5-5-2-entry-args-exit.md new file mode 100644 index 0000000..3785972 --- /dev/null +++ b/docs/intro-5-5-2-entry-args-exit.md @@ -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 `. + +### 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) \ No newline at end of file diff --git a/docs/intro-7-0-development-tools.md b/docs/intro-7-0-development-tools.md new file mode 100644 index 0000000..0b0978a --- /dev/null +++ b/docs/intro-7-0-development-tools.md @@ -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 \ No newline at end of file diff --git a/docs/intro-7-2-emacs-protel-mode.md b/docs/intro-7-2-emacs-protel-mode.md new file mode 100644 index 0000000..17db721 --- /dev/null +++ b/docs/intro-7-2-emacs-protel-mode.md @@ -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` | \ No newline at end of file diff --git a/docs/intro-7-3-foreign-interop.md b/docs/intro-7-3-foreign-interop.md new file mode 100644 index 0000000..6078ee7 --- /dev/null +++ b/docs/intro-7-3-foreign-interop.md @@ -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, _ 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 +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. \ No newline at end of file diff --git a/docs/reference-13-export-external.md b/docs/reference-13-export-external.md new file mode 100644 index 0000000..2281c2b --- /dev/null +++ b/docs/reference-13-export-external.md @@ -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 + +``` + ::= + + ::= IS + | IS INTRINSIC + | IS ENTRY + | EXTERNAL + | EXPORT + + ::= +``` + +**EXTERNAL** and **EXPORT** are mutually exclusive with **IS** \, **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`) \ No newline at end of file diff --git a/docs/reference-error-messages.md b/docs/reference-error-messages.md new file mode 100644 index 0000000..cfece65 --- /dev/null +++ b/docs/reference-error-messages.md @@ -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 '':` + +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 '':` + +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 '':` + +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 '': …` | Missing or unreadable source path | +| `protel: cannot write '': …` | Output path not writable | +| `protel: '' 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 \ No newline at end of file diff --git a/emacs/protel-mode.el b/emacs/protel-mode.el new file mode 100644 index 0000000..09beb15 --- /dev/null +++ b/emacs/protel-mode.el @@ -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 diff --git a/examples/#Hello.protel# b/examples/#Hello.protel# new file mode 100755 index 0000000..d46e9e7 --- /dev/null +++ b/examples/#Hello.protel# @@ -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; \ No newline at end of file diff --git a/examples/Hello.P b/examples/Hello.P new file mode 100644 index 0000000..4a6bfa5 --- /dev/null +++ b/examples/Hello.P @@ -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; \ No newline at end of file diff --git a/examples/Hello.aa01 b/examples/Hello.aa01 new file mode 100644 index 0000000..e9fd790 --- /dev/null +++ b/examples/Hello.aa01 @@ -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; \ No newline at end of file diff --git a/examples/Hello.protel b/examples/Hello.protel new file mode 100755 index 0000000..d46e9e7 --- /dev/null +++ b/examples/Hello.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_assign_incompatible_pointer.protel b/examples/errors/err_assign_incompatible_pointer.protel new file mode 100644 index 0000000..36168b3 --- /dev/null +++ b/examples/errors/err_assign_incompatible_pointer.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_assign_integer_to_bool.protel b/examples/errors/err_assign_integer_to_bool.protel new file mode 100644 index 0000000..ae88757 --- /dev/null +++ b/examples/errors/err_assign_integer_to_bool.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_assign_integer_to_char.protel b/examples/errors/err_assign_integer_to_char.protel new file mode 100644 index 0000000..1c3e6a4 --- /dev/null +++ b/examples/errors/err_assign_integer_to_char.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_assign_integer_to_packed_byte.protel b/examples/errors/err_assign_integer_to_packed_byte.protel new file mode 100644 index 0000000..4e2e98a --- /dev/null +++ b/examples/errors/err_assign_integer_to_packed_byte.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_constant_out_of_range.protel b/examples/errors/err_constant_out_of_range.protel new file mode 100644 index 0000000..b78534f --- /dev/null +++ b/examples/errors/err_constant_out_of_range.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/err_return_type_mismatch.protel b/examples/errors/err_return_type_mismatch.protel new file mode 100644 index 0000000..7852bc5 --- /dev/null +++ b/examples/errors/err_return_type_mismatch.protel @@ -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; \ No newline at end of file diff --git a/examples/errors/ok_assign_char_literal.protel b/examples/errors/ok_assign_char_literal.protel new file mode 100644 index 0000000..4bb8431 --- /dev/null +++ b/examples/errors/ok_assign_char_literal.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/GreetHelper.java b/examples/interop/GreetHelper.java new file mode 100644 index 0000000..2e56047 --- /dev/null +++ b/examples/interop/GreetHelper.java @@ -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(); + } +} \ No newline at end of file diff --git a/examples/interop/JavaCallsProtel.java b/examples/interop/JavaCallsProtel.java new file mode 100644 index 0000000..c152913 --- /dev/null +++ b/examples/interop/JavaCallsProtel.java @@ -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); + } +} \ No newline at end of file diff --git a/examples/interop/build_interop.sh b/examples/interop/build_interop.sh new file mode 100755 index 0000000..e17c156 --- /dev/null +++ b/examples/interop/build_interop.sh @@ -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" \ No newline at end of file diff --git a/examples/interop/build_interop_java.sh b/examples/interop/build_interop_java.sh new file mode 100755 index 0000000..675ac9c --- /dev/null +++ b/examples/interop/build_interop_java.sh @@ -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 \ No newline at end of file diff --git a/examples/interop/build_interop_python.sh b/examples/interop/build_interop_python.sh new file mode 100755 index 0000000..b50a052 --- /dev/null +++ b/examples/interop/build_interop_python.sh @@ -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" \ No newline at end of file diff --git a/examples/interop/build_interop_rust.sh b/examples/interop/build_interop_rust.sh new file mode 100755 index 0000000..a87c6af --- /dev/null +++ b/examples/interop/build_interop_rust.sh @@ -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" \ No newline at end of file diff --git a/examples/interop/c_greet.c b/examples/interop/c_greet.c new file mode 100644 index 0000000..9fb927a --- /dev/null +++ b/examples/interop/c_greet.c @@ -0,0 +1,11 @@ +/* C function called from PROTEL via EXTERNAL (examples/interop reference). */ +#include +#include + +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); +} \ No newline at end of file diff --git a/examples/interop/greet_helper.py b/examples/interop/greet_helper.py new file mode 100644 index 0000000..c72edec --- /dev/null +++ b/examples/interop/greet_helper.py @@ -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) \ No newline at end of file diff --git a/examples/interop/java_calls_protel.c b/examples/interop/java_calls_protel.c new file mode 100644 index 0000000..1500a7e --- /dev/null +++ b/examples/interop/java_calls_protel.c @@ -0,0 +1,13 @@ +/* JNI bridge: JavaCallsProtel.protelAdd -> EXPORTed protel_add (C ABI). */ +#include +#include + +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); +} \ No newline at end of file diff --git a/examples/interop/java_greet.c b/examples/interop/java_greet.c new file mode 100644 index 0000000..41d0846 --- /dev/null +++ b/examples/interop/java_greet.c @@ -0,0 +1,88 @@ +/* C ABI entry point: embeds the JVM and calls GreetHelper.greet (PROTEL EXTERNAL). */ +#include +#include +#include +#include +#include + +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); +} \ No newline at end of file diff --git a/examples/interop/protel_calls_java.protel b/examples/interop/protel_calls_java.protel new file mode 100644 index 0000000..2ba123a --- /dev/null +++ b/examples/interop/protel_calls_java.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_calls_python.protel b/examples/interop/protel_calls_python.protel new file mode 100644 index 0000000..ee92d45 --- /dev/null +++ b/examples/interop/protel_calls_python.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_calls_rust.protel b/examples/interop/protel_calls_rust.protel new file mode 100644 index 0000000..7d18a5c --- /dev/null +++ b/examples/interop/protel_calls_rust.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_calls_swift.protel b/examples/interop/protel_calls_swift.protel new file mode 100644 index 0000000..6a1269c --- /dev/null +++ b/examples/interop/protel_calls_swift.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_for_java.protel b/examples/interop/protel_for_java.protel new file mode 100644 index 0000000..4c60909 --- /dev/null +++ b/examples/interop/protel_for_java.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_for_python.protel b/examples/interop/protel_for_python.protel new file mode 100644 index 0000000..121cd63 --- /dev/null +++ b/examples/interop/protel_for_python.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_for_rust.protel b/examples/interop/protel_for_rust.protel new file mode 100644 index 0000000..0517e0d --- /dev/null +++ b/examples/interop/protel_for_rust.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/protel_for_swift.protel b/examples/interop/protel_for_swift.protel new file mode 100644 index 0000000..28f1d9b --- /dev/null +++ b/examples/interop/protel_for_swift.protel @@ -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; \ No newline at end of file diff --git a/examples/interop/python_calls_protel.py b/examples/interop/python_calls_protel.py new file mode 100644 index 0000000..6e08aea --- /dev/null +++ b/examples/interop/python_calls_protel.py @@ -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() \ No newline at end of file diff --git a/examples/interop/python_greet.c b/examples/interop/python_greet.c new file mode 100644 index 0000000..a5aa532 --- /dev/null +++ b/examples/interop/python_greet.c @@ -0,0 +1,50 @@ +/* C ABI entry point: embeds Python and calls greet_helper.greet (PROTEL EXTERNAL). */ +#include +#include + +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); +} \ No newline at end of file diff --git a/examples/interop/rust_calls_protel.rs b/examples/interop/rust_calls_protel.rs new file mode 100644 index 0000000..fa804a9 --- /dev/null +++ b/examples/interop/rust_calls_protel.rs @@ -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}"); +} \ No newline at end of file diff --git a/examples/interop/rust_greet.rs b/examples/interop/rust_greet.rs new file mode 100644 index 0000000..265ed0c --- /dev/null +++ b/examples/interop/rust_greet.rs @@ -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() { + "" + } else { + CStr::from_ptr(name).to_str().unwrap_or("") + } + }; + println!("Rust: rust_greet(name={label}, value={value})"); +} \ No newline at end of file diff --git a/examples/interop/swift_calls_protel.swift b/examples/interop/swift_calls_protel.swift new file mode 100644 index 0000000..0f05cbf --- /dev/null +++ b/examples/interop/swift_calls_protel.swift @@ -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)") \ No newline at end of file diff --git a/examples/interop/swift_greet.swift b/examples/interop/swift_greet.swift new file mode 100644 index 0000000..f0d1757 --- /dev/null +++ b/examples/interop/swift_greet.swift @@ -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, _ value: Int32) { + let label = String(cString: name) + print("Swift: swift_greet(name=\(label), value=\(value))") +} \ No newline at end of file diff --git a/examples/intro_1_3_factorial.protel b/examples/intro_1_3_factorial.protel new file mode 100644 index 0000000..eff4d00 --- /dev/null +++ b/examples/intro_1_3_factorial.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_1_3_factorial_cli.protel b/examples/intro_1_3_factorial_cli.protel new file mode 100644 index 0000000..0583a6b --- /dev/null +++ b/examples/intro_1_3_factorial_cli.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_2_1_types.protel b/examples/intro_2_1_types.protel new file mode 100644 index 0000000..6c130a0 --- /dev/null +++ b/examples/intro_2_1_types.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_2_2_calculate_average.protel b/examples/intro_2_2_calculate_average.protel new file mode 100644 index 0000000..89147a7 --- /dev/null +++ b/examples/intro_2_2_calculate_average.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_3_2_4_case.protel b/examples/intro_3_2_4_case.protel new file mode 100644 index 0000000..fe67054 --- /dev/null +++ b/examples/intro_3_2_4_case.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_3_2_6_sum_table.protel b/examples/intro_3_2_6_sum_table.protel new file mode 100644 index 0000000..ddc9ba0 --- /dev/null +++ b/examples/intro_3_2_6_sum_table.protel @@ -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; \ No newline at end of file diff --git a/examples/intro_5_5_2_args_exit.protel b/examples/intro_5_5_2_args_exit.protel new file mode 100644 index 0000000..db9e619 --- /dev/null +++ b/examples/intro_5_5_2_args_exit.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_10_0_bind_with.protel b/examples/ref/ref_10_0_bind_with.protel new file mode 100644 index 0000000..07edb3d --- /dev/null +++ b/examples/ref/ref_10_0_bind_with.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_11_0_type_compat.protel b/examples/ref/ref_11_0_type_compat.protel new file mode 100644 index 0000000..7c35351 --- /dev/null +++ b/examples/ref/ref_11_0_type_compat.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_12_0_intrinsic.protel b/examples/ref/ref_12_0_intrinsic.protel new file mode 100644 index 0000000..f248c10 --- /dev/null +++ b/examples/ref/ref_12_0_intrinsic.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_13_0_descriptors.protel b/examples/ref/ref_13_0_descriptors.protel new file mode 100644 index 0000000..1e31bbd --- /dev/null +++ b/examples/ref/ref_13_0_descriptors.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_14_0_keyword_exercise.protel b/examples/ref/ref_14_0_keyword_exercise.protel new file mode 100644 index 0000000..609339a --- /dev/null +++ b/examples/ref/ref_14_0_keyword_exercise.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_1_0_introduction.protel b/examples/ref/ref_1_0_introduction.protel new file mode 100644 index 0000000..e52fd24 --- /dev/null +++ b/examples/ref/ref_1_0_introduction.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_3_0_lexical.protel b/examples/ref/ref_3_0_lexical.protel new file mode 100644 index 0000000..54af0fb --- /dev/null +++ b/examples/ref/ref_3_0_lexical.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_4_0_data_elements.protel b/examples/ref/ref_4_0_data_elements.protel new file mode 100644 index 0000000..a0374ad --- /dev/null +++ b/examples/ref/ref_4_0_data_elements.protel @@ -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 {}; \ No newline at end of file diff --git a/examples/ref/ref_5_0_compilation_unit.protel b/examples/ref/ref_5_0_compilation_unit.protel new file mode 100644 index 0000000..c4f9b99 --- /dev/null +++ b/examples/ref/ref_5_0_compilation_unit.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_5_0_directives.aa01 b/examples/ref/ref_5_0_directives.aa01 new file mode 100644 index 0000000..35a04c5 --- /dev/null +++ b/examples/ref/ref_5_0_directives.aa01 @@ -0,0 +1,5 @@ +$LI modentry restart +$EJECT +SECTION ref_directives; +TYPE integer {-32768 TO 32767}; +DCL noop PROC() IS BLOCK ENDBLOCK; \ No newline at end of file diff --git a/examples/ref/ref_6_0_module_types.protel b/examples/ref/ref_6_0_module_types.protel new file mode 100644 index 0000000..eb4f950 --- /dev/null +++ b/examples/ref/ref_6_0_module_types.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_7_0_declarations.protel b/examples/ref/ref_7_0_declarations.protel new file mode 100644 index 0000000..0113574 --- /dev/null +++ b/examples/ref/ref_7_0_declarations.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_7_1_1_simple_types.protel b/examples/ref/ref_7_1_1_simple_types.protel new file mode 100644 index 0000000..ffcd92f --- /dev/null +++ b/examples/ref/ref_7_1_1_simple_types.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_7_1_2_aggregates.protel b/examples/ref/ref_7_1_2_aggregates.protel new file mode 100644 index 0000000..02bac73 --- /dev/null +++ b/examples/ref/ref_7_1_2_aggregates.protel @@ -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}; \ No newline at end of file diff --git a/examples/ref/ref_7_1_3_procedures.protel b/examples/ref/ref_7_1_3_procedures.protel new file mode 100644 index 0000000..fd4ecc8 --- /dev/null +++ b/examples/ref/ref_7_1_3_procedures.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_7_2_data_declarations.protel b/examples/ref/ref_7_2_data_declarations.protel new file mode 100644 index 0000000..9f40dfc --- /dev/null +++ b/examples/ref/ref_7_2_data_declarations.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_7_3_overlays.protel b/examples/ref/ref_7_3_overlays.protel new file mode 100644 index 0000000..9ecba38 --- /dev/null +++ b/examples/ref/ref_7_3_overlays.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_8_0_scope.protel b/examples/ref/ref_8_0_scope.protel new file mode 100644 index 0000000..43dbd9e --- /dev/null +++ b/examples/ref/ref_8_0_scope.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_0_statements.protel b/examples/ref/ref_9_0_statements.protel new file mode 100644 index 0000000..35bcb20 --- /dev/null +++ b/examples/ref/ref_9_0_statements.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_1_expressions.protel b/examples/ref/ref_9_1_expressions.protel new file mode 100644 index 0000000..a6f2a88 --- /dev/null +++ b/examples/ref/ref_9_1_expressions.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_2_return.protel b/examples/ref/ref_9_2_return.protel new file mode 100644 index 0000000..1c38d8d --- /dev/null +++ b/examples/ref/ref_9_2_return.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_3_if.protel b/examples/ref/ref_9_3_if.protel new file mode 100644 index 0000000..e8c9e6d --- /dev/null +++ b/examples/ref/ref_9_3_if.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_4_case.protel b/examples/ref/ref_9_4_case.protel new file mode 100644 index 0000000..6aaa3a2 --- /dev/null +++ b/examples/ref/ref_9_4_case.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_5_select.protel b/examples/ref/ref_9_5_select.protel new file mode 100644 index 0000000..08e8b55 --- /dev/null +++ b/examples/ref/ref_9_5_select.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_6_exit.protel b/examples/ref/ref_9_6_exit.protel new file mode 100644 index 0000000..472bd2c --- /dev/null +++ b/examples/ref/ref_9_6_exit.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_9_7_iterative.protel b/examples/ref/ref_9_7_iterative.protel new file mode 100644 index 0000000..da9c32c --- /dev/null +++ b/examples/ref/ref_9_7_iterative.protel @@ -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; \ No newline at end of file diff --git a/examples/ref/ref_oo_classes.protel b/examples/ref/ref_oo_classes.protel new file mode 100644 index 0000000..7c97b01 --- /dev/null +++ b/examples/ref/ref_oo_classes.protel @@ -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; diff --git a/examples/ref_8_1_task_block_struct.protel b/examples/ref_8_1_task_block_struct.protel new file mode 100644 index 0000000..861aed2 --- /dev/null +++ b/examples/ref_8_1_task_block_struct.protel @@ -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; \ No newline at end of file diff --git a/examples/ref_oo_class_method_invoke.protel b/examples/ref_oo_class_method_invoke.protel new file mode 100644 index 0000000..6f80c04 --- /dev/null +++ b/examples/ref_oo_class_method_invoke.protel @@ -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; diff --git a/examples/ref_oo_class_with_var.cpp b/examples/ref_oo_class_with_var.cpp new file mode 100644 index 0000000..58ec874 --- /dev/null +++ b/examples/ref_oo_class_with_var.cpp @@ -0,0 +1,41 @@ +/* Generated by PROTEL 2026 C++ transpiler */ +/* Source: /Users/vincente/PROTEL/examples/ref_oo_class_with_var.protel */ +#include +#include +#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 + diff --git a/examples/ref_oo_class_with_var.protel b/examples/ref_oo_class_with_var.protel new file mode 100644 index 0000000..8e00c22 --- /dev/null +++ b/examples/ref_oo_class_with_var.protel @@ -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; \ No newline at end of file diff --git a/protel b/protel new file mode 100755 index 0000000..35b0eee --- /dev/null +++ b/protel @@ -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()) \ No newline at end of file diff --git a/protel-run b/protel-run new file mode 100755 index 0000000..e2014d9 --- /dev/null +++ b/protel-run @@ -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()) \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..4b17e11 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1 @@ +pytest>=8.0 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1c9a632 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +lark>=1.2.0 \ No newline at end of file diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..aa244c1 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,3 @@ +"""PROTEL 2026 parser and transpiler.""" + +__version__ = "0.1.0" \ No newline at end of file diff --git a/src/ast_nodes.py b/src/ast_nodes.py new file mode 100644 index 0000000..c6f9d70 --- /dev/null +++ b/src/ast_nodes.py @@ -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 \ No newline at end of file diff --git a/src/compile.py b/src/compile.py new file mode 100644 index 0000000..d943f29 --- /dev/null +++ b/src/compile.py @@ -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 \ No newline at end of file diff --git a/src/cpp_transpiler.py b/src/cpp_transpiler.py new file mode 100644 index 0000000..39c612a --- /dev/null +++ b/src/cpp_transpiler.py @@ -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": "", + "atoi": "", +} + + +@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 ') + + 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) \ No newline at end of file diff --git a/src/extensions.py b/src/extensions.py new file mode 100644 index 0000000..e1c3b77 --- /dev/null +++ b/src/extensions.py @@ -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}" \ No newline at end of file diff --git a/src/grammar/protel.lark b/src/grammar/protel.lark new file mode 100644 index 0000000..08c12bf --- /dev/null +++ b/src/grammar/protel.lark @@ -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: /'(?:''|[^'])*'/ \ No newline at end of file diff --git a/src/keywords.py b/src/keywords.py new file mode 100644 index 0000000..caa6e73 --- /dev/null +++ b/src/keywords.py @@ -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", +}) \ No newline at end of file diff --git a/src/module_resolver.py b/src/module_resolver.py new file mode 100644 index 0000000..5ffb055 --- /dev/null +++ b/src/module_resolver.py @@ -0,0 +1,158 @@ +"""Resolve USES module links and merge embedded PROTEL sections.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from . import ast_nodes as ast +from .extensions import is_protel_source +from .parser import parse_protel +from .transpiler import TranspileError + +_ROOT = Path(__file__).resolve().parent.parent +_SECTION_INDEX: dict[str, Path] | None = None + + +def _search_dirs(source_path: Path | None) -> list[Path]: + dirs: list[Path] = [] + if source_path is not None: + dirs.append(source_path.parent.resolve()) + examples = _ROOT / "examples" + if examples.is_dir(): + dirs.append(examples.resolve()) + return dirs + + +def _build_section_index(search_dirs: list[Path]) -> dict[str, Path]: + index: dict[str, Path] = {} + for base in search_dirs: + if not base.is_dir(): + continue + for path in sorted(base.rglob("*")): + if not path.is_file() or not is_protel_source(path): + continue + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + for line in text.splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("%"): + continue + upper = stripped.upper() + if upper.startswith("SECTION ") or upper.startswith("INTERFACE "): + parts = stripped.split() + if len(parts) >= 2: + name = parts[1].rstrip(";") + index.setdefault(name, path.resolve()) + break + return index + + +def _find_module_path( + module_name: str, + *, + source_path: Path | None, + index: dict[str, Path], +) -> Path | None: + if module_name in index: + return index[module_name] + for base in _search_dirs(source_path): + candidate = base / f"{module_name}.protel" + if candidate.is_file(): + return candidate.resolve() + return None + + +def _load_named_section( + path: Path, + module_name: str, + *, + classical: bool, +) -> ast.Section: + try: + source = path.read_text(encoding="utf-8", errors="replace") + except OSError as exc: + raise TranspileError( + f"cannot read USES module {module_name!r} from '{path}': {exc}" + ) from exc + try: + sections = parse_protel(source, classical=classical) + except Exception as exc: + raise TranspileError( + f"parse error in USES module {module_name!r} ({path.name}): {exc}" + ) from exc + for section in sections: + if section.name == module_name: + return section + names = ", ".join(section.name for section in sections) or "(none)" + raise TranspileError( + f"USES module {module_name!r} not found in '{path.name}' " + f"(sections: {names})" + ) + + +def _collect_uses_modules(sections: list[ast.Section]) -> list[str]: + ordered: list[str] = [] + seen: set[str] = set() + for section in sections: + for module_name in section.uses_modules: + if module_name not in seen: + seen.add(module_name) + ordered.append(module_name) + return ordered + + +def resolve_compilation_unit( + sections: list[ast.Section], + *, + source_path: Path | None = None, + classical: bool = False, +) -> list[ast.Section]: + """Expand USES links by loading embedded sections from other PROTEL sources.""" + uses = _collect_uses_modules(sections) + if not uses: + return sections + + search_dirs = _search_dirs(source_path) + index = _build_section_index(search_dirs) + + merged: list[ast.Section] = [] + merged_names: set[str] = set() + visiting: set[str] = set() + + def embed(module_name: str) -> None: + if module_name in merged_names: + return + if module_name in visiting: + raise TranspileError( + f"circular USES imbedding involving module {module_name!r}" + ) + visiting.add(module_name) + path = _find_module_path(module_name, source_path=source_path, index=index) + if path is None: + print( + f"protel: warning: USES module {module_name!r} not found; " + f"skipping embed", + file=sys.stderr, + ) + visiting.remove(module_name) + return + section = _load_named_section(path, module_name, classical=classical) + for dep in section.uses_modules: + embed(dep) + if module_name not in merged_names: + merged.append(section) + merged_names.add(module_name) + visiting.remove(module_name) + + for module_name in uses: + embed(module_name) + + for section in sections: + if section.name not in merged_names: + merged.append(section) + merged_names.add(section.name) + + return merged \ No newline at end of file diff --git a/src/parser.py b/src/parser.py new file mode 100644 index 0000000..1edfe0f --- /dev/null +++ b/src/parser.py @@ -0,0 +1,996 @@ +"""PROTEL 2026 Lark parser and AST builder.""" + +from __future__ import annotations + +from pathlib import Path + +from lark import Lark, Transformer, Tree + +from . import ast_nodes as ast +from .preprocess import normalize_keywords + +_GRAMMAR_PATH = Path(__file__).parent / "grammar" / "protel.lark" + + +def _token_values(children) -> list: + out = [] + for child in children: + if isinstance(child, str): + out.append(child) + elif hasattr(child, "type") and child.type not in {"RULE"}: + out.append(str(child)) + elif isinstance(child, list): + out.extend(_token_values(child)) + elif isinstance(child, Tree): + out.extend(_token_values(child.children)) + return out + + +def _only_nodes(children): + return [c for c in children if not isinstance(c, str) and not hasattr(c, "type")] + + +class ProtelASTBuilder(Transformer): + def compilation_unit(self, children): + sections: list[ast.Section] = [] + current: ast.Section | None = None + for item in children: + if isinstance(item, dict) and "section_kind" in item: + current = ast.Section( + module_type=item["module_type"], + section_kind=item["section_kind"], + name=item["name"], + of_modules=item.get("of_modules", []), + uses_modules=item.get("uses_modules", []), + ) + sections.append(current) + elif current is None: + raise ValueError("PROTEL declaration or statement appears before SECTION/INTERFACE header") + elif isinstance(item, ast.ClassImplSection): + current.class_impls.append(item) + elif isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)): + current.declarations.append(item) + else: + current.statements.append(item) + return sections + + def unit_item(self, children): + return children[0] + + def interface_kind(self, _children=None): + return "INTERFACE" + + def section_kind_kw(self, _children=None): + return "SECTION" + + def module_type(self, children): + return str(children[0]) if children else "FAST" + + def _section_head_meta( + self, + children, + *, + of_modules: list[str] | None = None, + uses_modules: list[str] | None = None, + ) -> dict: + module_type = "FAST" + section_kind = "SECTION" + name = "" + for child in children: + if isinstance(child, list): + continue + text = str(child) + if text in {"FAST", "SWAPPABLE", "PERPROCESS", "DEFINITIONS"}: + module_type = text + elif text in {"INTERFACE", "SECTION"}: + section_kind = text + elif not name: + name = text + return { + "module_type": module_type, + "section_kind": section_kind, + "name": name, + "of_modules": of_modules or [], + "uses_modules": uses_modules or [], + } + + def section_plain(self, children): + return self._section_head_meta(children) + + def section_uses(self, children): + id_lists = [c for c in children if isinstance(c, list)] + return self._section_head_meta(children, uses_modules=id_lists[0]) + + def section_of(self, children): + id_lists = [c for c in children if isinstance(c, list)] + return self._section_head_meta(children, of_modules=id_lists[0]) + + def section_of_uses(self, children): + id_lists = [c for c in children if isinstance(c, list)] + return self._section_head_meta( + children, + of_modules=id_lists[0], + uses_modules=id_lists[1], + ) + + def declaration(self, children): + return children[0] + + def type_dcl_stmt(self, children): + return children[-1] + + def type_dcl_list_tail(self, children): + return children[-1] + + def type_dcl(self, children): + return ast.TypeDecl(names=list(children[0]), type_spec=children[1]) + + def variable_dcl_stmt(self, children): + return children[-1] + + def variable_dcl_list_tail(self, children): + return children[-1] + + def variable_init_init(self, children): + return ("INIT", children[0]) + + def variable_init_is(self, children): + return ("IS", children[0]) + + def _var_decl_from_parts( + self, + names, + type_spec, + *, + storage_class: str | None = None, + init_tail=None, + ): + init = None + if init_tail is not None: + kind, value = init_tail + if kind == "INIT": + init = value + else: + init = value + return ast.VarDecl( + names=list(names), + type_spec=type_spec, + init=init, + storage_class=storage_class, + ) + + def variable_dcl_literal(self, children): + init_tail = children[2] if len(children) > 2 else None + return self._var_decl_from_parts( + children[0], + children[1], + storage_class="LITERAL", + init_tail=init_tail, + ) + + def variable_dcl_variable(self, children): + init_tail = children[2] if len(children) > 2 else None + return self._var_decl_from_parts( + children[0], + children[1], + storage_class="VARIABLE", + init_tail=init_tail, + ) + + def variable_dcl_ovly(self, children): + return ast.VarDecl( + names=[], + type_spec=children[0], + ovly_fields=list(children[1]), + ) + + def variable_dcl(self, children): + if len(children) == 3 and isinstance(children[2], tuple): + return self._var_decl_from_parts( + children[0], children[1], init_tail=children[2] + ) + names = list(children[0]) + type_spec = children[1] + return ast.VarDecl(names=names, type_spec=type_spec) + + def proc_dcl_stmt(self, children): + return children[-1] + + def proc_dcl_intrinsic(self, children): + names = children[0] + proc_sig = children[1] + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=proc_sig["return_type"], + body=None, + pclass=proc_sig.get("pclass"), + intrinsic=True, + ) + + def proc_dcl_external(self, children): + names = children[0] + proc_sig = children[1] + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=proc_sig["return_type"], + body=None, + pclass=proc_sig.get("pclass"), + external=True, + ) + + def proc_dcl_forward(self, children): + names = children[0] + proc_sig = children[1] + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=proc_sig["return_type"], + body=None, + pclass=proc_sig.get("pclass"), + forward=True, + ) + + def proc_dcl_entry(self, children): + names = children[0] + proc_sig = children[1] + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=None, + body=None, + pclass=proc_sig.get("pclass"), + entry=True, + ) + + def proc_dcl_export(self, children): + names = children[0] + proc_sig = children[1] + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=proc_sig["return_type"], + body=None, + pclass=proc_sig.get("pclass"), + export=True, + ) + + def proc_dcl(self, children): + names = children[0] + proc_sig = children[1] + body = children[-1] if len(children) > 2 else None + if body == proc_sig or isinstance(body, str): + body = None + return ast.ProcDecl( + name=names[0], + parms=proc_sig["parms"], + return_type=proc_sig["return_type"], + body=body, + pclass=proc_sig.get("pclass"), + intrinsic=False, + ) + + def proc_sig(self, children): + return self._build_proc_sig(children) + + def paren_parms(self, children): + for child in children: + if isinstance(child, list) and child and isinstance(child[0], tuple): + return child + if isinstance(child, list) and (not child or not isinstance(child[0], str)): + return child + return [] + + def _build_proc_sig(self, children): + tokens = _token_values(children) + pclass = None + if tokens and tokens[0] in {"QUICK", "OPERAND"}: + pclass = tokens[0] + parms: list = [] + return_type = None + for child in children: + if isinstance(child, list) and child and isinstance(child[0], tuple): + parms = child + elif not isinstance(child, (str, list)) and child is not None: + if not isinstance(child, dict): + return_type = child + return {"pclass": pclass, "parms": parms, "return_type": return_type} + + def parm_list(self, children): + return list(children) + + def parm_updates(self, children): + return (list(children[0]), children[1], "UPDATES") + + def parm(self, children): + if children[0] == "REF": + return (list(children[1]), children[2], True) + return (list(children[0]), children[1], False) + + def bind_stmt(self, children): + return ast.BindStmt(bindings=list(children[0])) + + def bind_list(self, children): + return list(children) + + def bind_item(self, children): + name = str(children[0]) + ref = children[1] + as_type = children[2] if len(children) > 2 else None + return (name, ref, as_type) + + def opt_as_clause(self, children): + return children[0] if children else None + + def with_stmt(self, children): + return ast.WithStmt(refs=list(children[0])) + + def with_ref_list(self, children): + return list(children) + + def block(self, children): + innards = children[-1] + decls, stmts = innards + return ast.Block(declarations=list(decls), statements=list(stmts)) + + def block_innards(self, children): + decls = [] + stmts = [] + for item in children: + if isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)): + decls.append(item) + else: + stmts.append(item) + return decls, stmts + + def if_stmt(self, children): + condition = children[0] + then_part = list(children[1]) + else_part = list(children[2]) if len(children) > 2 else [] + return ast.IfStmt(condition=condition, then_part=then_part, else_part=else_part) + + def statement_list(self, children): + return list(children) + + def loop_stmt(self, children): + if len(children) >= 2 and not isinstance(children[0], list): + return ast.LoopStmt(while_expr=children[0], body=list(children[-1])) + return ast.LoopStmt(while_expr=None, body=list(children[-1])) + + def for_over_range(self, children): + return {"over_type": children[0]} + + def for_index_range(self, children): + parts = children[0] + return { + "from_expr": parts[0], + "direction": parts[1][0] if parts[1] else None, + "to_expr": parts[1][1] if parts[1] else None, + "by_expr": parts[2], + "while_expr": parts[3], + "over_type": None, + } + + def from_to_parts(self, children): + from_expr = None + to_part = None + by_expr = None + while_expr = None + idx = 0 + if idx < len(children): + if isinstance(children[idx], tuple) and children[idx][0] in {"UP", "DOWN"}: + to_part = children[idx] + idx += 1 + else: + from_expr = children[idx] + idx += 1 + if idx < len(children): + to_part = children[idx] + idx += 1 + if idx < len(children): + by_expr = children[idx] + idx += 1 + if idx < len(children): + while_expr = children[idx] + return (from_expr, to_part, by_expr, while_expr) + + def opt_from_clause(self, children): + return children[0] if children else None + + def up_to_clause(self, children): + return ("UP", children[0]) + + def down_to_clause(self, children): + return ("DOWN", children[0]) + + def opt_by_clause(self, children): + return children[0] if children else None + + def opt_while_clause(self, children): + return children[0] if children else None + + def for_stmt(self, children): + var = str(children[0]) + range_info = children[1] + body = list(children[-1]) + if range_info.get("over_type") is not None: + return ast.ForStmt( + var=var, + from_expr=None, + to_expr=None, + direction=None, + by_expr=None, + while_expr=None, + over_type=range_info["over_type"], + body=body, + ) + return ast.ForStmt( + var=var, + from_expr=range_info.get("from_expr"), + to_expr=range_info.get("to_expr"), + direction=range_info.get("direction"), + by_expr=range_info.get("by_expr"), + while_expr=range_info.get("while_expr"), + over_type=None, + body=body, + ) + + def over_stmt(self, children): + return ast.OverStmt(over_type=children[0], body=list(children[-1])) + + def case_list(self, children): + if len(children) == 1: + item = children[0] + return [item] if isinstance(item, ast.CaseArm) else list(item) + left = children[0] + right = children[1] + if not isinstance(left, list): + left = [left] + return left + [right] + + def case_body(self, children): + arms = children[0] if children else [] + if isinstance(arms, ast.CaseArm): + arms = [arms] + out_statements: list = [] + if len(children) > 1: + out_statements = children[1] if isinstance(children[1], list) else [] + return list(arms), out_statements + + def case_item_empty(self, children): + return ast.CaseArm(labels=children[0], statements=[]) + + def case_item_nonempty(self, children): + return ast.CaseArm(labels=children[0], statements=list(children[1])) + + def case_arm_nonempty(self, children): + return list(children) + + def out_case_empty(self, children): + return [] + + def out_case_with_stmts(self, children): + return list(children) + + def case_stmt(self, children): + arms, out_statements = children[1] + return ast.CaseStmt(selector=children[0], arms=arms, out_statements=out_statements, is_select=False) + + def select_stmt(self, children): + arms, out_statements = children[1] + return ast.CaseStmt(selector=children[0], arms=arms, out_statements=out_statements, is_select=True) + + def exit_stmt(self, children): + return ast.ExitStmt() + + def upb_expr(self, children): + return ast.BuiltinExpr(name="UPB", operand=children[0]) + + def tdsize_expr(self, children): + return ast.BuiltinExpr(name="TDSIZE", operand=children[0]) + + def typedesc_expr(self, children): + return ast.BuiltinExpr(name="TYPEDESC", operand=children[0]) + + def vardesc_expr(self, children): + return ast.BuiltinExpr(name="VARDESC", operand=children[0]) + + def refdesc_expr(self, children): + return ast.BuiltinExpr(name="REFDESC", operand=children[0]) + + def cast_expr(self, children): + return ast.CastExpr(operand=children[0], target_type=children[1]) + + def bin_incl(self, children): + return self._bin("INCL", children) + + def bin_notincl(self, children): + return self._bin("NOTINCL", children) + + def return_stmt(self, children): + if not children: + return ast.ReturnStmt(value=None) + return ast.ReturnStmt(value=children[0]) + + def expr_stmt(self, children): + return children[0] + + def id_list(self, children): + return [str(c) for c in children] + + def statement(self, children): + return children[0] + + def unpacked_type(self, children): + return children[0] + + + + def pack_type(self, children): + width_child = children[0] + if isinstance(width_child, ast.Literal) and width_child.kind == "int": + width = int(width_child.value) + else: + width = int(str(width_child)) + unpacked = children[1] + if isinstance(unpacked, ast.BoolType): + unpacked.packed = width + elif isinstance(unpacked, ast.TableType): + unpacked.packed = width + elif isinstance(unpacked, ast.RangeType): + unpacked.packed = width + return unpacked + + def val_type(self, children): + return children[0] + + def type_spec(self, children): + return children[0] + + def range_type(self, children): + low, high = children[0] + return ast.RangeType(low=low, high=high) + + def symbolic_range(self, children): + return ast.SymbolicRange(members=list(children[0])) + + def bool_type(self, children): + return ast.BoolType() + + def ptr_type(self, children): + return ast.PtrType(target=children[-1]) + + def set_type(self, children): + return ast.SetType(member_type=children[-1]) + + def area_unrestricted(self, _children=None): + return "UNRESTRICTED" + + def area_nontransparent(self, _children=None): + return "NONTRANSPARENT" + + def area_field(self, children): + return (list(children[0]), children[1]) + + def area_field_list(self, children): + return list(children) + + def area_type(self, children): + options: list[str] = [] + idx = 0 + while idx < len(children) and isinstance(children[idx], str): + options.append(children[idx]) + idx += 1 + size_expr = children[idx] + fields = children[idx + 1] + return ast.AreaType(options=options, size_expr=size_expr, fields=fields) + + def ovly_field(self, children): + return (children[0], list(children[1]), children[2]) + + def ovly_body(self, children): + return list(children) + + def struct_type(self, children): + return ast.StructType(fields=list(children[0])) + + def struct_field_list(self, children): + return list(children) + + def struct_field(self, children): + return (list(children[0]), children[1]) + + def opt_refines(self, children): + return children[0] if children else None + + def seg_protected(self, _children=None): + return "PROTECTED" + + def seg_shared(self, _children=None): + return "SHARED" + + def seg_private(self, _children=None): + return "PRIVATE" + + def seg_exclusive(self, _children=None): + return "EXCLUSIVE" + + def seg_readable(self, _children=None): + return "READABLE" + + def seg_writable(self, _children=None): + return "WRITABLE" + + def segment_attr_list(self, children): + return [str(c) for c in children] + + def meth_abstract(self, _children=None): + return "ABSTRACT" + + def meth_class(self, _children=None): + return "CLASS" + + def meth_create(self, _children=None): + return "CREATE" + + def meth_exclusive(self, _children=None): + return "EXCLUSIVE" + + def meth_fixed(self, _children=None): + return "FIXED" + + def meth_hidden(self, _children=None): + return "HIDDEN" + + def meth_overriding(self, _children=None): + return "OVERRIDING" + + def segment_flags(self, children): + return list(children[0]) if children else [] + + def class_field(self, children): + return (list(children[0]), children[1]) + + def class_field_list(self, children): + return list(children) + + def class_data_section(self, children): + return ast.ClassDataPart(access_attrs=list(children[0]), fields=list(children[1])) + + def class_data_sections(self, children): + return list(children) + + def method_attr_list(self, children): + return [str(c) for c in children] + + def method_segment_flags(self, children): + return list(children[0]) if children else [] + + def method_id_list(self, children): + return [str(c) for c in children] + + def opt_method_parms(self, children): + return children[0] if children else [] + + def opt_method_returns(self, children): + return children[0] if children else None + + def method_decl_sig(self, children): + parms = [] + return_type = None + for child in children: + if isinstance(child, list) and (not child or isinstance(child[0], tuple)): + parms = child + elif child is not None and not isinstance(child, str): + return_type = child + return {"parms": parms, "return_type": return_type} + + def method_group(self, children): + names = list(children[0]) + sig = children[1] + return ast.MethodDecl( + names=names, + parms=sig["parms"], + return_type=sig["return_type"], + ) + + def method_group_list(self, children): + return list(children) + + def method_section(self, children): + attrs = list(children[0]) + methods = list(children[1]) + for method in methods: + method.attrs = attrs + return ast.MethodSection(attrs=attrs, methods=methods) + + def method_section_list(self, children): + return list(children) + + def operations_section(self, children): + return list(children[0]) if children else [] + + def class_type(self, children): + if len(children) == 3: + base = None + data_parts, operations, end_name = children + else: + base, data_parts, operations, end_name = children + return ast.ClassType( + end_name=str(end_name), + base=base, + data_parts=list(data_parts), + operations=list(operations), + ) + + def class_impl_section(self, children): + class_name = str(children[0]) + decls: list = [] + stmts: list = [] + for item in children[1:]: + if isinstance(item, ast.MethodImplDecl): + decls.append(item) + elif isinstance(item, (ast.TypeDecl, ast.VarDecl, ast.ProcDecl)): + decls.append(item) + else: + stmts.append(item) + return ast.ClassImplSection(class_name=class_name, declarations=decls, statements=stmts) + + def in_impl_item(self, children): + return children[0] + + def method_impl_dcl(self, children): + return ast.MethodImplDecl(name=str(children[0]), body=children[1]) + + def init_value(self, children): + return children[0] + + def table_type(self, children): + low, high = children[0] + return ast.TableType(low=low, high=high, element_type=children[1]) + + def desc_type(self, children): + if len(children) == 1: + return ast.DescType(low=None, high=None, element_type=children[0]) + low, high = children[0] + return ast.DescType(low=low, high=high, element_type=children[1]) + + def bounds(self, children): + return children[0] + + def defined_type(self, children): + if not children: + return ast.DefinedType(name="") + return ast.DefinedType(name=str(children[0])) + + def constant_subrange(self, children): + if len(children) >= 3: + return self._const_value(children[0]), self._const_value(children[2]) + return self._const_value(children[0]), self._const_value(children[1]) + + def constant_expr_atom(self, children): + return self._const_value(children[0]) + + def _const_value(self, node): + if isinstance(node, ast.Literal): + return node + if isinstance(node, Tree): + return self._const_value(node.children[0]) + return self.literal([node]) + + def assign_expr(self, children): + expr = children[0] + for tail in children[1:]: + expr = ast.AssignExpr(value=expr, target=tail) + return expr + + def assign_tail(self, children): + return children[-1] + + def or_expr(self, children): + expr = children[0] + for rhs in children[1:]: + expr = ast.BinExpr(op="|", left=expr, right=rhs) + return expr + + def and_expr(self, children): + expr = children[0] + for rhs in children[1:]: + expr = ast.BinExpr(op="&", left=expr, right=rhs) + return expr + + def xor_expr(self, children): + expr = children[0] + for rhs in children[1:]: + expr = ast.BinExpr(op="^", left=expr, right=rhs) + return expr + + def _bin(self, op: str, children): + return ast.BinExpr(op=op, left=children[0], right=children[1]) + + def bin_or(self, c): + return self._bin("|", c) + + def bin_and(self, c): + return self._bin("&", c) + + def bin_xor(self, c): + return self._bin("^", c) + + def bin_eq(self, c): + return self._bin("=", c) + + def bin_ne(self, c): + return self._bin("^=", c) + + def bin_gt(self, c): + return self._bin(">", c) + + def bin_ge(self, c): + return self._bin(">=", c) + + def bin_lt(self, c): + return self._bin("<", c) + + def bin_le(self, c): + return self._bin("<=", c) + + def bin_add(self, c): + return self._bin("+", c) + + def bin_sub(self, c): + return self._bin("-", c) + + def bin_mul(self, c): + return self._bin("*", c) + + def bin_div(self, c): + return self._bin("/", c) + + def bin_mod(self, c): + return self._bin("MOD", c) + + def unary_expr(self, children): + if len(children) == 1: + return children[0] + return ast.UnaryExpr(op=str(children[0]), operand=children[1]) + + def ref_segment(self, children): + name = str(children[0]) + if name == "SELF": + return ast.VarRef(name="SELF", is_self=True) + if name == "SUPER": + return ast.VarRef(name="SUPER", is_super=True) + return ast.VarRef(name=name) + + def self_ref(self, _children=None): + return ast.VarRef(name="SELF", is_self=True) + + def super_ref(self, _children=None): + return ast.VarRef(name="SUPER", is_super=True) + + def qual_index(self, children): + return ("index", children[0]) + + def dot_suffix(self, children): + return ("dot", str(children[0])) + + def call_suffix(self, children): + if not children: + return ("call", []) + return ("call", list(children[0])) + + def _normalize_suffix(self, suffix): + if isinstance(suffix, tuple): + return suffix + if isinstance(suffix, Tree): + if suffix.data == "dot_suffix": + return ("dot", str(suffix.children[0])) + if suffix.data in {"qual_index", "index_suffix"}: + return ("index", suffix.children[0]) + if suffix.data == "call_suffix": + if not suffix.children: + return ("call", []) + args = suffix.children[0] + return ("call", list(args) if isinstance(args, list) else []) + return suffix + + def _flatten_suffixes(self, nodes): + out = [] + for node in nodes: + if isinstance(node, Tree) and node.data == "qual_suffix": + out.extend(self._flatten_suffixes(node.children)) + else: + out.append(self._normalize_suffix(node)) + return out + + def qualified_ref(self, children): + root = children[0] + suffixes = self._flatten_suffixes(children[1:]) + if suffixes and isinstance(suffixes[-1], tuple) and suffixes[-1][0] == "call": + args = suffixes[-1][1] + path = suffixes[:-1] + if not path: + name = root.name if isinstance(root, ast.VarRef) else "?" + return ast.ProcCall(name=name, args=args) + if path[-1][0] != "dot": + return ast.ProcCall(name="?", args=args) + method_name = path[-1][1] + receiver = self._build_qualified(root, path[:-1]) + return ast.MethodCall(receiver=receiver, name=method_name, args=args) + return self._build_qualified(root, suffixes) + + def _build_qualified(self, root, suffixes): + result = root + for suffix in suffixes: + if not isinstance(suffix, tuple): + continue + if suffix[0] == "dot": + result = ast.MemberRef(base=result, member=suffix[1]) + elif suffix[0] == "index" and isinstance(result, ast.VarRef): + result.indices.append(suffix[1]) + return result + + def index_suffix(self, children): + if len(children) == 1: + return children[0] + return (children[0], children[1]) + + def actual_list(self, children): + return list(children) + + def true_lit(self, _children=None): + return ast.Literal(kind="true", value="TRUE") + + def false_lit(self, _children=None): + return ast.Literal(kind="false", value="FALSE") + + def nil_lit(self, _children=None): + return ast.Literal(kind="nil", value="NIL") + + def literal(self, children): + text = str(children[0]) + if text.startswith("'"): + return ast.Literal(kind="string", value=text) + if any(ch in text for ch in ".eE"): + return ast.Literal(kind="float", value=text) + return ast.Literal(kind="int", value=text) + + def tuple(self, children): + if not children: + return ast.TupleLit(elements=[]) + return ast.TupleLit(elements=list(children[0])) + + def tuple_body_list(self, children): + return list(children) + + def tuple_elem(self, children): + return children[0] + + def NUMBER(self, token): + return str(token) + + def STRING(self, token): + return str(token) + + def IDENT(self, token): + return str(token) + + +class ProtelParser: + def __init__(self, *, classical: bool = False): + self.classical = classical + grammar = _GRAMMAR_PATH.read_text(encoding="utf-8") + # Earley is required for CASE/SELECT bodies with multiple labelled arms. + self._lark = Lark(grammar, start="start", parser="earley", lexer="basic") + self._transformer = ProtelASTBuilder() + + def parse(self, source: str): + normalized = normalize_keywords(source, classical=self.classical) + tree = self._lark.parse(normalized) + return self._transformer.transform(tree) + + +def parse_protel(source: str, *, classical: bool = False): + return ProtelParser(classical=classical).parse(source) \ No newline at end of file diff --git a/src/preprocess.py b/src/preprocess.py new file mode 100644 index 0000000..e8003e2 --- /dev/null +++ b/src/preprocess.py @@ -0,0 +1,111 @@ +"""Lexical preprocessing for PROTEL source before parsing.""" + +from __future__ import annotations + +import re + +from .keywords import PROTEL_KEYWORDS + +_DOLLAR_DIRECTIVES = frozenset(k for k in PROTEL_KEYWORDS if k.startswith("$")) + +KEYWORD_RE = re.compile( + r"\b(" + "|".join(sorted(PROTEL_KEYWORDS, key=len, reverse=True)) + r")\b", + re.IGNORECASE, +) + +TOKEN_SPEC = [ + ("STRING", r"'(?:''|[^'])*'"), + ("IDENT", 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.DOTALL, +) + + +def _find_comment_start(line: str) -> int: + in_string = False + i = 0 + while i < len(line): + ch = line[i] + if ch == "'": + in_string = not in_string + if in_string and i + 1 < len(line) and line[i + 1] == "'": + i += 1 + elif ch == "%" and not in_string: + return i + i += 1 + return -1 + + +def _is_dollar_directive_line(code_part: str) -> bool: + """True for linker control lines such as ``$li modentry restart``.""" + for match in TOKEN_RE.finditer(code_part): + kind = match.lastgroup + if kind == "WHITESPACE": + continue + if kind == "IDENT": + return match.group().upper() in _DOLLAR_DIRECTIVES + return False + return False + + +def strip_shebang(source: str) -> str: + """ + Remove a UNIX shebang (``#!...``) from the first line when present. + + The shebang is host metadata for direct execution; it is not PROTEL syntax. + """ + if source.startswith("#!"): + _, _, rest = source.partition("\n") + return rest + return source + + +def normalize_keywords(source: str, *, classical: bool = False) -> str: + """ + Uppercase reserved keywords outside comments and strings. + + In modern mode, keywords are normalized to UPPERCASE before parsing. + In classical mode, the same normalization applies but identifiers remain + case-sensitive when not matching reserved words. + """ + del classical # reserved for future classical-only identifier rules + source = strip_shebang(source) + output_parts: list[str] = [] + + for line in source.splitlines(keepends=True): + comment_pos = _find_comment_start(line) + if comment_pos != -1: + code_part = line[:comment_pos] + # Drop comments before parse; the transpiler re-emits source file name. + else: + code_part = line + + if _is_dollar_directive_line(code_part): + continue + + line_out: list[str] = [] + for match in TOKEN_RE.finditer(code_part): + kind = match.lastgroup + token = match.group() + if kind == "STRING": + line_out.append(token) + elif kind == "IDENT": + upper = token.upper() + line_out.append(upper if upper in PROTEL_KEYWORDS else token) + else: + line_out.append(token) + + normalized = "".join(line_out) + if normalized.strip(): + if not normalized.endswith("\n"): + normalized += "\n" + output_parts.append(normalized) + + return "".join(output_parts) \ No newline at end of file diff --git a/src/runtime/protel_io.c b/src/runtime/protel_io.c new file mode 100644 index 0000000..327d018 --- /dev/null +++ b/src/runtime/protel_io.c @@ -0,0 +1,28 @@ +/* Minimal PROTEL 2026 I/O runtime: POSIX write(2) only, no iostream. */ +#include +#include + +#include "protel_io.h" + +static void write_cstr(const char* s) +{ + size_t n = 0; + while (s[n] != '\0') { + n++; + } + if (n > 0) { + (void)write(1, s, n); + } +} + +void writeln(const char* msg) +{ + if (msg == NULL) { + msg = ""; + } + write_cstr(msg); + { + const char nl = '\n'; + (void)write(1, &nl, 1); + } +} \ No newline at end of file diff --git a/src/runtime/protel_io.h b/src/runtime/protel_io.h new file mode 100644 index 0000000..dfa3ffe --- /dev/null +++ b/src/runtime/protel_io.h @@ -0,0 +1,11 @@ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void writeln(const char* msg); /* EXTERNAL C I/O */ + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/src/transpiler.py b/src/transpiler.py new file mode 100644 index 0000000..bf9bd76 --- /dev/null +++ b/src/transpiler.py @@ -0,0 +1,822 @@ +"""PROTEL 2026 to C transpiler.""" + +from __future__ import annotations + +import textwrap +from typing import Any, TextIO + +from . import ast_nodes as ast + + +class TranspileError(Exception): + """Raised when PROTEL source cannot be transpiled.""" + + +class TypeContext: + def __init__(self): + self.aliases: dict[str, Any] = {} + self.predefined = { + "integer": ast.RangeType( + low=ast.Literal(kind="int", value="-32768"), + high=ast.Literal(kind="int", value="32767"), + ) + } + + def declare(self, names: list[str], spec): + for name in names: + self.aliases[name] = spec + + def resolve(self, spec): + if isinstance(spec, ast.DefinedType): + if spec.name in self.aliases: + return self.aliases[spec.name] + if spec.name in self.predefined: + return self.predefined[spec.name] + return spec + + +class CTranspiler: + def __init__(self, *, classical: bool = False, source_name: str = "input.protel"): + self.classical = classical + self.source_name = source_name + self.types = TypeContext() + self.indent = 0 + self.lines: list[str] = [] + self._proc_decls: list[ast.ProcDecl] = [] + self._method_impls: list[tuple[str, ast.MethodImplDecl, ast.MethodDecl | None]] = [] + self._class_methods: dict[str, dict[str, ast.MethodDecl]] = {} + self._class_vars: dict[str, set[str]] = {} + self._var_types: dict[str, str] = {} + self._current_class: str | None = None + self._current_self: str = "self" + + def emit(self, line: str = ""): + if line: + self.lines.append(" " * 4 * self.indent + line) + else: + self.lines.append("") + + def transpile(self, compilation_unit: list[ast.Section]) -> str: + self.lines = [] + self._proc_decls = [] + self._method_impls = [] + self._class_methods = {} + self._class_vars = {} + self._var_types = {} + self.emit("/* Generated by PROTEL 2026 transpiler */") + self.emit(f"/* Source: {self.source_name} */") + self.emit('#include ') + self.emit('#include ') + self.emit("") + + for section in compilation_unit: + self._emit_section(section) + + for proc in self._proc_decls: + if proc.body: + self._emit_procedure(proc) + + for class_name, impl, method_decl in self._method_impls: + self._emit_method_impl(class_name, impl, method_decl) + + return "\n".join(self.lines) + "\n" + + def _emit_section(self, section: ast.Section): + self.emit(f"/* SECTION {section.name} ({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("") + + for decl in section.declarations: + self._emit_toplevel_decl(decl) + for impl in section.class_impls: + self._queue_class_impl(impl) + for stmt in section.statements: + self._emit_stmt(stmt) + + def _emit_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.StructType): + self._emit_struct_typedef(decl.names[0], decl.type_spec) + elif isinstance(decl.type_spec, ast.ClassType): + self._emit_class_typedef(decl.names[0], decl.type_spec) + elif isinstance(decl.type_spec, ast.SymbolicRange): + self._emit_symbolic_typedef(decl.names[0], decl.type_spec) + elif isinstance(decl.type_spec, ast.AreaType): + for name in decl.names: + self._emit_area_typedef(name, decl.type_spec) + else: + for name in decl.names: + self.emit(f"typedef {self._c_type_decl(decl.type_spec, name)};") + self.emit("") + elif isinstance(decl, ast.VarDecl): + if decl.ovly_fields is not None: + self.emit("/* OVLY overlay declaration */") + for labels, names, field_type in decl.ovly_fields: + for name in names: + self.emit( + f"/* OVLY {self._c_expr(labels)}: " + f"{self._c_type_decl(field_type, name)} */" + ) + self.emit("") + return + type_name = self._decl_type_name(decl.type_spec) + for name in decl.names: + if type_name: + self._var_types[name] = type_name + prefix = "" + if decl.storage_class: + prefix = f"/* {decl.storage_class} */ " + line = f"{prefix}{self._c_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._proc_signature(decl) + ";") + self.emit("") + return + if decl.external: + self.emit(f"extern {self._proc_signature(decl)};") + self.emit("") + return + self._proc_decls.append(decl) + self.emit(self._proc_signature(decl) + ";") + self.emit("") + + def _proc_signature(self, proc: ast.ProcDecl) -> str: + ret = self._c_type(proc.return_type) if proc.return_type else "void" + args = self._c_parm_list(proc.parms) + return f"{ret} {proc.name}({args})" + + def _c_parm_list(self, parms: list[tuple[list[str], Any, bool]]) -> str: + if not parms: + return "void" + parts: list[str] = [] + for names, type_spec, parm_mode in parms: + c_type = self._c_type(type_spec) + for name in names: + if parm_mode is True: + parts.append(f"{c_type} *{name}") + elif parm_mode == "UPDATES": + parts.append(f"{c_type} *{name} /* UPDATES */") + else: + parts.append(f"{c_type} {name}") + return ", ".join(parts) + + def _emit_procedure(self, proc: ast.ProcDecl): + self.emit(self._proc_signature(proc)) + self.emit("{") + self.indent += 1 + self._emit_block_body(proc.body) + self.indent -= 1 + self.emit("}") + self.emit("") + + def _emit_block_body(self, block: ast.Block): + for decl in block.declarations: + if isinstance(decl, ast.VarDecl): + c_type = self._c_type(decl.type_spec) + for name in decl.names: + init = f" = {self._c_expr(decl.init)}" if decl.init is not None else "" + self.emit(f"{c_type} {name}{init};") + elif isinstance(decl, ast.TypeDecl): + self.types.declare(decl.names, decl.type_spec) + for stmt in block.statements: + self._emit_stmt(stmt) + + def _emit_stmt(self, stmt): + if isinstance(stmt, ast.Block): + self.emit("{") + self.indent += 1 + self._emit_block_body(stmt) + self.indent -= 1 + self.emit("}") + elif isinstance(stmt, ast.IfStmt): + self.emit(f"if ({self._c_expr(stmt.condition)}) {{") + self.indent += 1 + for s in stmt.then_part: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + if stmt.else_part: + self.emit("else {") + self.indent += 1 + for s in stmt.else_part: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + elif isinstance(stmt, ast.LoopStmt): + if stmt.while_expr is not None: + self.emit(f"while ({self._c_expr(stmt.while_expr)}) {{") + else: + self.emit("while (1) {") + self.indent += 1 + for s in stmt.body: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + elif isinstance(stmt, ast.ForStmt): + self._emit_for(stmt) + elif isinstance(stmt, ast.OverStmt): + self._emit_over(stmt) + elif isinstance(stmt, ast.CaseStmt): + self._emit_case(stmt) + elif isinstance(stmt, ast.ExitStmt): + self.emit("break;") + elif isinstance(stmt, ast.ReturnStmt): + if stmt.value is None: + self.emit("return;") + else: + self.emit(f"return {self._c_expr(stmt.value)};") + elif isinstance(stmt, ast.BindStmt): + for name, ref, as_type in stmt.bindings: + cast = f" AS {self._c_type(as_type)}" if as_type is not None else "" + self.emit( + f"/* BIND {name} TO {self._c_expr(ref)}{cast} */" + ) + elif isinstance(stmt, ast.WithStmt): + refs = ", ".join(self._c_expr(ref) for ref in stmt.refs) + self.emit(f"/* WITH {refs} */") + else: + expr_code = self._c_expr(stmt) + if expr_code: + self.emit(f"{expr_code};") + + def _unwrap_type(self, spec): + from lark import Tree + + while isinstance(spec, Tree): + if spec.children: + spec = spec.children[0] + else: + break + return spec + + def _c_type_decl(self, spec, name: str) -> str: + spec = self._unwrap_type(spec) + if isinstance(spec, ast.TableType): + elem = self._c_type(spec.element_type) + count = self._table_count(spec.low, spec.high) + return f"{elem} {name}[{count}]" + return f"{self._c_type(spec)} {name}" + + def _c_type(self, spec) -> str: + if spec is None: + return "void" + spec = self._unwrap_type(spec) + spec = self.types.resolve(spec) + if isinstance(spec, ast.RangeType): + return self._range_to_c(spec) + if isinstance(spec, ast.BoolType): + return "uint8_t" + if isinstance(spec, ast.SymbolicRange): + return "int32_t" + if isinstance(spec, ast.DefinedType): + return spec.name + if isinstance(spec, ast.PtrType): + target = self._unwrap_type(spec.target) + if isinstance(target, ast.DefinedType): + return f"{target.name} *" + return f"{self._c_type(spec.target)} *" + if isinstance(spec, ast.TableType): + elem = self._c_type(spec.element_type) + count = self._table_count(spec.low, spec.high) + return f"{elem}[{count}]" # used for value contexts, not typedef names + if isinstance(spec, ast.DescType): + return "void * /* DESC */" + if isinstance(spec, ast.AreaType): + opts = " ".join(spec.options) if spec.options else "AREA" + return f"uint8_t /* {opts} AREA({self._c_expr(spec.size_expr)}) */" + if isinstance(spec, ast.ClassType): + return spec.end_name + if isinstance(spec, ast.StructType): + return f"struct {self._struct_tag(spec)}" + if isinstance(spec, ast.SetType): + return "uint32_t" + if isinstance(spec, dict) and "parms" in spec: + ret = self._c_type(spec.get("return_type")) if spec.get("return_type") else "void" + args = self._c_parm_list(spec.get("parms", [])) + return f"{ret} (*)({args})" + if isinstance(spec, ast.ProcTypeSig): + ret = self._c_type(spec.return_type) if spec.return_type else "void" + args = self._c_parm_list(spec.parms) + return f"{ret} (*)({args})" + return "int32_t" + + def _range_to_c(self, spec: ast.RangeType) -> str: + low = self._literal_int(spec.low) + high = self._literal_int(spec.high) + if low is not None and high is not None: + if low >= 0 and high <= 255: + return "uint8_t" + if low >= -32768 and high <= 32767: + return "int16_t" + if low >= 0 and high <= 65535: + return "uint16_t" + if low >= -2147483648 and high <= 2147483647: + return "int32_t" + return "int32_t" + + def _literal_int(self, node) -> int | None: + if isinstance(node, ast.Literal) and node.kind == "int": + return int(node.value) + if isinstance(node, str) and node.lstrip("-").isdigit(): + return int(node) + return None + + def _table_count(self, low, high) -> int: + lo = self._literal_int(low) + hi = self._literal_int(high) + if lo is not None and hi is not None: + return hi - lo + 1 + return 0 + + def _protel_string_chars(self, protel_str: str) -> list[str]: + return list(protel_str[1:-1].replace("''", "'")) + + def _c_char_code(self, code: int) -> str: + if code == 0: + return "0" + if 32 <= code <= 126 and code not in (ord("\\"), ord("'")): + return f"'{chr(code)}'" + return str(code) + + def _c_char_array_literal(self, codes: list[int]) -> str: + items = ", ".join(self._c_char_code(code) for code in codes) + return f"(const char[]){{ {items} }}" + + def _flatten_char_tuple_elements(self, elements: list[Any]) -> list[int]: + codes: list[int] = [] + for elem in elements: + if isinstance(elem, ast.Literal) and elem.kind == "string": + codes.extend(ord(ch) for ch in self._protel_string_chars(elem.value)) + elif isinstance(elem, ast.Literal) and elem.kind == "int": + codes.append(int(elem.value)) + else: + raise ValueError( + "char tuple for C interop may only contain string literals " + "and integer byte values (e.g. 0 for NUL)" + ) + return codes + + def _is_char_sequence_tuple(self, elements: list[Any]) -> bool: + if not elements: + return False + return all( + isinstance(elem, ast.Literal) and elem.kind in {"string", "int"} + for elem in elements + ) + + def _c_char_sequence_tuple(self, elements: list[Any]) -> str: + return self._c_char_array_literal(self._flatten_char_tuple_elements(elements)) + + def _c_init(self, init) -> str: + if isinstance(init, ast.TupleLit): + if self._is_char_sequence_tuple(init.elements): + return self._c_char_sequence_tuple(init.elements) + items = ", ".join(self._c_expr(e) for e in init.elements) + return f"{{ {items} }}" + return self._c_expr(init) + + def _c_expr(self, expr) -> str: + if isinstance(expr, ast.Literal): + if expr.kind == "string": + return self._c_string(expr.value) + if expr.kind == "int": + return str(expr.value) + if expr.kind == "float": + return str(expr.value) + if expr.kind == "true": + return "true" + if expr.kind == "false": + return "false" + if expr.kind == "NIL".lower(): + return "NULL" + if isinstance(expr, ast.VarRef): + if expr.is_self: + base = self._current_self + elif expr.is_super: + base = f"/* SUPER */ {self._current_self}" + else: + base = expr.name + for idx in expr.indices: + if isinstance(idx, tuple): + lo, hi = idx + base = f"{base}[{self._c_expr(lo)} /* TO {self._c_expr(hi)} */]" + else: + base = f"{base}[{self._c_expr(idx)}]" + return base + if isinstance(expr, ast.MemberRef): + return self._c_member_ref(expr) + 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: + return f"{class_name}_{expr.name}({self._method_call_args(expr, args)})" + receiver = self._c_expr(expr.receiver) if expr.receiver is not None else "" + if receiver: + return f"{receiver}.{expr.name}({args})" + return f"{expr.name}({args})" + if isinstance(expr, ast.ProcCall): + args = ", ".join( + self._c_proc_call_arg(expr, index, arg) + for index, arg in enumerate(expr.args) + ) + return f"{expr.name}({args})" + if isinstance(expr, ast.UnaryExpr): + if expr.op == "!": + return f"!({self._c_expr(expr.operand)})" + if expr.op == "-": + return f"-({self._c_expr(expr.operand)})" + if isinstance(expr, ast.BinExpr): + op = self._c_binop(expr.op) + return f"({self._c_expr(expr.left)} {op} {self._c_expr(expr.right)})" + if isinstance(expr, ast.AssignExpr): + target = self._c_assign_target(expr.target) + value = self._c_expr(expr.value) + return f"({target} = {value})" + if isinstance(expr, ast.TupleLit): + if self._is_char_sequence_tuple(expr.elements): + return self._c_char_sequence_tuple(expr.elements) + items = ", ".join(self._c_expr(e) for e in expr.elements) + return f"{{ {items} }}" + if isinstance(expr, ast.CastExpr): + return ( + f"/* CAST AS {self._c_type(expr.target_type)} */ " + f"({self._c_type(expr.target_type)})({self._c_expr(expr.operand)})" + ) + if isinstance(expr, ast.BuiltinExpr): + operand = self._c_expr(expr.operand) + if expr.name == "UPB": + return f"(sizeof({operand}) / sizeof(({operand})[0]) - 1)" + if expr.name == "TDSIZE": + return f"(sizeof({operand}) / sizeof(({operand})[0]))" + if expr.name in {"TYPEDESC", "VARDESC", "REFDESC"}: + return f"/* {expr.name} */ ({operand})" + if isinstance(expr, ast.Block): + return "/* block expr not supported at expression position */ 0" + return "/* unknown expr */ 0" + + def _struct_tag(self, spec: ast.StructType) -> str: + return "protel_struct" + + def _emit_struct_typedef(self, name: str, spec: ast.StructType): + self.types.declare([name], spec) + self.emit(f"typedef struct {{") + self.indent += 1 + for field_names, field_type in spec.fields: + for field_name in field_names: + self.emit(f"{self._c_type_decl(field_type, field_name)};") + self.indent -= 1 + self.emit(f"}} {name};") + + def _emit_symbolic_typedef(self, name: str, spec: ast.SymbolicRange): + enum_items = ", ".join(f"{member} = {idx}" for idx, member in enumerate(spec.members)) + self.emit(f"typedef enum {{ {enum_items} }} {name};") + + def _is_class_var_segment(self, attrs: list[str]) -> bool: + return "PROTECTED" in attrs or "SHARED" in attrs + + 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"self->{expr.member}" + return f"{self._c_expr(expr.base)}.{expr.member}" + + def _emit_class_typedef(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"typedef struct {name}_t {{") + self.indent += 1 + for part in spec.data_parts: + if 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._c_type_decl(field_type, field_name)};") + self.indent -= 1 + self.emit(f"}} {name};") + self.emit("") + for part in spec.data_parts: + if not self._is_class_var_segment(part.access_attrs): + continue + segment = "protected" if "PROTECTED" in part.access_attrs else "shared" + for field_names, field_type in part.fields: + for field_name in field_names: + class_vars.add(field_name) + self.emit( + f"static {self._c_type(field_type)} {name}_{field_name}; " + f"/* class var ({segment}) */" + ) + self.emit("") + self._class_vars[name] = class_vars + for section in spec.operations: + for method in section.methods: + for method_name in method.names: + method_map[method_name] = method + self.emit(self._method_prototype(name, method_name, method) + ";") + self.emit("") + self._class_methods[name] = method_map + + def _method_is_class_method(self, method: ast.MethodDecl) -> bool: + return "CLASS" in method.attrs + + def _method_prototype(self, class_name: str, method_name: str, method: ast.MethodDecl) -> str: + ret = self._c_type(method.return_type) if method.return_type else "void" + args = self._method_parm_list(class_name, method) + return f"{ret} {class_name}_{method_name}({args})" + + def _method_parm_list(self, class_name: str, method: ast.MethodDecl) -> str: + parts: list[str] = [] + if not self._method_is_class_method(method): + parts.append(f"{class_name} *{self._current_self}") + proc_parts = self._c_parm_list(method.parms) + if proc_parts != "void": + parts.append(proc_parts) + if not parts: + return "void" + return ", ".join(parts) + + 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._method_impls.append((impl.class_name, decl, method_decl)) + else: + self._emit_toplevel_decl(decl) + for stmt in impl.statements: + self._emit_stmt(stmt) + self.emit("") + + def _emit_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) + if method_decl is not None: + self.emit(self._method_prototype(class_name, impl.name, method_decl)) + else: + self.emit(f"void {class_name}_{impl.name}(void)") + self.emit("{") + self.indent += 1 + if not is_class_method: + self._current_self = "self" + else: + self._current_self = class_name + self._emit_block_body(impl.body) + self.indent -= 1 + self.emit("}") + self.emit("") + self._current_class = None + self._current_self = "self" + + def _decl_type_name(self, spec) -> str | None: + spec = self._unwrap_type(spec) + spec = self.types.resolve(spec) + if isinstance(spec, ast.DefinedType): + return spec.name + if isinstance(spec, ast.ClassType): + return spec.end_name + return None + + def _method_class_name(self, call: ast.MethodCall) -> str | None: + if call.receiver is None: + return self._current_class + if isinstance(call.receiver, ast.VarRef): + if call.receiver.is_self: + return self._current_class + 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 self._current_class + + def _method_call_args(self, call: ast.MethodCall, args: str) -> str: + class_name = self._method_class_name(call) + method_decl = None + if class_name and class_name in self._class_methods: + method_decl = self._class_methods[class_name].get(call.name) + if method_decl is not None and not self._method_is_class_method(method_decl): + receiver = self._c_expr(call.receiver) if call.receiver is not None else self._current_self + if isinstance(call.receiver, ast.VarRef) and not call.receiver.is_self: + receiver = f"&{receiver}" + if args: + return f"{receiver}, {args}" + return receiver + return args + + def _emit_for(self, stmt: ast.ForStmt): + if stmt.over_type is not None: + members = self._symbolic_members(stmt.over_type) + if members: + self.emit("{") + self.indent += 1 + self.emit(f"{self._c_type(stmt.over_type)} {stmt.var};") + for member in members: + self.emit(f"{stmt.var} = {member};") + self.emit("{") + self.indent += 1 + for s in stmt.body: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + self.indent -= 1 + self.emit("}") + return + from_expr = self._c_expr(stmt.from_expr) if stmt.from_expr is not None else "0" + to_expr = self._c_expr(stmt.to_expr) if stmt.to_expr is not None else "0" + by_expr = self._c_expr(stmt.by_expr) if stmt.by_expr is not None else "1" + cmp = "<=" if stmt.direction != "DOWN" else ">=" + self.emit(f"for (int32_t {stmt.var} = {from_expr}; {stmt.var} {cmp} {to_expr}; {stmt.var} += {by_expr}) {{") + self.indent += 1 + if stmt.while_expr is not None: + self.emit(f"if (!({self._c_expr(stmt.while_expr)})) break;") + for s in stmt.body: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + + def _emit_over(self, stmt: ast.OverStmt): + members = self._symbolic_members(stmt.over_type) + if not members: + self.emit("/* OVER unsupported type */ {") + self.indent += 1 + for s in stmt.body: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + return + for member in members: + self.emit("{") + self.indent += 1 + for s in stmt.body: + self._emit_stmt(s) + self.indent -= 1 + self.emit("}") + + def _symbolic_members(self, spec) -> list[str]: + spec = self.types.resolve(self._unwrap_type(spec)) + if isinstance(spec, ast.SymbolicRange): + return list(spec.members) + if isinstance(spec, ast.DefinedType): + resolved = self.types.resolve(spec) + if isinstance(resolved, ast.SymbolicRange): + return list(resolved.members) + return [] + + def _emit_case(self, stmt: ast.CaseStmt): + keyword = "SELECT" if stmt.is_select else "CASE" + self.emit(f"/* {keyword} */ switch ({self._c_expr(stmt.selector)}) {{") + self.indent += 1 + for arm in stmt.arms: + labels = self._case_labels(arm.labels) + for label in labels: + self.emit(f"case {label}:") + self.emit("{") + self.indent += 1 + for s in arm.statements: + self._emit_stmt(s) + self.emit("break;") + self.indent -= 1 + self.emit("}") + if stmt.out_statements: + self.emit("default:") + self.emit("{") + self.indent += 1 + for s in stmt.out_statements: + self._emit_stmt(s) + self.emit("break;") + self.indent -= 1 + self.emit("}") + self.indent -= 1 + self.emit("}") + + def _case_labels(self, labels) -> list[str]: + if isinstance(labels, ast.TupleLit): + out: list[str] = [] + for elem in labels.elements: + if isinstance(elem, ast.Literal): + if elem.kind == "string": + for ch in self._protel_string_chars(elem.value): + out.append(self._c_char_code(ord(ch))) + else: + out.append(str(elem.value)) + else: + out.append(self._c_expr(elem)) + return out + if isinstance(labels, ast.Literal) and labels.kind == "string": + return [ + self._c_char_code(ord(ch)) + for ch in self._protel_string_chars(labels.value) + ] + return [self._c_expr(labels)] + + def _c_proc_call_arg(self, call: ast.ProcCall, index: int, arg: Any) -> str: + if isinstance(arg, ast.Literal) and arg.kind == "string": + codes = [ord(ch) for ch in self._protel_string_chars(arg.value)] + if codes and codes[-1] != 0: + self._warn_missing_nul_terminator(call.name, arg.value) + return self._c_char_array_literal(codes) + if isinstance(arg, ast.TupleLit) and self._is_char_sequence_tuple(arg.elements): + codes = self._flatten_char_tuple_elements(arg.elements) + if not codes or codes[-1] != 0: + self._warn_missing_nul_terminator(call.name, None) + return self._c_char_array_literal(codes) + return self._c_expr(arg) + + def _warn_missing_nul_terminator(self, proc_name: str, protel_str: str | None) -> None: + import sys + + if protel_str is not None: + msg = ( + f"protel: warning: call to {proc_name} uses a PROTEL string without " + f"an explicit NUL (0) suffix; append ', 0' in a char tuple for C " + f"interoperability" + ) + else: + msg = ( + f"protel: warning: call to {proc_name} uses a char tuple without " + f"a trailing 0 byte for C interoperability" + ) + print(msg, file=sys.stderr) + + def _c_assign_target(self, target) -> str: + if isinstance(target, ast.VarRef): + return self._c_expr(target) + return self._c_expr(target) + + def _emit_area_typedef(self, name: str, spec: ast.AreaType) -> None: + opts = " ".join(spec.options) if spec.options else "" + self.emit(f"/* TYPE {name}: {opts} AREA({self._c_expr(spec.size_expr)}) */") + self.emit("struct {") + self.indent += 1 + for field_names, field_type in spec.fields: + for field_name in field_names: + self.emit(f"{self._c_type_decl(field_type, field_name)};") + self.indent -= 1 + self.emit(f"}} {name};") + + def _c_binop(self, op: str) -> str: + mapping = { + "->": "=", + "MOD": "%", + "^=": "!=", + "^": "^", + "&": "&", + "|": "|", + "INCL": "/* INCL */", + "NOTINCL": "/* NOTINCL */", + } + return mapping.get(op, op) + + def _c_string(self, protel_str: str) -> str: + codes = [ord(ch) for ch in self._protel_string_chars(protel_str)] + return self._c_char_array_literal(codes) + + +def transpile_to_c( + compilation_unit, + *, + classical: bool = False, + source_name: str = "input.protel", + source_path: "Path | None" = None, +) -> str: + from pathlib import Path + + 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 CTranspiler(classical=classical, source_name=source_name).transpile(compilation_unit) + + +def transpile_file(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_c(tree, classical=classical, source_name=source_name) \ No newline at end of file diff --git a/src/type_checker.py b/src/type_checker.py new file mode 100644 index 0000000..ce2c56f --- /dev/null +++ b/src/type_checker.py @@ -0,0 +1,338 @@ +"""Static type checking for PROTEL 2026 (Reference Manual §11, strong typing).""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from . import ast_nodes as ast +from .transpiler import TranspileError, TypeContext + + +class TypeCheckError(TranspileError): + """Raised when a PROTEL construct violates type-compatibility rules.""" + + +@dataclass(frozen=True) +class TypeInfo: + kind: str + name: str | None = None + low: int | None = None + high: int | None = None + packed_bits: int | None = None + pointee: TypeInfo | None = None + + def label(self) -> str: + if self.name: + return self.name + if self.kind == "bool": + return "BOOL" + if self.kind == "numeric" and self.low is not None and self.high is not None: + suffix = f" PACK({self.packed_bits})" if self.packed_bits else "" + return f"{{{self.low} TO {self.high}}}{suffix}" + if self.kind == "ptr" and self.pointee is not None: + return f"PTR TO {self.pointee.label()}" + return self.kind + + +class TypeChecker: + def __init__(self, *, source_name: str = "input.protel"): + self.source_name = source_name + self.types = TypeContext() + self._scopes: list[dict[str, TypeInfo]] = [{}] + self._return_type: TypeInfo | None = None + self._proc_name: str | None = None + + def check(self, compilation_unit: list[ast.Section]) -> None: + for section in compilation_unit: + self._check_section(section) + + def _fail(self, message: str) -> None: + raise TypeCheckError(f"{message} ({self.source_name})") + + def _literal_int(self, value: Any) -> int | None: + if isinstance(value, ast.Literal) and value.kind == "int": + return int(value.value) + return None + + def _resolve_spec(self, spec: Any) -> Any: + from lark import Tree + + while isinstance(spec, Tree): + spec = spec.children[0] if spec.children else spec + return self.types.resolve(spec) + + def _type_info(self, spec: Any) -> TypeInfo: + spec = self._resolve_spec(spec) + if isinstance(spec, ast.BoolType): + return TypeInfo( + kind="bool", + name="BOOL", + packed_bits=getattr(spec, "packed", None), + ) + if isinstance(spec, ast.RangeType): + return TypeInfo( + kind="numeric", + low=self._literal_int(spec.low), + high=self._literal_int(spec.high), + packed_bits=getattr(spec, "packed", None), + ) + if isinstance(spec, ast.DefinedType): + alias = self.types.aliases.get(spec.name) + if alias is not None: + base = self._type_info(alias) + return TypeInfo( + kind=base.kind, + name=spec.name, + low=base.low, + high=base.high, + packed_bits=base.packed_bits, + pointee=base.pointee, + ) + return TypeInfo(kind="defined", name=spec.name) + if isinstance(spec, ast.PtrType): + return TypeInfo( + kind="ptr", + pointee=self._type_info(spec.target), + ) + if isinstance(spec, ast.SymbolicRange): + return TypeInfo(kind="symbolic", name="{" + ", ".join(spec.members) + "}") + return TypeInfo(kind="unknown") + + def _bounds(self, info: TypeInfo) -> tuple[int, int] | None: + if info.low is not None and info.high is not None: + return info.low, info.high + if info.name and info.name in self.types.aliases: + return self._bounds(self._type_info(self.types.aliases[info.name])) + if info.name == "integer": + return -32768, 32767 + return None + + def _is_char_type(self, info: TypeInfo) -> bool: + if info.name == "char": + return True + bounds = self._bounds(info) + return bounds == (0, 255) + + def _is_wide_integer(self, info: TypeInfo) -> bool: + if info.name == "integer": + return True + bounds = self._bounds(info) + if bounds is None: + return False + low, high = bounds + if low == high: + return False + return low < 0 or high > 255 or (high - low) > 255 + + def _pointee_compatible(self, dest: TypeInfo, src: TypeInfo) -> bool: + if dest.name and src.name: + return dest.name == src.name + if dest.kind == "numeric" and src.kind == "numeric": + return dest.low == src.low and dest.high == src.high + return dest.kind == src.kind and dest.label() == src.label() + + def _compatible(self, dest: TypeInfo, src: TypeInfo) -> bool: + if dest.kind == "unknown" or src.kind == "unknown": + return True + if dest.kind == "bool": + return src.kind == "bool" + if dest.kind == "ptr" and src.kind == "ptr": + if src.pointee is not None and src.pointee.kind == "unknown": + return True + return ( + dest.pointee is not None + and src.pointee is not None + and self._pointee_compatible(dest.pointee, src.pointee) + ) + if self._is_char_type(dest) and self._is_wide_integer(src): + return False + if dest.packed_bits and self._is_wide_integer(src): + return False + if dest.name and src.name and dest.name == src.name: + return True + if dest.kind == "numeric" and src.kind == "numeric": + db = self._bounds(dest) + sb = self._bounds(src) + if db and sb: + return db[0] <= sb[0] and sb[1] <= db[1] + if dest.name and dest.name in self.types.aliases: + return self._compatible(self._type_info(self.types.aliases[dest.name]), src) + return False + + def _declare_types(self, decl: ast.TypeDecl) -> None: + self.types.declare(decl.names, decl.type_spec) + + def _declare_vars(self, names: list[str], type_spec: Any) -> None: + info = self._type_info(type_spec) + for name in names: + self._scopes[-1][name] = info + + def _lookup(self, name: str) -> TypeInfo | None: + for scope in reversed(self._scopes): + if name in scope: + return scope[name] + return None + + def _expr_type(self, expr: Any) -> TypeInfo: + if isinstance(expr, ast.Literal): + if expr.kind == "int": + value = int(expr.value) + return TypeInfo(kind="numeric", low=value, high=value) + if expr.kind in {"true", "false"}: + return TypeInfo(kind="bool", name="BOOL") + if expr.kind == "NIL".lower(): + return TypeInfo(kind="ptr", pointee=TypeInfo(kind="unknown")) + if isinstance(expr, ast.VarRef) and not expr.is_self and not expr.is_super: + return self._lookup(expr.name) or TypeInfo(kind="unknown") + if isinstance(expr, ast.BinExpr) and expr.op in {"+", "-", "*", "/", "MOD"}: + left = self._expr_type(expr.left) + right = self._expr_type(expr.right) + if self._is_wide_integer(left) or self._is_wide_integer(right): + return TypeInfo(kind="numeric", name="integer", low=-32768, high=32767) + lb = [t.low for t in (left, right) if t.low is not None] + hb = [t.high for t in (left, right) if t.high is not None] + if lb and hb: + return TypeInfo(kind="numeric", low=min(lb), high=max(hb)) + if isinstance(expr, ast.CastExpr): + return self._type_info(expr.target_type) + return TypeInfo(kind="unknown") + + def _check_assignment(self, target: Any, value: Any, *, context: str) -> None: + if not isinstance(target, ast.VarRef) or target.is_self or target.is_super: + return + dest = self._lookup(target.name) + if dest is None: + self._fail(f"unknown identifier {target.name!r} in {context}") + src = self._expr_type(value) + if dest.packed_bits and self._is_wide_integer(src): + self._fail( + f"cannot assign wide integer to packed byte-sized type " + f"{dest.label()} in {context}" + ) + if self._is_char_type(dest) and self._is_wide_integer(src): + self._fail(f"cannot assign integer to char in {context}") + if ( + dest.kind == "numeric" + and src.kind == "numeric" + and src.low is not None + and src.high is not None + and src.low == src.high + ): + db = self._bounds(dest) + if db and (src.low < db[0] or src.high > db[1]): + self._fail( + f"value {src.low}..{src.high} is out of range for " + f"{dest.label()} in {context}" + ) + if not self._compatible(dest, src): + self._fail( + f"cannot assign {src.label()} to {dest.label()} in {context}" + ) + + def _check_return(self, value: Any | None) -> None: + if self._return_type is None: + if value is not None: + self._fail(f"procedure {self._proc_name!r} cannot RETURN a value") + return + if value is None: + self._fail( + f"procedure {self._proc_name!r} must RETURN {self._return_type.label()}" + ) + src = self._expr_type(value) + if not self._compatible(self._return_type, src): + self._fail( + f"RETURN type {src.label()} is not compatible with " + f"RETURNS {self._return_type.label()} in procedure {self._proc_name!r}" + ) + + def _check_block(self, block: ast.Block) -> None: + self._scopes.append({}) + for decl in block.declarations: + if isinstance(decl, ast.TypeDecl): + self._declare_types(decl) + elif isinstance(decl, ast.VarDecl) and decl.names: + self._declare_vars(decl.names, decl.type_spec) + if decl.init is not None: + for name in decl.names: + self._check_assignment( + ast.VarRef(name=name), + decl.init, + context=f"initialization of {name!r}", + ) + for stmt in block.statements: + self._check_stmt(stmt) + self._scopes.pop() + + def _check_stmt(self, stmt: Any) -> None: + if isinstance(stmt, ast.Block): + self._check_block(stmt) + elif isinstance(stmt, ast.IfStmt): + for part in (stmt.then_part, stmt.else_part): + for inner in part: + self._check_stmt(inner) + elif isinstance(stmt, ast.LoopStmt): + for inner in stmt.body: + self._check_stmt(inner) + elif isinstance(stmt, ast.ForStmt): + for inner in stmt.body: + self._check_stmt(inner) + elif isinstance(stmt, ast.OverStmt): + for inner in stmt.body: + self._check_stmt(inner) + elif isinstance(stmt, ast.CaseStmt): + for arm in stmt.arms: + for inner in arm.statements: + self._check_stmt(inner) + for inner in stmt.out_statements: + self._check_stmt(inner) + elif isinstance(stmt, ast.ReturnStmt): + self._check_return(stmt.value) + elif isinstance(stmt, ast.AssignExpr): + self._check_assignment( + stmt.target, stmt.value, context="assignment statement" + ) + + def _check_procedure(self, proc: ast.ProcDecl) -> None: + if proc.body is None: + return + self._scopes.append({}) + self._proc_name = proc.name + self._return_type = ( + self._type_info(proc.return_type) if proc.return_type else None + ) + for names, type_spec, _mode in proc.parms: + self._declare_vars(names, type_spec) + self._check_block(proc.body) + self._return_type = None + self._proc_name = None + self._scopes.pop() + + def _check_section(self, section: ast.Section) -> None: + self._scopes.append({}) + for decl in section.declarations: + if isinstance(decl, ast.TypeDecl): + self._declare_types(decl) + elif isinstance(decl, ast.VarDecl) and decl.names: + self._declare_vars(decl.names, decl.type_spec) + if decl.init is not None: + for name in decl.names: + self._check_assignment( + ast.VarRef(name=name), + decl.init, + context=f"initialization of {name!r}", + ) + elif isinstance(decl, ast.ProcDecl) and decl.body is not None: + if not ( + decl.external or decl.export or decl.forward or decl.intrinsic + ): + self._check_procedure(decl) + self._scopes.pop() + + +def check_types( + compilation_unit: list[ast.Section], + *, + source_name: str = "input.protel", +) -> None: + TypeChecker(source_name=source_name).check(compilation_unit) \ No newline at end of file diff --git a/tests/ref_manual_manifest.py b/tests/ref_manual_manifest.py new file mode 100644 index 0000000..28d7702 --- /dev/null +++ b/tests/ref_manual_manifest.py @@ -0,0 +1,109 @@ +"""Reference Manual section and keyword coverage registry (oflpr TOC).""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +EXAMPLES = ROOT / "examples" +REF = EXAMPLES / "ref" + +# Every numbered Reference Manual section maps to at least one example or test corpus file. +REFERENCE_MANUAL_SECTIONS: dict[str, list[str]] = { + "1.0": ["ref/ref_1_0_introduction.protel"], + "2.0": ["ref/ref_9_1_expressions.protel"], + "3.0": ["ref/ref_3_0_lexical.protel"], + "3.1": ["ref/ref_3_0_lexical.protel"], + "3.2": ["ref/ref_3_0_lexical.protel"], + "3.3": ["ref/ref_3_0_lexical.protel"], + "3.4": ["ref/ref_3_0_lexical.protel"], + "4.0": ["ref/ref_4_0_data_elements.protel"], + "4.1": ["ref/ref_4_0_data_elements.protel"], + "4.2": ["ref/ref_4_0_data_elements.protel"], + "4.3": ["ref/ref_4_0_data_elements.protel"], + "4.4": ["ref/ref_4_0_data_elements.protel"], + "4.5": ["ref/ref_4_0_data_elements.protel"], + "5.0": [ + "ref/ref_5_0_compilation_unit.protel", + "ref/ref_5_0_directives.aa01", + "Hello.aa01", + ], + "6.0": ["ref/ref_6_0_module_types.protel"], + "7.0": ["ref/ref_7_0_declarations.protel"], + "7.1": ["ref/ref_7_1_1_simple_types.protel", "ref/ref_7_1_2_aggregates.protel"], + "7.1.1": ["ref/ref_7_1_1_simple_types.protel"], + "7.1.1.1": ["ref/ref_7_1_1_simple_types.protel"], + "7.1.1.2": ["intro_2_1_types.protel"], + "7.1.1.3": ["ref/ref_7_1_1_simple_types.protel", "intro_2_1_types.protel"], + "7.1.1.4": ["ref/ref_7_1_1_simple_types.protel"], + "7.1.1.5": ["ref/ref_7_1_1_simple_types.protel"], + "7.1.2": ["ref/ref_7_1_2_aggregates.protel"], + "7.1.2.1": ["ref/ref_7_1_2_aggregates.protel"], + "7.1.2.2": ["ref/ref_7_1_2_aggregates.protel", "ref_8_1_task_block_struct.protel"], + "7.1.2.3": ["intro_2_1_types.protel", "intro_3_2_6_sum_table.protel"], + "7.1.2.4": ["intro_2_1_types.protel"], + "7.1.2.5": ["ref/ref_7_1_2_aggregates.protel"], + "7.1.3": ["ref/ref_7_1_3_procedures.protel"], + "7.1.3.1": ["ref/ref_7_1_3_procedures.protel"], + "7.1.3.2": ["ref/ref_7_1_3_procedures.protel"], + "7.2": ["ref/ref_7_2_data_declarations.protel"], + "7.2.1": ["ref/ref_7_2_data_declarations.protel"], + "7.2.2": ["intro_2_2_calculate_average.protel"], + "7.2.3": ["ref/ref_7_2_data_declarations.protel"], + "7.3": ["ref/ref_7_3_overlays.protel"], + "8.0": ["ref/ref_8_0_scope.protel"], + "8.1": ["ref/ref_8_0_scope.protel"], + "8.2": ["ref/ref_8_0_scope.protel"], + "9.0": ["ref/ref_9_0_statements.protel"], + "9.1": ["ref/ref_9_1_expressions.protel"], + "9.1.1": ["ref/ref_9_1_expressions.protel"], + "9.1.1.1": ["ref/ref_4_0_data_elements.protel"], + "9.1.1.2": ["ref/ref_9_1_expressions.protel"], + "9.1.1.3": ["ref/ref_7_1_3_procedures.protel"], + "9.1.2": ["ref/ref_9_1_expressions.protel"], + "9.2": ["ref/ref_9_2_return.protel", "intro_5_5_2_args_exit.protel"], + "9.3": ["ref/ref_9_3_if.protel"], + "9.4": ["ref/ref_9_4_case.protel", "intro_3_2_4_case.protel"], + "9.5": ["ref/ref_9_5_select.protel"], + "9.6": ["ref/ref_9_6_exit.protel"], + "9.7": [ + "ref/ref_9_7_iterative.protel", + "intro_1_3_factorial.protel", + "intro_1_3_factorial_cli.protel", + "intro_3_2_6_sum_table.protel", + ], + "10.0": ["ref/ref_10_0_bind_with.protel"], + "11.0": ["ref/ref_11_0_type_compat.protel"], + "11.1": ["ref/ref_11_0_type_compat.protel"], + "11.2": ["ref/ref_11_0_type_compat.protel"], + "11.3": ["ref/ref_11_0_type_compat.protel"], + "12.0": ["ref/ref_12_0_intrinsic.protel"], + "13.0": [ + "ref/ref_13_0_descriptors.protel", + "interop/protel_for_python.protel", + "interop/protel_calls_python.protel", + "Hello.protel", + ], + "14.0": ["ref/ref_14_0_keyword_exercise.protel"], + "15.0": ["tests/test_parser.py"], + "16.0": ["tests/ref_manual_manifest.py"], + "OO": ["ref/ref_oo_classes.protel", "ref_oo_class_with_var.protel", "ref_oo_class_method_invoke.protel"], +} + +# Keywords exercised outside .protel examples (preprocessor / tooling). +KEYWORD_EXTERNAL_SOURCES: dict[str, list[str]] = { + "$EJECT": ["ref/ref_5_0_directives.aa01", "tests/test_pb.py"], + "$LI": ["ref/ref_5_0_directives.aa01", "vdi.aa01", "tests/test_pb.py"], + "$OBJECT": ["ref/ref_oo_classes.protel", "ref_oo_class_with_var.protel"], + "$REFDESC": ["ref/ref_9_1_expressions.protel"], + "$TYPEDESC": ["ref/ref_9_1_expressions.protel"], + "$UNIVERSAL_PTR": ["ref/ref_9_1_expressions.protel"], + "$VARDESC": ["ref/ref_9_1_expressions.protel"], +} + +# All ref_* and intro_* example files that must parse. +REF_EXAMPLE_SOURCES: list[str] = sorted( + p.relative_to(EXAMPLES).as_posix() + for p in EXAMPLES.rglob("*.protel") + if p.is_file() and not p.name.endswith("~") +) \ No newline at end of file diff --git a/tests/test_args_exit.py b/tests/test_args_exit.py new file mode 100644 index 0000000..54b9c3a --- /dev/null +++ b/tests/test_args_exit.py @@ -0,0 +1,73 @@ +"""ENTRY argc/argv and RETURN exit status (Introductory Manual §5.5.2).""" + +import subprocess +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel +from src.transpiler import TranspileError + +ROOT = Path(__file__).resolve().parent.parent +EXAMPLE = ROOT / "examples" / "intro_5_5_2_args_exit.protel" +PROTEL = ROOT / "protel" +PYTHON = ROOT / ".venv" / "bin" / "python" + + +def test_parse_entry_with_unix_argv_parms(): + tree = parse_protel( + "SECTION demo;\n" + "TYPE integer {-1 TO 1};\n" + "TYPE char {0 TO 255};\n" + "DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;\n" + ) + decl = tree[0].declarations[-1] + assert decl.entry + assert decl.name == "Start" + assert len(decl.parms) == 2 + + +def test_entry_unix_argv_emits_main_with_forwarding(): + source = EXAMPLE.read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name=EXAMPLE.name) + assert "int main(int argc, char** argv)" in cpp + assert "return protel_generated::ArgsExit::Start(argc, argv);" in cpp + assert "int16_t Start(int16_t argc, char * * argv)" in cpp + + +def test_entry_parm_mismatch_raises(): + with pytest.raises(TranspileError, match="parameters must match"): + transpile_to_cpp( + parse_protel( + "SECTION s;\n" + "TYPE integer {-1 TO 1};\n" + "TYPE char {0 TO 255};\n" + "DCL Start PROC(argc integer, argv PTR TO PTR TO char) IS ENTRY;\n" + "DCL Start PROC() RETURNS integer IS BLOCK RETURN 0; ENDBLOCK;\n" + ) + ) + + +def test_args_exit_compiles_prints_and_returns_argc(): + binary = ROOT / "build" / "ArgsExit_test" + result = subprocess.run( + [ + str(PYTHON), + str(PROTEL), + str(EXAMPLE), + "-o", + str(binary), + "--run", + "--", + "one", + "two", + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 3, result.stderr + lines = [line for line in result.stdout.splitlines() if line.strip()] + assert lines[-2:] == ["one", "two"] + assert lines[0].endswith("ArgsExit_test") or "ArgsExit" in lines[0] \ No newline at end of file diff --git a/tests/test_cpp_transpiler.py b/tests/test_cpp_transpiler.py new file mode 100644 index 0000000..de6766f --- /dev/null +++ b/tests/test_cpp_transpiler.py @@ -0,0 +1,118 @@ +"""C++ transpiler and Hello World tests.""" + +import os +import stat +import subprocess +from pathlib import Path + +from src.parser import parse_protel +from src.cpp_transpiler import transpile_to_cpp + +ROOT = Path(__file__).resolve().parent.parent +EXAMPLES = ROOT / "examples" +PROTEL = ROOT / "protel" + + +def _transpile_hello() -> str: + source = (EXAMPLES / "Hello.protel").read_text(encoding="utf-8") + tree = parse_protel(source) + return transpile_to_cpp(tree, source_name="Hello.protel") + + +def test_cpp_hello_emits_namespace_and_main(): + cpp = _transpile_hello() + assert "namespace protel_generated" in cpp + assert "namespace Hello" in cpp + assert "IS ENTRY" in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8") + assert "void Start()" in cpp + assert 'extern "C"' in cpp + assert "void writeln(const char* msg)" in cpp + assert "" not in cpp + assert "IS INTRINSIC" not in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8") + assert "EXTERNAL" in (EXAMPLES / "Hello.protel").read_text(encoding="utf-8") + assert "int main()" in cpp + assert "protel_generated::Hello::Start()" in cpp + assert "(const char[]){" in cpp + assert ", 0 }" in cpp + assert '"Hello, World!"' not in cpp + + +def test_cpp_hello_class_uses_this(): + source = (EXAMPLES / "ref_oo_class_with_var.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="ref_oo_class_with_var.protel") + assert "class class_with_var" in cpp + assert "static int16_t class_var" in cpp + assert "class_with_var::class_method" in cpp + assert "class_with_var::class_var = 5" in cpp + assert "void class_with_var::instance_method" in cpp + assert "this->instance_var" in cpp + + +def test_hello_compiles_and_runs(): + result = subprocess.run( + [ + str(ROOT / ".venv/bin/python"), + str(PROTEL), + str(EXAMPLES / "Hello.protel"), + "-o", + str(ROOT / "build" / "Hello"), + "--run", + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 0, result.stderr + assert "Hello, World!" in result.stdout + + +def test_hello_shebang_direct_execution(): + hello = EXAMPLES / "Hello.protel" + assert hello.read_text(encoding="utf-8").startswith("#!/usr/bin/env protel-run") + mode = hello.stat().st_mode + hello.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + env = dict(os.environ) + env["PATH"] = f"{ROOT}:{env.get('PATH', '')}" + result = subprocess.run( + [str(hello.resolve())], + capture_output=True, + text=True, + cwd=ROOT, + env=env, + ) + assert result.returncode == 0, result.stderr + assert "Hello, World!" in result.stdout + + +def test_hello_compiles_and_runs_a_out(): + result = subprocess.run( + [str(ROOT / ".venv/bin/python"), str(PROTEL), "examples/Hello.protel", "--run"], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 0, result.stderr + assert "Hello, World!" in result.stdout + assert (ROOT / "a.out").exists() + + +def test_cpp_oo_examples_compile(): + from src.compile import check_cpp_syntax + + for name in ("ref_oo_class_with_var.protel", "ref_oo_class_method_invoke.protel"): + source = EXAMPLES / name + tree = parse_protel(source.read_text(encoding="utf-8")) + cpp = transpile_to_cpp(tree, source_name=name) + cpp_path = ROOT / "build" / f"{name.replace('.protel', '.cpp')}" + cpp_path.parent.mkdir(parents=True, exist_ok=True) + cpp_path.write_text(cpp, encoding="utf-8") + check_cpp_syntax(cpp_path) + + +def test_parse_external_proc(): + tree = parse_protel( + "SECTION s;\nDCL writeln PROC(msg PTR TO char) EXTERNAL;\n" + ) + decl = tree[0].declarations[0] + assert decl.external + assert decl.name == "writeln" \ No newline at end of file diff --git a/tests/test_emacs_extensions.py b/tests/test_emacs_extensions.py new file mode 100644 index 0000000..e873705 --- /dev/null +++ b/tests/test_emacs_extensions.py @@ -0,0 +1,92 @@ +"""PROTEL file extension conventions (Emacs mode + compiler driver).""" + +import re +import subprocess +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.extensions import format_suffix_list, is_pls_suffix, is_protel_source, is_protel_suffix +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +EXAMPLES = ROOT / "examples" +MODE_EL = ROOT / "emacs" / "protel-mode.el" +PROTEL = ROOT / "protel" + + +@pytest.mark.parametrize( + "name,expected", + [ + ("Hello.protel", True), + ("Hello.P", True), + ("Hello.p", True), + ("Hello.pt", True), + ("Hello.ptl", True), + ("vdi.aa01", True), + ("module.AB18", True), + ("module.ZZ99", True), + ("module.aa00", True), + ("readme.txt", False), + ("bad.A1", False), + ("bad.ABC1", False), + ("bad.1A01", False), + ("bad.AA1", False), + ], +) +def test_is_protel_source_recognizes_fixed_and_pls_suffixes(name, expected): + assert is_protel_source(name) is expected + + +def test_is_pls_suffix_matches_letter_digit_pattern(): + assert is_pls_suffix(".aa01") + assert is_pls_suffix(".AB99") + assert not is_pls_suffix(".protel") + + +def test_format_suffix_list_mentions_pls_range(): + text = format_suffix_list() + assert ".AA01" in text + assert ".ZZ99" in text + + +def test_protel_mode_registers_legacy_p_extension(): + source = MODE_EL.read_text(encoding="utf-8") + assert re.search(r'auto-mode-alist.*\\\.P\\', source) + + +def test_protel_mode_font_locks_shebang_as_comment(): + source = MODE_EL.read_text(encoding="utf-8") + assert '(list "^#![^\\n]*" 0 \'font-lock-comment-face)' in source + + +def test_protel_mode_registers_pls_edition_suffixes(): + source = MODE_EL.read_text(encoding="utf-8") + assert "PLS edition suffixes" in source + assert "[A-Za-z][A-Za-z][0-9][0-9]" in source + + +def test_hello_p_transpiles(): + legacy = (EXAMPLES / "Hello.P").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(legacy), source_name="Hello.P") + assert "protel_generated::Hello::Start()" in cpp + assert "writeln(" in cpp + + +def test_hello_pls_transpiles(): + pls = (EXAMPLES / "Hello.aa01").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(pls), source_name="Hello.aa01") + assert "protel_generated::Hello::Start()" in cpp + assert "writeln(" in cpp + + +def test_protel_driver_accepts_pls_suffix_without_warning(): + result = subprocess.run( + [str(ROOT / ".venv/bin/python"), str(PROTEL), str(EXAMPLES / "Hello.aa01"), "--emit-c"], + cwd=ROOT, + capture_output=True, + text=True, + ) + assert result.returncode == 0 + assert "does not use a PROTEL extension" not in result.stderr \ No newline at end of file diff --git a/tests/test_entry.py b/tests/test_entry.py new file mode 100644 index 0000000..fee3407 --- /dev/null +++ b/tests/test_entry.py @@ -0,0 +1,55 @@ +"""ENTRY procedure tests (Introductory Manual 5.5.2).""" + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel +from src.transpiler import TranspileError + + +def test_parse_entry_declaration(): + tree = parse_protel("SECTION demo;\nDCL Start PROC() IS ENTRY;\n") + decl = tree[0].declarations[0] + assert decl.entry + assert decl.name == "Start" + assert decl.body is None + + +def test_entry_emits_c_main_wrapper(): + source = """ +SECTION Hello; +DCL Start PROC() IS ENTRY; +DCL Start PROC() IS BLOCK ENDBLOCK; +""" + cpp = transpile_to_cpp(parse_protel(source), source_name="Hello.protel") + assert "/* ENTRY Start */" in cpp + assert "void Start()" in cpp + assert "int main()" in cpp + assert "protel_generated::Hello::Start();" in cpp + assert "return 0;" in cpp + + +def test_procedure_named_main_without_entry_has_no_c_main(): + source = """ +SECTION demo; +DCL main PROC() IS BLOCK ENDBLOCK; +""" + cpp = transpile_to_cpp(parse_protel(source), source_name="demo.protel") + assert "void main()" in cpp + assert "int main()" not in cpp + + +def test_missing_entry_body_raises(): + with pytest.raises(TranspileError, match="has no procedure body"): + transpile_to_cpp(parse_protel("SECTION s;\nDCL Start PROC() IS ENTRY;\n")) + + +def test_multiple_entry_raises(): + with pytest.raises(TranspileError, match="multiple ENTRY"): + transpile_to_cpp( + parse_protel( + "SECTION s;\n" + "DCL Start PROC() IS ENTRY;\n" + "DCL Other PROC() IS ENTRY;\n" + ) + ) \ No newline at end of file diff --git a/tests/test_factorial_cli.py b/tests/test_factorial_cli.py new file mode 100644 index 0000000..60a1b25 --- /dev/null +++ b/tests/test_factorial_cli.py @@ -0,0 +1,76 @@ +"""Factorial CLI example: USES §1.3 module + printf/atoi C interop.""" + +import subprocess +from pathlib import Path + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +EXAMPLE = ROOT / "examples" / "intro_1_3_factorial_cli.protel" +FACTORIAL = ROOT / "examples" / "intro_1_3_factorial.protel" +PROTEL = ROOT / "protel" +PYTHON = ROOT / ".venv" / "bin" / "python" + + +def test_factorial_cli_transpile_uses_and_externals(): + source = EXAMPLE.read_text(encoding="utf-8") + cpp = transpile_to_cpp( + parse_protel(source), + source_name=EXAMPLE.name, + source_path=EXAMPLE, + ) + assert "/* USES: factorial_demo */" in cpp + assert "using factorial_demo::factorial;" in cpp + assert "int16_t factorial(int16_t n)" in cpp + assert "#include " in cpp + assert "#include " in cpp + assert "int main(int argc, char** argv)" in cpp + + +def test_factorial_source_unchanged(): + text = FACTORIAL.read_text(encoding="utf-8") + assert "SECTION factorial_demo;" in text + assert "IS ENTRY" not in text + assert "USES" not in text + + +def test_factorial_cli_compiles_and_prints_result(): + binary = ROOT / "build" / "factorial_cli_test" + result = subprocess.run( + [ + str(PYTHON), + str(PROTEL), + str(EXAMPLE), + "-o", + str(binary), + "--run", + "--", + "5", + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 0, result.stderr + assert "5! = 120" in result.stdout + + +def test_factorial_cli_usage_exit_status(): + binary = ROOT / "build" / "factorial_cli_usage" + result = subprocess.run( + [ + str(PYTHON), + str(PROTEL), + str(EXAMPLE), + "-o", + str(binary), + "--run", + "--", + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 1, result.stderr + assert "Usage: factorial N" in result.stdout \ No newline at end of file diff --git a/tests/test_java_interop.py b/tests/test_java_interop.py new file mode 100644 index 0000000..aadf129 --- /dev/null +++ b/tests/test_java_interop.py @@ -0,0 +1,56 @@ +"""Java interop example tests (transpile + optional link).""" + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +INTEROP = ROOT / "examples" / "interop" + + +def _java_runtime_available() -> bool: + if shutil.which("javac") is None or shutil.which("java") is None: + return False + try: + subprocess.run(["java", "-version"], capture_output=True, check=True) + return True + except (subprocess.CalledProcessError, FileNotFoundError): + return False + + +def test_protel_calls_java_emits_external_java_greet(): + source = (INTEROP / "protel_calls_java.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_java.protel") + assert 'extern "C"' in cpp + assert "void java_greet(const char* name, int16_t value)" in cpp + assert "java_greet(" in cpp + assert "protel_generated::protel_calls_java::Start()" in cpp + + +def test_protel_for_java_exports_c_linkage(): + source = (INTEROP / "protel_for_java.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_java.protel") + assert "/* EXPORT protel_add" in cpp + assert "int16_t protel_add(int16_t a, int16_t b)" in cpp + assert "return (a + b)" in cpp + assert "int main()" not in cpp + + +def test_java_calls_protel_uses_jni_bridge(): + bridge = (INTEROP / "java_calls_protel.c").read_text(encoding="utf-8") + java_src = (INTEROP / "JavaCallsProtel.java").read_text(encoding="utf-8") + assert "Java_JavaCallsProtel_protelAdd" in bridge + assert "protel_add" in bridge + assert "System.loadLibrary" in java_src + assert "native short protelAdd" in java_src + + +@pytest.mark.skipif(not _java_runtime_available(), reason="JDK not installed") +def test_java_interop_examples_build_and_run(): + script = INTEROP / "build_interop_java.sh" + subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True) \ No newline at end of file diff --git a/tests/test_parser.py b/tests/test_parser.py new file mode 100644 index 0000000..04598af --- /dev/null +++ b/tests/test_parser.py @@ -0,0 +1,158 @@ +"""Parser tests correlated to PROTEL 2026 manuals.""" + +from pathlib import Path + +import pytest + +from src.parser import parse_protel +from src import ast_nodes as ast + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" + + +def _read(name: str) -> str: + return (EXAMPLES / name).read_text(encoding="utf-8") + + +def test_parse_section_uses_and_of(): + tree = parse_protel( + "SECTION ref_provider;\n" + "SECTION ref_consumer OF ref_provider USES ref_provider;\n" + ) + assert tree[1].of_modules == ["ref_provider"] + assert tree[1].uses_modules == ["ref_provider"] + + +def test_parse_factorial_example(): + tree = parse_protel(_read("intro_1_3_factorial.protel")) + assert len(tree) == 1 + section = tree[0] + assert isinstance(section, ast.Section) + assert section.name == "factorial_demo" + + proc = next(d for d in section.declarations if isinstance(d, ast.ProcDecl)) + assert proc.name == "factorial" + assert proc.return_type is not None + assert isinstance(proc.body, ast.Block) + assert any(isinstance(s, ast.LoopStmt) for s in proc.body.statements) + + +def test_parse_types_example(): + tree = parse_protel(_read("intro_2_1_types.protel")) + section = tree[0] + type_names = {d.names[0] for d in section.declarations if isinstance(d, ast.TypeDecl)} + assert "integer" in type_names + assert "digit_register" in type_names + assert "features_table" in type_names + + +def test_parse_calculate_average(): + tree = parse_protel(_read("intro_2_2_calculate_average.protel")) + proc = next( + d for d in tree[0].declarations if isinstance(d, ast.ProcDecl) + ) + assert proc.name == "calculate_average" + assert len(proc.parms) == 1 + assert proc.parms[0][0] == ["number_1", "number_2"] + + +def test_classical_keyword_casing(): + source = """ + section demo; + type integer {-32768 to 32767}; + dcl x integer; + """ + tree = parse_protel(source, classical=True) + assert tree[0].name == "demo" + type_decl = next(d for d in tree[0].declarations if isinstance(d, ast.TypeDecl)) + assert type_decl.names == ["integer"] + + +def test_parse_case_statement(): + tree = parse_protel(_read("intro_3_2_4_case.protel")) + proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl)) + case_stmt = proc.body.statements[0] + assert isinstance(case_stmt, ast.CaseStmt) + assert len(case_stmt.arms) == 3 + assert case_stmt.out_statements == [] + + +def test_parse_for_loop_with_upb(): + tree = parse_protel(_read("intro_3_2_6_sum_table.protel")) + proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl)) + for_stmt = next(s for s in proc.body.statements if isinstance(s, ast.ForStmt)) + assert for_stmt.var == "i" + assert isinstance(for_stmt.to_expr, ast.BuiltinExpr) + assert for_stmt.to_expr.name == "UPB" + + +def test_parse_struct_type(): + tree = parse_protel(_read("ref_8_1_task_block_struct.protel")) + task_block = next( + d for d in tree[0].declarations + if isinstance(d, ast.TypeDecl) and d.names == ["task_block"] + ) + assert isinstance(task_block.type_spec, ast.StructType) + assert len(task_block.type_spec.fields) == 5 + + +def test_var_init_not_wrapped_in_tree(): + tree = parse_protel(_read("intro_2_1_types.protel")) + primes = next(d for d in tree[0].declarations if isinstance(d, ast.VarDecl) and "primes" in d.names) + assert isinstance(primes.init, ast.TupleLit) + + +def test_parse_class_type_with_operations(): + tree = parse_protel(_read("ref_oo_class_with_var.protel")) + section = tree[0] + assert section.section_kind == "INTERFACE" + class_decl = next( + d for d in section.declarations + if isinstance(d, ast.TypeDecl) and d.names == ["class_with_var"] + ) + spec = class_decl.type_spec + assert isinstance(spec, ast.ClassType) + assert spec.end_name == "class_with_var" + assert spec.base.name == "$OBJECT" + assert len(spec.data_parts) == 2 + assert spec.data_parts[0].access_attrs == ["PROTECTED"] + method = spec.operations[0].methods[0] + assert method.names == ["class_method"] + assert method.attrs == ["CLASS"] + assert len(section.class_impls) == 1 + assert section.class_impls[0].class_name == "class_with_var" + + +def test_parse_class_method_invocation(): + tree = parse_protel(_read("ref_oo_class_method_invoke.protel")) + proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl)) + assert isinstance(proc.body.statements[0], ast.MethodCall) + assert proc.body.statements[0].name == "class_method" + assert isinstance(proc.body.statements[1], ast.MethodCall) + + +def test_parse_self_member_assignment(): + tree = parse_protel(_read("ref_oo_class_with_var.protel")) + impl = tree[0].class_impls[0] + stmt = impl.declarations[0].body.statements[0] + assert isinstance(stmt, ast.AssignExpr) + assert isinstance(stmt.target, ast.MemberRef) + assert stmt.target.member == "class_var" + + +def test_assignment_expression_chaining(): + source = """ + SECTION demo; + TYPE integer {-32768 TO 32767}; + DCL p PROC() IS + BLOCK + DCL a, b, c integer; + 1 -> a -> b -> c; + ENDBLOCK; + """ + tree = parse_protel(source) + proc = next(d for d in tree[0].declarations if isinstance(d, ast.ProcDecl)) + stmt = proc.body.statements[0] + assert isinstance(stmt, ast.AssignExpr) + assert isinstance(stmt.target, ast.VarRef) + assert stmt.target.name == "c" \ No newline at end of file diff --git a/tests/test_pb.py b/tests/test_pb.py new file mode 100644 index 0000000..c49a526 --- /dev/null +++ b/tests/test_pb.py @@ -0,0 +1,48 @@ +"""Pb beautifier tests.""" + +import importlib.util +import sys +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parent.parent + + +def _load_pb() -> ModuleType: + path = ROOT / "Pb" + spec = importlib.util.spec_from_loader("pb_module", loader=None) + module = importlib.util.module_from_spec(spec) + exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), module.__dict__) + return module + + +def test_dollar_li_line_is_fully_uppercased(): + pb = _load_pb() + source = "section VDI;\n$li modentry restart\nDCL x BOOL;\n" + result = pb.beautify_protel(source) + assert "$LI MODENTRY RESTART\n" in result + assert "$li modentry" not in result + assert "DCL" in result + + +def test_dollar_li_line_with_leading_whitespace(): + pb = _load_pb() + source = " $Li modentry restart\n" + result = pb.beautify_protel(source) + assert result == " $LI MODENTRY RESTART\n" + + +def test_pb_preserves_shebang_first_line(): + pb = _load_pb() + source = "#!/usr/bin/env protel-run\nsection s;\nDCL x BOOL;\n" + result = pb.beautify_protel(source) + assert result.startswith("#!/usr/bin/env protel-run\n") + assert "SECTION" in result + assert "DCL" in result + + +def test_vdi_aa01_dollar_li_directive(): + pb = _load_pb() + vdi = (ROOT / "vdi.aa01").read_text(encoding="utf-8") + result = pb.beautify_protel(vdi) + assert "$LI MODENTRY RESTART" in result \ No newline at end of file diff --git a/tests/test_preprocess_shebang.py b/tests/test_preprocess_shebang.py new file mode 100644 index 0000000..3ec0b77 --- /dev/null +++ b/tests/test_preprocess_shebang.py @@ -0,0 +1,37 @@ +"""Preprocessor shebang stripping (Introductory Manual §7.0.5).""" + +from pathlib import Path + +from src.parser import parse_protel +from src.preprocess import normalize_keywords, strip_shebang + +ROOT = Path(__file__).resolve().parent.parent +HELLO = ROOT / "examples" / "Hello.protel" + + +def test_strip_shebang_removes_first_line(): + source = "#!/usr/bin/env -S protel --run --\nSECTION s;\n" + assert strip_shebang(source) == "SECTION s;\n" + + +def test_strip_shebang_passthrough_without_hash_bang(): + source = "% comment\nSECTION s;\n" + assert strip_shebang(source) == source + + +def test_normalize_keywords_strips_shebang_before_parse(): + source = "#!/usr/bin/env protel --run\n% hi\nSECTION s;\n" + norm = normalize_keywords(source) + assert "#!" not in norm + assert "SECTION" in norm + + +def test_hello_protel_parses_with_shebang(): + tree = parse_protel(HELLO.read_text(encoding="utf-8")) + assert tree[0].name == "Hello" + entries = [ + decl + for decl in tree[0].declarations + if hasattr(decl, "entry") and decl.entry + ] + assert entries and entries[0].name == "Start" \ No newline at end of file diff --git a/tests/test_python_interop.py b/tests/test_python_interop.py new file mode 100644 index 0000000..c14576f --- /dev/null +++ b/tests/test_python_interop.py @@ -0,0 +1,44 @@ +"""Python interop example tests (transpile + optional link).""" + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +INTEROP = ROOT / "examples" / "interop" + + +def test_protel_calls_python_emits_external_python_greet(): + source = (INTEROP / "protel_calls_python.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_python.protel") + assert 'extern "C"' in cpp + assert "void python_greet(const char* name, int16_t value)" in cpp + assert "python_greet(" in cpp + assert "protel_generated::protel_calls_python::Start()" in cpp + + +def test_protel_for_python_exports_c_linkage(): + source = (INTEROP / "protel_for_python.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_python.protel") + assert "/* EXPORT protel_add" in cpp + assert "int16_t protel_add(int16_t a, int16_t b)" in cpp + assert "return (a + b)" in cpp + assert "int main()" not in cpp + + +def test_python_calls_protel_script_mentions_ctypes(): + script = (INTEROP / "python_calls_protel.py").read_text(encoding="utf-8") + assert "ctypes.CDLL" in script + assert "protel_add" in script + + +@pytest.mark.skipif(shutil.which("python3") is None, reason="python3 not installed") +def test_python_interop_examples_build_and_run(): + script = INTEROP / "build_interop_python.sh" + subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True) \ No newline at end of file diff --git a/tests/test_ref_manual_coverage.py b/tests/test_ref_manual_coverage.py new file mode 100644 index 0000000..472474d --- /dev/null +++ b/tests/test_ref_manual_coverage.py @@ -0,0 +1,108 @@ +"""Reference Manual section and keyword coverage tests.""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.keywords import PROTEL_KEYWORDS +from src.parser import parse_protel +from tests.ref_manual_manifest import ( + EXAMPLES, + KEYWORD_EXTERNAL_SOURCES, + REFERENCE_MANUAL_SECTIONS, + REF_EXAMPLE_SOURCES, + ROOT, +) + +_KEYWORD_BOUNDARY = re.compile( + r"(? list[Path]: + patterns = ( + "examples/**/*.protel", + "examples/**/*.aa01", + "examples/**/*.P", + "vdi.aa01", + "Pb", + "tests/test_pb.py", + "tests/test_vdi_aa01.py", + "tests/ref_manual_manifest.py", + ) + files: list[Path] = [] + for pattern in patterns: + files.extend(ROOT.glob(pattern)) + return sorted({p.resolve() for p in files if p.is_file()}) + + +def _file_contains_keyword(path: Path, keyword: str) -> bool: + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + return False + return bool(_KEYWORD_BOUNDARY.search(text)) + + +@pytest.mark.parametrize("section", sorted(REFERENCE_MANUAL_SECTIONS)) +def test_reference_manual_section_has_example_mapping(section: str): + mapped = REFERENCE_MANUAL_SECTIONS[section] + assert mapped, f"section {section} has no mapped sources" + for rel in mapped: + if rel.startswith("tests/"): + assert (ROOT / rel).is_file(), f"missing test corpus for §{section}: {rel}" + else: + assert (EXAMPLES / rel).is_file() or (ROOT / rel).is_file(), ( + f"missing example for §{section}: {rel}" + ) + + +@pytest.mark.parametrize("rel_source", REF_EXAMPLE_SOURCES) +def test_example_parses(rel_source: str): + source = (EXAMPLES / rel_source).read_text(encoding="utf-8") + tree = parse_protel(source) + assert tree + + +@pytest.mark.parametrize("rel_source", [s for s in REF_EXAMPLE_SOURCES if s.startswith("ref/")]) +def test_ref_example_transpiles(rel_source: str): + path = EXAMPLES / rel_source + source = path.read_text(encoding="utf-8") + tree = parse_protel(source) + cpp = transpile_to_cpp(tree, source_name=path.name) + assert "Generated by PROTEL" in cpp + + +@pytest.mark.parametrize("keyword", sorted(PROTEL_KEYWORDS)) +def test_reserved_keyword_exercised_in_corpus(keyword: str): + if keyword in KEYWORD_EXTERNAL_SOURCES: + for rel in KEYWORD_EXTERNAL_SOURCES[keyword]: + path = ROOT / rel if (ROOT / rel).exists() else EXAMPLES / rel + assert path.is_file(), f"missing external keyword source for {keyword}: {rel}" + assert _file_contains_keyword(path, keyword), ( + f"keyword {keyword!r} not found in {rel}" + ) + return + + for path in _corpus_files(): + if _file_contains_keyword(path, keyword): + return + + pytest.fail(f"reserved keyword {keyword!r} not found in examples or test corpus") + + +def test_keyword_manifest_covers_all_keywords(): + covered = set(KEYWORD_EXTERNAL_SOURCES) + for path in _corpus_files(): + text = path.read_text(encoding="utf-8", errors="replace") + for match in _KEYWORD_BOUNDARY.finditer(text): + covered.add(match.group(1).upper()) + missing = PROTEL_KEYWORDS - {k.upper() for k in covered} + assert not missing, f"keywords missing from corpus: {sorted(missing)}" \ No newline at end of file diff --git a/tests/test_rust_interop.py b/tests/test_rust_interop.py new file mode 100644 index 0000000..d12320b --- /dev/null +++ b/tests/test_rust_interop.py @@ -0,0 +1,37 @@ +"""Rust interop example tests (transpile + optional link).""" + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +INTEROP = ROOT / "examples" / "interop" + + +def test_protel_calls_rust_emits_external_rust_greet(): + source = (INTEROP / "protel_calls_rust.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_rust.protel") + assert 'extern "C"' in cpp + assert "void rust_greet(const char* name, int16_t value)" in cpp + assert "rust_greet(" in cpp + assert "protel_generated::protel_calls_rust::Start()" in cpp + + +def test_protel_for_rust_exports_c_linkage(): + source = (INTEROP / "protel_for_rust.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_rust.protel") + assert "/* EXPORT protel_add" in cpp + assert "int16_t protel_add(int16_t a, int16_t b)" in cpp + assert "return (a + b)" in cpp + assert "int main()" not in cpp + + +@pytest.mark.skipif(shutil.which("rustc") is None, reason="rustc not installed") +def test_rust_interop_examples_build_and_run(): + script = INTEROP / "build_interop_rust.sh" + subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True) \ No newline at end of file diff --git a/tests/test_string_codegen.py b/tests/test_string_codegen.py new file mode 100644 index 0000000..f0fd13d --- /dev/null +++ b/tests/test_string_codegen.py @@ -0,0 +1,42 @@ +"""PROTEL string tuple codegen (no implicit NUL termination).""" + +from pathlib import Path + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" + + +def test_string_literal_emits_char_tuple_not_c_string(): + tree = parse_protel( + "SECTION s;\n" + "DCL writeln PROC(m PTR TO char) EXTERNAL;\n" + "DCL Start PROC() IS ENTRY;\n" + "DCL Start PROC() IS BLOCK writeln({'Hi', 0}); ENDBLOCK;\n" + ) + cpp = transpile_to_cpp(tree) + assert '"Hi"' not in cpp + assert "(const char[]){ 'H', 'i', 0 }" in cpp + + +def test_string_without_nul_emits_no_trailing_zero(): + tree = parse_protel( + "SECTION s;\n" + "DCL writeln PROC(m PTR TO char) EXTERNAL;\n" + "DCL Start PROC() IS ENTRY;\n" + "DCL Start PROC() IS BLOCK writeln({'Hi'}); ENDBLOCK;\n" + ) + cpp = transpile_to_cpp(tree) + assert "(const char[]){ 'H', 'i' }" in cpp + assert ", 0 }" not in cpp + + +def test_hello_uses_explicit_nul_suffix(): + source = (EXAMPLES / "Hello.protel").read_text(encoding="utf-8") + assert "{'Hello, World!', 0}" in source + cpp = transpile_to_cpp(parse_protel(source), source_name="Hello.protel") + assert "(const char[]){" in cpp + assert "'!'" in cpp + assert ", 0 }" in cpp + assert '"Hello, World!"' not in cpp \ No newline at end of file diff --git a/tests/test_swift_interop.py b/tests/test_swift_interop.py new file mode 100644 index 0000000..0c025a9 --- /dev/null +++ b/tests/test_swift_interop.py @@ -0,0 +1,37 @@ +"""Swift interop example tests (transpile + optional link).""" + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel + +ROOT = Path(__file__).resolve().parent.parent +INTEROP = ROOT / "examples" / "interop" + + +def test_protel_calls_swift_emits_external_swift_greet(): + source = (INTEROP / "protel_calls_swift.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_calls_swift.protel") + assert 'extern "C"' in cpp + assert "void swift_greet(const char* name, int16_t value)" in cpp + assert "swift_greet(" in cpp + assert "protel_generated::protel_calls_swift::Start()" in cpp + + +def test_protel_for_swift_exports_c_linkage(): + source = (INTEROP / "protel_for_swift.protel").read_text(encoding="utf-8") + cpp = transpile_to_cpp(parse_protel(source), source_name="protel_for_swift.protel") + assert "/* EXPORT protel_add" in cpp + assert "int16_t protel_add(int16_t a, int16_t b)" in cpp + assert "return (a + b)" in cpp + assert "int main()" not in cpp + + +@pytest.mark.skipif(shutil.which("swiftc") is None, reason="swiftc not installed") +def test_interop_examples_build_and_run(): + script = INTEROP / "build_interop.sh" + subprocess.run(["bash", str(script)], cwd=ROOT, check=True, text=True) \ No newline at end of file diff --git a/tests/test_transpiler.py b/tests/test_transpiler.py new file mode 100644 index 0000000..20cd449 --- /dev/null +++ b/tests/test_transpiler.py @@ -0,0 +1,75 @@ +"""Transpiler tests correlated to PROTEL 2026 manuals.""" + +from pathlib import Path + +from src.parser import parse_protel +from src.transpiler import transpile_to_c + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" + + +def _transpile_example(name: str) -> str: + source = (EXAMPLES / name).read_text(encoding="utf-8") + tree = parse_protel(source) + return transpile_to_c(tree, source_name=name) + + +def test_transpile_factorial_contains_procedure(): + c = _transpile_example("intro_1_3_factorial.protel") + assert "int16_t factorial(" in c + assert "while (" in c + assert "return result;" in c + + +def test_transpile_types_emits_typedefs(): + c = _transpile_example("intro_2_1_types.protel") + assert "typedef int16_t integer;" in c + assert "typedef int16_t digit_register[16];" in c + assert "seconds_per_hour" in c + + +def test_transpile_assignment_maps_arrow_to_equals(): + c = _transpile_example("intro_2_2_calculate_average.protel") + assert "average =" in c + assert "return average;" in c + + +def test_transpile_case_emits_switch(): + c = _transpile_example("intro_3_2_4_case.protel") + assert "switch (n)" in c + assert "case 0:" in c + assert "default:" not in c + + +def test_transpile_for_emits_c_for_loop(): + c = _transpile_example("intro_3_2_6_sum_table.protel") + assert "for (int32_t i = 0;" in c + assert "return sum;" in c + + +def test_transpile_struct_emits_fields(): + c = _transpile_example("ref_8_1_task_block_struct.protel") + assert "typedef struct {" in c + assert "uint8_t priority;" in c + assert "uint8_t completed;" in c + assert "task_block * next_task;" in c + + +def test_transpile_class_type_emits_static_class_var(): + c = _transpile_example("ref_oo_class_with_var.protel") + assert "typedef struct class_with_var_t" in c + assert "static int16_t class_with_var_class_var" in c + assert "void class_with_var_class_method(int16_t parameter)" in c + assert "class_with_var_class_var = 5" in c + + +def test_transpile_class_method_invocation(): + c = _transpile_example("ref_oo_class_method_invoke.protel") + assert "class_with_class_method_class_method(5)" in c + assert "class_with_class_method_class_method(6)" in c + + +def test_transpile_emits_header(): + c = _transpile_example("intro_1_3_factorial.protel") + assert "Generated by PROTEL 2026 transpiler" in c + assert "#include " in c \ No newline at end of file diff --git a/tests/test_type_errors.py b/tests/test_type_errors.py new file mode 100644 index 0000000..d52010f --- /dev/null +++ b/tests/test_type_errors.py @@ -0,0 +1,75 @@ +"""Type error examples and strong typing tests (Reference Manual §11.3).""" + +from pathlib import Path + +import pytest + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel +from src.type_checker import TypeCheckError + +ROOT = Path(__file__).resolve().parent.parent +ERRORS = ROOT / "examples" / "errors" + + +def _read(name: str) -> str: + return (ERRORS / name).read_text(encoding="utf-8") + + +@pytest.mark.parametrize( + "filename,message_fragment", + [ + ("err_assign_integer_to_char.protel", "cannot assign integer to char"), + ( + "err_assign_integer_to_packed_byte.protel", + "packed byte-sized type", + ), + ("err_assign_integer_to_bool.protel", "cannot assign"), + ("err_constant_out_of_range.protel", "out of range"), + ("err_assign_incompatible_pointer.protel", "cannot assign"), + ("err_return_type_mismatch.protel", "RETURN type"), + ], +) +def test_error_examples_fail_type_check(filename: str, message_fragment: str): + source = _read(filename) + tree = parse_protel(source) + with pytest.raises(TypeCheckError, match=message_fragment): + transpile_to_cpp(tree, source_name=filename) + + +def test_ok_char_literal_transpiles(): + source = _read("ok_assign_char_literal.protel") + tree = parse_protel(source) + cpp = transpile_to_cpp(tree, source_name="ok_assign_char_literal.protel") + assert "Generated by PROTEL" in cpp + + +def test_protel_driver_reports_type_error(): + import subprocess + + result = subprocess.run( + [ + str(ROOT / ".venv" / "bin" / "python"), + str(ROOT / "protel"), + str(ERRORS / "err_assign_integer_to_char.protel"), + "--parse-only", + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 0 + + result = subprocess.run( + [ + str(ROOT / ".venv" / "bin" / "python"), + str(ROOT / "protel"), + str(ERRORS / "err_assign_integer_to_char.protel"), + ], + capture_output=True, + text=True, + cwd=ROOT, + ) + assert result.returncode == 1 + assert "protel: type error" in result.stderr + assert "cannot assign integer to char" in result.stderr \ No newline at end of file diff --git a/tests/test_vdi_aa01.py b/tests/test_vdi_aa01.py new file mode 100644 index 0000000..248e866 --- /dev/null +++ b/tests/test_vdi_aa01.py @@ -0,0 +1,51 @@ +"""Legacy PLS module vdi.aa01 parse and compile tests.""" + +import subprocess +from pathlib import Path + +from src.cpp_transpiler import transpile_to_cpp +from src.parser import parse_protel +from src.preprocess import normalize_keywords + +ROOT = Path(__file__).resolve().parent.parent +VDI = ROOT / "vdi.aa01" +PROTEL = ROOT / "protel" + + +def test_preprocess_strips_dollar_li_directive(): + norm = normalize_keywords(VDI.read_text(encoding="utf-8"), classical=True) + assert "$LI" not in norm + assert "modentry" not in norm + assert "DCL" in norm + assert "vdi_debugging_flag" in norm + assert "BOOL IS TRUE" in norm + + +def test_vdi_aa01_parses(): + tree = parse_protel(VDI.read_text(encoding="utf-8"), classical=True) + assert len(tree) == 1 + section = tree[0] + assert section.name == "VDI" + assert len(section.declarations) == 1 + assert section.declarations[0].names == ["vdi_debugging_flag"] + + +def test_vdi_aa01_transpiles_debug_flag(): + tree = parse_protel(VDI.read_text(encoding="utf-8"), classical=True) + cpp = transpile_to_cpp(tree, source_name="vdi.aa01", classical=True) + assert "bool vdi_debugging_flag = true;" in cpp + assert "namespace VDI" in cpp + + +def test_vdi_aa01_compiles_to_object(): + out = ROOT / "build" / "test_vdi.aa01.o" + if out.exists(): + out.unlink() + subprocess.run( + [str(ROOT / ".venv/bin/python"), str(PROTEL), str(VDI), "-c", "-o", str(out)], + cwd=ROOT, + check=True, + text=True, + ) + assert out.is_file() + assert out.stat().st_size > 0 \ No newline at end of file