commit
e092cb029c
252 files changed
+35037
No files matched your search
+100
@@ -0,0 +1,100 @@
|
|||||||
|
# EditorConfig: https://editorconfig.org
|
||||||
|
# In VS Code, install the "EditorConfig for VS Code" extension (EditorConfig.EditorConfig).
|
||||||
|
|
||||||
|
root = true
|
||||||
|
|
||||||
|
# Defaults for every file
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
end_of_line = lf
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
# Python
|
||||||
|
[*.{py,pyi}]
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 88
|
||||||
|
|
||||||
|
# Mojo (`mojo format` is Black-style, 88 columns; the fire emoji extension is also valid)
|
||||||
|
[*.{mojo,🔥}]
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 88
|
||||||
|
|
||||||
|
# Rust (rustfmt defaults: 4 spaces, 100 columns)
|
||||||
|
[*.rs]
|
||||||
|
indent_size = 4
|
||||||
|
max_line_length = 100
|
||||||
|
|
||||||
|
# Cargo manifests and rustfmt config
|
||||||
|
[{Cargo.toml,Cargo.lock,rustfmt.toml,.rustfmt.toml,clippy.toml}]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
# Mojo project manifest
|
||||||
|
[{mojoproject.toml,pixi.toml,pixi.lock}]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
# YAML
|
||||||
|
[*.{yml,yaml}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# JSON and friends
|
||||||
|
[*.{json,jsonc,json5}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# Web
|
||||||
|
[*.{js,jsx,mjs,cjs,ts,tsx,css,scss,less,html,vue,svelte}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# Config formats
|
||||||
|
[*.{toml,ini,cfg}]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
[*.xml]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# Markdown: trailing spaces are significant (hard line breaks)
|
||||||
|
[*.{md,markdown}]
|
||||||
|
indent_size = 2
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
# typst
|
||||||
|
[*.{typ}]
|
||||||
|
indent_size = 4
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
# Shell scripts
|
||||||
|
[*.{sh,bash,zsh}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# Makefiles require tabs
|
||||||
|
[{Makefile,makefile,*.mk}]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
# Go uses tabs
|
||||||
|
[*.go]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
# Windows-only scripts need CRLF
|
||||||
|
[*.{bat,cmd,ps1}]
|
||||||
|
end_of_line = crlf
|
||||||
|
|
||||||
|
# Dockerfiles
|
||||||
|
[{Dockerfile,Dockerfile.*,*.dockerfile}]
|
||||||
|
indent_size = 4
|
||||||
|
|
||||||
|
# Terraform
|
||||||
|
[*.{tf,tfvars,hcl}]
|
||||||
|
indent_size = 2
|
||||||
|
|
||||||
|
# Don't touch these
|
||||||
|
[LICENSE*]
|
||||||
|
insert_final_newline = false
|
||||||
|
|
||||||
|
[*.{diff,patch}]
|
||||||
|
trim_trailing_whitespace = false
|
||||||
|
|
||||||
|
[*.min.{js,css}]
|
||||||
|
insert_final_newline = unset
|
||||||
|
trim_trailing_whitespace = unset
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# SCM syntax highlighting & preventing 3-way merges
|
||||||
|
pixi.lock merge=binary linguist-language=YAML linguist-generated=true -diff
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# Programming+ on Gitea Actions, with a runner that has no container image: the act_runner runs jobs directly on
|
||||||
|
# the droplet's shell ("host mode"). docs/deploy.md has the runner's setup, once.
|
||||||
|
#
|
||||||
|
# Every push and pull request runs `pixi run ci`, the same task a developer runs, in the environment pixi.lock pins
|
||||||
|
# (Node, Python, pandoc, Mojo): every test of the site (the Quarto ones fail, not skip, without pandoc), and core's
|
||||||
|
# tests and mojo-status-strict at the pinned commit. A push to main also checks the chain of pointers
|
||||||
|
# (`pixi run release-check`) and publishes the site to /srv/www/<slug> as an atomic release (scripts/deploy.sh).
|
||||||
|
#
|
||||||
|
# On GitHub Actions the build and test steps run with one change, `runs-on: ubuntu-latest`; the publish step needs
|
||||||
|
# a host that serves /srv/www, so it is the droplet's.
|
||||||
|
#
|
||||||
|
# Repository -> Settings -> Actions -> Variables (all optional):
|
||||||
|
# SITE_SLUG the directory under /srv/www (defaults to the repository name)
|
||||||
|
# SITE_URL e.g. https://pplus.scient.ing, turns on the smoke test
|
||||||
|
name: Build, test, deploy
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
# set by Gitea and GitHub Actions already; written here so the tests' "fail, not skip, under CI" never depends on it
|
||||||
|
CI: "true"
|
||||||
|
# the pixi that reads pixi.lock; when the host has another version, this one is fetched into the cache below
|
||||||
|
PIXI_VERSION: "0.83.0"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
site:
|
||||||
|
# a pull request runs only from a branch of this repository: on a host runner a fork's workflow would run its
|
||||||
|
# own code on the droplet (docs/deploy.md in pplus-web). Drop this line for a runner that is a throwaway VM.
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||||
|
# The host-mode label from the runner registration. Jobs run as the runner's user, in a fresh working directory.
|
||||||
|
runs-on: quarto-deploy
|
||||||
|
timeout-minutes: 60
|
||||||
|
steps:
|
||||||
|
# core/ is pplus-core, a submodule pinned to one commit, and core/library/ is pplus-library, pinned by core;
|
||||||
|
# the job's token must be able to read both repositories while they are private
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
# pixi: the host's when it is the pinned version, else the pinned release, fetched once into a cache directory
|
||||||
|
# the runner's user owns (no sudo), checked by SHA-256
|
||||||
|
- name: pixi, pinned
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if command -v pixi >/dev/null && [ "$(pixi --version | cut -d' ' -f2)" = "$PIXI_VERSION" ]; then
|
||||||
|
echo "pixi $PIXI_VERSION is on the host: $(command -v pixi)"; exit 0
|
||||||
|
fi
|
||||||
|
dir="${PPLUS_CI_CACHE:-$HOME/.cache/pplus-ci}/pixi-$PIXI_VERSION"
|
||||||
|
if [ ! -x "$dir/pixi" ]; then
|
||||||
|
case "$(uname -s)-$(uname -m)" in
|
||||||
|
Linux-x86_64) asset=pixi-x86_64-unknown-linux-musl.tar.gz; sum=064f371e692aaa3400ac581c89da2843c91437f20c2d9155395a5d0037f33551 ;;
|
||||||
|
Linux-aarch64) asset=pixi-aarch64-unknown-linux-musl.tar.gz; sum=d08403d8f048626ec93ba7b7c56e3b747a5f3a95c4e6e0c815ceb264f5f0b9ce ;;
|
||||||
|
*) echo "no pinned pixi for $(uname -sm)" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
curl -fsSL --retry 3 -o "$tmp/$asset" "https://github.com/prefix-dev/pixi/releases/download/v$PIXI_VERSION/$asset"
|
||||||
|
echo "$sum $tmp/$asset" | sha256sum -c -
|
||||||
|
mkdir -p "$dir" && tar -xzf "$tmp/$asset" -C "$dir" pixi && rm -rf "$tmp"
|
||||||
|
fi
|
||||||
|
echo "$dir" >> "$GITHUB_PATH"
|
||||||
|
"$dir/pixi" --version
|
||||||
|
|
||||||
|
- name: The pinned environment, exactly as pixi.lock has it
|
||||||
|
run: pixi install --locked
|
||||||
|
|
||||||
|
# every test of the site; core's tests and mojo-status-strict at the pinned commit (pixi.toml)
|
||||||
|
- name: pixi run ci
|
||||||
|
run: pixi run ci
|
||||||
|
|
||||||
|
# each pointer on its pushed branch, the generated files current, Mojo pinned alike (scripts/release.mjs);
|
||||||
|
# a pointer it cannot check (a private remote the job cannot ask) is reported, not failed
|
||||||
|
- name: The chain of pointers
|
||||||
|
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||||
|
run: pixi run release-check
|
||||||
|
|
||||||
|
- name: Assemble the site
|
||||||
|
run: scripts/assemble.sh
|
||||||
|
env:
|
||||||
|
GITHUB_SHA: ${{ github.sha }}
|
||||||
|
|
||||||
|
- name: Publish to /srv/www
|
||||||
|
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||||
|
env:
|
||||||
|
SLUG: ${{ vars.SITE_SLUG || github.event.repository.name }}
|
||||||
|
GITHUB_SHA: ${{ github.sha }}
|
||||||
|
run: scripts/deploy.sh "$SLUG"
|
||||||
|
|
||||||
|
- name: Smoke test
|
||||||
|
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && vars.SITE_URL != ''
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
SITE_URL: ${{ vars.SITE_URL }}
|
||||||
|
GITHUB_SHA: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
sleep 2
|
||||||
|
live=$(curl -fsS "$SITE_URL/VERSION")
|
||||||
|
case "$live" in
|
||||||
|
"${GITHUB_SHA:0:12}"*) echo "live site is at $live" ;;
|
||||||
|
*) echo "live site reports '$live', expected ${GITHUB_SHA:0:12}" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
site/
|
||||||
|
node_modules/
|
||||||
|
.DS_Store
|
||||||
|
dist/
|
||||||
|
patches/
|
||||||
|
package/
|
||||||
|
# pixi environments
|
||||||
|
.pixi/*
|
||||||
|
!.pixi/config.toml
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
# the Quarto example site's output and Quarto's own state
|
||||||
|
quarto/_site/
|
||||||
|
quarto/.quarto/
|
||||||
|
quarto/_extensions/pplus/engine/
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
[submodule "core"]
|
||||||
|
path = core
|
||||||
|
url = https://git.scient.ing/pplus/pplus-core.git
|
||||||
|
branch = main
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
Instructions for coding agents (and people) changing Programming+. Read this first, then the [README](README.md) for what the app is and where things are. When this file and a task's instructions disagree, the task wins; say so in your summary.
|
||||||
|
|
||||||
|
## Build, test, and the gate
|
||||||
|
|
||||||
|
The engine core (the languages, translators, Mojo checker and interpreter, prover, fuzzer, machine model and the Mojo corpus) is **pplus-core**, the git submodule `core/`, with its own rules in [core/AGENTS.md](core/AGENTS.md). This file is for the site.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pixi run test # build core, then the site, then every test of the site
|
||||||
|
pixi run core-test # core's own tests, at the pinned commit
|
||||||
|
```
|
||||||
|
|
||||||
|
Without pixi (a sandbox with only Node and Python):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install && npm test
|
||||||
|
(cd core && node --test tests/*.test.mjs && python3 scripts/mojo/corpus.py status --strict)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Finish every change with the gate green**, both commands. The baseline passes completely; there is no known failure to work around. If a test fails, fix the cause or stop and report it. Do not skip, loosen, or delete a test to get green.
|
||||||
|
|
||||||
|
The site's suite takes under a minute. While iterating, build and run one file: `npm run build && node --test tests/state.test.mjs`.
|
||||||
|
|
||||||
|
## Hard rules
|
||||||
|
|
||||||
|
1. **A change to what programs mean belongs in core.** A translator, the checker, the interpreter, the prover, the fuzzer, the machine model, the catalog's problems, the Mojo corpus: change them in pplus-core under its rules (its own commit, its own gate), then move the `core` pointer here in a commit that says what it brings. Never edit `core/` from a site change without that. The site imports core only as `#core/<path>.js` (the import map in `index.html`, `imports` in `package.json`), from its built `core/dist/`.
|
||||||
|
2. **Do not edit generated files by hand.** `quarto/_extensions/pplus/pplus-views.css` comes from `styles.css`, `pplus-hw.css` and `course/*.css` beside it from `styles/course/`, and `syntax/mojo.xml` from core's `core/library/syntax/mojo.xml` (`pixi run quarto-css`; a test fails while they are out of date, so run it after changing a rule the views use). Core's generated files are listed in its AGENTS.md.
|
||||||
|
3. **Never claim Mojo compiles, runs, or prints something without the real compiler's answer.** Mojo is pinned to 1.2.0 by core. What the app shows about Mojo comes from core's checker and interpreter and from godbolt's answers (stored in `core/library/mojo/golden/`, or asked live by Compile & run); the site never invents a verdict, and every Mojo construct written into the app must pass `checkMojo`.
|
||||||
|
4. **Never show "proved" for something that is not a proof.** The badges and verdicts are in [core/docs/trust.md](core/docs/trust.md); the site shows what core decided and does not soften or upgrade it.
|
||||||
|
5. **No new dependencies.** TypeScript is the only npm package. There is no bundler, no framework, and no npm runtime dependency: CodeMirror, the one library the page runs, is vendored as one built module (`src/vendor/`), rebuilt only by `scripts/vendor/codemirror.sh`. `tests/tasks.test.mjs` holds `package.json` to that.
|
||||||
|
6. **You have no network** in most sandboxes. Godbolt (Compile & run) needs one, and so do core's network tasks. Never fake their results; leave those steps to the owner and list them.
|
||||||
|
7. **Keep the workspace working while you change it.** Code panes are always the CodeMirror editor (`Editor` in `src/ui/editor.ts`, over the vendored `src/vendor/codemirror.js`), never a `<textarea>`; `tests/editor.test.mjs` checks it. Keep the workspace's parts as they are unless the task changes them: the pane tabs over one editor, the stepper docked under the editor, the side column (the inspect panel, whose first tab is the Run view), and the dock; in the Hardware area, the code on the left and the arrangeable board on the right. Restyle or rearrange them only when asked, and after any UI change open the app (`pixi run dev`) and check that the editor has line numbers and highlighting, the stepper steps, and the styles loaded.
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- **Commands are pixi tasks.** Name them as `pixi run <task>` in docs, comments, and messages. A new command is a task in `pixi.toml` with a `description` and a row in the README's Commands table; `tests/tasks.test.mjs` fails otherwise, and also fails on any `pixi run <name>` that names no task. `package.json` keeps only `build`, `watch`, `check`, `dev`, `test` (what CI uses).
|
||||||
|
- **Docs.** The README is the front door: keep it short. Put behavior in [docs/app.md](docs/app.md), deployment in [docs/deploy.md](docs/deploy.md), and the Quarto extension in [quarto/README.md](quarto/README.md). Exercises, the Mojo corpus, the engines and the prover's soundness are core's documents (`core/docs/`). Update the document a change belongs in, in the same commit.
|
||||||
|
- **Tests run against `dist/` with no DOM.** Logic about programs belongs in core; the site's own DOM-free logic (`src/core/`, `src/quarto/`) is tested here. A test that needs a piece of work uses a `Session` (`src/core/session.ts`), which extends core's `Workspace`. The views in `src/ui/views/` also run outside a browser, under the small document of `src/quarto/dom.ts`, when the Quarto extension renders them: a view may use the selectors that document knows (compound selectors and the descendant combinator) and must not need layout to produce its markup. When a test needs `localStorage`, install a fake on `globalThis` and remove it in `finally`, as `tests/state.test.mjs` does. For a UI change, write a short manual check list in the commit message.
|
||||||
|
- **TypeScript.** Strict mode, ES modules, imports with the `.js` suffix (`from './state.js'`). Indent like the file you are editing (some files use two spaces, some four).
|
||||||
|
- **Stable ids.** Diagnostic ids (`matho-refused`, `reserved-name`, ...) and reference section ids are asserted by tests and linked from guides. Change one only on purpose, and update every test and link that names it.
|
||||||
|
- **Saved state.** `PlayState` in `src/core/state.ts` is what share links, `localStorage`, and `.pplus.json` files hold, and `normalize()` reads it. A new field goes into `normalize()`; a field the student edits goes into `EDITS` (it drives `editedFrom()` and `editsFingerprint()`).
|
||||||
|
- **Writing.** User-facing copy is US English (color, behavior, optimized, labeled). Plain sentences; say what a thing does, not how good it is.
|
||||||
|
|
||||||
|
## Adding things
|
||||||
|
|
||||||
|
| To add | Do |
|
||||||
|
|---|---|
|
||||||
|
| A catalog problem, a probe, a stress program, a corpus or prover regression, a language, a library routine | in core (a library routine in pplus-library, core's submodule `library/`) ([core/AGENTS.md](core/AGENTS.md#adding-things)), then move the `core` pointer here; a problem's area comes from `defaultAreaFor` in `src/core/catalog.ts` |
|
||||||
|
| A command | a task in `pixi.toml` and a row in the README's Commands table |
|
||||||
|
| A Quarto shortcode | a function in the table `quarto/_extensions/pplus/pplus.lua` returns, a row in `SHORTCODES` (`src/quarto/shortcodes.ts`) and in `scripts/check-pages.mjs`, a sample in the gallery (`src/ui/quarto.ts`) and a use in `quarto/example/`; a rendered view is a case of `renderStatic` (`src/quarto/render.ts`); a view of the machine is a name in `HW_NAMES` (`src/quarto/machine.ts`), `HW_VIEWS` in `pplus.lua` and `HW_VIEWS` in `scripts/check-pages.mjs` |
|
||||||
|
|
||||||
|
## Delivering work
|
||||||
|
|
||||||
|
- One logical change per commit, with a message that says what changed and why: the problem first, then what each part of the change does.
|
||||||
|
- When the owner asks for patches, export them with `git format-patch -o patches/ <base>` (the `patches/` folder is ignored by git) and do not paste whole files into chat. If the tree you were given has no `.git`, run `git init` and commit it unchanged first, so the patches have a base.
|
||||||
|
- End with a summary: what you changed, the gate's result, the core commit the site is pinned to if it moved, anything you could not verify (network steps, manual UI checks), and anything you noticed but left alone.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
No version has been tagged yet. What programs mean is pplus-core's, and its changelog has those changes; this one says what changed on the site.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The site runs on pplus-core for Mojo 1.2.0: generated Mojo the real compiler accepts and that prints what the pseudo prints, 18 prover rules that proved what a run breaks closed, and the interpreter audit's fixes. The pin is consistent again: a fresh clone's tests pass.
|
||||||
|
- The deployed site carries its license and the third-party notices (`LICENSE.md`, `NOTICE.md`, `THIRD_PARTY.md`).
|
||||||
|
- Compile & run asks before the first send to godbolt.org, builds every program one stated way (`--target-cpu x86-64-v3 --fp-mode contract=off`, shown on each compile), and shows the kept answer when the source, the input and the level are unchanged.
|
||||||
|
- The site serves its own fonts; nothing is asked of any other server except godbolt.org by Compile & run. A Content-Security-Policy and the other security headers are in `docs/Caddyfile`.
|
||||||
|
- The copy says what the site holds and no more: what runs in the browser and what does not, that the Hardware area is a model machine, and what "verified" means.
|
||||||
|
- A shared link never saves over the reader's own work on the same problem.
|
||||||
|
- Below 700px a workspace shows one part at a time; every page has a main landmark and a heading, and the contrast findings are fixed.
|
||||||
|
- The Quarto extension's syntax definitions state their license as Apache-2.0 (they said MIT), and `THIRD_PARTY.md` says that the stylesheets and syntax definitions that came from the course are under this repository's copyright and license.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `THIRD_PARTY.md`, with the copyright notice of every package bundled into the editor, and a test that holds it to the bundle, the copied stylesheets, the fonts and the locks.
|
||||||
|
- The Apache License 2.0, a NOTICE, contributing rules, a security policy, a code of conduct, and a citation file.
|
||||||
|
- A footer with the license, the notices, the disclaimer about Modular, the build's commit, and "What this site stores and sends", each statement held to the code by a test.
|
||||||
|
- `pixi run caddy-check` serves an assembled site with a real Caddy under `docs/Caddyfile` and holds its headers, caching and missing-path answers; `pixi run release-check` says whether the three repositories' pointers line up; `site/build.json` names the three commits a site was built from.
|
||||||
|
- Tests for the copy, for every badge having a row in core's `docs/trust.md`, for what the site stores and sends, for load, accessibility and narrow screens.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- `docs/Caddyfile` served the page in place at a missing nested path, where its own files could not be found (a blank page). A missing page is sent to `/`; a missing file is a plain 404.
|
||||||
|
- Core's limits reach the site: no text in a pane, a link or a file ends in the engine's own error; a CSV export cannot start a spreadsheet formula; a framed Quarto view cannot make itself taller than 4,000px.
|
||||||
|
- From the library, the nav's Problems and Reference links opened nothing.
|
||||||
|
- Open in Hardware on a large compiled function made work whose share link the app then refused to open (its setup was 2.5 MB); core writes the function's data compactly now, and a link for it opens.
|
||||||
|
- A Quarto page's Mojo run, and the page checker, build Mojo as the app does.
|
||||||
|
- `pixi run check-pages` read only shortcode names with one hyphen, so it skipped every `pplus-hw-<view>` shortcode: a missing file or a misspelled view went unreported.
|
||||||
|
- With `pplus-strict: true`, a program with `EXPECT` lines that does not run at all stops the render; it was only a warning.
|
||||||
|
- `quarto/README.md` is corrected against the extension: `follow` belongs to the stepper only, the defaults and limits of `height` and `max`, what a non-HTML format gets, what `check-pages` runs, and what `quarto-export` writes.
|
||||||
|
- From core: brackets that each hold a long chain are one `too-deep` error in the pseudo pane; they ended in the engine's own stack error.
|
||||||
|
|
||||||
|
## [0.1.0] - 2026-10-06
|
||||||
|
|
||||||
|
The first version of the site, as `main` holds it. Never tagged.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Three areas: the Bridge (lingo, matho, pseudo and speco, kept in step as you type, with Mojo generated from the pseudo), the Developer area (Mojo with the checker, a Run view of every step, a fuzzer and Compile & run on godbolt.org), and the Hardware area (the code beside a board of registers, memory, caches, the pipeline and the out-of-order core).
|
||||||
|
- The library page (`#/library`): every verified routine with how its checks ended, its pseudo, cases, references and proof, and a way to open it in the Bridge.
|
||||||
|
- A catalog of worked problems, share links that carry the whole state, embeds, and a Quarto extension that renders the views into a page.
|
||||||
|
- A static deployment: `pixi run site` and `pixi run deploy`, a Caddy site block, and a CI workflow.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The engines live in pplus-core, the submodule `core/`; the site keeps its session over core's `Workspace`.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
cff-version: 1.2.0
|
||||||
|
message: "If you use Programming+ in published work, please cite it as below."
|
||||||
|
type: software
|
||||||
|
title: "Programming+: from an idea to Mojo to the machine"
|
||||||
|
version: 0.1.0
|
||||||
|
authors:
|
||||||
|
- family-names: Maldonado
|
||||||
|
given-names: Alex M.
|
||||||
|
email: alex@scient.ing
|
||||||
|
orcid: "https://orcid.org/0000-0003-3280-062X"
|
||||||
|
- name: Scientific Computing Studio, LLC
|
||||||
|
email: us@scient.ing
|
||||||
|
url: "https://pplus.scient.ing"
|
||||||
|
repository-code: "https://git.scient.ing/pplus/pplus-web"
|
||||||
|
license: Apache-2.0
|
||||||
|
keywords:
|
||||||
|
- programming education
|
||||||
|
- pseudocode
|
||||||
|
- Mojo
|
||||||
|
- program verification
|
||||||
|
- computer architecture
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at alex@scient.ing. All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||||
|
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||||
|
[FAQ]: https://www.contributor-covenant.org/faq
|
||||||
|
[translations]: https://www.contributor-covenant.org/translations
|
||||||
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Contributing
|
||||||
|
|
||||||
|
Thank you for reading this far.
|
||||||
|
pplus-web is the site of Programming+: the editor, the views, the embeds and the Quarto extension, over pplus-core.
|
||||||
|
It is maintained by one person, and the rules below keep it honest about what it can take on.
|
||||||
|
|
||||||
|
## Two rules first
|
||||||
|
|
||||||
|
- **No outside code is merged until a contributor license agreement exists.** Until then, bug reports, questions, and documentation fixes are welcome, and code changes are read and used as guidance but not merged. The agreement will be short and will ask you to confirm that you may license your change under Apache-2.0.
|
||||||
|
- **No contributions from students enrolled at the University of Pittsburgh.** The maintainer teaches there, and this project is separate from that job. Students may use Programming+ like anyone else.
|
||||||
|
|
||||||
|
## Running the checks
|
||||||
|
|
||||||
|
Programming+ uses [pixi](https://pixi.sh/latest/) for its environments; it brings the pinned Mojo, Node and Python.
|
||||||
|
From a clone with its submodule (`git clone --recurse-submodules`):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pixi run test # build core and the site, then every test of the site
|
||||||
|
pixi run dev # build, then serve on http://localhost:4173
|
||||||
|
```
|
||||||
|
|
||||||
|
Without pixi, with Node 20 or later: `npm install && npm test`.
|
||||||
|
[AGENTS.md](AGENTS.md) has the rules every change follows, whoever writes it; a change to what a program means belongs in pplus-core, under its own rules.
|
||||||
|
|
||||||
|
## Reporting a bug
|
||||||
|
|
||||||
|
Say what you did, what you expected, and what happened, with the share link of the view (it holds the whole state) and the browser you used.
|
||||||
|
Where to file issues will be in the README once the repository is public.
|
||||||
|
|
||||||
|
## Style
|
||||||
|
|
||||||
|
US English, plain sentences, in the code and in everything a student reads.
|
||||||
|
A commit says the problem first, then what each part of the change does; a fix comes with a test that fails without it, and a change to the interface comes with a short manual check list in its message.
|
||||||
|
Every change for a user has a line in `CHANGELOG.md`.
|
||||||
+167
@@ -0,0 +1,167 @@
|
|||||||
|
# Apache License
|
||||||
|
|
||||||
|
_Version 2.0, January 2004_
|
||||||
|
_<<http://www.apache.org/licenses/>>_
|
||||||
|
|
||||||
|
## Terms and Conditions for use, reproduction, and distribution
|
||||||
|
|
||||||
|
### 1. Definitions
|
||||||
|
|
||||||
|
“License” shall mean the terms and conditions for use, reproduction, and
|
||||||
|
distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
“Licensor” shall mean the copyright owner or entity authorized by the copyright
|
||||||
|
owner that is granting the License.
|
||||||
|
|
||||||
|
“Legal Entity” shall mean the union of the acting entity and all other entities
|
||||||
|
that control, are controlled by, or are under common control with that entity.
|
||||||
|
For the purposes of this definition, “control” means **(i)** the power, direct or
|
||||||
|
indirect, to cause the direction or management of such entity, whether by
|
||||||
|
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or **(iii)** beneficial ownership of such entity.
|
||||||
|
|
||||||
|
“You” (or “Your”) shall mean an individual or Legal Entity exercising
|
||||||
|
permissions granted by this License.
|
||||||
|
|
||||||
|
“Source” form shall mean the preferred form for making modifications, including
|
||||||
|
but not limited to software source code, documentation source, and configuration
|
||||||
|
files.
|
||||||
|
|
||||||
|
“Object” form shall mean any form resulting from mechanical transformation or
|
||||||
|
translation of a Source form, including but not limited to compiled object code,
|
||||||
|
generated documentation, and conversions to other media types.
|
||||||
|
|
||||||
|
“Work” shall mean the work of authorship, whether in Source or Object form, made
|
||||||
|
available under the License, as indicated by a copyright notice that is included
|
||||||
|
in or attached to the work (an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
“Derivative Works” shall mean any work, whether in Source or Object form, that
|
||||||
|
is based on (or derived from) the Work and for which the editorial revisions,
|
||||||
|
annotations, elaborations, or other modifications represent, as a whole, an
|
||||||
|
original work of authorship. For the purposes of this License, Derivative Works
|
||||||
|
shall not include works that remain separable from, or merely link (or bind by
|
||||||
|
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
“Contribution” shall mean any work of authorship, including the original version
|
||||||
|
of the Work and any modifications or additions to that Work or Derivative Works
|
||||||
|
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||||
|
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||||
|
on behalf of the copyright owner. For the purposes of this definition,
|
||||||
|
“submitted” means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems, and
|
||||||
|
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||||
|
the purpose of discussing and improving the Work, but excluding communication
|
||||||
|
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||||
|
owner as “Not a Contribution.”
|
||||||
|
|
||||||
|
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
|
||||||
|
of whom a Contribution has been received by Licensor and subsequently
|
||||||
|
incorporated within the Work.
|
||||||
|
|
||||||
|
### 2. Grant of Copyright License
|
||||||
|
|
||||||
|
Subject to the terms and conditions of this License, each Contributor hereby
|
||||||
|
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||||
|
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||||
|
Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
### 3. Grant of Patent License
|
||||||
|
|
||||||
|
Subject to the terms and conditions of this License, each Contributor hereby
|
||||||
|
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||||
|
irrevocable (except as stated in this section) patent license to make, have
|
||||||
|
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||||
|
such license applies only to those patent claims licensable by such Contributor
|
||||||
|
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||||
|
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||||
|
submitted. If You institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||||
|
Contribution incorporated within the Work constitutes direct or contributory
|
||||||
|
patent infringement, then any patent licenses granted to You under this License
|
||||||
|
for that Work shall terminate as of the date such litigation is filed.
|
||||||
|
|
||||||
|
### 4. Redistribution
|
||||||
|
|
||||||
|
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||||
|
in any medium, with or without modifications, and in Source or Object form,
|
||||||
|
provided that You meet the following conditions:
|
||||||
|
|
||||||
|
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
|
||||||
|
this License; and
|
||||||
|
* **(b)** You must cause any modified files to carry prominent notices stating that You
|
||||||
|
changed the files; and
|
||||||
|
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
|
||||||
|
all copyright, patent, trademark, and attribution notices from the Source form
|
||||||
|
of the Work, excluding those notices that do not pertain to any part of the
|
||||||
|
Derivative Works; and
|
||||||
|
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
|
||||||
|
Derivative Works that You distribute must include a readable copy of the
|
||||||
|
attribution notices contained within such NOTICE file, excluding those notices
|
||||||
|
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||||
|
following places: within a NOTICE text file distributed as part of the
|
||||||
|
Derivative Works; within the Source form or documentation, if provided along
|
||||||
|
with the Derivative Works; or, within a display generated by the Derivative
|
||||||
|
Works, if and wherever such third-party notices normally appear. The contents of
|
||||||
|
the NOTICE file are for informational purposes only and do not modify the
|
||||||
|
License. You may add Your own attribution notices within Derivative Works that
|
||||||
|
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||||
|
provided that such additional attribution notices cannot be construed as
|
||||||
|
modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and may provide
|
||||||
|
additional or different license terms and conditions for use, reproduction, or
|
||||||
|
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||||
|
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||||
|
with the conditions stated in this License.
|
||||||
|
|
||||||
|
### 5. Submission of Contributions
|
||||||
|
|
||||||
|
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||||
|
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||||
|
conditions of this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||||
|
any separate license agreement you may have executed with Licensor regarding
|
||||||
|
such Contributions.
|
||||||
|
|
||||||
|
### 6. Trademarks
|
||||||
|
|
||||||
|
This License does not grant permission to use the trade names, trademarks,
|
||||||
|
service marks, or product names of the Licensor, except as required for
|
||||||
|
reasonable and customary use in describing the origin of the Work and
|
||||||
|
reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
### 7. Disclaimer of Warranty
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||||
|
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||||
|
including, without limitation, any warranties or conditions of TITLE,
|
||||||
|
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||||
|
solely responsible for determining the appropriateness of using or
|
||||||
|
redistributing the Work and assume any risks associated with Your exercise of
|
||||||
|
permissions under this License.
|
||||||
|
|
||||||
|
### 8. Limitation of Liability
|
||||||
|
|
||||||
|
In no event and under no legal theory, whether in tort (including negligence),
|
||||||
|
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||||
|
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special, incidental,
|
||||||
|
or consequential damages of any character arising as a result of this License or
|
||||||
|
out of the use or inability to use the Work (including but not limited to
|
||||||
|
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||||
|
any and all other commercial damages or losses), even if such Contributor has
|
||||||
|
been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
### 9. Accepting Warranty or Additional Liability
|
||||||
|
|
||||||
|
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||||
|
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||||
|
other liability obligations and/or rights consistent with this License. However,
|
||||||
|
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||||
|
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||||
|
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason of your
|
||||||
|
accepting any such warranty or additional liability.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# pplus-web
|
||||||
|
|
||||||
|
Copyright 2026 Scientific Computing Studio, LLC
|
||||||
|
|
||||||
|
This product includes software developed by Scienting ([scient.ing](https://scient.ing/)).
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0.
|
||||||
|
See the `LICENSE.md` file for the full license text.
|
||||||
|
|
||||||
|
## Third-party material
|
||||||
|
|
||||||
|
`THIRD_PARTY.md` lists what is not ours: CodeMirror and the packages bundled with it in `src/vendor/codemirror.js` (MIT; the notices are in `THIRD_PARTY.md`), the IBM Plex fonts, and the tools the build installs and does not redistribute. It also says where the widget stylesheets in `styles/course/` and two syntax definitions came from (the course site); they are ours, under the same license. The submodule `core/` (pplus-core) has its own `LICENSE.md`, `NOTICE.md` and `THIRD_PARTY.md`.
|
||||||
|
|
||||||
|
## Trademarks
|
||||||
|
|
||||||
|
"Mojo" and "Modular" are trademarks of Modular Inc. Programming+ is not affiliated with, sponsored by, or endorsed by Modular Inc.; it uses the names only to say which language and compiler it works with. "Compiler Explorer" and "godbolt.org" name the service by Matt Godbolt that Programming+ asks for the compiler's answers; Programming+ is not affiliated with it either.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Programming+ (pplus-web)
|
||||||
|
|
||||||
|
Programming+ takes a procedure from an idea to Mojo to the machine. It is built for a world where writing code is easy and knowing what it does is the job. It has three areas (`src/core/areas.ts`):
|
||||||
|
|
||||||
|
- **Bridge**: write the procedure as plain-English steps (**lingo**), equations written in LaTeX (**matho**), pseudocode precise enough to run, prove and translate (**pseudo**), or a specification you prove against (**speco**); the others follow as you type, and Mojo is generated from the pseudo, always labeled as generated.
|
||||||
|
- **Developer**: Mojo only. The checker's advice as you type; every step and every value of the Mojo that Programming+'s interpreter reads (a subset of the language: it says why when it declines a program) in one Run view; a fuzzer that lists what it tried; and the real Mojo compiler's answer, from godbolt.org.
|
||||||
|
- **Hardware**: the code beside a board you arrange, on a model machine: registers, memory, the stack, cache lines, the caches, virtual memory, the pipeline and the out-of-order core, with Mojo and its x86-64 as tabs, linked line by line. Its cycle counts are a teaching model, not a measurement of a real processor.
|
||||||
|
|
||||||
|
A library of verified routines (statistics, numerics, sequence alignment, molecular simulation, sequences, special functions; `#/library`) comes with it, each one usable by name with `USE` and open to step through, and so does a catalog of worked problems, each opening in every area it has something to show in, and any view can be shared as a link or embedded in a page. With Quarto, a page can also run a program kept beside it while the page renders, and show the run, a stepper, the flowchart, the proof and the rest without an iframe, down to the machine itself (registers, caches, the pipeline, the core, stepped). The **With Quarto** page (`#/quarto`) is a gallery of every shortcode.
|
||||||
|
|
||||||
|
It is a static single-page app: TypeScript compiled by `tsc`, no bundler, no framework, and no npm runtime dependency (CodeMirror 6 is vendored as one built module, `src/vendor/`). The site serves its own fonts and asks no other host for anything, except that Compile & run sends the Mojo pane and its input to godbolt.org, after asking the first time. This repository is the site; what programs mean (the languages, the translators, the Mojo checker and interpreter, the prover, the fuzzer, the machine model, and the stored answers of the real tools) is **pplus-core**, a project of its own, kept here as the git submodule `core/` and imported as `#core/...` ([core/README.md](core/README.md)). Everything it says about Mojo is pinned to **Mojo 1.2.0**: core's checker and interpreter are held to the real compiler's answers ([Compiler Explorer](https://godbolt.org)) on every program in core's corpus, and Compile & run asks the compiler about any other.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
Clone with the submodule (`git clone --recurse-submodules`, or `git submodule update --init` in an existing clone). With [pixi](https://pixi.sh) (it brings the pinned Mojo, Node and Python):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pixi run dev # build, then serve on http://localhost:4173
|
||||||
|
pixi run test # build, then every test
|
||||||
|
```
|
||||||
|
|
||||||
|
Without pixi, with Node (pixi pins 26; `package.json` asks for 20 or later, which nothing tests), `python3` for `npm run dev`'s server, and pandoc 3 for the Quarto extension's tests (without it they are skipped and say so):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install && npm test
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
Every command is a pixi task (`pixi task list` shows them with their descriptions). `tests/tasks.test.mjs` fails if this table and `pixi.toml` disagree. Core's own commands (the Mojo corpus, `play`, the CLI, the pinned Dafny) are in [core/README.md](core/README.md) and run with `pixi run --manifest-path core/pixi.toml <task>`.
|
||||||
|
|
||||||
|
| Task | What it does |
|
||||||
|
|---|---|
|
||||||
|
| **Build and test the site** | |
|
||||||
|
| `install` | Install TypeScript, the only npm dependency |
|
||||||
|
| `core-build` | Build pplus-core (`core/`) into `core/dist/`, which the site imports as `#core/` |
|
||||||
|
| `core-test` | Run pplus-core's own tests |
|
||||||
|
| `core-status` | Core's `mojo-status-strict` at the pinned commit: no Mojo program of ours fails (offline) |
|
||||||
|
| `build` | Build core, then compile `src/` to `dist/` |
|
||||||
|
| `watch` | Rebuild `dist/` on every change |
|
||||||
|
| `check` | Type-check only |
|
||||||
|
| `dev` | Build, then serve on http://localhost:4173 |
|
||||||
|
| `test` | Build, then run every test of the site |
|
||||||
|
| `check-pages <dir>` | Run every program embedded in the Quarto pages under a folder ([quarto/README.md](quarto/README.md)) |
|
||||||
|
| **Quarto** | |
|
||||||
|
| `quarto-export <name> <dir>` | Copy a `core/library/mojo/local/` program, its x86-64 and setup beside a Quarto page, and print the shortcode |
|
||||||
|
| `quarto-css` | Regenerate the extension's generated files (a test fails while they are out of date) |
|
||||||
|
| `quarto-engine <dir>` | Copy a built Programming+ and core into a site's `_extensions/pplus/engine`, for the rendered views ([quarto/README.md](quarto/README.md)) |
|
||||||
|
| `quarto-example` | Render the example site in `quarto/example`, every shortcode on real pages (needs Quarto) |
|
||||||
|
| **Ship** ([docs/deploy.md](docs/deploy.md)) | |
|
||||||
|
| `ci` | What CI runs: every test of the site, against the pinned core |
|
||||||
|
| `release-check` | Is the chain web → core → library consistent: each pointer checked out, clean and on its pushed branch, generated files current, Mojo pinned alike |
|
||||||
|
| `release-bump` | After a change in `core/library` or `core`: move the pointers bottom up, regenerate, run each gate, print what to push in order (`--commit` commits; nothing pushes) |
|
||||||
|
| `site` | Test, then assemble `site/` |
|
||||||
|
| `caddy-check` | Serve the assembled `site/` with a real Caddy under `docs/Caddyfile` and hold its headers, caching and missing-path answers |
|
||||||
|
| `package` | Zip what git tracks, and nothing it ignores, into `package/` for sharing |
|
||||||
|
| `deploy [slug] [target]` | Publish `site/` to `/srv/www/<slug>`, optionally over SSH |
|
||||||
|
|
||||||
|
## Where things are
|
||||||
|
|
||||||
|
```
|
||||||
|
AGENTS.md rules for changing the site (read first)
|
||||||
|
index.html, styles.css the page (with the import map that points #core/ at core/dist/) and the app's stylesheet
|
||||||
|
core/ pplus-core, a git submodule: languages, translators, prover, corpus, and the library
|
||||||
|
(pplus-library, its own submodule core/library) (core/README.md)
|
||||||
|
src/
|
||||||
|
main.ts the hash router
|
||||||
|
core/ the app's state and its URL codec, the session (a core Workspace with storage, versions,
|
||||||
|
compiles and the helper), the catalog with areas, the areas, saved versions, preferences
|
||||||
|
ui/ the shell (one per area), the home page, the library, the "With Quarto" gallery, the editor, the embeds, the views
|
||||||
|
ui/hw/ the Hardware area's machine board, over the course's x86-64 views (from core)
|
||||||
|
quarto/ the Quarto extension's rendered views: a program run and drawn by the views, as HTML (render.ts),
|
||||||
|
the small document they draw into outside a browser (dom.ts), the shortcode list (shortcodes.ts)
|
||||||
|
vendor/ CodeMirror 6 as one built module; scripts/vendor/ rebuilds it
|
||||||
|
styles/course/ the course site's widget stylesheets, copied unchanged (and bridge.css, ours)
|
||||||
|
tests/ node --test against dist/ (and core/dist/)
|
||||||
|
scripts/ the tasks above
|
||||||
|
quarto/ the Quarto extension (_extensions/pplus) and an example site using every shortcode (example/)
|
||||||
|
docs/ the documents below, and the Caddy site block
|
||||||
|
scratch/ ignored by git: a place for experiments
|
||||||
|
```
|
||||||
|
|
||||||
|
## Read next
|
||||||
|
|
||||||
|
| Document | For |
|
||||||
|
|---|---|
|
||||||
|
| [AGENTS.md](AGENTS.md) | Rules for anyone changing the site, coding agents included: the gate, what not to edit, conventions |
|
||||||
|
| [docs/app.md](docs/app.md) | What the app does: the three areas, translation between languages, its links, and how embeds behave |
|
||||||
|
| [docs/deploy.md](docs/deploy.md) | Building the site and publishing it to the droplet |
|
||||||
|
| [quarto/README.md](quarto/README.md) | Embedding views in a Quarto site |
|
||||||
|
| [core/README.md](core/README.md) | pplus-core: the engines, the prover, the Mojo corpus, the CLI, the pinned Dafny, and their docs |
|
||||||
|
| [core/docs/trust.md](core/docs/trust.md) | Every badge and verdict the app shows: what earns it, what it means, and what it does not mean |
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Copyright 2026 Scientific Computing Studio, LLC, under the Apache License 2.0 ([LICENSE.md](LICENSE.md)); [NOTICE.md](NOTICE.md) has the notices and a disclaimer of affiliation with Modular, and [THIRD_PARTY.md](THIRD_PARTY.md) lists what is not ours and its licenses.
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
# Security
|
||||||
|
|
||||||
|
Programming+ is a static site: the server sends files and keeps nothing.
|
||||||
|
There are no accounts. What a visitor writes stays in their browser: `localStorage` keeps their work, their saved versions, their recent compiles and their preferences, and a share link carries a program in the part of the URL after `#`, which browsers do not send to the server.
|
||||||
|
The site sends a program somewhere in one case: **Compile & run** posts the program's text, its input and the build options to [Compiler Explorer](https://godbolt.org) (godbolt.org), whose [privacy policy](https://github.com/compiler-explorer/compiler-explorer/blob/main/static/generated/privacy.pug) says what it keeps.
|
||||||
|
The page, its scripts, its styles and its fonts all come from the site itself; no other server is asked for anything (`tests/site-data.test.mjs` holds this, and the Content-Security-Policy in `docs/Caddyfile` enforces it in the browser).
|
||||||
|
|
||||||
|
## In scope
|
||||||
|
|
||||||
|
The site at pplus.scient.ing and this repository, in particular:
|
||||||
|
|
||||||
|
- **State from a link.** A share link, an embed URL and a `.pplus.json` file are decoded into the app's state (`src/core/state.ts`). A crafted one that runs script, reaches another origin, makes the page unusable, or changes what another visitor's saved work holds is a vulnerability.
|
||||||
|
- **Text that reaches the page.** Programs, their output, compiler messages, routine notes and every other string that ends up in the DOM, the views rendered by the Quarto extension included.
|
||||||
|
- **Embeds.** The app inside an iframe on another site (`#/embed/...`), the messages it exchanges with the page around it, and which sites may frame it (the `frame-ancestors` rule in `docs/Caddyfile`).
|
||||||
|
- **What goes to godbolt.org.** Anything other than the program, its input and the build options, or a request sent without the visitor pressing Compile & run.
|
||||||
|
- **The engines**, through the site: a program that makes pseudo, Mojo or x86-64 hang the page past its step limits or crash it (pplus-core's `SECURITY.md` has the engines' side).
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
godbolt.org itself (report to Compiler Explorer), the hosting provider, the volume of requests a visitor can make, and a visitor running code on their own machine with the repository's tasks.
|
||||||
|
|
||||||
|
## Reporting
|
||||||
|
|
||||||
|
Report a problem to Alex M. Maldonado at alex@scient.ing, with the link or file that shows it, the browser, and what happened.
|
||||||
|
You will get an acknowledgment within a week.
|
||||||
|
We promise no response time beyond that; one person maintains Programming+.
|
||||||
|
Please do not open a public issue for a problem that could hurt someone else until a fix is out.
|
||||||
|
|
||||||
|
Only what is deployed from the latest commit on `main` gets fixes.
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# Third-party material in pplus-web
|
||||||
|
|
||||||
|
Everything in this repository is ours, under the Apache License 2.0 ([LICENSE.md](LICENSE.md)), except what this file lists. `tests/third-party.test.mjs` holds it to the CodeMirror bundle's own banner, `styles/course/`, the Quarto extension's copies, the fonts `index.html` loads, `pixi.lock` and `package-lock.json`, so a change there fails the tests until this file says so. The submodule `core/` (pplus-core, and through it pplus-library) has its own THIRD_PARTY.md.
|
||||||
|
|
||||||
|
## Shipped with the site
|
||||||
|
|
||||||
|
### CodeMirror 6 (`src/vendor/`)
|
||||||
|
|
||||||
|
`src/vendor/codemirror.js` is one ES module that `scripts/vendor/codemirror.sh` builds with esbuild from these packages' sources on GitHub; `src/vendor/cm-types/` and `codemirror.d.ts` are their type declarations. Every package is under the MIT license, by Marijn Haverbeke and others. `src/vendor/CODEMIRROR-LICENSE` (a copy of @codemirror/state's LICENSE) carries the first notice below; the others are here.
|
||||||
|
|
||||||
|
| Package | Version | Repository | Copyright notice |
|
||||||
|
|---|---|---|---|
|
||||||
|
| @codemirror/state | 6.6.0 | codemirror/state | Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @codemirror/view | 6.41.0 | codemirror/view | Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @codemirror/language | 6.12.3 | codemirror/language | Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @codemirror/commands | 6.10.3 | codemirror/commands | Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @codemirror/search | 6.6.0 | codemirror/search | Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @lezer/common | 1.5.2 | lezer-parser/common | Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @lezer/highlight | 1.2.3 | lezer-parser/highlight | Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| @lezer/lr | 1.4.8 | lezer-parser/lr | Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| style-mod | 4.1.3 | marijnh/style-mod | Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| w3c-keyname | 2.2.8 | marijnh/w3c-keyname | Copyright (C) 2016 by Marijn Haverbeke <marijn@haverbeke.berlin> and others |
|
||||||
|
| crelt | 1.0.6 | marijnh/crelt | Copyright (C) 2020 by Marijn Haverbeke <marijn@haverbeke.berlin> |
|
||||||
|
| @marijn/find-cluster-break | 1.0.2 | marijnh/find-cluster-break | Copyright (C) 2024 by Marijn Haverbeke <marijn@haverbeke.berlin> |
|
||||||
|
|
||||||
|
Each notice above goes with this permission notice, which every package's LICENSE file carries word for word:
|
||||||
|
|
||||||
|
```
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
```
|
||||||
|
|
||||||
|
### The course's widget stylesheets (`styles/course/`, `quarto/_extensions/pplus/course/`)
|
||||||
|
|
||||||
|
`tokens.css`, `kit.css` and `asm86.css` are the course site's own stylesheets (`static/css/` in its repository), copied unchanged; [styles/course/README.md](styles/course/README.md) records each one's course path and sha256, and `tests/course-css.test.mjs` holds the copies to those hashes. `pixi run quarto-css` copies the same three into `quarto/_extensions/pplus/course/`. `bridge.css` was written for this repository. All four are ours: Copyright Scientific Computing Studio, LLC, under the Apache License 2.0. The three are listed here because they are copies held to the course's own files, not because they are someone else's.
|
||||||
|
|
||||||
|
### The Quarto extension's syntax definitions (`quarto/_extensions/pplus/syntax/`)
|
||||||
|
|
||||||
|
`pseudo.xml` and `lingo.xml` are KDE syntax definitions that came from the course; their headers say `author="BIOSC 1540"` (the course) and `license="Apache-2.0"`. They are ours, like the stylesheets above. `mojo.xml` is pplus-core's `library/syntax/mojo.xml`, copied by `pixi run quarto-css` (its header says `author="Programming+"` and `license="Apache-2.0"`).
|
||||||
|
|
||||||
|
### Fonts
|
||||||
|
|
||||||
|
| Font | License | How the site gets it |
|
||||||
|
|---|---|---|
|
||||||
|
| IBM Plex Sans, IBM Plex Mono | SIL Open Font License 1.1, Copyright 2017 IBM Corp. with Reserved Font Name "Plex" | Seven `.woff2` files in `fonts/`, copied unchanged from npm `@ibm/plex-sans@1.1.0` and `@ibm/plex-mono@1.1.0` and served by the site (`fonts/plex.css`); the OFL text is `fonts/LICENSE.txt`, and `fonts/README.md` gives each file's source and sha256. No font host is asked for anything. |
|
||||||
|
|
||||||
|
## Installed to build and test, not redistributed
|
||||||
|
|
||||||
|
pixi installs these into `.pixi/` and npm into `node_modules/`; git ignores both, and `scripts/assemble.sh` copies none of them into `site/`.
|
||||||
|
|
||||||
|
| Tool | Version | From | License | In what we ship |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Mojo | 1.2.0 | conda.modular.com, by pixi | LicenseRef-Modular-Proprietary (Modular's license, as `pixi.lock` records it) | Nothing. The Quarto views can run a page's Mojo on the compiler a site's author installs. |
|
||||||
|
| Node.js | 26.10.0 | conda-forge, by pixi | MIT | Nothing. |
|
||||||
|
| Python | 3.14.7 | conda-forge, by pixi | Python-2.0 | Nothing. The dev server and the package script. |
|
||||||
|
| pandoc | 3.14 | conda-forge, by pixi | GPL-2.0-or-later | Nothing. The Quarto extension's tests run its Lua filter in pandoc. |
|
||||||
|
| TypeScript | 6.0.3 | npm (`package-lock.json`) | Apache-2.0 | Nothing. `tsc` compiles `src/`; the output is our code. |
|
||||||
|
|
||||||
|
Dafny, the other pinned tool, is pplus-core's (`core/scripts/dafny.py` downloads its release zip into `core/.tools/`, ignored by git); the site neither downloads nor serves it.
|
||||||
|
|
||||||
|
## Services the site uses
|
||||||
|
|
||||||
|
- [Compiler Explorer](https://godbolt.org) (godbolt.org): **Compile & run** sends the program, its input and the build options there; its [privacy policy](https://github.com/compiler-explorer/compiler-explorer/blob/main/static/generated/privacy.pug) says what it keeps.
|
||||||
|
|
||||||
|
## Names
|
||||||
|
|
||||||
|
"Mojo" and "Modular" are trademarks of Modular Inc. Programming+ is not affiliated with or endorsed by Modular. "Compiler Explorer" and "godbolt.org" name the service by Matt Godbolt that the app asks.
|
||||||
Submodule
+1
Submodule core added at 401084bab3.
@@ -0,0 +1,76 @@
|
|||||||
|
# The site block for one slug under /srv/www. Caddy issues and renews the
|
||||||
|
# certificate itself, so this is the whole configuration for the host.
|
||||||
|
#
|
||||||
|
# /srv/www/pplus is a symlink to the current release (scripts/deploy.sh);
|
||||||
|
# Caddy follows symlinks by default. Routing lives in the URL hash, so the one
|
||||||
|
# page is /, and a path that is not a file is sent there (see handle_errors).
|
||||||
|
# `pixi run caddy-check` serves site/ with a real Caddy under this file and
|
||||||
|
# holds what it answers.
|
||||||
|
# Add both blocks: the snippet first, then the site.
|
||||||
|
|
||||||
|
# The security headers, for every answer: the files, and index.html served for a 404.
|
||||||
|
(pplus_headers) {
|
||||||
|
# What the page may load and where it may send. Everything is this site's own,
|
||||||
|
# except Compile & run, which posts the Mojo pane and its input to godbolt.org.
|
||||||
|
# script-src the modules, plus the two inline scripts of index.html by
|
||||||
|
# hash: the theme set before paint, and the import map (which
|
||||||
|
# cannot be a file). tests/csp.test.mjs fails when index.html
|
||||||
|
# and these hashes disagree.
|
||||||
|
# style-src 'unsafe-inline' because the views and CodeMirror set style
|
||||||
|
# attributes and <style> elements; no markup comes from data.
|
||||||
|
# frame-src the With Quarto gallery shows this app's own embeds.
|
||||||
|
# frame-ancestors course pages embed views in iframes, so no
|
||||||
|
# X-Frame-Options here; framing is allowed from the course
|
||||||
|
# origins, and from a local `quarto preview` of them.
|
||||||
|
header {
|
||||||
|
Content-Security-Policy "default-src 'self'; script-src 'self' 'sha256-I0FTUDEvZjevwnUsTxL/Wv6yjSk4+kJk+rHFqkJdfzU=' 'sha256-RDS2ylVnVHGfhqa7CxiLHKiZwFxVxLSwfQQ6NYsJmuM='; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data: blob:; connect-src 'self' https://godbolt.org; frame-src 'self'; worker-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self' https://scient.ing https://*.scient.ing http://localhost:* http://127.0.0.1:*"
|
||||||
|
Referrer-Policy "no-referrer"
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), clipboard-write=(self)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pplus.scient.ing {
|
||||||
|
root * /srv/www/pplus
|
||||||
|
encode zstd gzip
|
||||||
|
file_server
|
||||||
|
|
||||||
|
# Caching. Only a file whose name changes with its content may be cached as
|
||||||
|
# immutable, and no file here has such a name (no bundler adds hashes), so:
|
||||||
|
# the page, the modules and the stylesheets change on any deploy: the
|
||||||
|
# browser keeps them but asks again each time (no-cache), and the answer
|
||||||
|
# is a 304 with no body while the file is unchanged (file_server sends an
|
||||||
|
# ETag), so a stale module never runs against a new index.html;
|
||||||
|
# the fonts change only when fonts/ is replaced by hand, and a stale one
|
||||||
|
# is only an older glyph: kept for 30 days without asking;
|
||||||
|
# VERSION is what CI's smoke test reads back after a deploy: never kept.
|
||||||
|
@page path / /index.html
|
||||||
|
header @page Cache-Control "no-cache"
|
||||||
|
@code path *.js *.css
|
||||||
|
header @code Cache-Control "no-cache"
|
||||||
|
@fonts path /fonts/*.woff2
|
||||||
|
header @fonts Cache-Control "public, max-age=2592000"
|
||||||
|
header /VERSION Cache-Control "no-store"
|
||||||
|
# build.json names the three commits the site was built from: asked again each time, like the page
|
||||||
|
header /build.json Cache-Control "no-cache"
|
||||||
|
# the license and notices beside index.html: shown as text, not downloaded
|
||||||
|
@notes path /LICENSE.md /NOTICE.md /THIRD_PARTY.md
|
||||||
|
header @notes Content-Type "text/plain; charset=utf-8"
|
||||||
|
|
||||||
|
import pplus_headers
|
||||||
|
|
||||||
|
# A path that is not a file. The app's routes live after the #, so the only page is /, and index.html names its
|
||||||
|
# scripts, styles and fonts relative to itself: served in place at /a/b/c it would ask for /a/b/dist/main.js
|
||||||
|
# and come up blank. So a missing path that looks like a page (no file extension) is sent to /, and the browser
|
||||||
|
# carries the # across; a missing file is a plain 404, which is what a script or font that is gone should be.
|
||||||
|
handle_errors {
|
||||||
|
import pplus_headers
|
||||||
|
header Cache-Control "no-store"
|
||||||
|
@lostpage {
|
||||||
|
expression {http.error.status_code} == 404
|
||||||
|
not path *.*
|
||||||
|
}
|
||||||
|
redir @lostpage / 302
|
||||||
|
respond "{http.error.status_code} {http.error.status_text}" {http.error.status_code}
|
||||||
|
}
|
||||||
|
}
|
||||||
+234
@@ -0,0 +1,234 @@
|
|||||||
|
# What the app does
|
||||||
|
|
||||||
|
Programming+ takes a procedure from an idea to Mojo to the machine. This is the reference for the app itself: the three areas, their links and embeds, and what each part of the workspace does. For commands, see the [README](../README.md).
|
||||||
|
|
||||||
|
## The areas
|
||||||
|
|
||||||
|
The app has three areas, one workspace layout each (`src/core/areas.ts`, the `AREAS` table; the names are placeholders the owner can change in one line). A problem is one saved state shared by all three, so moving from one area to another carries the work along. The area comes from the route, not the state. Each area is its own page, reached from the nav and the home page; the toolbar names the area you are in and offers a switch only to an area that would show the open pane exactly as it is (`safeSwitches` in `src/core/areas.ts`): in practice Developer and Hardware on the same Mojo, and the Bridge's Mojo tab once the student's Mojo is its translation. A learner moving between areas therefore never finds the work changed by the move itself; **Edit in Developer** and **Open in Hardware** are the deliberate moves that carry work across.
|
||||||
|
|
||||||
|
| Area | For | Panes | Inspect tabs | Dock |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **Bridge** (`bridge`) | taking a written problem or idea into Mojo | lingo, matho, pseudo, speco, Mojo | run, flowchart, data flow, prove, tests | setup, output, problems, compiler |
|
||||||
|
| **Developer** (`dev`) | Mojo coding | Mojo | run, flowchart, data flow, tests | setup, output, problems, compiler |
|
||||||
|
| **Hardware** (`hw`) | Mojo and x86-64 with the machine in view | Mojo, x86-64 | none: two panes, the code and the board, whose cards hold the run, registers, memory, caches, pipeline, chip, setup, output, problems and compiler | none |
|
||||||
|
|
||||||
|
Each catalog problem names the area it opens in (`area` on the exercise): Hardware for `asm-*` problems, Developer for ones that are only a Mojo program, Bridge for the rest. The panes a state is shown with come from the area, so a link made in one area opens in another on that area's first choice of pane. Layout (the dividers, the dock tab, what is folded) is kept per area (`layout: { bridge, dev, hw }` in the state). **Open in Hardware** on the compiler's listing puts a function into the x86-64 pane and switches area.
|
||||||
|
|
||||||
|
### The home page
|
||||||
|
|
||||||
|
The home page (`src/ui/home.ts`) opens with why the platform exists: work is done by human and artificial agents, producing code and analyses is cheap, and someone still has to take responsibility for the output, which takes knowing what it does step by step (the hero's sign-off panel lists who might have made it above the sentence that has to be signed). Under that reason the hero says what Programming+ is, in the sentence this document, the README and `index.html` share (`DESCRIPTION` in `src/core/site.ts`). Three columns follow (producing got cheap, ownership did not, the gap from novice to expert is where tools are missing), with AlphaFold as the example. Then each area gets a card with its name and tagline from `AREAS` and a sample the engines make on the spot, each in a window of the same height: the Bridge turns the mean, written as an equation, into pseudo, lingo and labeled Mojo through the same hub the panes use, with what each notation is beside its name, since this is where the names first appear; Developer shows the checker's advice on a moved-out value and the first steps of `count_base`; Hardware shows the registers and the cache line of the first load in `asm-two-pointers` on the teaching machine. **Why Mojo** says why it is the one real language: it reads plainly, it is compiled with strict rules there is always a precise answer to, it spans a first program to hand-written GPU kernels (which Programming+ does not show yet), and, as an opinion marked as one, we believe it will lead in the computational sciences. The notations section shows `count_base` in six even boxes, except matho, which cannot express it (B is a character) and says so. The problem list shows the areas each problem opens in (`areasFor` in `src/core/areas.ts`: its own area first, then the Bridge if it has lingo, matho, pseudo or speco, Developer if it has Mojo, Hardware if it has x86-64), with a link to each, and filters by area. The footer (`src/ui/footer.ts`, on the home page, the library and With Quarto) links the license and notices that `scripts/assemble.sh` ships with the site (`LICENSE.md`, `NOTICE.md`, `THIRD_PARTY.md`), says that Programming+ is not affiliated with or endorsed by Modular, links the source when `SOURCE_URL` in `src/core/site.ts` is set, shows the commit an assembled site was built from, and holds **What this site stores and sends** (`SITE_DATA`; `tests/site-data.test.mjs` holds each statement to the code).
|
||||||
|
|
||||||
|
### The Bridge workspace
|
||||||
|
|
||||||
|
Four languages are kept in step (see [Translation between languages](#translation-between-languages)): tabs run **lingo, matho, pseudo, speco**, then **Mojo (from pseudo)** set slightly apart.
|
||||||
|
|
||||||
|
- **Link state on every tab.** ✎ the pane you are editing (the others follow it), ⇄ in step, ⚠ not in step (the reason is in the tooltip and in the banner above the editor), nothing for a pane still **as authored** (nothing has been translated yet; the first edit makes that pane the authority).
|
||||||
|
- **Typing never fights the cursor.** The pane being edited is never rewritten. The other panes are brought up to date when their tab is shown, replacing only the part of the text that changed, so the cursor and scroll position of a pane stay put. Each such update is its own undo step (the editor's `setSynced`, a `sync` user event that history does not join to typing), so Ctrl+Z in a pane steps back to what it showed before the sync, and, as with any change to a pane, that pane then becomes the authority. Loading a problem is not an undoable edit.
|
||||||
|
- **A pane that is not in step** (matho for a `WHILE`; anything while the pane you edited does not read) keeps its last text, is read-only, and says why, with an **Edit anyway** button that makes it the authority. The stepper does not step a stale lingo or matho pane; it steps the pseudo.
|
||||||
|
- **Mojo (from pseudo)** is read-only, labeled *Generated from pseudo*, and computed from the pseudo on the fly (`Session.derivedMojo()`; the state's own `sources.mojo` is untouched). It steps in the Mojo interpreter, is checked, and **Compile & run** sends it to the real compiler. **Edit in Developer** copies it into the Developer area's Mojo pane (asking first if that pane holds something else) and records `mojoOrigin: 'generated'`; the first edit there makes it `'generated-edited'`, and the Mojo pane says so.
|
||||||
|
- **Prove and Tests** work on the hub's pseudo with the speco woven in, whichever pane you edited.
|
||||||
|
|
||||||
|
Every area is an IDE-style workspace: the language panes as tabs over one editor; under it the stepper and what runs next; beside it an inspect panel (the Run view, flowchart, data flow, proof, tests) whose tabs appear only when they apply to the pane; under everything a dock for the output, the problems, the real compiler's answer, and the machine model's numbers. A catalog of worked problems comes with it.
|
||||||
|
|
||||||
|
### The Hardware area
|
||||||
|
|
||||||
|
Two panes, and nothing shown twice. Everything the board shows is the model machine's (core's `src/engines/asm86/`): its cycle counts and cache behavior are a teaching model, not a measurement of a real processor, and the views say "on the model machine" where they state a cost. On the left the code (the Mojo and x86-64 tabs over one editor) and the stepper under it. On the right the **board** (`src/ui/hw/board.ts`), a set of cards in a two-column grid (twelve tracks, a half card spanning six): the course's own x86-64 views (`core/src/engines/asm86/views.js` and `hwviews.js`, the widgets the course pages use, with the course's stylesheets from `styles/course/`), mounted over the x86-64 pane's run and moved by the stepper, and the app's own views as cards too: Setup, Output, Problems, the Compiler, the Run view (for the Mojo pane), the counters, and the cache lines. The area has no inspect panel and no dock (`workspace: 'board'` in `AREAS`); Compile & run and a click on a diagnostic bring their card into view, adding it if the board does not show it.
|
||||||
|
|
||||||
|
**Arranging it.** Presets along the top set out cards that make sense to see at once. **+ Add a view** opens every card by group (Program, Registers and memory, Memory system, Time, The chip); click one to put it on the board or take it off. Drag a card by its title to move it (or use ↑ ↓), ↔ widens it to the whole row or narrows it to share one, × takes it off. The arrangement is kept per area (`layout.hw.board`, a list of `{ id, wide? }`, cleaned by `normalizeBoard`), and the preset buttons show which preset it is, if any. Every change is a pure function in `src/core/hardware.ts` (`moveItem`, `addItem`, `removeItem`, `toggleWide`, `presetOf`).
|
||||||
|
|
||||||
|
The presets:
|
||||||
|
|
||||||
|
- **Registers and memory**: a card per register the program touches (amber when the last instruction wrote it, with the value before), with every narrower name (`eax`, `ax`, `al`, `ah`) for the registers the program also uses at a narrower width; the flags, with the ones the last instruction read; the effective address as base + index × scale + displacement; the memory regions byte by byte with the load (blue) or store (purple) highlighted; and the stack as eight-byte slots with `rsp` and `rbp` marked.
|
||||||
|
- **Caches**: memory below the instruction set. **Cache lines** (the board's own view, `src/ui/hw/lines.ts`) shows, for each load and store of the last instruction, the whole line it touched as a row of bytes: the bytes this access used, the ones the program used before, the ones it uses later, and the ones it never uses, with where the line was found (an L1d hit, or the level it came from) and "used 8 of this line's 64 bytes". Beside it the course's L1d cache as sets and ways (hit green, miss red, the evicted line named), the hierarchy with the path each access took and running totals, and, with virtual memory on, the page walk and the TLB.
|
||||||
|
- **Pipeline**: time. The classic five-stage pipeline cycle by cycle (stalls amber, wrong-path fetches red, the whole run's lost cycles by cause), the micro-ops the last instruction became and the ports each can run on, what bounds the whole run (the dependency chain, the busiest ports, the front end), and the out-of-order timeline of when each instruction entered, ran and retired.
|
||||||
|
- **Whole chip**: the core from branch predictor to memory with the parts the last instruction used lit up, each lit edge with an arrowhead on the end its data reached (a load's data back up from wherever it was found to the load port, a fetch that missed back into L1i, a store out through the store buffer, the result into the registers from the port that produced it); the listing with each instruction's address and bytes beside the last instruction's machine code broken into prefix, REX, opcode, ModRM, SIB, displacement and immediate; and last, inside the out-of-order core (reorder buffer, ports, rename table, with its own cycle buttons), whose table grows and shrinks with what is in flight.
|
||||||
|
|
||||||
|
**The listing and the encoding as a pair.** When the two are next to each other at half width, `board.ts` marks them as a pair: on a board at least 960px wide they share a row two to one, and on a narrower one the encoding sits under the listing. The listing then scrolls in its own box, as tall as the encoding (300px when stacked), and keeps the instruction about to run in view; only that box scrolls, never the page.
|
||||||
|
|
||||||
|
**Nothing moves while stepping.** A card never gets shorter while one run is stepped: each keeps the tallest height it has reached as its minimum. When the board is built it first draws a spread of the run's steps (all of a short run, forty of a long one, always the last) before the browser paints, so views that grow with the run (the pipeline, the timeline) start at their final size. The minimums start over with a new run, machine or arrangement, and when the board's width changes. The same rule holds the Run view's panel of followed variables, and a string or list with no value yet keeps the height of its ruler. Elsewhere the boxes that change with each step have fixed sizes: what runs next (two lines, each cut with an ellipsis, the whole text in its tooltip), the loop status (one line), the register cards' "was" line, and in `styles/course/bridge.css` the core's caption, the address arithmetic and the cache-line list.
|
||||||
|
- **Mojo and the compiler**: the Run view of the Mojo pane, the real compiler's answer and listing (with Open in Hardware), the output and the problems.
|
||||||
|
- **Counters** (a card in any arrangement): the model machine's totals for the run, in the style of `perf stat`, and for code sent from the Compiler view what each Mojo line cost on it.
|
||||||
|
|
||||||
|
**Mojo and x86-64.** The two are tabs over the one editor, never split side by side. x86-64 sent from the Compiler view ends each instruction with `; mojo line N`, godbolt's own line table (`forSimulator` in `core/src/mojo/att.ts`); through it, clicking a line in either pane marks the matching lines in the other tab, lit when that tab is selected (`asmMojoLines` and `relateAsmMojo` in `src/core/hardware.ts`). A short note in the pane head says so; for x86-64 written by hand, which has no such table, it says the lines are not linked. The Mojo there carries its generated label and godbolt badge, as everywhere. Compiling needs the network; without a listing the area works on hand-written x86-64 alone.
|
||||||
|
|
||||||
|
The board's **machine** switch (also in the Setup card): `teaching` (caches small enough that misses happen on small data), `realistic` (shaped like a desktop core: 64-byte lines, an L3, a next-line prefetcher), or `ideal`; and **virtual memory** turns on paging with a TLB. The state stores it as one string (`machine: 'teaching+paging'`; `parseMachine` and `machineSpec` in `src/core/hardware.ts`), and the run hands it to the hardware model through the trace, so the board's views and the counters always describe the same machine. With virtual memory on, a line is the physical one and the access keeps the address the program wrote.
|
||||||
|
|
||||||
|
What each card mounts, with what options, and the frame each view draws at each step are decided DOM-free in `src/core/hardware.ts` and tested for every problem with assembly (`tests/hardware.test.mjs`); a view that throws says so in its own card and leaves the rest working. The course files draw dark on `body.quarto-dark`, so the app keeps exactly one of `quarto-light` and `quarto-dark` on `<body>`, matching the theme it shows (`src/ui/theme.ts`).
|
||||||
|
|
||||||
|
### Mojo badges
|
||||||
|
|
||||||
|
Two independent badges sit beside any Mojo the site shows (pane head, Compiler view, Mojo embeds, Share dialog):
|
||||||
|
|
||||||
|
- **Generated from pseudo** (or **Started from generated Mojo** once edited). `mojoProvenance` (`src/core/provenance.ts`) answers for every view: the Bridge's Mojo is always generated, elsewhere `PlayState.mojoOrigin` says. Generated Mojo starts with a header comment, so copying it keeps the warning. It never shows beside "verified on Mojo" (which is only for an exercise's own program). Only the Developer area's **I've reviewed this** button clears it (`Session.clearMojoOrigin`), taking the header comment off too; compiling and editing do not.
|
||||||
|
- **Compiled on godbolt**, with the outcome (ran, exit N / did not compile / timed out), the compiler and build level in the tooltip, or **Edited since compile**. It is keyed by a hash of source, input and build level (`compiledStatus` in `src/core/compiles.ts`), so a one-character edit, another level or another input removes it. Full answers are the newest 16 in `pplus.compiles`; a summary index (`pplus.compiled`, up to 300) lets the badge outlive them. Neither is in `PlayState`, a share link or a file: a link never claims a compile that this browser did not make. The badge means the compiler answered, not that the program is right.
|
||||||
|
|
||||||
|
### Best practices (the helper)
|
||||||
|
|
||||||
|
`core/src/mojo/practices.ts` (DOM-free) turns the gap between the translator's literal Mojo and the Mojo a person would write into things to learn from. It is **off by default in both the Bridge and the Developer area**: each area has its own switch (the toolbar's "Best practices" button), remembered in this browser (`pplus.practices.bridge`, `pplus.practices.dev`; `src/core/prefs.ts`), never in `PlayState` or a link. While a switch is off the rules never run (a spy test holds it to that) and nothing about them is shown. The translator never imports the helper, so the Bridge's Mojo is the same literal translation either way (a grep gate and a snapshot test keep it so).
|
||||||
|
|
||||||
|
A rule is `{ id, title, why, docUrl, example, apis, detect }`. The starting rules: declare-then-assign → `var n = …`; `x = x + 1` → `x += 1`; an index loop that only reads codepoints → `for cp in t.codepoint_slices()`; `raises` on a function that cannot raise; a never-changed number that sizes a loop → `comptime`; argument conventions (`imm` written out is the default; `mut` on an argument never changed); `reserve` before a loop that appends a known number of times; `name^` for a last use handed to a `var` argument; `.copy()` for a list copy that says so. (Mojo 1.1.0 renamed the `read` convention `imm`, so the helper says `imm`.)
|
||||||
|
|
||||||
|
- **Bridge:** the Best practices dock tab lists each finding with the Mojo line, the pseudo line it came from (the hub's line map), the reason, before and after, the manual link, and, where true, how to write the pseudo so the translator writes the better form. Clicking one lights both lines. The Mojo is read-only, so rewrites are shown, not applied. **Show idiomatic version** (in the Mojo tab, off until chosen) shows a copy with the safe rewrites applied, only if it passes the checker no worse than the literal one and the interpreter prints exactly what the literal one prints; it keeps the generated label ("Generated from pseudo, with N best-practice rewrites").
|
||||||
|
- **Developer:** findings are `note` diagnostics with origin "best practices" (never an error or a warning, so they never look like the compiler) in Problems and the gutter, each with a one-click fix where the rewrite is safe. A rule that cannot promise a safe rewrite (`comptime`) explains and leaves the editing to the student.
|
||||||
|
- **Tests** (`core/tests/practices.test.mjs`): every rule's example passes the checker, runs, and prints the same before and after, and the rule's fix turns one into the other; every method a rewrite names is in the harvested index; a false-positive gate runs the rules over Modular's own tested programs in `core/library/mojo/corpus/manual/` against a reviewed allowlist; each exercise's findings are pinned by a snapshot; applying every fix to each exercise's generated Mojo and each `core/library/mojo/local/` program keeps it checking and printing the same.
|
||||||
|
|
||||||
|
### Saved versions
|
||||||
|
|
||||||
|
A student can save the state of their work under a name and come back to any saved version from the **Versions** menu in every area's toolbar (`src/core/versions.ts`, DOM-free, storage injectable).
|
||||||
|
|
||||||
|
- **What a version holds:** every source, the link bookkeeping (`sync`), where the Mojo came from (`mojoOrigin`), the call, the input, the assembly setup and machine, and the build level, plus the area it was saved in, a name, and a time. Not the layout, the step, or the open tab: restoring a version changes the work and never where you are looking. (`EDITS`, which decides whether work differs from the problem as written, keeps leaving `sync` out; the version fingerprint adds it, so restoring brings the links back as they were.)
|
||||||
|
- **Where they live:** `localStorage`, one list per piece of work: `pplus.versions.<problemId>`, or `pplus.versions.ws.<workspaceId>` for work that began from a share link or a file (`PlayState.workspace` is added when such work is first saved, and the address is updated so a reload finds it). Every area shows the same list. At most 50 per list: when it is full the oldest automatic version makes room, and if only named ones are left the save is refused rather than delete one. The menu says when the browser's storage is nearly full.
|
||||||
|
- **Never losing work:** choosing a version, **Reset**, and **See the new version** first save work that no version holds as "Before switching (time)" or "Before reset (time)". If that save is refused, the switch does not happen.
|
||||||
|
- **A problem that changed under saved edits** shows a banner with **See the new version**: your edits become the version "My edits, before the problem changed" and the problem opens as it is now.
|
||||||
|
- **Between browsers:** Share → Download writes the state and, with a checkbox (on by default), its versions; Open… puts them in the right list and never overwrites a version that has the same id. A share link carries only the current state.
|
||||||
|
|
||||||
|
### The library
|
||||||
|
|
||||||
|
**Library** (`#/library`, `src/ui/library.ts`) lists every routine of pplus-library, as core's registry holds it (`#core/library/registry.js`, generated from the submodule `core/library`), grouped by module, each with a count of how its checks ended. A routine's page (`#/library/md.LennardJones`) shows the routine's pseudo, its cases with the results the pseudo gives, every check with its detail (cases, prover, fuzzer, generated Mojo, each reference implementation per way of running it, the proof), each reference's source with its note and tolerance, the Dafny proof, and the sources of the method. **Open in the Bridge** opens the routine as a problem with the id `lib:<module>.<Name>` (`src/core/library.ts`): its pseudo in the pseudo pane and its first case as the call, so it can be stepped through, which a program that only USEs it never does (a run steps over library routines; core's [docs/library.md](../core/docs/library.md)). Edits are saved per routine, like a problem's.
|
||||||
|
|
||||||
|
### With Quarto
|
||||||
|
|
||||||
|
`#/quarto` (`src/ui/quarto.ts`, linked from the nav, the footer, and a section of the home page that shows one shortcode beside the stepper it makes) is a gallery of the Quarto extension's shortcodes ([quarto/README.md](../quarto/README.md)). Each card shows what an author writes (the shortcode, and every program file it names, in tabs) and what the reader gets, drawn when the card scrolls into view by the same code `quarto render` runs: `renderStatic` for the rendered views and the machine, this app's own `#/embed/...` route in an iframe for the live ones. The cards can be filtered by kind (rendered with the page, the machine, live, text); one machine card has a menu of every `pplus-hw-<view>` and draws the one chosen. `#/quarto#<shortcode>` scrolls to a card, `#/quarto#setup` to the set-up steps. The page loads the extension's `pplus.css` and `pplus.js` from the site (`scripts/assemble.sh` copies the extension into `site/`), so the steppers and "make it live" behave exactly as on a Quarto page. The shortcodes, their options and the sample programs come from `src/quarto/shortcodes.ts` and `galleryFiles()`; `tests/quarto-gallery.test.mjs` renders every sample and holds each program in it to its header lines.
|
||||||
|
|
||||||
|
## Links
|
||||||
|
|
||||||
|
| URL | Opens |
|
||||||
|
|---|---|
|
||||||
|
| `/#/` | the home page: pitch, problems, reference |
|
||||||
|
| `/#/<area>/p/<problem>` | a catalog problem in an area (`bridge`, `dev` or `hw`), with the student's saved edits (localStorage) |
|
||||||
|
| `/#/<area>/s/<state>` | a shared state in an area: every pane, the call, the setup, the step — compressed into the link |
|
||||||
|
| `/#/embed/<view>/<state>` | one view, no chrome, for an `<iframe>` |
|
||||||
|
| `/#/embed/<view>/p/<problem>` | one view of a catalog problem |
|
||||||
|
| `/#/quarto` | With Quarto: the gallery of the Quarto extension's shortcodes (`#/quarto#<section>` scrolls to one) |
|
||||||
|
|
||||||
|
**What a link may hold.** Anyone can make a link, so the app reads one with limits (`LIMITS`, `decodeState` and `readStateFile` in `src/core/state.ts`): a blob of more than a million characters, one that unpacks to more than 2 MB (a decompression bomb), a `.pplus.json` larger than that, a link cut short or changed, and a file that is not a Programming+ state are each refused with a sentence that says which (`StateError`), before any engine sees them. A shared state (`#/<area>/s/...`) is the sender's work: it is never saved over this browser's own save for the problem it names, so opening someone's link to `count-base` cannot replace your `count-base` work (its saved versions still go to that problem's list, which only adds). A problem id in a state is only ever an id (`PROBLEM_ID`). A pane that an engine cannot read without failing (brackets nested tens of thousands deep, past what a parser's recursion can follow) gets one error, `engine-stop`, and the rest of the page keeps working (`Session.cached`); anything else that goes wrong while a page opens shows a page that says what, never a blank one.
|
||||||
|
|
||||||
|
**Work that takes the page down.** The engines stop a program that runs too long or makes values too large (core's [limits.md](../core/docs/limits.md)), but should a program still use up the tab's memory first, the browser kills the page. Saved work runs again as the page opens, so before it runs its save is marked busy in this tab (`src/core/guard.ts`, in `sessionStorage`), and the mark is cleared once the page has been idle for a moment and when it closes normally. A reload that finds the mark puts that save aside as a named version, "When the page stopped (time)", opens the problem as written, and says so; an embed drops the reader's edits instead. If a saved state makes the page fail in any other way, the page that says so offers the same: keep the work as a version and open the problem as written.
|
||||||
|
|
||||||
|
Nothing else is a route: `#/p/<problem>`, `#/s/<state>` and the other earlier forms open the home page, with a note at the foot of the page that there is no page at that address (`isUnknownRoute` in `src/core/state.ts`). A problem or library routine that does not exist, in the app or in an embed, is a page that says so; so is a link that does not open (below). `<view>` is `playground` (the whole workspace; `?area=dev` picks the area, Bridge by default or the problem's own), `trace`, `table`, `flow`, `data`, `life`, `proof`, `tests`, `problems`, `compiler`, `asm` (the machine numbers), or a pane name (`lingo`, `pseudo`, `speco`, `mojo`, `asm`) to show just that editor with its problems under it. Query parameters on an embed: `?t=12` parks the stepper, `?ro=1` makes the editor read-only; `area`, `panel`, `lang`, `build`, `machine`, `dock`, `docktab`, `editor`, `side`, `dockheight` and `theme` arrange the example as the playground's controls do (`applyEmbedParams` in `src/core/state.ts`).
|
||||||
|
|
||||||
|
A reader's edits in an embed are saved in their browser, in that embed's own save (one per embedded example, shared by pages that embed the same one), never in the app's save for the problem. Once they have changed something, **Reset** appears beside "open in Programming+" and puts the author's version back. An embed keeps a save only while it holds edits, so a reader who has not changed an example always sees the author's current version. A read-only embed (`?ro=1`) saves nothing.
|
||||||
|
|
||||||
|
The **Share** button in the app produces the app link, a ready-to-paste `<iframe>` for any view, and the Quarto shortcode for the same state (`{{< pplus-playground state=… >}}` or `{{< pplus-embed state=… view=… >}}`). Without the extension, in a Quarto page:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<iframe src="https://pplus.scient.ing/#/embed/trace/p/match?t=12"
|
||||||
|
width="100%" height="520" style="border:1px solid #ccc;border-radius:8px"
|
||||||
|
loading="lazy" title="Programming+: find a pattern, stepped through"></iframe>
|
||||||
|
```
|
||||||
|
|
||||||
|
## The workspace
|
||||||
|
|
||||||
|
- **Step through**, with the tools a tutor would use at a whiteboard: the next line is called out before it runs with what it reads and writes; strings and lists draw as rulers with the position being read highlighted; every variable shows its previous value and a link to the step that changed it; click a line number for a breakpoint and run to it; jump by loop pass; **predict mode** asks what the next step will write before you take it and keeps score; play at any speed; export the trace as CSV (a cell that a spreadsheet would read as a formula, one starting with `=`, `+`, `-` or `@` that is not a number, is written with a leading apostrophe: `src/core/csv.ts`). Keyboard: → ← Shift+→ Home End Space B P, and ? in the toolbar lists them.
|
||||||
|
- **Light and dark**: the ☾/☀ button; follows the system until you choose. Embeds take `?theme=dark`.
|
||||||
|
- **A phone-width screen** (under 700px): the workspace fills the screen and shows one part at a time, chosen in a bar at the foot of the toolbar: **Code** (the panes with the stepper under them), **Run and views** (the side column, with the stepper's first row and what runs next above it) and **Setup and output** (the dock); in Hardware, **Code** and **Board**. Each part scrolls inside itself. **Run** shows the Run view, Compile & run and a click on a problem's tab show the dock (or the board), and a click on a line in a view shows the code. A wider screen never sees the bar, and every part stays where it is (`tests/narrow.test.mjs` holds the rules to the media query).
|
||||||
|
- **Table of values**: the table a student draws by hand, drawn by the machine: a column per step that changed something, a row per name, the new value in the cell, blank for unchanged; click a step to jump the stepper there; copy as text (tab-separated, with the same guard against formulas as the CSV).
|
||||||
|
- **Flowchart**: laid out from the structure of the pseudo (so loops loop and branches branch), each box shaded by how often its line ran in the last run, each loop labeled with its passes, each arrow out of a decision with how often it was taken; a box that never ran is dashed. Click a box to reveal its line; download as SVG.
|
||||||
|
- **Data flow**: inputs on the left, `RETURN` and `OUTPUT` on the right, one arrow per assignment that reads the one and writes the other, labeled with its line, dashed when a condition only decides whether it happens.
|
||||||
|
- **matho pane**: equations as a source language, written in LaTeX (`core/src/services/matho.ts`). One `FUNCTION` per equation; `\sum` and `\prod` become accumulator loops, subscripts become positions (with the 1-based shift when the sum starts at 1), `\begin{cases}` becomes `IF`/`ELSEIF`, Greek letters become names, references to earlier equations become calls hoisted out of loops when their arguments do not change. Every decision is a note on the equation's line; integrals, infinity, limits and derivatives are refused with the finite procedure to write instead. The trace steps the pseudo with the marker on the equation each step came from.
|
||||||
|
- **Numerics**: `SUM_OF MEAN_OF VARIANCE_OF STDEV_OF MEDIAN_OF DOT NORM_OF FILL CHOOSE RANDN FLOOR CEIL LOG10 SIN COS TAN ATAN2 PI()`, and `PARALLEL FOR`, a loop whose passes may run at once, checked at run time: two passes touching one location stop the run with a data race that names the location and the passes.
|
||||||
|
|
||||||
|
- **Mojo for every exercise with pseudo**: each has its Mojo in `core/library/mojo/local/`, so the Developer and Hardware areas always have something to show for it; `core/tests/mojo.test.mjs` runs each Mojo program in the interpreter and checks it prints what the exercise expects.
|
||||||
|
- **Panes**: the area's own (see the table above), dimmed when empty (a dimmed tab opens an empty pane to write in), as tabs over one editor (CodeMirror: search and replace with Ctrl+F, go to line with Ctrl+G, bracket matching, undo and redo; Tab indents, Ctrl+/ comments). The editor is never split: in the Bridge a short note in the pane head says the other tabs update as you type (lingo and matho update the pseudo, and the pseudo the Mojo made from it), and clicking a line marks the lines it became in the next tab down; Hardware does the same between Mojo and x86-64. Drag the dividers to resize (double-click resets); the widths, the dock tab, and what is folded are remembered in the share link.
|
||||||
|
- **The side column** is the inspect panel. Its tabs are offered only when they mean something for the pane (Prove for the pseudo family) and dimmed, with the reason, when the run has nothing for them yet.
|
||||||
|
- **The Run view** (the first tab, in the Bridge and the Developer area; `src/core/runview.ts`, drawn by `src/ui/views/run.ts`) is the whole run read top to bottom, one row per step: its number, its line, what ran (indented by call depth, with what it printed), and a column for each variable you **follow**, holding its value after that step: in color where the step wrote it (with the position, `[5, 6]`, when it wrote one element), faded where it carries over, underlined where the step reads it, hatched where it is not in scope. The lifecycle of the value a variable names (Mojo: made ●, copied ⧉, moved in ⇢, moved out ⇥, destroyed ✕) is marked in the same cell; events of values no column names are noted beside the step. Above the rows, the followed variables as they stand at the stepper's position, with a ruler for a string or list and a grid for a table, the element just written and the one about to be read marked. **+ variables** opens a picker of every variable in the run, by routine; until you choose, it follows the variables of the routine that does the most work. The choice is kept per area (`layout.follow`). "Only steps that change something" hides the rest. Click a row to step there; the stepper keeps its row in view. It replaces the Variables panel, the trace table, the table of values and the Lifetimes tab, which each showed part of this.
|
||||||
|
- **The Tests tab** is a fuzzer that shows its work (`core/src/common/fuzz.ts`, drawn by `src/ui/views/tests.ts`). For each routine (the pseudo's, with the speco woven in; or each Mojo function other than `main`) it lists **what each input must do** (finish within the step limit; raise no runtime error, or for Mojo no abort and no uncaught raise; keep every REQUIRE, ENSURE, INVARIANT, DECREASES and ASSERT, with inputs that break a REQUIRE skipped rather than failed; give the same answer when run again), **how the inputs were made** (each parameter's generator, with the values it tries first, and each strategy with how many inputs it made: edge cases in combination, every DNA string up to three letters for a routine that reads one, seeded random values, and mutations of the inputs that reached a line nothing earlier had reached, as a coverage-guided fuzzer does), each **failure** with the case that found it and every step of shrinking it to a smaller input that still fails the same way (the shrinking is greedy, so the input it ends on is the smallest it found, not always the smallest there is) (**Step through this input** puts that call in the call box and shows the run), the **lines reached** by how many inputs (a line no input reached is flagged), the **answers** given and how often, and **every case** run with its strategy, input, outcome, answer or error, and steps, filterable by outcome and strategy. The seed and the number of inputs (100 to 3,000) are chosen at the top; the same seed always makes the same inputs. `core/tests/fuzz.test.mjs` runs it on every exercise.
|
||||||
|
- **Views that follow the run**: the **Flowchart** shades by the run so far and marks the box that runs next; the **Data flow** lights up the names the next line reads and the name the last line wrote.
|
||||||
|
- **Step colors**: every step in the Run view and the "next" box is colored by what it does (writes a value, decides, loop control, enters a routine, returns, input or output, a value destroyed, raises or fails); the legend is in the inspect panel's tab row.
|
||||||
|
- **The stepper** is docked under the editor, at the editor column's width, as part of it: first, back, step, last, play and the slider; the loop-pass jumps, run to breakpoint, predict mode, only writes, speed and CSV; the loops in flight (or the machine's counts); and what runs next. It stays visible when the dock is folded.
|
||||||
|
- **The dock** under everything holds **Setup** (the call and the input lines for pseudo, lingo and matho; the build level and stdin for Mojo; the machine and the setup block for x86-64, in fixed-size boxes), Output, Problems (with the count on its tab), Compiler (Mojo) and Machine (the Hardware area's board); ▾ folds it away.
|
||||||
|
- **Hover** any word or symbol in any editor for its reference entry: keywords, built-ins, operators, English phrasings, speco symbols, instructions, registers, condition codes.
|
||||||
|
- **Language reference** at the bottom of the home page, rendered from core's `src/common/reference.ts`. Where an engine already holds a fact (keywords, built-ins, precedence, sentence forms, instruction glosses, condition codes, machine presets) the reference reads it from the engine; the tables written by hand carry examples, and core's `tests/reference.test.mjs` parses every statement, speco and setup example through the real parsers and runs every idiom against the output its note names, so an example cannot drift from the tool. The meanings beside the examples are written by hand, and no test reads them.
|
||||||
|
- **Save and load**: Share → Download writes `<title>.pplus.json`; Open… loads one back (here or on another machine). A `.pplus.json` file, a share link, or a `state=` shortcode from an earlier state format opens an empty workspace, and a save in the browser from an earlier format is discarded, so the problem opens as written; Programming+ makes no promise to keep old saves and links working. The share link and the embed code carry the same state.
|
||||||
|
- **Input**: the input box in Run setup feeds `INPUT` (pseudo) and `input()` (Mojo), one value per line; the lines travel in the share link.
|
||||||
|
|
||||||
|
## Translation between languages
|
||||||
|
|
||||||
|
Pseudo is the hub: every other notation translates to or from it, so four languages need six translators. The translators are DOM-free functions of text under `core/src/sync/`; `core/src/sync/types.ts` has their shapes and the line maps that say which input line each output line came from.
|
||||||
|
|
||||||
|
**pseudo → Mojo** (`core/src/sync/pseudo-to-mojo.ts`) is one way only, and its output is always labeled generated: the first line is `# Generated by Programming+ from pseudo. Not reviewed for Mojo best practices.` (`core/src/sync/header.ts`). It is an app-owned port of the Mojo half of the course engine's `translate.js`, and it is deliberately literal: `var n: Int` then `n = …`, `total = total + 1`, an index loop over codepoints. Idiomatic rewrites belong to the optional best-practices helper, so a student can see the difference.
|
||||||
|
|
||||||
|
- `def main()` is written from the pseudo's own lines, then from the call being run: `COUNT_BASE('A', "GATTACA")` becomes `print(count_base("A", "GATTACA"))`, with `TRUE` as `True`, a character as a one-letter `String`, and an integer given to a `FLOAT` parameter as `1.0`.
|
||||||
|
- `raises` is inferred (a dictionary read, `input()`, `atol`, a failed `ASSERT`, or a call to a routine that raises, transitively). Imports (`Set`, `sort`, the math functions) come from the harvested standard-library index, and only for names the translation uses.
|
||||||
|
- Where the notation has a built-in with no one-line Mojo spelling (`FORALL`, `EXISTS`, `SUM`, a set written by rule, `KEYS`, `SORTED`, `SPLIT`, `FILL`, `SLICE` of a String, the statistics), the translation writes a short loop just before the line that uses it. A fixed-length `ARRAY` is an append loop, as in the verified programs, because the interpreter does not run `List(length=…)`.
|
||||||
|
- It never invents Mojo. A line with no faithful spelling (a loop condition that would need such a loop, a built-in the standard library lacks) becomes `raise Error("not translated: pseudo line N")` and a `translate-gap` warning on the pseudo line; the program stops there instead of printing a plausible wrong answer. The pseudo's own mistakes (`unsupported`) are reported, not translated.
|
||||||
|
- Two behaviors differ by design, and a literal translation keeps Mojo's: dividing a `FLOAT` by zero stops the notation but gives `inf`, `-inf` or `nan` in Mojo (`nan` only for zero divided by zero), and `PARALLEL FOR` runs its passes in order with no race detector. Translation notes (`translate-divide`, `translate-each-order`, and so on) say so on the line.
|
||||||
|
|
||||||
|
`core/tests/sync-mojo.test.mjs` holds the translation to the pseudo: for every exercise with pseudo and every program in `core/library/pseudo/programs/`, the generated Mojo has no checker errors, runs in the interpreter, and prints what the pseudo prints (compared by value, not text: `TRUE` and `True`, `3` and `3.0`, a map's keys in any order). Programs it cannot hold to that are listed in the test with a reason (the interpreter declines random numbers and the math functions Mojo computes with routines of its own, such as `sin`, `cos`, `log` and `log10`; `EXACT` has no Mojo spelling; the checker is right about the two programs that read a variable with no value; dividing a FLOAT by zero and `PARALLEL FOR` differ by design), and `AGREE_AT_LEAST` is a floor that can only rise. A snapshot of the generated Mojo for every exercise is in `core/tests/snapshots/sync-mojo/`; when a change to the translator is wanted, run the test with `UPDATE_SNAPSHOTS=1` and review the diff.
|
||||||
|
|
||||||
|
**pseudo → lingo** (`core/src/sync/pseudo-to-lingo.ts`) writes the English that the lingo reader (`readSteps` in the course engine's `english.js`) understands, so the lingo pane can follow the pseudo pane. The grammar belongs to the reader, and the translator is held to it: before returning, it reads its own output back and checks that the same routines come out with the same kinds of input. If English cannot say something the way the reader needs it, the result is `unsupported` with a warning on the pseudo line, and the pane keeps its last good text instead of showing English that does not read.
|
||||||
|
|
||||||
|
- Names follow the reader's slots: a single letter or a Capitalized word. A name that is neither (`CURRENT_MAX`) has no English form yet.
|
||||||
|
- Each input is first written tersely, letting the steps show what it is. If the reader would take an input as something else, the translator adds a sentence saying what each input is ("L is a list of whole numbers.") and reads again.
|
||||||
|
- A name first set inside a block is given its value before the block, because English names are scoped by block.
|
||||||
|
- Left unsupported on purpose, each with its reason on the line: steps outside a routine (every English step belongs to a routine), records, `BYREF`, `REPEAT`, `PARALLEL FOR`, `DEFINE`, `CONSTANT`, a fixed-length `ARRAY`, maps keyed by a character, and `IN` over a String.
|
||||||
|
|
||||||
|
`core/tests/sync-lingo.test.mjs` holds it to that for every exercise, every corpus program, and the single-construct fixtures in `core/tests/helpers/sync-programs.mjs`: the English reads; lowering it back to pseudo gives a program with the same output and the same kind of stop; and writing English again from that pseudo gives the same text (comments aside). `SUPPORTED_AT_LEAST` is a floor that can only rise.
|
||||||
|
|
||||||
|
**pseudo → matho** (`core/src/sync/pseudo-to-matho.ts`) writes the equations, in LaTeX, for the programs that are equations, and refuses the rest. It recognizes the shapes the matho reader lowers: a `FUNCTION` that returns one value; an accumulator loop (`Total <- 0` then `Total <- Total + …`, or `1` and `*`) as `\sum` or `\prod`, with the bounds the reader uses (`FOR I <- 0 TO N` is `i=0` to `n-1`; a 1-based loop is `i=1` to `n`, and `X[I - 1]` is `x_i`); `FOR EACH` over an input list as a sum over a set; an `IF`/`ELSEIF` chain whose every branch returns as `\begin{cases}`; a call of an earlier function as a reference to its equation; and `SQRT`, `ABS`, `FLOOR`, `CEIL`, `CHOOSE`, `SIN`/`COS`/`TAN`/`EXP`/`LOG`/`LOG10`/`LOG2`, `MIN`, `MAX`, `PI()`, `DOT` and `NORM_OF`. Names given to values before the `RETURN` (the reader's hoisted calls, a temporary) are substituted where they are used.
|
||||||
|
|
||||||
|
- Everything else is `unsupported` with the construct and its line: "matho has no form for a WHILE loop (line 4)". An equation has a value, so output, input, text, a yes-or-no answer, a procedure, a record, steps outside a function, and a loop that does more than add up are all refused.
|
||||||
|
- Names. The reader makes `\bar{x}` into `X_BAR` and `\sigma` into `SIGMA`, so the pseudo has lost the student's spelling. The `NameMap` hint (`hints.names`, keyed by the upper-case pseudo name) carries it back; without one, `SIGMA` is `\sigma`, `X_BAR` is `\bar{x}`, a single letter is lower case, and a longer name is `\text{...}`. A hint is checked like everything else, and one that does not lower back to the function is refused.
|
||||||
|
- It never writes an equation that reads as something else. The LaTeX is lowered again by the matho reader and held to the pseudo: the same function names, inputs of the same kind, and the same values on three sets of sample inputs (stopping the same way where the pseudo stops). A program that fails is refused.
|
||||||
|
- Comments are not carried across. The lowering writes each equation as a comment above its function, and carrying that back would put a stale copy of the equation above the new one.
|
||||||
|
|
||||||
|
`core/tests/sync-matho.test.mjs` holds it to three checks on every equation set in `core/tests/helpers/sync-programs.mjs` (the sets `core/tests/matho.test.mjs` works by hand): the LaTeX reads, the pseudo it lowers to behaves like the original, and writing it again from that pseudo gives the same LaTeX. Two sets are listed as gaps with their reasons (a matrix row written `y_i`, and a second factorial whose counter the reader names `K2`); `SUPPORTED_AT_LEAST` is a floor that can only rise. Programs from the exercises and the corpus are accepted or refused the same way, with a located reason.
|
||||||
|
|
||||||
|
**The hub** (`core/src/sync/hub.ts`, tests in `core/tests/sync-hub.test.mjs`) puts the translators together. It is pure: a function of the texts it is given, with no DOM and no `localStorage`. `Session.setSource` hands an edit in a linked pane (lingo, matho, pseudo, speco) to it and applies the result in one change event; Mojo and x86-64 are stored as typed.
|
||||||
|
|
||||||
|
1. **The pane you edit is the authority** (`state.sync.authority`). The edit produces a new pseudo, directly or by lowering, and the other linked panes are regenerated from it. The pane that was edited is never rewritten, so typing never fights the cursor.
|
||||||
|
2. **Contracts ride along.** Lingo and matho cannot say contracts, so an edit in either weaves the speco into the pseudo it produced, and the speco is re-derived from that pseudo (`reconcileSpec`, which keeps claims about a routine or loop that is gone). An edit in speco replaces the pseudo's contracts with its own (`weave` in replace mode), and lingo and matho, which ignore contracts, follow.
|
||||||
|
3. **An authority with errors changes nothing.** If the edited pane does not read, every other pane keeps its text and is marked stale: "lingo line 3 does not read yet".
|
||||||
|
4. **A language that cannot say the program goes stale, not blank.** When a generator returns `unsupported` (matho has no form for a `WHILE` loop), that pane keeps its last text and is marked stale with the reason, until the program is expressible again.
|
||||||
|
5. **Mojo is produced only from pseudo**, as the literal translation, memoized by the pseudo and the call (`Session.derivedMojo()`); it is not stored.
|
||||||
|
6. **Opening a problem rewrites nothing.** Panes with text are shown as written; a linked pane that is empty is generated from the pseudo for display (`Session.source`), and reaches the saved state only with the first edit. Until then `state.sync` is absent and a pane's link state is "authored".
|
||||||
|
7. **Line maps compose through the hub.** `SyncHub.relate(maps, from, line, to)` answers which lines of one pane match a line of another, going through the pseudo; `Session.lineMaps()` has the maps of the last cascade.
|
||||||
|
|
||||||
|
`state.sync` (`{ authority, stale, names }`) is part of the saved state and the share link. It is bookkeeping, not an edit: a state whose texts are the problem's own is unedited whatever `sync` says. `names` is the student's spelling of equation names (`\overline{x}`), so a trip through pseudo restores it.
|
||||||
|
|
||||||
|
**Coverage.** `core/tests/sync-coverage.test.mjs` runs all three translators over every exercise, corpus program and fixture and writes [sync-coverage.md](../core/docs/sync-coverage.md): how many each says completely, and, for every program it cannot say, what it has no form for. Each translator has a floor in the test.
|
||||||
|
|
||||||
|
## Mojo
|
||||||
|
|
||||||
|
The distinction that shapes it: [Mojo Quest](https://quest.mojolang.org) teaches you to *write* Mojo, with the compiler as the judge; Programming+ shows you what Mojo *does when it runs*: every step of a run in its own interpreter (which reads a subset of Mojo and says why when it declines a program), the life of every value (made, copied, moved, borrowed, destroyed), and the instructions the compiler produced, stepped on a model machine. The + is those views.
|
||||||
|
|
||||||
|
Programming+ is pinned to **Mojo 1.2.0** (`mojo_1_2_0` on [Compiler Explorer](https://godbolt.org)). Core's checker and interpreter are held to the real compiler's answers on every program in core's corpus; for any other program, Compile & run asks the compiler. Programming+ ships no compiler and never claims a program compiles without asking one.
|
||||||
|
|
||||||
|
**The Mojo pane** is edited like the pseudo: highlighting built from the compiler's own token table (docstrings across lines, the ownership words `imm`/`mut`/`out`/`deinit`/`var`/`ref`, the transfer `^`, and the words Mojo has removed, such as `fn`, underlined), the VS Code extension's indentation rule, Ctrl+/ for comments, and hover text for the ownership vocabulary. Before compiling, Programming+'s own checker (`core/src/mojo/`) reports what it is certain the compiler would: code at file scope, an empty body, an untyped parameter, a method without self, no `main`, an implicit declaration, an unknown name (with the compiler's import hint), removed syntax such as `fn`, each in the compiler's own words. `core/tests/mojo-check.test.mjs` scores it against godbolt: it may never report an error on a program the compiler accepts, or one the compiler did not make. Code it cannot read yet gets a note, not an error.
|
||||||
|
|
||||||
|
**Compile & run** (Ctrl+Enter on the Mojo pane) sends the program to godbolt.org in one request: the compiler's answer, the program's output (the input box feeds `input()`), and the listing. What leaves the browser is the Mojo pane's text, the input box's lines, and the build flags (`mojoRequestBody` in core's `src/services/godbolt.ts`), and nothing else: no title, problem, other pane or anything stored. The first Compile & run in a browser says so and asks (`src/ui/consent.ts`; the answer is kept in this browser as `pplus.send.godbolt`, never in a link or a file), and the Compiler view says it under its button until something has been compiled. One thing differs from the Run view there: in Mojo 1.1.0 and 1.2.0 every `input()` opens its own buffered reader, so on the compiler's side, where the input arrives all at once, the first `input()` takes every line and a second one raises `EOF`. The Run view hands out one line per call, as a terminal does ([core/docs/trust.md](../core/docs/trust.md)). The Compiler view says so where it matters: when a program that may call `input()` more than once (two call sites, a call in a loop or a comprehension, or a call in a function other than `main`, read from the text with core's Mojo lexer: `inputReads` in `src/core/inputnote.ts`) was sent with input, a note under its output explains why the compiler's run may stop with `EOF` where the Run view does not. The **Compiler** view shows them. The compiler's messages land on their lines with its fix-its as one-click fixes (an implicit copy offers "transferring the value with '^'" or "copy it explicitly with '.copy()'"). The listing is grouped by function, your own first, in Intel syntax translated from godbolt's AT&T (or the original). **Send to x86-64 pane** puts one function, and the functions of yours it calls, on the model machine with its arguments' registers ready and the listing's read-only strings placed in memory; each call into the standard library becomes a stub that stops the run where the real program would enter the library, and says so. `core/docs/asm-coverage.md` is the census of every instruction compiled Mojo uses against what the machine models (everything but 256-bit AVX2), and `core/tests/asm-coverage.test.mjs` keeps it that way. Build "as written" (`-O0`, the default, which keeps every function you wrote) or "optimized" (what `mojo build` does: small functions fold into their callers). An edit after compiling marks the answer stale rather than showing it on the wrong lines. Compile & run (or **Compile again**) on work this browser already has godbolt's answer for, the same source, input and build level, sends nothing: it shows that answer again and says so, with **Ask again** to send the same program anyway (`Session.keptCompile`, `reuseCompile`). A request that failed is not kept as an answer. **Step through** runs the Mojo pane in Programming+'s own interpreter (`core/src/mojo/interp.ts`): line by line, with the variables it follows, what each line reads and writes, loop passes, breakpoints, and each value's lifetime, in the Run view. `core/tests/mojo-run.test.mjs` holds it to godbolt: on every program godbolt ran, it prints exactly what that run printed, or declines and says why. A program outside that set can still run here although the compiler rejects it (`Int(3.9)` on a literal, for one), so Compile & run is the word on whether a program compiles.
|
||||||
|
|
||||||
|
**How it is built.** Every build is asked for with the arguments core's pin states, `--target-cpu x86-64-v3 --fp-mode contract=off`, before the level the student chose (`-O0`, or the compiler's default): the listing is the same whichever of godbolt's machines answers and stays inside what the Hardware area's model machine knows, and a multiply is never fused with an add, so a decimal result is the one the Run view shows. The summary line of a compile shows the arguments. `mojo build` on a reader's own machine targets its own processor and may fuse, so its listing and its last digit can differ ([core/docs/trust.md](../core/docs/trust.md)).
|
||||||
|
|
||||||
|
**An exercise's Mojo** is a program in `core/library/mojo/local/`, named by the exercise's `mojoProgram`. `corpus.py verify` checks it on godbolt, and the pane's badge says "verified on Mojo 1.2.0" only when godbolt's answer passed the program's own expectation.
|
||||||
|
|
||||||
|
**The corpus** behind all of this (the compiler's own words, Modular's tested programs, our probes, and godbolt's stored answers) is described in [mojo-corpus.md](../core/docs/mojo-corpus.md).
|
||||||
|
|
||||||
|
## speco
|
||||||
|
|
||||||
|
The course's contracts (`REQUIRE`, `ENSURE`, `INVARIANT`, `DECREASES`) can only live inside pseudocode. The speco pane lets a student write them as a separate document, in math notation, and **weaves** them into the pseudocode before proving:
|
||||||
|
|
||||||
|
```
|
||||||
|
SPEC COUNT_BASE(B, T)
|
||||||
|
ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|
|
||||||
|
LOOP FOR I
|
||||||
|
INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|
|
||||||
|
```
|
||||||
|
|
||||||
|
`∀ ∃ Σ ∈ ∧ ∨ ¬ ≤ ≥ ≠ = |…|` lower to `FORALL EXISTS SUM IN AND OR NOT <= >= != == LENGTH(…)`. `LOOP FOR I`, `LOOP WHILE`, or `LOOP 2` names the loop an invariant belongs to. Contracts already in the pseudocode are shown in the pane and never duplicated. The proof view reports each obligation against the speco line it came from.
|
||||||
|
|
||||||
|
**Where speco is going.** The next stage lets the same claims live as comments on the pseudo and the Mojo a student already has (`# @requires`, `# @ensures`, `# @invariant` on the line they govern), so a specification never has to be a separate document. Checking is two-layered and honest about which layer answered: every claim is evaluated on every step of the interpreter's run and on the generated inputs (a runtime check: "held on 300 inputs", or a small input that broke it), and the claims the prover can read are handed to it, so an obligation shows as *proved*, *tested*, or *broken*, never conflated.
|
||||||
|
|
||||||
|
**Speco and pseudo are two views of one set of contracts** (`core/src/services/speco.ts`), and neither loses a claim:
|
||||||
|
|
||||||
|
- `extractSpec(pseudo)` reads the contracts out of the pseudo as a speco document.
|
||||||
|
- `weave(pseudo, spec)` inserts a speco's claims, never duplicating what is there. This is what the proof view uses. `weave(pseudo, spec, { replace: true })` is the other mode, for when the speco is the authority: for each `SPEC` unit it first removes the routine's `REQUIRE`/`ENSURE`/`DECREASES` and the `INVARIANT`/`DECREASES` of every loop the unit selects, then inserts the speco's. Routines and loops the speco does not name are left alone.
|
||||||
|
- `reconcileSpec(pseudo, previous)` is the speco that follows the pseudo when the pseudo is edited: what the pseudo says, plus every claim the previous speco made about a routine or loop the pseudo no longer has. Those stay, under a `// kept:` comment that says why, with a warning on their line; they return to the routine or loop when it comes back, even before the pseudo has written them. A contract deleted in the pseudo, from a spec that was not waiting, is deleted from the speco too.
|
||||||
|
|
||||||
|
These laws are tested in `core/tests/sync-speco.test.mjs`, for `count-base-proved`, `match-proved`, and every corpus program with contracts: `extract(weave(P, extract(P))) === extract(P)`; weaving twice changes nothing; a speco woven into the same pseudo with its contracts removed, then extracted, comes back (and the contracts written are the original's, up to spelling); and reconciling is a fixed point. Holding the laws found one bug, now fixed: a symbol just inside a bracket, `(∀ K …)`, was lowered to `( FORALL K …)`, so the text drifted by a space on every round trip.
|
||||||
|
|
||||||
|
## Known limits
|
||||||
|
|
||||||
|
- The engines live in pplus-core, the `core/` submodule ([engines.md](../core/docs/engines.md)). The prover is meant to be sound, and is incomplete: it proves only what follows on every path it examined. `core/tests/prover-soundness.test.mjs` holds it to every known hole (the regression programs in `core/library/pseudo/prover/`) and to every corpus program; an audit in November 2026 closed 18 rules that proved what a run breaks. English is still lowered to pseudo through text. The pseudo parser, checker, interpreter and prover are strict TypeScript; the English reader, the analysis, the coach and the course's page widgets are still JavaScript (core's [engines.md](../core/docs/engines.md#the-prover)).
|
||||||
|
- The assembly pane takes the course's Intel-syntax subset; directives and `[rip + label]` are not supported yet.
|
||||||
|
- Student work is kept in this browser only (`localStorage`); Share → Download makes a file of it. The footer's **What this site stores and sends** lists everything kept and everything sent.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Deploying
|
||||||
|
|
||||||
|
The site builds against pplus-core, the git submodule `core/`, at the commit this repository pins. A checkout needs it (`git clone --recurse-submodules`, or `git submodule update --init`); `npm run build` builds core first. To take a newer core: `git -C core pull` (or check out a tag), `pixi run test`, and commit the new `core` pointer with what it changes on this side.
|
||||||
|
|
||||||
|
`pixi run site` tests the app and assembles `site/`; `pixi run deploy [slug] [user@host]` does that and publishes it. CI (`.gitea/workflows/deploy.yml`) runs `pixi run ci` on every push and pull request, and on a push to `main` checks the chain of pointers (`pixi run release-check`), assembles and publishes.
|
||||||
|
|
||||||
|
The site is seven things: `index.html`, `styles.css`, `fonts/` (IBM Plex, served by the site so a visit asks no font host for anything; `fonts/README.md` says where the files came from), `styles/` (the course's widget styles, which the Hardware area's machine views use), `dist/`, `core/` (pplus-core's built `core/dist/`, which `index.html`'s import map names as `#core/`), and the Quarto extension (`quarto/_extensions/pplus`, without an engine copy), which the With Quarto page loads (`pplus.css`, `pplus.js`) and links to file by file. `scripts/assemble.sh` copies them into `site/` with a `VERSION` file holding the commit, a `build.json` naming the three commits the site was built from (below), and the license and notices (`LICENSE.md`, `NOTICE.md`, `THIRD_PARTY.md`, which the footer links), then `scripts/assemble-page.mjs` adds two things to `site/index.html`: the commit as `<meta name="pplus-version">`, which the footer shows, and a `<link rel="modulepreload">` for every module the page's imports reach, after the import map, so a first visit asks for all of them at once instead of one level of imports at a time (`tests/load.test.mjs` holds the list to the import graph and the inline scripts to their hashes). And `scripts/deploy.sh <slug> [user@host]` publishes `site/` to `/srv/www/<slug>` as an atomic release:
|
||||||
|
|
||||||
|
```
|
||||||
|
/srv/www/pplus -> symlink to the live release
|
||||||
|
/srv/www/pplus.releases/ one directory per deployed commit, the five newest kept
|
||||||
|
```
|
||||||
|
|
||||||
|
The swap is one rename, so nobody sees a half-copied site, and a rollback is `ln -sfn /srv/www/pplus.releases/<sha> /srv/www/pplus`. A pre-existing plain directory at `/srv/www/<slug>` is moved to `<slug>.releases/before-releases` on the first run.
|
||||||
|
|
||||||
|
**Caddy**: [`Caddyfile`](Caddyfile) is the site block (root on the symlink, `file_server`, a missing path that looks like a page sent to `/` (the app's routes are after the `#`, and the page names its files relative to itself, so it cannot be served in place at a deeper path) while a missing file is a plain 404, and caching: `no-cache` on the page, the modules and the stylesheets, so the browser asks again on every load and gets a bodiless 304 while a file is unchanged; 30 days on the fonts, which change only when `fonts/` is replaced; `no-store` on `VERSION`; nothing is `immutable`, since no file name here changes with its content; the license and notices are served as plain text) and a snippet of security headers it imports: a Content-Security-Policy (everything from the site itself, the two inline scripts of `index.html` by their hashes, `connect-src` open only to godbolt.org for Compile & run, and `frame-ancestors` so course pages can embed views), `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and a `Permissions-Policy` that turns off the camera, microphone, location, payments and USB. `tests/csp.test.mjs` fails when an inline script of `index.html` changes without its hash, or when the page names another origin; a new backend for Compile & run needs its origin in `connect-src`. The live shortcodes and `live="click"` put the app in an iframe, so a Quarto site on another origin needs that origin added to `frame-ancestors`; the rendered views need nothing from the host. Caddy issues the certificate itself; add the block to `/etc/caddy/Caddyfile` and `systemctl reload caddy`. The tests read the file as text; `pixi run caddy-check` serves an assembled `site/` with a real Caddy under it (localhost, plain HTTP) and holds the headers, the caching and both missing-path answers. Run it after changing the Caddyfile.
|
||||||
|
|
||||||
|
**Gitea Actions without a container image** (`.gitea/workflows/deploy.yml`, and pplus-core's and pplus-library's `.gitea/workflows/`): the act_runner on the droplet runs jobs on the host shell instead of in docker. Once, on the droplet:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# tools the jobs use: git and node for actions/checkout, curl, tar and sha256sum to fetch the pinned pixi,
|
||||||
|
# rsync for SSH deploys, a C compiler for the C references core's library-check builds
|
||||||
|
apt install -y git rsync curl tar coreutils build-essential
|
||||||
|
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt install -y nodejs # any node >= 20, for actions/checkout
|
||||||
|
# a user for the runner that owns the web root
|
||||||
|
useradd -m -s /bin/bash deploy
|
||||||
|
mkdir -p /srv/www && chown deploy:deploy /srv/www
|
||||||
|
# register the runner with a host-mode label (the :host suffix is the whole trick)
|
||||||
|
sudo -u deploy act_runner register --instance https://<your-gitea> --token <runner token> --labels "quarto-deploy:host" --no-interactive
|
||||||
|
# run it as a service (act_runner generate-config > config.yaml; systemd unit per the Gitea docs, User=deploy)
|
||||||
|
```
|
||||||
|
|
||||||
|
With that label, `runs-on: quarto-deploy` executes steps directly as `deploy`. Every job then does what a developer does:
|
||||||
|
|
||||||
|
1. `actions/checkout` with `submodules: recursive` (the job's token must be able to read pplus-core and pplus-library while they are private);
|
||||||
|
2. **pixi**, at the version `PIXI_VERSION` names in the workflow: the host's when it is that version, else the release fetched once into `~deploy/.cache/pplus-ci/pixi-<version>/`, checked by SHA-256. Nothing needs installing for it; to have it on the host anyway, as `deploy`: `curl -fsSL https://pixi.sh/install.sh | PIXI_VERSION=v0.83.0 bash`;
|
||||||
|
3. `pixi install --locked`: Node, Python, pandoc and the Mojo compiler, exactly as `pixi.lock` has them (the package cache in `~deploy/.cache/rattler` keeps about 2 GB after the first run);
|
||||||
|
4. `pixi run ci`: every test of the site (the Quarto ones run in pandoc and fail, not skip, if it is missing), and core's tests and `mojo-status-strict` at the pinned commit;
|
||||||
|
5. on `main`: `pixi run release-check`, `scripts/assemble.sh`, and `scripts/deploy.sh` into `/srv/www`.
|
||||||
|
|
||||||
|
`SITE_SLUG` (repository variable) names the directory and defaults to the repository name; set it to `pplus`. `SITE_URL` turns on a smoke test that fetches `/VERSION` from the live site and fails the job if it is not the deployed commit. pplus-core's workflows (its `docs/ci.md`) use the same runner and also keep the pinned Dafny and the Mojo build answers in `~deploy/.cache/pplus-ci/core-tools`; the runner takes one job at a time (the default `capacity: 1`), which those caches assume. On GitHub Actions the build and test steps run unchanged with `runs-on: ubuntu-latest`; publishing needs the droplet.
|
||||||
|
|
||||||
|
**Once the repositories are public**, a pull request from a fork runs its own workflow file and code on this runner, as `deploy`, which can write `/srv/www`. Run pull requests only from branches of the repository itself (each workflow's job has an `if:` that does that), or require approval for fork runs in Gitea's repository settings where the version offers it, or give pull requests a separate runner that cannot write the web root.
|
||||||
|
|
||||||
|
If the runner ever moves off the droplet, `scripts/deploy.sh pplus deploy@droplet` rsyncs over SSH instead; give that runner a key whose public half is in `deploy`'s `authorized_keys`.
|
||||||
|
|
||||||
|
By hand, on the droplet: `pixi run deploy pplus`. From elsewhere: `pixi run deploy pplus deploy@droplet`.
|
||||||
|
|
||||||
|
## Moving the pointers
|
||||||
|
|
||||||
|
The site pins pplus-core by commit (`core/`), and core pins pplus-library (`core/library/`). A change at the bottom reaches the site in three commits, pushed in order: library, then core with its new `library` pointer and what it regenerates from it, then the site with its new `core` pointer. Done by hand the first time, it broke twice: a pointer named a commit from before a move, and a pointer named a commit that existed on one machine only. Two tasks (`scripts/release.mjs`) hold the order:
|
||||||
|
|
||||||
|
- `pixi run release-check` says whether the chain is consistent, and what to run when it is not: each pointer's commit is in the checkout, the checkout is at it and has no uncommitted change, and the commit is on the submodule's branch (`main`) on its remote. It asks the remote with `git ls-remote` (never a fetch); with `--offline`, or when the remote cannot be asked, it reads the last fetch and says "cannot tell" where that cannot settle it. It also checks that the generated files are current (core's `library.mjs emit --check`, `corpus.py emit` writing nothing new, `quarto-css --check`) and that Mojo is pinned alike in `core/library/mojo/pin.json`, both `pixi.toml` files and both `pixi.lock` files, with Node and Python alike in core and the site. Exit status 1 on a problem.
|
||||||
|
- `pixi run release-bump`, after a change committed in `core/library` (or in `core`): moves core's pointer to the library checkout, regenerates core's registry and the corpus's generated files, runs core's gate and `library-check`; then builds the site against that core, regenerates the Quarto extension's files, runs the site's tests; and prints the commits to make and push, in order. With `--commit` it makes the commits; it never pushes, tags or fetches. `--no-gate` skips the gates.
|
||||||
|
|
||||||
|
`tests/chain.test.mjs` runs the cheap half of `release-check` with every `npm test`: it fails when a pointer names a commit its checkout does not have, or a checkout is behind its pointer, and names the command that fixes it (`git submodule update --init --recursive`). Core's `tests/chain.test.mjs` does the same for its own pointer.
|
||||||
|
|
||||||
|
## Versions and tags
|
||||||
|
|
||||||
|
Today core is 0.2.0 and the site 0.1.0 (`package.json` and `pixi.toml` say the same, and `tests/tasks.test.mjs` keeps them so); the library has no version, and nothing is tagged. A built site says what it is made of: `site/build.json` (`scripts/build-info.mjs`) holds each repository's version, commit and `git describe --tags --always --dirty`, and the Mojo the corpus is pinned to. The app does not show it yet; an About line that reads `build.json` is the remaining step.
|
||||||
|
|
||||||
|
Proposed for the first public release (the owner's to decide; nothing here creates a tag):
|
||||||
|
|
||||||
|
- Each repository keeps its own version, in its `package.json` and `pixi.toml` (the library, which has neither, in its tag only), and a release is an annotated tag `vX.Y.Z` on the commit the repository above pins.
|
||||||
|
- First release: pplus-library `v0.1.0`; pplus-core `v0.3.0`, because its exports changed since 0.2.0 (`linear()`, `LIBRARY_COMMIT`); the site `v0.2.0`. The version bumps are commits of their own, made before the tags.
|
||||||
|
- Tag bottom up, after `pixi run release-check` is clean and each commit is pushed: the library at the commit core pins, core at the commit the site pins, then the site. `git describe` in `build.json` then reads `v0.3.0` instead of a hash.
|
||||||
|
- `release-bump` stays out of tagging: moving a pointer is not a release. What it could do later is refuse to move a pointer onto a commit that is behind a pinned tag, and `release-check --release` could require each pinned commit to carry a `v*` tag that matches its `package.json`.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
+93
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
|
||||||
|
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# IBM Plex, served by the site
|
||||||
|
|
||||||
|
`index.html` loads `fonts/plex.css`, which names these files, so a visit asks no font host for anything. They are
|
||||||
|
the faces the app uses: IBM Plex Sans at 400, 500, 600 and 700, and IBM Plex Mono at 400, 400 italic and 600.
|
||||||
|
|
||||||
|
| File | From |
|
||||||
|
|---|---|
|
||||||
|
| `IBMPlexSans-{Regular,Medium,SemiBold,Bold}.woff2` | npm `@ibm/plex-sans@1.1.0`, `fonts/complete/woff2/` (tarball sha256 `c3818979c2a2c82927ea3e7c485e389a18de0b7462887dd4f7acc9a525568962`) |
|
||||||
|
| `IBMPlexMono-{Regular,Italic,SemiBold}.woff2` | npm `@ibm/plex-mono@1.1.0`, `fonts/complete/woff2/` (tarball sha256 `744157918f504d2ec10ef2a26b7ec080e362743dda99618c8ff547e946e40d45`) |
|
||||||
|
| `LICENSE.txt` | the license in both packages (identical): SIL Open Font License 1.1, Copyright 2017 IBM Corp., Reserved Font Name "Plex" |
|
||||||
|
|
||||||
|
Both packages are published by IBM from <https://github.com/IBM/plex>. The files are copied unchanged (the
|
||||||
|
"complete" builds, every glyph Plex has); the OFL allows redistributing them with the license beside them, and
|
||||||
|
the Reserved Font Name means a modified copy could not be called Plex. The Quarto extension does not load them: on
|
||||||
|
a course page the views use the page's own monospace font (`--bs-font-monospace`), then IBM Plex Mono if the
|
||||||
|
reader has it installed.
|
||||||
|
|
||||||
|
sha256 of each file, to check a copy:
|
||||||
|
|
||||||
|
```
|
||||||
|
ba711a3085ff9f27440b6b9c4550cfc47c97bf36591d5da958b975bb3add8c1a IBMPlexSans-Regular.woff2
|
||||||
|
5660f8a658f8bb50dbc005232f885eadffd2bc1c235c4f6fbb63469d1f9cde6d IBMPlexSans-Medium.woff2
|
||||||
|
f78048030eab62e860efa39a0df79e2e5581bf122eb95b9bc42c0b8a4988d205 IBMPlexSans-SemiBold.woff2
|
||||||
|
fa7130d854a660b39a7fc9e6e0f2dc23dba5f1346e2adea3e1fe37b6d884133d IBMPlexSans-Bold.woff2
|
||||||
|
49ce58b41a0e1cb921c0f58d9a5b8b96a2cc21437c7066f3ba4f24873076d131 IBMPlexMono-Regular.woff2
|
||||||
|
6afc2a6edd9a1d1f8104daf139a5062392f47da2f97fe19cb18a6a5a1fa67ec3 IBMPlexMono-Italic.woff2
|
||||||
|
ed5eaca7522336959d6c3810bd9bb78424f0d964082d581bfbea169ee08d14e3 IBMPlexMono-SemiBold.woff2
|
||||||
|
```
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/* IBM Plex, served by this site (fonts/README.md): no request leaves for a font host on any visit. */
|
||||||
|
@font-face { font-family: "IBM Plex Sans"; font-style: normal; font-weight: 400; font-display: swap; src: url("./IBMPlexSans-Regular.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Sans"; font-style: normal; font-weight: 500; font-display: swap; src: url("./IBMPlexSans-Medium.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Sans"; font-style: normal; font-weight: 600; font-display: swap; src: url("./IBMPlexSans-SemiBold.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Sans"; font-style: normal; font-weight: 700; font-display: swap; src: url("./IBMPlexSans-Bold.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Mono"; font-style: normal; font-weight: 400; font-display: swap; src: url("./IBMPlexMono-Regular.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Mono"; font-style: italic; font-weight: 400; font-display: swap; src: url("./IBMPlexMono-Italic.woff2") format("woff2"); }
|
||||||
|
@font-face { font-family: "IBM Plex Mono"; font-style: normal; font-weight: 600; font-display: swap; src: url("./IBMPlexMono-SemiBold.woff2") format("woff2"); }
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Programming+: from an idea to Mojo to the machine</title>
|
||||||
|
<meta name="description"
|
||||||
|
content="Programming+ takes a procedure from an idea to Mojo to the machine. The Bridge translates it as you type between plain-English steps (lingo), equations (matho), pseudocode (pseudo) and a specification (speco), and generates Mojo labeled as generated; Developer is for writing Mojo, stepping through it in Programming+'s own interpreter, and asking the real compiler on godbolt.org; Hardware steps its x86-64 on a model machine with caches and a pipeline. Nothing to install.">
|
||||||
|
<!-- IBM Plex, served from this site (fonts/README.md) -->
|
||||||
|
<link rel="stylesheet" href="./fonts/plex.css">
|
||||||
|
<!-- the two faces every page uses, asked for with the stylesheet rather than after it is read (crossorigin: fonts are fetched in CORS mode) -->
|
||||||
|
<link rel="preload" href="./fonts/IBMPlexSans-Regular.woff2" as="font" type="font/woff2" crossorigin>
|
||||||
|
<link rel="preload" href="./fonts/IBMPlexMono-Regular.woff2" as="font" type="font/woff2" crossorigin>
|
||||||
|
<link rel="stylesheet" href="./styles.css">
|
||||||
|
<!-- the course's widget styles, for the Hardware area's machine views (styles/course/README.md); this order -->
|
||||||
|
<link rel="stylesheet" href="./styles/course/bridge.css">
|
||||||
|
<link rel="stylesheet" href="./styles/course/tokens.css">
|
||||||
|
<link rel="stylesheet" href="./styles/course/kit.css">
|
||||||
|
<link rel="stylesheet" href="./styles/course/asm86.css">
|
||||||
|
<script>try { var t = localStorage.getItem("pplus.theme"); if (t === "light" || t === "dark") document.documentElement.setAttribute("data-theme", t); } catch (e) { }</script>
|
||||||
|
<link rel="icon"
|
||||||
|
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><style>rect{fill:%23f6c453}text{fill:%2316191f}@media (prefers-color-scheme:dark){rect{fill:%230e1117}text{fill:%23f0c05a}}</style><rect width='16' height='16' rx='3'/><text x='8' y='12' font-size='8' text-anchor='middle' font-family='monospace' font-weight='700'>P+</text></svg>">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div id="app"><noscript>Programming+ needs JavaScript.</noscript>
|
||||||
|
<!-- replaced as soon as the app starts; shown only if it has not after a few seconds (styles.css, .boot-note) -->
|
||||||
|
<p class="boot-note">Programming+ did not start. It has to be served by a web server (<code>pixi run dev</code>,
|
||||||
|
or the site), not opened as a file, and its scripts must be allowed to run. Reload to try again.</p>
|
||||||
|
</div>
|
||||||
|
<!-- pplus-core's modules (core/, a git submodule built into core/dist): the app imports them as #core/... -->
|
||||||
|
<script type="importmap">{ "imports": { "#core/": "./core/dist/" } }</script>
|
||||||
|
<script type="module" src="./dist/main.js"></script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
Generated
+33
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"name": "pplus-web",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "pplus-web",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript": {
|
||||||
|
"version": "6.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
|
||||||
|
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"tsc": "bin/tsc",
|
||||||
|
"tsserver": "bin/tsserver"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.17"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"name": "pplus-web",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"type": "module",
|
||||||
|
"description": "Programming+ web: the site, the editor, the views and the Quarto extension, over pplus-core (core/). Day-to-day commands are pixi tasks (pixi.toml); these scripts are what CI and a machine without pixi need.",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc -p core/tsconfig.json && tsc -p tsconfig.json",
|
||||||
|
"watch": "tsc -p tsconfig.json --watch",
|
||||||
|
"check": "tsc -p core/tsconfig.json && tsc -p tsconfig.json --noEmit",
|
||||||
|
"dev": "npm run build && python3 -m http.server 4173",
|
||||||
|
"test": "npm run build && node --test tests/*.test.mjs"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^6.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"imports": {
|
||||||
|
"#core/*": "./core/dist/*"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# pplus-web — every command a person runs, in one place.
|
||||||
|
#
|
||||||
|
# pixi run <task> [args] list them all: `pixi task list`
|
||||||
|
#
|
||||||
|
# The README's "Commands" table lists every task here; tests/tasks.test.mjs
|
||||||
|
# keeps the two in step. Without pixi, `npm install && npm test` builds core
|
||||||
|
# (core/, the pplus-core submodule) and the site, and tests the site, with
|
||||||
|
# whatever node and python3 are on the PATH; everything else assumes the
|
||||||
|
# pinned environment below, and CI runs `pixi run ci` in it. Core's own
|
||||||
|
# commands are in core/pixi.toml: `pixi run --manifest-path core/pixi.toml <task>`.
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
authors = ["Alex Maldonado <alex@scient.ing>"]
|
||||||
|
channels = ["https://conda.modular.com/max/", "conda-forge"]
|
||||||
|
name = "pplus-web"
|
||||||
|
platforms = ["linux-64", "osx-arm64"]
|
||||||
|
license = "Apache-2.0"
|
||||||
|
license-file = "LICENSE.md"
|
||||||
|
version = "0.1.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
mojo = "==1.2.0" # for the Quarto views that run a page's Mojo on a real compiler (core/library/mojo/pin.json)
|
||||||
|
nodejs = ">=26.10.0,<26.11" # building core and the site, and the tests
|
||||||
|
python = ">=3.14.7,<3.15" # the dev server and the package script (standard library only)
|
||||||
|
pandoc = ">=3.6,<4" # the Quarto extension's tests run its Lua filter in pandoc; without it eleven of them are skipped
|
||||||
|
|
||||||
|
[tasks]
|
||||||
|
# --- build and test the site -----------------------------------------------
|
||||||
|
install = { cmd = "npm install", inputs = ["package.json"], outputs = ["node_modules/.package-lock.json"], description = "Install TypeScript (the only npm dependency)" }
|
||||||
|
core-build = { cmd = "npx tsc -p core/tsconfig.json", depends-on = ["install"], description = "Build pplus-core (core/, a git submodule) into core/dist/ with the site's TypeScript; the site imports it as #core/" }
|
||||||
|
core-test = { cmd = "node --test --test-concurrency=8 tests/*.test.mjs", cwd = "core", depends-on = ["core-build"], description = "Run pplus-core's own tests (its gate is core's pixi run ci)" }
|
||||||
|
core-status = { cmd = "python scripts/mojo/corpus.py status --strict", cwd = "core", description = "Core's mojo-status-strict at the pinned commit: no Mojo program of ours fails, from godbolt's stored answers (offline)" }
|
||||||
|
build = { cmd = "npx tsc -p tsconfig.json", depends-on = ["install", "core-build"], description = "Build core, then compile src/ to dist/" }
|
||||||
|
watch = { cmd = "npx tsc -p tsconfig.json --watch", depends-on = ["install", "core-build"], description = "Rebuild dist/ on every change (core is built once first)" }
|
||||||
|
check = { cmd = "npx tsc -p tsconfig.json --noEmit", depends-on = ["install", "core-build"], description = "Type-check only" }
|
||||||
|
dev = { cmd = "python -m http.server 4173", depends-on = ["build"], description = "Build, then serve the app on http://localhost:4173" }
|
||||||
|
test = { cmd = "node --test tests/*.test.mjs", depends-on = ["build"], description = "Build, then run every test of the site" }
|
||||||
|
check-pages = { cmd = "node scripts/check-pages.mjs {{ dir }}", args = ["dir"], depends-on = ["build"], description = "Run every program embedded in the Quarto pages under <dir> (quarto/README.md)" }
|
||||||
|
|
||||||
|
# --- Quarto ------------------------------------------------------------------
|
||||||
|
quarto-export = { cmd = "node scripts/quarto-export.mjs {{ name }} {{ dir }}", args = ["name", "dir"], depends-on = ["build"], description = "Copy core/library/mojo/local/<name>.mojo, its x86-64 and setup beside a Quarto page, and print the shortcode" }
|
||||||
|
quarto-css = { cmd = "node scripts/quarto-css.mjs", depends-on = ["build"], description = "Regenerate the extension's generated files: pplus-views.css, pplus-hw.css, course/*.css and syntax/mojo.xml (from core)" }
|
||||||
|
quarto-engine = { cmd = "node scripts/quarto-engine.mjs {{ dir }}", args = ["dir"], depends-on = ["build"], description = "Copy a built Programming+ (and core) into a site's _extensions/pplus/engine, for the rendered views (quarto/README.md)" }
|
||||||
|
quarto-example = { cmd = "quarto render quarto", depends-on = ["build"], description = "Render the example site in quarto/example with every shortcode (needs Quarto on the PATH)" }
|
||||||
|
|
||||||
|
# --- ship ------------------------------------------------------------------
|
||||||
|
ci = { depends-on = ["test", "core-test", "core-status"], description = "What CI runs: every test of the site, and core's tests and mojo-status-strict at the pinned commit (docs/deploy.md)" }
|
||||||
|
release-check = { cmd = "node scripts/release.mjs check", depends-on = ["build"], description = "Is the chain web -> core -> library consistent: pointers checked out, clean and pushed to their branch, generated files current, Mojo pinned alike (docs/deploy.md); --offline asks no remote" }
|
||||||
|
release-bump = { cmd = "node scripts/release.mjs bump", depends-on = ["build"], description = "After a change in core/library or core: move the pointers bottom up, regenerate, run each gate, print what to push in order; --commit makes the commits, nothing pushes (docs/deploy.md)" }
|
||||||
|
site = { cmd = "scripts/assemble.sh", depends-on = ["test"], description = "Test, then assemble site/ for publishing" }
|
||||||
|
caddy-check = { cmd = "node scripts/caddy-check.mjs", description = "Serve the assembled site/ with a real Caddy under docs/Caddyfile and hold its headers, caching and missing-path answers (needs site/; fetches Caddy with pixi exec the first time)" }
|
||||||
|
package = { cmd = "python scripts/package.py", description = "Zip the files git tracks (and new ones it does not ignore) into package/ for sharing" }
|
||||||
|
deploy = { cmd = "scripts/deploy.sh {{ slug }} {{ target }}", args = [{ arg = "slug", default = "pplus" }, { arg = "target", default = "" }], depends-on = ["site"], description = "Publish site/ to /srv/www/<slug>, optionally on <target> (user@host) over SSH (docs/deploy.md)" }
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/.quarto/
|
||||||
|
|
||||||
|
**/*.quarto_ipynb
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
# Programming+ for Quarto
|
||||||
|
|
||||||
|
A Quarto extension that puts [Programming+](https://pplus.scient.ing) in a page. A program lives in a file beside the `.qmd`, and a shortcode says where it appears and how. The app's **With Quarto** page (`#/quarto`) is a gallery of every shortcode beside what it makes. [`example/`](example/) is a site that uses every shortcode on real pages (`pixi run quarto-example`): rendered views, the machine, and live views.
|
||||||
|
|
||||||
|
There are two kinds of shortcode (the machine's are a family of the first):
|
||||||
|
|
||||||
|
- **Rendered with the page.** While Quarto renders, the extension runs the program through Programming+'s own engines and writes what its views draw into the page. The result has no iframe and needs no network, it prints, and a program that stops printing its `EXPECT` lines is reported on the spot. These need Node 20 or later and a built Programming+ on the machine that renders the page (see [The engine](#the-engine)).
|
||||||
|
- **Live.** The app itself, in an `<iframe>`, with the program carried in its URL. The reader edits, steps and runs it. These need nothing at render time, but readers need the network, and the app's host has to allow your site to frame it.
|
||||||
|
|
||||||
|
| Shortcode | Kind | Shows |
|
||||||
|
|---|---|---|
|
||||||
|
| `pplus-run` | rendered | what the program prints and returns, checked against its `EXPECT` lines; a Mojo file runs on the real `mojo` when one is on the PATH |
|
||||||
|
| `pplus-steps` | rendered | the listing beside a stepper: every step, its line, what it wrote, the values after it, and what has been printed (a small script moves through a run recorded at render time) |
|
||||||
|
| `pplus-table` | rendered | the table of values: a column per step that changed something, a row per name |
|
||||||
|
| `pplus-flow` | rendered | the flowchart, each box shaded by how often its line ran |
|
||||||
|
| `pplus-dataflow` | rendered | the data-flow graph: which names feed which |
|
||||||
|
| `pplus-lifetimes` | rendered | each Mojo value made, copied, moved and destroyed |
|
||||||
|
| `pplus-proof` | rendered | every claim of the specification: proved, broken or open |
|
||||||
|
| `pplus-tests` | rendered | the fuzzer's report for every routine |
|
||||||
|
| `pplus-check` | rendered | what the checker finds in each file, on the file's own lines |
|
||||||
|
| `pplus-translate` | rendered | the procedure in every notation, with Mojo generated from the pseudo and labeled so (as Quarto tabs, columns, or the app's panes) |
|
||||||
|
| `pplus-machine` | rendered | the x86-64 run on the model machine: instructions, cycles, cache misses, branches |
|
||||||
|
| `pplus-view` | rendered | any of the above, by `view=` |
|
||||||
|
| `pplus-hw` | machine | the Hardware area's board over an x86-64 run: the listing beside a preset's cards (`preset=regs`, `caches`, `pipeline`, `chip`) or the cards you name (`views=`), each drawn at every step, with a stepper |
|
||||||
|
| `pplus-hw-<view>` | machine | one card of the board: `code`, `explain`, `registers`, `flags`, `address`, `memory`, `stack`, `dataflow`, `alu`, `branches`, `vectors`, `lines`, `cache`, `hierarchy`, `paging`, `pipeline`, `uops`, `timeline`, `bottleneck`, `counters`, `chip`, `core`, `encoding` (see [The machine](#the-machine)) |
|
||||||
|
| `pplus-playground` | live | the whole playground |
|
||||||
|
| `pplus-embed` | live | one view of it (`view=trace`, `table`, `flow`, `data`, `life`, `problems`, `proof`, `tests`, `compiler`, `asm`, or a pane) |
|
||||||
|
| `pplus` | live | the original shortcode: a live embed, a listing, or both (`show=`); pages written for it keep working |
|
||||||
|
| `pplus-listing` | text | the files as highlighted code blocks; a `.tex` file typeset as equations |
|
||||||
|
| `pplus-tabs` | text | the files as a tabset, one tab per notation |
|
||||||
|
| `pplus-link` | text | a link that opens the program in the app |
|
||||||
|
|
||||||
|
Every rendered view also takes `live="click"`. That adds a **make it live** button, which puts the live view in its place.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
1. Copy `quarto/_extensions/pplus` into your site's `_extensions/`.
|
||||||
|
2. Name the syntax definitions it ships, so listings of lingo, pseudo and Mojo are highlighted. Then, for the rendered views, name the engine (next section):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# _quarto.yml
|
||||||
|
syntax-definitions:
|
||||||
|
- _extensions/pplus/syntax/pseudo.xml
|
||||||
|
- _extensions/pplus/syntax/lingo.xml
|
||||||
|
- _extensions/pplus/syntax/mojo.xml
|
||||||
|
|
||||||
|
pplus-engine: ../programming-plus # a built Programming+ (its folder, or its dist/)
|
||||||
|
pplus-url: "https://pplus.scient.ing" # where the live views point (this is the default)
|
||||||
|
pplus-strict: true # optional: a view that cannot be rendered, or a run that does not print its EXPECT lines, stops the render
|
||||||
|
```
|
||||||
|
|
||||||
|
`mojo.xml` is generated from the same words as the Mojo pane's highlighter (the compiler's own token table, at the pinned Mojo version). A printed listing therefore colors `mut`, `deinit`, the transfer `^`, and removed words such as `fn` exactly as the pane does. If the project already has its own `pseudo.xml`, keep that and add only `lingo.xml`.
|
||||||
|
|
||||||
|
The stylesheets (`pplus-views.css`, `pplus.css`) and the script (`pplus.js`) are attached to every page that uses a shortcode.
|
||||||
|
|
||||||
|
### The engine
|
||||||
|
|
||||||
|
A rendered view runs `node _extensions/pplus/render.mjs <engine>` once per shortcode. The extension looks for a built Programming+ in this order:
|
||||||
|
|
||||||
|
1. `pplus-engine` in the project's or the page's metadata, relative to the project. Set it to `none` to render nothing with the page: each rendered view then shows its listing and the live view.
|
||||||
|
2. The `PPLUS_ENGINE` environment variable.
|
||||||
|
3. `_extensions/pplus/engine/`. `pixi run quarto-engine <your site>/_extensions/pplus` copies one there, so the site needs no checkout beside it. Run it again after rebuilding.
|
||||||
|
4. The repository the extension sits in, when it is the one in this repository (`quarto/_extensions/pplus`). This is how `example/` renders.
|
||||||
|
|
||||||
|
`pplus-node` (or `PPLUS_NODE`) names the node to use. Results are cached in `.quarto/pplus/`, keyed by the request and the engine's build. Set `pplus-cache: false` to render every view again. With no engine found, the page still renders: each rendered view becomes its listing and the live view, and Quarto prints one warning.
|
||||||
|
|
||||||
|
A Mojo file asked to run (`pplus-run`) is also given to the real compiler when `mojo` is on the PATH (inside `pixi`, the pinned one). The view then shows that compiler's output and names it. Without one, Programming+'s interpreter runs it, and the view says so. `compiler="off"` always uses the interpreter, and `compiler="on"` fails without a compiler.
|
||||||
|
|
||||||
|
### Live views on your site
|
||||||
|
|
||||||
|
The live views and **make it live** load the app in an iframe. The app's host decides which sites may frame it: `pplus.scient.ing` allows `scient.ing` and its subdomains, and a local `quarto preview` ([docs/deploy.md](../docs/deploy.md)). For any other site, point `pplus-url` at a copy of the app you host, or add the site to the host's `frame-ancestors`. The rendered views need neither.
|
||||||
|
|
||||||
|
## Use
|
||||||
|
|
||||||
|
Programs are files next to the page: `count-base.lingo`, `match.pseudo`, `spec.speco`, `mean.tex`, `count_base.mojo`, `two-pointers.asm` (with `two-pointers.setup`). Paths are relative to the page.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{< pplus-run pseudo="count-base.pseudo" code="1" >}} the program, then what it printed
|
||||||
|
{{< pplus-steps lingo="count-base.lingo" t="6" >}} a stepper, parked at step 6
|
||||||
|
{{< pplus-steps asm="two.asm" setup="two.setup" max="40" >}} the machine's registers, step by step
|
||||||
|
{{< pplus-steps pseudo="count-base.pseudo" follow="Total,I" >}} a stepper over two names only
|
||||||
|
{{< pplus-table pseudo="count-base.pseudo" >}} the table of values
|
||||||
|
{{< pplus-flow pseudo="binary-search.pseudo" live="click" >}} the flowchart, and a button to go live
|
||||||
|
{{< pplus-dataflow pseudo="count-base.pseudo" >}}
|
||||||
|
{{< pplus-lifetimes mojo="lifecycle.mojo" >}}
|
||||||
|
{{< pplus-proof pseudo="count-base.pseudo" speco="count-base.speco" >}}
|
||||||
|
{{< pplus-tests pseudo="match-off-by-one.pseudo" >}}
|
||||||
|
{{< pplus-check pseudo="five-bugs.pseudo" code="1" numbers="1" >}}
|
||||||
|
{{< pplus-translate matho="mean.tex" >}} tabs: matho, lingo, pseudo, Mojo
|
||||||
|
{{< pplus-translate lingo="x.lingo" layout="grid" to="pseudo,mojo" >}}
|
||||||
|
{{< pplus-machine asm="two.asm" setup="two.setup" >}}
|
||||||
|
{{< pplus-view view="flow" pseudo="x.pseudo" >}}
|
||||||
|
|
||||||
|
{{< pplus-playground lingo="x.lingo" pseudo="x.pseudo" panel="flow" >}}
|
||||||
|
{{< pplus-embed pseudo="x.pseudo" view="trace" t="9" >}}
|
||||||
|
{{< pplus-listing pseudo="x.pseudo" numbers="1" >}}
|
||||||
|
{{< pplus-tabs lingo="x.lingo" pseudo="x.pseudo" mojo="x.mojo" >}}
|
||||||
|
{{< pplus-link pseudo="x.pseudo" text="Open it in Programming+" >}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Every option is documented at the top of `_extensions/pplus/pplus.lua`. These work with every shortcode:
|
||||||
|
|
||||||
|
| option | does |
|
||||||
|
|---|---|
|
||||||
|
| `lingo`, `matho`, `pseudo`, `speco`, `mojo`, `asm` | files beside the page whose text fills that pane |
|
||||||
|
| `setup` | a file holding the x86-64 pane's setup block (registers, memory) |
|
||||||
|
| `lang` | the pane that runs (default: the first of lingo, matho, pseudo, mojo, asm given) |
|
||||||
|
| `call`, `input` | the call to run, and lines INPUT reads separated by `\|` (default: the file's own `// CALL:` and `// INPUT:` lines) |
|
||||||
|
| `machine` | the x86-64 machine model preset |
|
||||||
|
| `t` | the step the stepper starts on (live: is parked at) |
|
||||||
|
| `title`, `caption` | a title over the view, a sentence under it |
|
||||||
|
| `collapse` | `1` folds it into a block titled with `title` |
|
||||||
|
| `area` | `bridge` (default), `dev` or `hw`: where "open in the playground" goes, and the area the live playground opens in |
|
||||||
|
|
||||||
|
And these work with the rendered ones:
|
||||||
|
|
||||||
|
| option | does |
|
||||||
|
|---|---|
|
||||||
|
| `code` | `1` prints the program inside the view's frame, above it |
|
||||||
|
| `numbers` | `1` numbers the listing's lines |
|
||||||
|
| `live` | `click`: a button that puts the live view in place of the rendered one |
|
||||||
|
| `height` | the live frame's height when it is put in place (default 520; 720 for translate and the machine's views, which open the whole playground) |
|
||||||
|
| `follow` | steps: the variables to show, comma-separated |
|
||||||
|
| `max` | steps: the most steps kept (default 400; from 10 to 5000) |
|
||||||
|
| `to`, `layout` | translate: the notations to show, comma-separated; `tabs` (default), `columns` or `grid` |
|
||||||
|
| `compiler` | run, for a Mojo file: `auto`, `on` or `off` |
|
||||||
|
| `column` | Quarto's column for the view (`page`, `screen`, `margin`, ...) |
|
||||||
|
|
||||||
|
In a format other than HTML (a PDF, a Word file), a rendered view becomes Markdown. The run is printed as a code block; the steps, the table of values and the machine's counters as tables; the proof, tests and checker's findings as lists; and translate as one listing per notation. The flowchart, the data flow and the lifetimes say they are drawn in the HTML version. A view of the machine gives the registers the run has written by step `t` and names the cards drawn in the HTML version. Each view except translate is followed by a link to the app.
|
||||||
|
|
||||||
|
### The live views, arranged
|
||||||
|
|
||||||
|
`pplus-playground` puts the full playground in the frame: every pane, the stepper, the variables, every inspect tab, the dock, Run (Compile & run on the Mojo pane), Share and the theme switch. `pplus-embed` (and `pplus`) shows one view with the code it reads. A reader's edits are kept in their browser for that example, and Reset brings the page's version back. The options arrange it the way the playground's own controls do:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{< pplus-playground mojo="demo.mojo" asm="demo.asm" setup="demo.setup" area="hw" >}}
|
||||||
|
{{< pplus-playground problem="demo" panel="compiler" build="default" dock="open" >}}
|
||||||
|
{{< pplus-playground mojo="demo.mojo" area="dev" editor="0.6" dockheight="0.75" panel="life" >}}
|
||||||
|
{{< pplus-embed mojo="demo.mojo" view="compiler" >}}
|
||||||
|
{{< pplus-embed pseudo="x.pseudo" view="flow" height="auto" showcall="0" >}}
|
||||||
|
{{< pplus pseudo="match.pseudo" show="both" title="MATCH" >}} the listing, then the embed
|
||||||
|
```
|
||||||
|
|
||||||
|
| option | does |
|
||||||
|
|---|---|
|
||||||
|
| `view` | `pplus-embed`, `pplus`: the view (default `trace`) |
|
||||||
|
| `panel` | the tab it opens on: `trace table flow data life proof tests` beside the editor, or `output problems compiler asm setup` in the dock |
|
||||||
|
| `build` | `O0` (as written) or `default` (as `mojo build` does) |
|
||||||
|
| `dock`, `docktab` | `open`/`closed`, and which dock tab |
|
||||||
|
| `editor`, `side`, `dockheight` | the playground's splits, as fractions |
|
||||||
|
| `theme` | `light`/`dark` (default: follows the page's switch) |
|
||||||
|
| `ro` | `1`: read-only, and nothing is saved |
|
||||||
|
| `showcall` | `0` hides the run box above a flow, data or table view |
|
||||||
|
| `split` | the share of a fixed-height frame the code takes above the panel (default 0.7) |
|
||||||
|
| `height` | the frame's height in px (default 520, or 720 for the playground), or `auto` to fit its content (not for the playground, which fills its frame) |
|
||||||
|
| `problem` | a catalog problem's id instead of files |
|
||||||
|
| `state` | a state from the playground's Share dialog |
|
||||||
|
| `show`, `mode`, `text` | `pplus`: `listing` or `both`; `mode="link"` for only a link, with `text` |
|
||||||
|
|
||||||
|
Or arrange it in the playground itself and paste the result: **Share** → *embed which view* → **Quarto** gives a `{{< pplus-playground state="…" >}}` or `{{< pplus-embed state="…" view="…" >}}` shortcode for exactly what you see, layout and step included.
|
||||||
|
|
||||||
|
### A Mojo program from `core/library/mojo/local/`, with its assembly
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pixi run --manifest-path core/pixi.toml play demo # verify it, and store the compiler's listing
|
||||||
|
pixi run quarto-export demo ../site/programmingplus/demo
|
||||||
|
```
|
||||||
|
|
||||||
|
This writes `demo.mojo`, `demo.asm` (the x86-64 pane's program) and `demo.setup` next to the page, and prints a `pplus-playground` shortcode that embeds them, and `pplus-run` and `pplus-lifetimes` shortcodes that render the program with the page. For a program with no stored listing it writes only `demo.mojo` and says so. The `# origin:`/`# probe:`/... header of a `core/library/mojo/local/` file is left out of the pane and the listing. Its `# expect-stdout:` lines count as `EXPECT` lines.
|
||||||
|
|
||||||
|
## The machine
|
||||||
|
|
||||||
|
`pplus-hw` and the `pplus-hw-<view>` shortcodes show what the Hardware area's board shows, over an x86-64 file beside the page (`asm=`, with its `setup=` for the registers and memory). While Quarto renders, the extension runs the program on the model machine and draws each card at every step. The cards are the course's own views (pplus-core's `core/src/engines/asm86/`) and, for `lines` and `counters`, the app's own, mounted as the board mounts them. The page keeps each card's distinct drawings and which one each step shows, compressed (deflate: for the 97 steps of the example's two-pointers run most cards take 1 to 12 KB, the pipeline about 30 KB and the out-of-order timeline about 80 KB), and `pplus.js` steps through them. Nothing runs in the reader's browser beyond that, and the step the page opens on (`t=`) is in the markup, so the page prints and reads without script.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{< pplus-hw asm="two-pointers.asm" setup="two-pointers.setup" >}} registers, flags, address, memory, stack
|
||||||
|
{{< pplus-hw asm="two.asm" setup="two.setup" preset="caches" t="12" >}} the caches, opening on step 12
|
||||||
|
{{< pplus-hw asm="two.asm" setup="two.setup" views="explain,registers,encoding" >}} the cards you name, in order
|
||||||
|
{{< pplus-hw-pipeline asm="two.asm" setup="two.setup" listing="0" max="40" >}} one card, no listing, at most 40 steps drawn
|
||||||
|
{{< pplus-hw-paging asm="two.asm" setup="two.setup" >}} virtual memory is switched on for it
|
||||||
|
{{< pplus-hw-encoding asm="two.asm" setup="two.setup" t="9" stepper="0" >}} one step, for a printed figure
|
||||||
|
```
|
||||||
|
|
||||||
|
| view | shows |
|
||||||
|
|---|---|
|
||||||
|
| `code` | the machine code: each instruction with its address and bytes |
|
||||||
|
| `explain` | the last instruction in words |
|
||||||
|
| `registers`, `flags`, `address` | the registers the program touches (with every narrower name it uses), the flags, base + index × scale + displacement |
|
||||||
|
| `memory`, `stack` | each region byte by byte with the load or store marked, and the stack's slots with rsp and rbp |
|
||||||
|
| `dataflow`, `alu` | where the last instruction's values came from and went, and the ALU at bit level |
|
||||||
|
| `branches`, `vectors` | each branch and whether the predictor guessed right, and the xmm registers lane by lane |
|
||||||
|
| `lines`, `cache`, `hierarchy` | the cache line each access touched, the L1 data cache as sets and ways, the path through L1, L2, L3 and memory |
|
||||||
|
| `paging` | the page walk and the TLB |
|
||||||
|
| `pipeline`, `uops`, `timeline`, `bottleneck` | the five-stage pipeline, micro-ops and ports, the out-of-order timeline, what limits the speed |
|
||||||
|
| `counters` | the run's totals, in the style of `perf stat` (the same at every step) |
|
||||||
|
| `chip`, `core`, `encoding` | the whole core with the parts the last instruction used lit up, inside the out-of-order core, the instruction's bytes field by field |
|
||||||
|
|
||||||
|
| option | does |
|
||||||
|
|---|---|
|
||||||
|
| `preset`, `views` | `pplus-hw`: the board's arrangement (`regs`, the default, `caches`, `pipeline`, `chip`), or the views, comma-separated |
|
||||||
|
| `machine` | the machine model: `teaching` (default), `realistic`, `ideal`; `+paging` for virtual memory |
|
||||||
|
| `t` | the step the page opens on |
|
||||||
|
| `max` | the most steps drawn (default 400); a longer run is sampled evenly, its last step always included |
|
||||||
|
| `listing` | `0` leaves out the x86-64 listing beside the cards |
|
||||||
|
| `stepper` | `0` draws only step `t` |
|
||||||
|
| `column` | Quarto's column for the figure; `pplus-hw` is `page`-wide by default, one card as wide as the text |
|
||||||
|
|
||||||
|
The machine's stylesheets are the course's own (`course/tokens.css`, `kit.css`, `asm86.css`, written for Quarto pages) and the board's adjustments to them (`pplus-hw.css`); they are attached only to a page that shows the machine. `pixi run quarto-css` copies the three course files from `styles/course/` and writes `pplus-hw.css` from `styles/course/bridge.css`.
|
||||||
|
|
||||||
|
For a Mojo program, `pixi run quarto-export <name> <folder>` writes the compiler's x86-64 for it and a setup for its arguments beside the page; [example/machine.qmd](example/machine.qmd) shows the demo's `cell` function this way.
|
||||||
|
|
||||||
|
## The header of a program file
|
||||||
|
|
||||||
|
A program file may start with lines the checker reads. The views honor them, and no listing, pane or editor shows them:
|
||||||
|
|
||||||
|
```
|
||||||
|
// CALL: MATCH("ATT", "GATTACA") the call to run
|
||||||
|
// INPUT: 4000 a line INPUT reads (repeatable)
|
||||||
|
// EXPECT: MATCH returned [1] a line of output, in order (repeatable); pplus-run checks it
|
||||||
|
// ERRORS: 2 pseudo, LaTeX: meant to be refused with this many errors (Mojo: meant not to compile)
|
||||||
|
// QUESTION: range-ends lingo: the reader is meant to ask this question
|
||||||
|
// STOPS: index the run is meant to stop with this kind of error
|
||||||
|
```
|
||||||
|
|
||||||
|
A `.tex` file uses `%` in place of `//`. A Mojo file's header is its leading block of `# key: value` lines (`# EXPECT: 3`, or the corpus's `# expect-stdout: 3`). Only that block is left out of a listing, so keep every header line in it.
|
||||||
|
|
||||||
|
## Check
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pixi run check-pages /path/to/site
|
||||||
|
```
|
||||||
|
|
||||||
|
(It builds first. To check several folders at once, run `node scripts/check-pages.mjs <folder> [...]` after `pixi run build`.)
|
||||||
|
|
||||||
|
Every `.lingo`, `.pseudo` and `.tex` file under the folders (names that start with `_` or `.` are skipped) is parsed and checked, and lingo and LaTeX are lowered to pseudo. A file with `// CALL:` or `// EXPECT:` lines is run with its `// CALL:` and `// INPUT:` lines and compared with its `// EXPECT:` lines; a lingo file with `// QUESTION:` lines is only held to asking them. A `.speco` file is only checked to exist where a shortcode names it. A `.mojo` file is checked for syntax the pinned Mojo removed; when a `mojo` compiler is on the PATH it is also run, with `mojo run` and the pin's build arguments, and must exit 0 and print its `EXPECT` lines (or, with `ERRORS`, not compile). Every shortcode must be one the extension has, and every file it names must exist. The exit status is 1 on any problem. A rendered page checks itself as well: with `pplus-strict: true`, `quarto render` stops at the first view that cannot be rendered (no engine, or the engine fails) or whose run does not print its `EXPECT` lines, which includes a program with `EXPECT` lines that does not run at all. A program without `EXPECT` lines that does not run is a warning.
|
||||||
|
|
||||||
|
## How it is built
|
||||||
|
|
||||||
|
- `pplus.lua` holds the shortcodes. It reads the files, writes the live views' URLs (the state as `~` + base64url JSON, which the app reads without decompression), and asks `render.mjs` for the rendered views.
|
||||||
|
- `render.mjs` loads the engine's `dist/quarto/render.js`. That is `src/quarto/render.ts` in Programming+: it builds the same `Session` the app does and draws the app's own views (`src/ui/views/`) into the small document of `src/quarto/dom.ts`, then returns their HTML and a Markdown form.
|
||||||
|
- `pplus-views.css` holds the app's rules for those views, scoped to `.pplus-static`, and is generated by `pixi run quarto-css`, which also copies the course's stylesheets into `course/`, writes `pplus-hw.css`, and copies core's `syntax/mojo.xml`. `pplus.css` holds the extension's own rules (the frames, the run, the stepper, the translations).
|
||||||
|
- `src/quarto/machine.ts` draws the machine's cards at every step for `pplus-hw`, with the board's own `mountView` and presets (`src/ui/hw/board.ts`, `src/core/hardware.ts`); `render.mjs` compresses the drawings.
|
||||||
|
- `pplus.js` moves the steppers (the machine's too, decompressing its drawings with the browser's `DecompressionStream`), puts a live view in place on **make it live**, sizes `height="auto"` frames (to what the frame asks for, between 120 and 4000 pixels: a frame cannot make the page longer than that), and passes the page's light/dark switch to live frames.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
title: Programming+
|
||||||
|
author: Alex Maldonado
|
||||||
|
version: 2.0.0
|
||||||
|
quarto-required: ">=1.5.0"
|
||||||
|
contributes:
|
||||||
|
shortcodes:
|
||||||
|
- pplus.lua
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,302 @@
|
|||||||
|
/* ============================================================================
|
||||||
|
widgets/kit.css -- what the two teaching-widget families have in common.
|
||||||
|
|
||||||
|
Two families of interactive widgets are built by static/js:
|
||||||
|
.a86 the x86-64 assembly widgets (js/asm86, css/widgets/asm86.css)
|
||||||
|
.pl the pseudocode lab (js/pseudo, css/widgets/pseudo-lab.css)
|
||||||
|
They were written as twins and shared a design system by copy and paste.
|
||||||
|
This file holds the shared half, written once, so a change to a color
|
||||||
|
role or a button reaches both. The two family stylesheets keep only what
|
||||||
|
is specific to them and must be loaded AFTER this one.
|
||||||
|
|
||||||
|
Color roles carry meaning, so they are worth learning once:
|
||||||
|
amber the step about to run, and anything the last step changed
|
||||||
|
blue a value that was read
|
||||||
|
purple a value that was written
|
||||||
|
green a match, a pass, a proof
|
||||||
|
red a mismatch, an error, a claim a run broke
|
||||||
|
The roles are stated once per theme below. Everything neutral is mixed
|
||||||
|
from the page colors (--bs-body-bg / --bs-body-color), so a widget sits
|
||||||
|
on whatever background the page gives it.
|
||||||
|
|
||||||
|
Dark mode keys off `body.quarto-dark`, which is what Quarto actually sets.
|
||||||
|
`[data-bs-theme="dark"]` is grouped in only as a fallback. Reading the OS
|
||||||
|
preference (prefers-color-scheme) on a Quarto page is the bug that once
|
||||||
|
made a light page render a dark widget, so nothing here does.
|
||||||
|
|
||||||
|
Tokens (--w-*)
|
||||||
|
--w-page --w-ink --w-dim --w-rule --w-surface --w-surface-2
|
||||||
|
--w-change --w-read --w-write --w-match --w-miss and their -bg washes
|
||||||
|
--w-mono --w-sans --w-fs
|
||||||
|
--w-fs is the one size that drives every piece of text in a widget. Each
|
||||||
|
rule states its size as a multiple of it, so fullscreen raises them all at
|
||||||
|
once. At 0.95rem a widget reads a step below the page's body text.
|
||||||
|
==========================================================================*/
|
||||||
|
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ tokens */
|
||||||
|
|
||||||
|
:is(.a86, .pl) {
|
||||||
|
--w-page: var(--bs-body-bg, #ffffff);
|
||||||
|
--w-ink: var(--bs-body-color, #1b1f24);
|
||||||
|
|
||||||
|
/* 70%, matching the muted gray in base/site.css and bio.css: at 60% the
|
||||||
|
result fails WCAG AA for normal-size text on a white background. */
|
||||||
|
--w-dim: color-mix(in srgb, var(--w-ink) 70%, transparent);
|
||||||
|
--w-rule: color-mix(in srgb, var(--w-ink) 20%, transparent);
|
||||||
|
--w-surface: var(--w-page);
|
||||||
|
--w-surface-2: color-mix(in srgb, var(--w-ink) 6%, var(--w-page));
|
||||||
|
|
||||||
|
--w-change: #8a5c05;
|
||||||
|
--w-read: #17618f;
|
||||||
|
--w-write: #6a4299;
|
||||||
|
--w-match: #266a41;
|
||||||
|
--w-miss: #93291f;
|
||||||
|
|
||||||
|
--w-change-bg: color-mix(in srgb, var(--w-change) 13%, var(--w-page));
|
||||||
|
--w-read-bg: color-mix(in srgb, var(--w-read) 13%, var(--w-page));
|
||||||
|
--w-write-bg: color-mix(in srgb, var(--w-write) 13%, var(--w-page));
|
||||||
|
--w-match-bg: color-mix(in srgb, var(--w-match) 15%, var(--w-page));
|
||||||
|
--w-miss-bg: color-mix(in srgb, var(--w-miss) 13%, var(--w-page));
|
||||||
|
|
||||||
|
--w-mono: var(--bs-font-monospace, ui-monospace, "SF Mono", Menlo, Consolas, monospace);
|
||||||
|
--w-sans: var(--bs-font-sans-serif, system-ui, sans-serif);
|
||||||
|
--w-fs: 0.95rem;
|
||||||
|
|
||||||
|
color: var(--w-ink);
|
||||||
|
font-size: var(--w-fs);
|
||||||
|
line-height: 1.45;
|
||||||
|
margin: 1.4rem 0;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A tinted panel needs a stronger wash to read against a dark page, and the
|
||||||
|
accents have to lighten to stay legible on it. */
|
||||||
|
body.quarto-dark :is(.a86, .pl),
|
||||||
|
[data-bs-theme="dark"] :is(.a86, .pl) {
|
||||||
|
--w-change: #e0a93a;
|
||||||
|
--w-read: #6fb4e3;
|
||||||
|
--w-write: #c0a0e0;
|
||||||
|
--w-match: #74c391;
|
||||||
|
--w-miss: #e08a80;
|
||||||
|
|
||||||
|
--w-rule: color-mix(in srgb, var(--w-ink) 28%, transparent);
|
||||||
|
--w-surface-2: color-mix(in srgb, var(--w-ink) 9%, var(--w-page));
|
||||||
|
|
||||||
|
--w-change-bg: color-mix(in srgb, var(--w-change) 22%, var(--w-page));
|
||||||
|
--w-read-bg: color-mix(in srgb, var(--w-read) 22%, var(--w-page));
|
||||||
|
--w-write-bg: color-mix(in srgb, var(--w-write) 22%, var(--w-page));
|
||||||
|
--w-match-bg: color-mix(in srgb, var(--w-match) 22%, var(--w-page));
|
||||||
|
--w-miss-bg: color-mix(in srgb, var(--w-miss) 22%, var(--w-page));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback for browsers without color-mix(). */
|
||||||
|
@supports not (background: color-mix(in srgb, white 50%, black)) {
|
||||||
|
:is(.a86, .pl) {
|
||||||
|
--w-dim: #666f78;
|
||||||
|
--w-rule: #d5dae0;
|
||||||
|
--w-surface-2: #f4f6f8;
|
||||||
|
--w-change-bg: #fdf1d8;
|
||||||
|
--w-read-bg: #e1eef9;
|
||||||
|
--w-write-bg: #efe6f7;
|
||||||
|
--w-match-bg: #dcefe2;
|
||||||
|
--w-miss-bg: #f8e3e1;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.quarto-dark :is(.a86, .pl) {
|
||||||
|
--w-dim: #98a2ab;
|
||||||
|
--w-rule: #3a424b;
|
||||||
|
--w-surface-2: #21262c;
|
||||||
|
--w-change-bg: #453518;
|
||||||
|
--w-read-bg: #1b3348;
|
||||||
|
--w-write-bg: #33254a;
|
||||||
|
--w-match-bg: #1d3a28;
|
||||||
|
--w-miss-bg: #3f2320;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------- shared rules
|
||||||
|
Each rule below was identical in both stylesheets. Rules that differ
|
||||||
|
between the families (panels, code rows, cells, legends...) stay in the
|
||||||
|
family file that owns them. */
|
||||||
|
|
||||||
|
/* --- Widget shell ------------------------------------------------------ */
|
||||||
|
|
||||||
|
.a86:focus-visible,
|
||||||
|
.pl:focus-visible {
|
||||||
|
box-shadow: 0 0 0 3px var(--w-change-bg);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86 code,
|
||||||
|
.a86 code:not(.sourceCode),
|
||||||
|
.pl code,
|
||||||
|
.pl code:not(.sourceCode) {
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
font-size: inherit;
|
||||||
|
color: inherit;
|
||||||
|
font-family: var(--w-mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Text -------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.a86-title,
|
||||||
|
.pl-title {
|
||||||
|
font-size: calc(var(--w-fs) * 1.13);
|
||||||
|
margin: 0 0 0.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-blurb,
|
||||||
|
.pl-blurb {
|
||||||
|
color: var(--w-dim);
|
||||||
|
margin: 0 0 0.7rem;
|
||||||
|
max-width: 62ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-muted,
|
||||||
|
.pl-muted {
|
||||||
|
color: var(--w-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-error,
|
||||||
|
.pl-error {
|
||||||
|
color: var(--w-miss);
|
||||||
|
background: var(--w-miss-bg);
|
||||||
|
border-left: 3px solid var(--w-miss);
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Controls ---------------------------------------------------------- */
|
||||||
|
|
||||||
|
.a86-controls,
|
||||||
|
.pl-controls {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding: 0.4rem 0.5rem;
|
||||||
|
margin-bottom: 0.7rem;
|
||||||
|
background: var(--w-surface-2);
|
||||||
|
border: 1px solid var(--w-rule);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-btn,
|
||||||
|
.pl-btn {
|
||||||
|
font: inherit;
|
||||||
|
font-size: calc(var(--w-fs) * 0.96);
|
||||||
|
padding: 0.22rem 0.62rem;
|
||||||
|
color: var(--w-ink);
|
||||||
|
background: var(--w-surface-2);
|
||||||
|
border: 1px solid var(--w-rule);
|
||||||
|
border-radius: 3px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-btn:hover,
|
||||||
|
.pl-btn:hover {
|
||||||
|
border-color: var(--w-change);
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-btn-primary,
|
||||||
|
.pl-btn-primary {
|
||||||
|
border-color: var(--w-change);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-slider,
|
||||||
|
.pl-slider {
|
||||||
|
flex: 1 1 140px;
|
||||||
|
min-width: 110px;
|
||||||
|
accent-color: var(--w-change);
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-readout,
|
||||||
|
.pl-readout {
|
||||||
|
font-family: var(--w-mono);
|
||||||
|
font-size: calc(var(--w-fs) * 0.93);
|
||||||
|
color: var(--w-dim);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-btn-full,
|
||||||
|
.pl-btn-full {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Layout ------------------------------------------------------------ */
|
||||||
|
|
||||||
|
.a86-grid,
|
||||||
|
.pl-grid {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.7rem;
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-panel-title,
|
||||||
|
.pl-panel-title {
|
||||||
|
font-family: var(--w-sans);
|
||||||
|
font-size: calc(var(--w-fs) * 0.89);
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
color: var(--w-dim);
|
||||||
|
margin: 0 0 0.45rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Fullscreen -------------------------------------------------------- */
|
||||||
|
|
||||||
|
.a86.is-fullscreen,
|
||||||
|
.pl.is-fullscreen {
|
||||||
|
--w-fs: clamp(1rem, 0.35rem + 0.62vw, 1.3rem);
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 1090;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.9rem 1.1rem 2rem;
|
||||||
|
background: var(--w-page);
|
||||||
|
overflow: auto;
|
||||||
|
overscroll-behavior: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86.is-fullscreen .a86-controls,
|
||||||
|
.pl.is-fullscreen .pl-controls {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86.is-fullscreen .a86-grid,
|
||||||
|
.pl.is-fullscreen .pl-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86.is-fullscreen .a86-trace-wrap,
|
||||||
|
.pl.is-fullscreen .pl-trace-wrap {
|
||||||
|
max-height: 28rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- Code listing ------------------------------------------------------ */
|
||||||
|
|
||||||
|
.a86-code-marker,
|
||||||
|
.pl-code-marker {
|
||||||
|
color: var(--w-change);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-code-row.is-last,
|
||||||
|
.pl-code-row.is-last {
|
||||||
|
background: var(--w-surface-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.a86-code-row.is-error,
|
||||||
|
.pl-code-row.is-error {
|
||||||
|
background: var(--w-miss-bg);
|
||||||
|
border-left-color: var(--w-miss);
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/* ============================================================================
|
||||||
|
base/tokens.css -- design tokens shared by the course kit
|
||||||
|
(blocks, algorithms, worked examples, page furniture, figures and the
|
||||||
|
viz.js chart helpers). Custom properties only: loading this file changes
|
||||||
|
nothing on a page that does not use them.
|
||||||
|
|
||||||
|
Everything is derived from --bs-body-color / --bs-body-bg, which Quarto
|
||||||
|
sets for each theme and swaps on the light/dark toggle, so a token that
|
||||||
|
mixes them needs no dark-mode rule of its own. Hue tokens (role colors,
|
||||||
|
the categorical palette) do have a dark value, set on body.quarto-dark.
|
||||||
|
==========================================================================*/
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* ---- surfaces and text ---- */
|
||||||
|
--course-ink: var(--bs-body-color, #212529);
|
||||||
|
--course-paper: var(--bs-body-bg, #fff);
|
||||||
|
--course-muted: color-mix(in srgb, var(--course-ink) 68%, transparent);
|
||||||
|
--course-rule: color-mix(in srgb, var(--course-ink) 18%, transparent);
|
||||||
|
--course-wash: color-mix(in srgb, var(--course-ink) 4%, var(--course-paper));
|
||||||
|
--course-radius: 6px;
|
||||||
|
|
||||||
|
/* ---- role colors: which kind of block a reader is looking at ---- */
|
||||||
|
--course-key: #2563eb;
|
||||||
|
/* key idea, definition, theorem */
|
||||||
|
--course-intuition: #7c3aed;
|
||||||
|
/* intuition, why it matters */
|
||||||
|
--course-caution: #b45309;
|
||||||
|
/* pitfall, misconception */
|
||||||
|
--course-practice: #047857;
|
||||||
|
/* in practice, worked example, checkpoint */
|
||||||
|
--course-algorithm: #0f766e;
|
||||||
|
/* algorithm cards */
|
||||||
|
--course-history: #78716c;
|
||||||
|
/* history, going deeper */
|
||||||
|
--course-draft: #c026d3;
|
||||||
|
/* author notes, never shown to students */
|
||||||
|
|
||||||
|
/* ---- categorical palette (Okabe & Ito), safe for color-vision deficiency.
|
||||||
|
viz.js and any hand-written figure take colors from here, in order. ---- */
|
||||||
|
--viz-1: #0072b2;
|
||||||
|
/* blue */
|
||||||
|
--viz-2: #d55e00;
|
||||||
|
/* vermillion */
|
||||||
|
--viz-3: #009e73;
|
||||||
|
/* bluish green */
|
||||||
|
--viz-4: #cc79a7;
|
||||||
|
/* reddish purple */
|
||||||
|
--viz-5: #e69f00;
|
||||||
|
/* orange */
|
||||||
|
--viz-6: #56b4e9;
|
||||||
|
/* sky blue */
|
||||||
|
--viz-7: #f0e442;
|
||||||
|
/* yellow */
|
||||||
|
--viz-8: #000000;
|
||||||
|
/* black */
|
||||||
|
|
||||||
|
/* diverging (negative .. positive) and the single-hue ramp for magnitudes */
|
||||||
|
--viz-neg: #0072b2;
|
||||||
|
--viz-pos: #d55e00;
|
||||||
|
--viz-ramp: #0072b2;
|
||||||
|
|
||||||
|
/* axes, gridlines, labels inside a chart */
|
||||||
|
--viz-ink: var(--course-ink);
|
||||||
|
--viz-muted: var(--course-muted);
|
||||||
|
--viz-grid: color-mix(in srgb, var(--course-ink) 12%, transparent);
|
||||||
|
--viz-bg: var(--course-paper);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.quarto-dark {
|
||||||
|
--course-key: #7aa2ff;
|
||||||
|
--course-intuition: #b79cff;
|
||||||
|
--course-caution: #f0a04b;
|
||||||
|
--course-practice: #4cc9a0;
|
||||||
|
--course-algorithm: #4fd1c5;
|
||||||
|
--course-history: #b4aca5;
|
||||||
|
--course-draft: #e879f9;
|
||||||
|
|
||||||
|
--viz-1: #56b4e9;
|
||||||
|
--viz-2: #f28e4b;
|
||||||
|
--viz-3: #2fc99a;
|
||||||
|
--viz-4: #e9a3c8;
|
||||||
|
--viz-5: #f5b942;
|
||||||
|
--viz-6: #8fd0f5;
|
||||||
|
--viz-7: #f5ec6a;
|
||||||
|
--viz-8: #e5e5e5;
|
||||||
|
--viz-neg: #56b4e9;
|
||||||
|
--viz-pos: #f28e4b;
|
||||||
|
--viz-ramp: #56b4e9;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback for browsers without color-mix(). */
|
||||||
|
@supports not (background: color-mix(in srgb, white 50%, black)) {
|
||||||
|
:root {
|
||||||
|
--course-muted: rgba(33, 37, 41, 0.68);
|
||||||
|
--course-rule: rgba(128, 128, 128, 0.3);
|
||||||
|
--course-wash: rgba(128, 128, 128, 0.06);
|
||||||
|
--viz-grid: rgba(128, 128, 128, 0.25);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
/* pplus-hw.css: GENERATED by `pixi run quarto-css` (scripts/quarto-css.mjs) from styles/course/bridge.css. Do not edit.
|
||||||
|
The Hardware board's adjustments to the course's machine views (course/*.css), for the pplus-hw shortcodes. A Quarto
|
||||||
|
page already has the colors and fonts those files read (--bs-body-bg, --bs-body-color, body.quarto-dark). */
|
||||||
|
/* ---------------------------------------------------------------------------
|
||||||
|
The Hardware area's machine board (src/ui/hw/board.ts) puts the course's
|
||||||
|
views in the app's dock. Adjustments for that home, never in the course files.
|
||||||
|
------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/* A register card that also shows its narrower names needs room for the
|
||||||
|
name, sixteen hex digits, and the width on one line. */
|
||||||
|
.board-a86 .a86-regs {
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(calc(var(--w-fs) * 17), 1fr));
|
||||||
|
}
|
||||||
|
|
||||||
|
.board-a86 .a86-width-row {
|
||||||
|
grid-template-columns: calc(var(--w-fs) * 2.83) minmax(0, 1fr) auto;
|
||||||
|
}
|
||||||
|
.board-a86 .a86-regs { align-items: start; }
|
||||||
|
|
||||||
|
/* The "was ..." line under a register's value is empty until the register
|
||||||
|
changes. asm86.css gives it a min-height (0.8rem) shorter than its own line
|
||||||
|
box, so a card grew a few pixels the step it changed and shrank on the next,
|
||||||
|
moving every card below it. Reserve the whole line, filled or not. */
|
||||||
|
.board-a86 .a86-reg-prev {
|
||||||
|
line-height: 1.35;
|
||||||
|
min-height: 1.35em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.board-a86.a86 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The board's own "Cache lines" view (src/ui/hw/lines.ts): a line as a row of
|
||||||
|
byte cells, in the course's load, store and match colors. */
|
||||||
|
.hw-line + .hw-line {
|
||||||
|
margin-top: 0.6rem;
|
||||||
|
padding-top: 0.6rem;
|
||||||
|
border-top: 1px dashed var(--w-rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
.hw-line-head,
|
||||||
|
.hw-line-use {
|
||||||
|
margin: 0.2rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hw-line-cells {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(var(--hw-line, 16), minmax(0, 1fr));
|
||||||
|
gap: 2px;
|
||||||
|
max-width: calc(var(--hw-line, 16) * 1.9rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.hw-line-cell {
|
||||||
|
display: block;
|
||||||
|
min-height: 1.6rem;
|
||||||
|
border: 1px solid var(--w-rule);
|
||||||
|
border-radius: 2px;
|
||||||
|
background: var(--w-surface);
|
||||||
|
color: var(--w-dim);
|
||||||
|
font-family: var(--w-mono);
|
||||||
|
font-size: 0.7rem;
|
||||||
|
line-height: 1.6rem;
|
||||||
|
text-align: center;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hw-line-cell.is-read { background: var(--w-read-bg); border-color: var(--w-read); color: var(--w-read); }
|
||||||
|
.hw-line-cell.is-write { background: var(--w-write-bg); border-color: var(--w-write); color: var(--w-write); }
|
||||||
|
.hw-line-cell.is-used { background: var(--w-match-bg); }
|
||||||
|
.hw-line-cell.is-later { background: var(--w-surface-2); border-style: dashed; }
|
||||||
|
|
||||||
|
.hw-swatch {
|
||||||
|
display: inline-block;
|
||||||
|
width: 1rem;
|
||||||
|
min-height: 0.9rem;
|
||||||
|
height: 0.9rem;
|
||||||
|
vertical-align: middle;
|
||||||
|
margin-right: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hw-hit { color: var(--w-match); font-weight: 600; }
|
||||||
|
.hw-miss { color: var(--w-miss); font-weight: 600; }
|
||||||
|
|
||||||
|
/* The whole core (machineView in hwviews.js): a lit edge's arrowhead takes the
|
||||||
|
edge's color, so the head shows which way that instruction's data moved. */
|
||||||
|
.a86-chip-svg marker.is-active path { fill: var(--w-change); }
|
||||||
|
.a86-chip-svg marker.is-load path { fill: var(--w-read); }
|
||||||
|
.a86-chip-svg marker.is-store path { fill: var(--w-write); }
|
||||||
|
.a86-chip-edge.is-active { stroke-width: 2.2; }
|
||||||
|
|
||||||
|
/* The sentence under the core is one line for some instructions and two for
|
||||||
|
others; hold two, so the legend under it stays put while stepping. */
|
||||||
|
.board-a86 .a86-chip-caption {
|
||||||
|
line-height: 1.45;
|
||||||
|
min-height: 4.35em;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A port's box is 29 units wide; at 9px "alu mul" fits only in a narrow face,
|
||||||
|
and spills into the next port in the wider fallback fonts. */
|
||||||
|
.a86-chip-node.is-port .a86-chip-sub { font-size: 7px; }
|
||||||
|
|
||||||
|
/* Address arithmetic is one line ("named no memory address") on most steps and
|
||||||
|
a two-row sum with a note on the others. Hold the taller shape, so the card
|
||||||
|
and everything below it keep their place. */
|
||||||
|
.board-a86 .a86-addr { min-height: calc(var(--w-fs) * 14.5); }
|
||||||
|
|
||||||
|
/* The cache-line view lists the lines the last access touched: none before the
|
||||||
|
first access, one or two after. Hold two, so the legend under it stays put. */
|
||||||
|
.board-a86 .hw-lines { min-height: 78px; }
|
||||||
|
|
||||||
|
/* A listing row's trailing comment takes what width is left. In a narrow card
|
||||||
|
that is nothing, and a wrapping comment then stood one character per line,
|
||||||
|
leaving tall blank rows. Cut it with an ellipsis instead (a comment on its
|
||||||
|
own line still wraps). */
|
||||||
|
.board-a86 .a86-code-row:not(.is-note) > .a86-code-comment {
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
@@ -0,0 +1,810 @@
|
|||||||
|
/* pplus-views.css: GENERATED by `pixi run quarto-css` (scripts/quarto-css.mjs) from styles.css. Do not edit.
|
||||||
|
The app's own rules for what the static views draw, scoped under .pplus-static, with the app's color tokens;
|
||||||
|
the paper and ink follow the Quarto page (Bootstrap's variables). */
|
||||||
|
.pplus-static {
|
||||||
|
--paper: var(--bs-body-bg, #ffffff);
|
||||||
|
--paper-2: color-mix(in srgb, var(--bs-body-bg, #ffffff) 94%, var(--bs-body-color, #16191f));
|
||||||
|
--paper-3: color-mix(in srgb, var(--bs-body-bg, #ffffff) 88%, var(--bs-body-color, #16191f));
|
||||||
|
--ink: var(--bs-body-color, #16191f);
|
||||||
|
--ink-2: color-mix(in srgb, var(--bs-body-color, #16191f) 68%, var(--bs-body-bg, #ffffff));
|
||||||
|
--ink-3: color-mix(in srgb, var(--bs-body-color, #16191f) 48%, var(--bs-body-bg, #ffffff));
|
||||||
|
--line: color-mix(in srgb, var(--bs-body-color, #16191f) 14%, var(--bs-body-bg, #ffffff));
|
||||||
|
--line-2: color-mix(in srgb, var(--bs-body-color, #16191f) 24%, var(--bs-body-bg, #ffffff));
|
||||||
|
--mono: var(--bs-font-monospace, "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace);
|
||||||
|
--sans: inherit;
|
||||||
|
--bg: var(--paper); --bg-2: var(--paper-2); --bg-3: var(--paper-3); --fg: var(--ink); --fg-2: var(--ink-2); --note: var(--ink-3);
|
||||||
|
--current: var(--marker-bg); --last: var(--last-bg); --radius: var(--r-lg);
|
||||||
|
--accent: #2f5bea;
|
||||||
|
--accent-ink: #ffffff;
|
||||||
|
--accent-bg: #e7edfd;
|
||||||
|
--marker: #f6c453;
|
||||||
|
--marker-bg: #fff3cf;
|
||||||
|
--last-bg: #e3ecfb;
|
||||||
|
--ok: #157a4c;
|
||||||
|
--ok-bg: #e2f5ea;
|
||||||
|
--warn: #8f5807;
|
||||||
|
--warn-bg: #fdf0d6;
|
||||||
|
--err: #b83232;
|
||||||
|
--err-bg: #fbe3e3;
|
||||||
|
--r: 6px;
|
||||||
|
--r-lg: 10px;
|
||||||
|
--shadow: 0 10px 30px rgba(22, 25, 31, .10);
|
||||||
|
--tok-keyword: #1d46c7;
|
||||||
|
--tok-builtin: #7a3fc4;
|
||||||
|
--tok-string: #a8580d;
|
||||||
|
--tok-number: #0f7b6c;
|
||||||
|
--tok-comment: #646b77;
|
||||||
|
--tok-label: #b4247a;
|
||||||
|
--brand-bg: #f6c453;
|
||||||
|
--brand-fg: #16191f;
|
||||||
|
--brand-edge: #e0ab35;
|
||||||
|
--bg: var(--paper);
|
||||||
|
--bg-2: var(--paper-2);
|
||||||
|
--bg-3: var(--paper-3);
|
||||||
|
--fg: var(--ink);
|
||||||
|
--fg-2: var(--ink-2);
|
||||||
|
--note: var(--ink-3);
|
||||||
|
--current: var(--marker-bg);
|
||||||
|
--last: var(--last-bg);
|
||||||
|
--radius: var(--r-lg);
|
||||||
|
--k-write: #2f5bea;
|
||||||
|
--k-decision: #b5700d;
|
||||||
|
--k-loop: #7a3fc4;
|
||||||
|
--k-call: #0f7b6c;
|
||||||
|
--k-return: #1f9d63;
|
||||||
|
--k-io: #b4247a;
|
||||||
|
--k-life: #8a919c;
|
||||||
|
--k-error: #d64545;
|
||||||
|
--k-other: #c9cfd8;
|
||||||
|
--lang-lingo: #1f9d63;
|
||||||
|
--lang-matho: #b5700d;
|
||||||
|
--lang-pseudo: #2f5bea;
|
||||||
|
--lang-speco: #7a3fc4;
|
||||||
|
--lang-mojo: #e0592a;
|
||||||
|
--lang-asm: #5c6370;
|
||||||
|
}
|
||||||
|
body.quarto-dark .pplus-static,
|
||||||
|
[data-bs-theme="dark"] .pplus-static {
|
||||||
|
--accent: #8db0ff;
|
||||||
|
--accent-ink: #0f1626;
|
||||||
|
--accent-bg: #1f2b4a;
|
||||||
|
--marker: #f0c05a;
|
||||||
|
--marker-bg: #4a3c12;
|
||||||
|
--last-bg: #1f3350;
|
||||||
|
--ok: #5fd39a;
|
||||||
|
--ok-bg: #16331f;
|
||||||
|
--warn: #f0b860;
|
||||||
|
--warn-bg: #3a2c12;
|
||||||
|
--err: #ff8585;
|
||||||
|
--err-bg: #3f1b1b;
|
||||||
|
--shadow: 0 10px 30px rgba(0, 0, 0, .45);
|
||||||
|
--tok-keyword: #8db0ff;
|
||||||
|
--tok-builtin: #c9a7ff;
|
||||||
|
--tok-string: #f2b56b;
|
||||||
|
--tok-number: #5fd3c6;
|
||||||
|
--tok-comment: #8b93a1;
|
||||||
|
--tok-label: #f49ac2;
|
||||||
|
--brand-bg: #0e1117;
|
||||||
|
--brand-fg: #f0c05a;
|
||||||
|
--brand-edge: #2c333f;
|
||||||
|
--k-write: #8db0ff;
|
||||||
|
--k-decision: #f0b860;
|
||||||
|
--k-loop: #c9a7ff;
|
||||||
|
--k-call: #5fd3c6;
|
||||||
|
--k-return: #5fd39a;
|
||||||
|
--k-io: #f49ac2;
|
||||||
|
--k-life: #7c8594;
|
||||||
|
--k-error: #ff8585;
|
||||||
|
--k-other: #3b4452;
|
||||||
|
--lang-mojo: #ff8a5c;
|
||||||
|
--lang-asm: #a7afbc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .mono {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .muted {
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .small {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .hint {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--ink-2);
|
||||||
|
background: var(--paper-3);
|
||||||
|
border-left: 3px solid var(--accent);
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .math {
|
||||||
|
font-family: "STIX Two Math", "Cambria Math", var(--mono);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .badge {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 11.5px;
|
||||||
|
padding: 1px 8px;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-right: 6px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .badge-proved {
|
||||||
|
background: var(--ok-bg);
|
||||||
|
color: var(--ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .badge-broken {
|
||||||
|
background: var(--err-bg);
|
||||||
|
color: var(--err);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .badge-open {
|
||||||
|
background: var(--warn-bg);
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .spacer {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .badge {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .legend {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--ink-2);
|
||||||
|
position: relative;
|
||||||
|
align-self: center;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .legend summary {
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .legend[open] summary {
|
||||||
|
background: var(--paper-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .view {
|
||||||
|
padding: 10px 14px 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-keyword {
|
||||||
|
color: var(--tok-keyword);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-builtin {
|
||||||
|
color: var(--tok-builtin);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-string {
|
||||||
|
color: var(--tok-string);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-number {
|
||||||
|
color: var(--tok-number);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-comment {
|
||||||
|
color: var(--tok-comment);
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-label {
|
||||||
|
color: var(--tok-label);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-op {
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-error {
|
||||||
|
color: var(--err);
|
||||||
|
text-decoration: underline wavy;
|
||||||
|
text-decoration-skip-ink: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-punct {
|
||||||
|
color: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-convention {
|
||||||
|
color: var(--tok-keyword);
|
||||||
|
font-style: italic;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-transfer {
|
||||||
|
color: var(--accent);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tok-name {
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tbl {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tbl caption {
|
||||||
|
text-align: left;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--ink-2);
|
||||||
|
padding: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tbl th {
|
||||||
|
text-align: left;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--ink-2);
|
||||||
|
padding: 3px 6px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .tbl td {
|
||||||
|
padding: 3px 6px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problems,
|
||||||
|
.pplus-static .obligations,
|
||||||
|
.pplus-static .facts {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 14px auto 1fr auto auto;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: start;
|
||||||
|
padding: 7px 0;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem-sev {
|
||||||
|
font-size: 10px;
|
||||||
|
padding-top: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem-error .problem-sev {
|
||||||
|
color: var(--err);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem-warning .problem-sev {
|
||||||
|
color: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem-note .problem-sev {
|
||||||
|
color: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .problem-guide {
|
||||||
|
font-size: 12px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .proof-counts {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .proof-unit {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r);
|
||||||
|
padding: 6px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .proof-unit summary {
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .obligation {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto auto 1fr;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: baseline;
|
||||||
|
padding: 6px 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .ob-detail {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .ob-detail summary {
|
||||||
|
color: var(--ink-2);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .facts li {
|
||||||
|
padding: 1px 0 1px 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .goal {
|
||||||
|
padding: 2px 0 2px 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .perf-tbl {
|
||||||
|
max-width: 520px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .perf-tbl td:first-child {
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .bounds {
|
||||||
|
padding-left: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .viz-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .viz-title {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .viz-scroll {
|
||||||
|
overflow: auto;
|
||||||
|
max-width: 100%;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-lg);
|
||||||
|
background: var(--paper-2);
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-svg {
|
||||||
|
display: block;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-svg text {
|
||||||
|
fill: var(--ink);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-shape {
|
||||||
|
stroke: var(--ink-2);
|
||||||
|
stroke-width: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-term {
|
||||||
|
stroke-width: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-edge {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--ink-2);
|
||||||
|
stroke-width: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-back {
|
||||||
|
stroke-dasharray: 4 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-arrowhead {
|
||||||
|
fill: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-badge {
|
||||||
|
fill: var(--paper-3);
|
||||||
|
stroke: var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-badge-never {
|
||||||
|
fill: var(--warn-bg);
|
||||||
|
stroke: var(--warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-badge-text {
|
||||||
|
font-size: 10.5px;
|
||||||
|
fill: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-never .flow-shape {
|
||||||
|
stroke-dasharray: 3 3;
|
||||||
|
stroke: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-never text {
|
||||||
|
fill: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-edge-label {
|
||||||
|
font-size: 10.5px;
|
||||||
|
fill: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-edge-label-bg {
|
||||||
|
fill: var(--paper-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-node {
|
||||||
|
stroke: var(--ink-2);
|
||||||
|
stroke-width: 1.2;
|
||||||
|
fill: var(--paper-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-node-in {
|
||||||
|
fill: var(--accent-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-node-out {
|
||||||
|
fill: var(--ok-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-node-loop {
|
||||||
|
stroke-dasharray: 5 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-edge {
|
||||||
|
fill: none;
|
||||||
|
stroke: var(--ink-2);
|
||||||
|
stroke-width: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-edge-ctrl {
|
||||||
|
stroke-dasharray: 4 3;
|
||||||
|
stroke: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-type {
|
||||||
|
font-size: 10px;
|
||||||
|
fill: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-label {
|
||||||
|
font-size: 10px;
|
||||||
|
fill: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .df-label-bg {
|
||||||
|
fill: var(--paper-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-scroll {
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-tbl {
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 12px;
|
||||||
|
min-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-tbl th,
|
||||||
|
.pplus-static .vals-tbl td {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
padding: 3px 8px;
|
||||||
|
text-align: left;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-tbl thead th {
|
||||||
|
background: var(--paper-3);
|
||||||
|
color: var(--ink-2);
|
||||||
|
font-weight: 500;
|
||||||
|
text-align: center;
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-tbl thead tr:nth-child(2) th {
|
||||||
|
top: 25px;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-corner,
|
||||||
|
.pplus-static .vals-var {
|
||||||
|
position: sticky;
|
||||||
|
left: 0;
|
||||||
|
background: var(--paper-3);
|
||||||
|
z-index: 1;
|
||||||
|
text-align: left !important;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-tbl thead .vals-corner {
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-changed {
|
||||||
|
font-weight: 600;
|
||||||
|
background: var(--accent-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-same {
|
||||||
|
color: var(--ink-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-absent {
|
||||||
|
background: repeating-linear-gradient(45deg, transparent 0 4px, var(--paper-3) 4px 5px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-unset {
|
||||||
|
color: var(--ink-3);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .vals-out {
|
||||||
|
background: var(--ok-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .view-table .viz-scroll,
|
||||||
|
.pplus-static .view-flow .viz-scroll,
|
||||||
|
.pplus-static .view-data .viz-scroll {
|
||||||
|
max-height: calc(100vh - 220px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(120px, 18%) 1fr minmax(140px, 20%);
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-id {
|
||||||
|
color: var(--ink-3);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-lane {
|
||||||
|
position: relative;
|
||||||
|
height: 22px;
|
||||||
|
border-bottom: 1px dashed var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-bar {
|
||||||
|
position: absolute;
|
||||||
|
top: 7px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--accent);
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-bar-copied {
|
||||||
|
background: var(--tok-string);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-bar-moved {
|
||||||
|
background: var(--tok-number);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
margin-left: -7px;
|
||||||
|
padding: 0;
|
||||||
|
border: 2px solid var(--paper);
|
||||||
|
border-radius: 50%;
|
||||||
|
cursor: pointer;
|
||||||
|
background: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark.legend {
|
||||||
|
position: relative;
|
||||||
|
display: inline-block;
|
||||||
|
top: 3px;
|
||||||
|
margin: 0 2px 0 8px;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark-copied {
|
||||||
|
background: var(--tok-string);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark-moved {
|
||||||
|
background: var(--tok-number);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark-moved-out {
|
||||||
|
background: var(--ink-3);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark-named {
|
||||||
|
background: var(--paper);
|
||||||
|
border-color: var(--accent);
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
top: 6px;
|
||||||
|
margin-left: -5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-mark-destroyed {
|
||||||
|
background: var(--err);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-cursor {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
width: 2px;
|
||||||
|
margin-left: -1px;
|
||||||
|
background: var(--ink-2);
|
||||||
|
opacity: 0.5;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .life-legend {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .cost-by-line {
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .flow-node.flow-last .flow-shape {
|
||||||
|
stroke: var(--accent);
|
||||||
|
stroke-width: 2.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-unit {
|
||||||
|
border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px 10px; margin-bottom: 10px; background: var(--paper-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-unit > summary {
|
||||||
|
cursor: pointer; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-sig {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-unit h5 {
|
||||||
|
margin: 14px 0 6px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-checks {
|
||||||
|
margin: 0; padding-left: 0; list-style: none; font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-checks li {
|
||||||
|
padding-left: 1.4em; position: relative; margin: 2px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-checks li::before {
|
||||||
|
content: '✓'; position: absolute; left: 0; color: #2f8f5b; font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-gens td,
|
||||||
|
.pplus-static .fuzz-gens th {
|
||||||
|
font-size: 12.5px; vertical-align: top;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-strats {
|
||||||
|
margin: 6px 0 0; padding-left: 1.2em; font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-strats li {
|
||||||
|
margin: 2px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-fail {
|
||||||
|
border: 1px solid color-mix(in srgb, #c0392b 40%, var(--line)); border-left: 3px solid #c0392b; border-radius: 6px; padding: 8px 10px; margin: 6px 0; background: var(--paper);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-fail-head {
|
||||||
|
display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-msg {
|
||||||
|
margin: 6px 0; font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-shrink {
|
||||||
|
margin: 4px 0 0; padding-left: 1.6em; font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-shrink li {
|
||||||
|
margin: 1px 0; color: var(--ink-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-shrink-last {
|
||||||
|
color: var(--ink) !important; font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cov {
|
||||||
|
display: flex; flex-direction: column; gap: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cov-bar {
|
||||||
|
display: inline-block; height: 8px; background: var(--paper-3); border-radius: 4px; overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cov-bar > span {
|
||||||
|
display: block; height: 100%; background: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-results {
|
||||||
|
display: flex; flex-direction: column; gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-result {
|
||||||
|
display: grid; grid-template-columns: minmax(8ch, max-content) 120px 4em; gap: 8px; align-items: center; font-size: 12.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-filter {
|
||||||
|
display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cases-wrap {
|
||||||
|
max-height: 360px; overflow: auto; border: 1px solid var(--line); border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cases {
|
||||||
|
width: 100%; font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-cases thead th {
|
||||||
|
position: sticky; top: 0; background: var(--paper); z-index: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-out {
|
||||||
|
font-size: 11px; padding: 0 6px; border-radius: 999px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-out-pass {
|
||||||
|
color: #2f8f5b; background: color-mix(in srgb, #2f8f5b 12%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-out-fail {
|
||||||
|
color: #c0392b; background: color-mix(in srgb, #c0392b 12%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-out-skip {
|
||||||
|
color: var(--ink-2); background: var(--paper-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pplus-static .fuzz-new {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/* The Programming+ Quarto extension: the frames around every view, the rendered views' own parts (the run, the
|
||||||
|
stepper, the translations), and lingo highlighting. Attached to every page that uses a shortcode, after
|
||||||
|
pplus-views.css (the app's rules for what its views draw, generated). Colors come from the page (Bootstrap's
|
||||||
|
variables) and from the app's tokens, which pplus-views.css defines on .pplus-static. */
|
||||||
|
|
||||||
|
/* ---------- the live frame ---------- */
|
||||||
|
figure.pplus-embed,
|
||||||
|
.pplus-figure {
|
||||||
|
margin: 1.25rem 0 1.75rem;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--bs-body-color) 16%, transparent);
|
||||||
|
border-radius: 10px;
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--bs-body-bg);
|
||||||
|
}
|
||||||
|
figure.pplus-embed .pplus-frame {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
border: 0;
|
||||||
|
background: var(--bs-body-bg);
|
||||||
|
}
|
||||||
|
figure.pplus-embed figcaption,
|
||||||
|
.pplus-figure figcaption,
|
||||||
|
.pplus-under figcaption {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: .5rem;
|
||||||
|
align-items: center;
|
||||||
|
padding: .4rem .8rem;
|
||||||
|
font-size: .85rem;
|
||||||
|
color: var(--bs-secondary-color, #6c757d);
|
||||||
|
border-top: 1px solid color-mix(in srgb, var(--bs-body-color) 12%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--bs-body-bg) 97%, var(--bs-body-color));
|
||||||
|
}
|
||||||
|
.pplus-under figcaption { border: 0; background: none; padding: .1rem 0 0; }
|
||||||
|
.pplus-under { margin: -.75rem 0 1.5rem; }
|
||||||
|
figure .pplus-brand, .pplus-figure .pplus-brand, .pplus-under .pplus-brand { font-weight: 700; color: var(--bs-body-color); }
|
||||||
|
figure .pplus-caption, .pplus-figure .pplus-caption, .pplus-under .pplus-caption { color: var(--bs-body-color); }
|
||||||
|
figcaption a { text-decoration: none; }
|
||||||
|
figcaption a:hover { text-decoration: underline; }
|
||||||
|
.pplus-figcode { padding: .75rem .9rem 0; }
|
||||||
|
.pplus-figcode div.sourceCode, .pplus-figcode pre { margin: 0 0 .25rem; }
|
||||||
|
.pplus-figcode .math.display { display: block; margin: .25rem 0; }
|
||||||
|
.pplus-figtitle {
|
||||||
|
padding: .5rem .9rem;
|
||||||
|
font-weight: 600;
|
||||||
|
border-bottom: 1px solid color-mix(in srgb, var(--bs-body-color) 12%, transparent);
|
||||||
|
}
|
||||||
|
button.pplus-golive {
|
||||||
|
font: inherit;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--bs-link-color, #2f5bea);
|
||||||
|
background: none;
|
||||||
|
border: 1px solid currentColor;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0 .6rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button.pplus-golive:hover { background: color-mix(in srgb, var(--bs-link-color, #2f5bea) 10%, transparent); }
|
||||||
|
div.pplus-figure.is-live .pplus-frame { display: block; width: 100%; border: 0; }
|
||||||
|
|
||||||
|
details.pplus-details { margin: 1rem 0 1.5rem; border: 1px solid color-mix(in srgb, var(--bs-body-color) 18%, transparent); border-radius: 10px; padding: .4rem .9rem; }
|
||||||
|
details.pplus-details > summary { cursor: pointer; font-weight: 600; padding: .25rem 0; }
|
||||||
|
details.pplus-details[open] > summary { margin-bottom: .5rem; }
|
||||||
|
details.pplus-details figure, details.pplus-details .pplus-figure { margin-top: .5rem; }
|
||||||
|
a.pplus-link::before { content: "▸ "; }
|
||||||
|
|
||||||
|
/* ---------- a rendered view ---------- */
|
||||||
|
.pplus-static {
|
||||||
|
padding: .75rem .9rem;
|
||||||
|
font-size: .9rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--ink);
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.pplus-static p { margin: .4rem 0; }
|
||||||
|
.pplus-static pre { margin: 0; }
|
||||||
|
.pplus-static code { color: inherit; background: none; padding: 0; }
|
||||||
|
.pplus-static table { margin: 0; }
|
||||||
|
.pplus-static details > summary { cursor: pointer; }
|
||||||
|
.pplus-head { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; margin-bottom: .5rem; }
|
||||||
|
.pplus-spacer { flex: 1; }
|
||||||
|
.pplus-muted { color: var(--ink-3); }
|
||||||
|
.pplus-small { font-size: .82em; }
|
||||||
|
.pplus-who { font-size: .82em; }
|
||||||
|
.pplus-call { font-family: var(--mono); font-size: .88em; }
|
||||||
|
.pplus-chip {
|
||||||
|
display: inline-block;
|
||||||
|
font: 600 .72rem/1.6 var(--mono);
|
||||||
|
padding: 0 .45rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: var(--paper);
|
||||||
|
/* the language's color moved a quarter of the way toward the ink, so the label reads at 4.5:1 or more in both
|
||||||
|
themes (the green, orange and red of lingo, matho and Mojo are 3.3 to 3.7:1 under white text as they are) */
|
||||||
|
background: color-mix(in srgb, var(--chip, var(--lang-pseudo, #2f5bea)) 75%, var(--ink, #16191f));
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
.pplus-chip-lingo { --chip: var(--lang-lingo); }
|
||||||
|
.pplus-chip-matho { --chip: var(--lang-matho); }
|
||||||
|
.pplus-chip-pseudo { --chip: var(--lang-pseudo); }
|
||||||
|
.pplus-chip-speco { --chip: var(--lang-speco); }
|
||||||
|
.pplus-chip-mojo { --chip: var(--lang-mojo); }
|
||||||
|
.pplus-chip-asm { --chip: var(--lang-asm); }
|
||||||
|
.pplus-tag-generated {
|
||||||
|
display: inline-block;
|
||||||
|
font: 600 .7rem/1.6 var(--mono, monospace);
|
||||||
|
padding: 0 .4rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: var(--warn, #b5700d);
|
||||||
|
background: var(--warn-bg, #fdf0d6);
|
||||||
|
}
|
||||||
|
.pplus-out {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: .85rem;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
padding: .55rem .7rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--paper-2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
min-height: 2.2em;
|
||||||
|
}
|
||||||
|
.pplus-err { color: var(--err); font-size: .85rem; }
|
||||||
|
.pplus-note { color: var(--ink-2); font-size: .85rem; font-style: italic; }
|
||||||
|
.pplus-expect { margin-top: .5rem; font-size: .85rem; }
|
||||||
|
.pplus-expect.is-ok { color: var(--ok); }
|
||||||
|
.pplus-expect.is-bad { color: var(--err); }
|
||||||
|
.pplus-expect .pplus-out { margin-top: .3rem; color: var(--ink); }
|
||||||
|
.pplus-ref { font-family: var(--mono); color: var(--accent); margin-right: .35rem; }
|
||||||
|
.pplus-option { display: inline-block; font-size: .8rem; margin: .15rem .3rem 0 0; padding: 0 .4rem; border: 1px solid var(--line-2); border-radius: 4px; }
|
||||||
|
.pplus-picked { font-weight: 600; }
|
||||||
|
|
||||||
|
/* a listing, as the editor highlights it */
|
||||||
|
.pplus-code {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: .82rem;
|
||||||
|
line-height: 1.55;
|
||||||
|
padding: .5rem 0;
|
||||||
|
margin: 0;
|
||||||
|
background: var(--paper-2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 6px;
|
||||||
|
overflow-x: auto;
|
||||||
|
white-space: pre;
|
||||||
|
}
|
||||||
|
.pplus-ln { display: inline-block; min-width: 100%; padding: 0 .7rem 0 0; }
|
||||||
|
.pplus-lno { display: inline-block; width: 2.6em; padding-right: .8em; text-align: right; color: var(--ink-3); user-select: none; }
|
||||||
|
.pplus-code:not(:has(.pplus-lno)) .pplus-ln { padding-left: .7rem; }
|
||||||
|
.pplus-ln.is-last { background: var(--last-bg); }
|
||||||
|
.pplus-ln.is-next { background: var(--marker-bg); box-shadow: inset 3px 0 0 var(--marker); }
|
||||||
|
|
||||||
|
/* ---------- the stepper ---------- */
|
||||||
|
.pplus-steps-bar { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; margin-bottom: .6rem; }
|
||||||
|
.pplus-btn {
|
||||||
|
font: 600 .8rem/1 var(--sans, inherit);
|
||||||
|
min-width: 2rem;
|
||||||
|
padding: .35rem .5rem;
|
||||||
|
color: var(--ink);
|
||||||
|
background: var(--paper-2);
|
||||||
|
border: 1px solid var(--line-2);
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.pplus-btn:hover { border-color: var(--accent); }
|
||||||
|
.pplus-btn:disabled { opacity: .45; cursor: default; }
|
||||||
|
.pplus-steps-slider { flex: 1 1 10rem; min-width: 8rem; accent-color: var(--accent); }
|
||||||
|
.pplus-steps-count { font: .8rem var(--mono); color: var(--ink-2); min-width: 5.5em; text-align: right; }
|
||||||
|
.pplus-steps-body { display: grid; grid-template-columns: minmax(0, 3fr) minmax(14rem, 2fr); gap: .8rem; align-items: start; }
|
||||||
|
@media (max-width: 760px) { .pplus-steps-body { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
.pplus-steps-code .pplus-code { max-height: 30rem; overflow: auto; position: relative; }
|
||||||
|
.pplus-steps-now {
|
||||||
|
font-size: .85rem;
|
||||||
|
padding: .45rem .6rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--marker-bg);
|
||||||
|
margin-bottom: .6rem;
|
||||||
|
min-height: 2.6em;
|
||||||
|
}
|
||||||
|
.pplus-vars { width: 100%; border-collapse: collapse; font-size: .84rem; }
|
||||||
|
.pplus-vars th, .pplus-vars td { padding: .25rem .5rem; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }
|
||||||
|
.pplus-vars th { font: 600 .82rem var(--mono); color: var(--ink-2); width: 1%; white-space: nowrap; }
|
||||||
|
.pplus-vars td { font-family: var(--mono); word-break: break-word; }
|
||||||
|
.pplus-vars tr.is-wrote td { color: var(--k-write, var(--accent)); font-weight: 600; background: color-mix(in srgb, var(--k-write, #2f5bea) 10%, transparent); }
|
||||||
|
.pplus-steps-out-h { margin: .7rem 0 .25rem; font-size: .75rem; text-transform: uppercase; letter-spacing: .04em; color: var(--ink-3); }
|
||||||
|
.pplus-steps-out { max-height: 9rem; overflow: auto; }
|
||||||
|
|
||||||
|
/* ---------- the machine (pplus-hw): the board's cards over an x86-64 run ---------- */
|
||||||
|
.pplus-hw-now { font-size: .85rem; padding: .4rem .6rem; border-radius: 6px; background: var(--marker-bg); margin-bottom: .7rem; }
|
||||||
|
.pplus-hw-now .pplus-hw-machine { font-size: .8rem; }
|
||||||
|
.pplus-hw-body { display: grid; grid-template-columns: minmax(0, 1fr); gap: .75rem; align-items: start; }
|
||||||
|
.pplus-hw-body.has-listing { grid-template-columns: minmax(12rem, 17rem) minmax(0, 1fr); }
|
||||||
|
.pplus-hw-body > .pplus-hw-listing { position: sticky; top: 4.5rem; }
|
||||||
|
@media (max-width: 760px) { .pplus-hw-body.has-listing { grid-template-columns: minmax(0, 1fr); } .pplus-hw-body > .pplus-hw-listing { position: static; } }
|
||||||
|
/* the cards: side by side when there is room (a page-wide figure), one under another otherwise */
|
||||||
|
.pplus-hw-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 24rem), 1fr)); gap: .75rem; align-items: start; }
|
||||||
|
.pplus-hw-card { min-width: 0; }
|
||||||
|
.pplus-hw-card.is-wide { grid-column: 1 / -1; }
|
||||||
|
.pplus-hw-title { font-size: .75rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; color: var(--ink-3); margin: 0 0 .3rem; }
|
||||||
|
.pplus-hw-listing .pplus-code { max-height: 26rem; overflow: auto; position: relative; }
|
||||||
|
.pplus-static .board-a86.a86 { margin: 0; overflow-x: auto; }
|
||||||
|
.pplus-static .a86-panel { margin: 0; }
|
||||||
|
|
||||||
|
/* ---------- translations, as the app's panes ---------- */
|
||||||
|
.pplus-translate-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(17rem, 1fr)); gap: .75rem; }
|
||||||
|
.pplus-pane-head { display: flex; align-items: center; gap: .4rem; margin-bottom: .3rem; }
|
||||||
|
.pplus-tabs .pplus-tab-note { font-size: .82rem; color: var(--bs-secondary-color, #6c757d); margin-top: -.4rem; }
|
||||||
|
.pplus-columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: 1rem; margin: 1rem 0; }
|
||||||
|
.pplus-columns .pplus-col > p:first-child { margin-bottom: .3rem; }
|
||||||
|
|
||||||
|
/* the app's views, on a page: their panels are not boxed in by a workspace */
|
||||||
|
.pplus-static .viz-scroll { max-height: none; }
|
||||||
|
.pplus-static .viz-scroll { overflow: auto; }
|
||||||
|
.pplus-static .flow-svg { max-width: none; }
|
||||||
|
.pplus-static .viz-head { margin-bottom: .5rem; }
|
||||||
|
|
||||||
|
/* A small translation table: pseudo on the left, the language on the right. */
|
||||||
|
.translation-table table { width: 100%; }
|
||||||
|
.translation-table td:first-child, .translation-table th:first-child { white-space: nowrap; }
|
||||||
|
.translation-table code { white-space: pre; }
|
||||||
|
|
||||||
|
/* lingo: the controlled English of Programming+. The colors fall back to the same roles the
|
||||||
|
course's pseudo.css uses, so a site that has that stylesheet gets one family; any other site gets
|
||||||
|
the fallbacks. */
|
||||||
|
.sourceCode.lingo .cf { color: var(--pseudo-flow, #9a2f4e); font-weight: 700; }
|
||||||
|
.sourceCode.lingo .kw { color: var(--pseudo-decl, #2f5d8c); font-weight: 600; }
|
||||||
|
.sourceCode.lingo .dt { color: var(--pseudo-type, #1f6f63); }
|
||||||
|
.sourceCode.lingo .fu { color: var(--pseudo-decl, #2f5d8c); font-weight: 700; }
|
||||||
|
.sourceCode.lingo .va { color: var(--pseudo-builtin, #5a4a8c); }
|
||||||
|
.sourceCode.lingo .op { color: var(--pseudo-keyword, #4a5568); }
|
||||||
|
.sourceCode.lingo .st, .sourceCode.lingo .ch, .sourceCode.lingo .dv { color: var(--pseudo-lit, #2f6f3f); }
|
||||||
|
.sourceCode.lingo .co { color: var(--pseudo-comment, #6f7680); font-style: italic; }
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.pplus-steps-bar, button.pplus-golive { display: none; }
|
||||||
|
.pplus-steps-code .pplus-code { max-height: none; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
// pplus.js: the page side of the Programming+ shortcodes. No dependencies; safe to load twice.
|
||||||
|
//
|
||||||
|
// Steppers a rendered pplus-steps view carries its run as JSON (<script class="pplus-steps-data">); this
|
||||||
|
// moves through it: the line that runs next, the values after each step, what was printed.
|
||||||
|
// Machine a rendered pplus-hw board carries every step's drawing of each card (compressed); this shows them.
|
||||||
|
// Make it live a rendered view's "make it live" button puts the live view (an <iframe> of the app) in its place.
|
||||||
|
// Live frames two messages cross the iframe boundary and nothing else:
|
||||||
|
// pplus:height (frame -> page) height="auto" frames grow to fit what they show.
|
||||||
|
// pplus:theme (page -> frame) the frame follows the site's light/dark switch.
|
||||||
|
//
|
||||||
|
// The app's "With Quarto" gallery loads this same file and calls PPlus.wire(element) on what it draws.
|
||||||
|
(function () {
|
||||||
|
if (typeof window === 'undefined' || window.PPlus) return;
|
||||||
|
|
||||||
|
/* ---------- steppers ---------- */
|
||||||
|
|
||||||
|
function text(node, s) { node.textContent = s; }
|
||||||
|
|
||||||
|
function wireStepper(root) {
|
||||||
|
if (root.__pplus) return;
|
||||||
|
var holder = root.querySelector('script.pplus-steps-data');
|
||||||
|
if (!holder) return;
|
||||||
|
var data;
|
||||||
|
try { data = JSON.parse(holder.textContent); } catch (e) { return; }
|
||||||
|
root.__pplus = true;
|
||||||
|
var lines = root.querySelectorAll('.pplus-ln');
|
||||||
|
var byLine = {};
|
||||||
|
for (var i = 0; i < lines.length; i++) byLine[lines[i].getAttribute('data-line')] = lines[i];
|
||||||
|
var slider = root.querySelector('.pplus-steps-slider');
|
||||||
|
var count = root.querySelector('.pplus-steps-count');
|
||||||
|
var now = root.querySelector('.pplus-steps-now');
|
||||||
|
var out = root.querySelector('.pplus-steps-out');
|
||||||
|
var cells = root.querySelectorAll('.pplus-vars td[data-col]');
|
||||||
|
var rows = root.querySelectorAll('.pplus-vars tr');
|
||||||
|
var code = root.querySelector('.pplus-steps-code .pplus-code');
|
||||||
|
var buttons = root.querySelectorAll('[data-go]');
|
||||||
|
var t = Math.max(0, Math.min(data.t || 0, data.count));
|
||||||
|
var timer = null;
|
||||||
|
|
||||||
|
function mark(cls, line) {
|
||||||
|
var old = root.querySelectorAll('.pplus-ln.' + cls);
|
||||||
|
for (var k = 0; k < old.length; k++) old[k].classList.remove(cls);
|
||||||
|
var el = line != null ? byLine[String(line)] : null;
|
||||||
|
if (el) el.classList.add(cls);
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function show() {
|
||||||
|
var last = t > 0 ? data.rows[t - 1] : null;
|
||||||
|
var next = t < data.count ? data.rows[t] : null;
|
||||||
|
mark('is-last', last ? last.l : null);
|
||||||
|
var cur = mark('is-next', next ? next.l : null);
|
||||||
|
// keep the line in view inside the listing, without moving the page
|
||||||
|
if (cur && code) {
|
||||||
|
var top = cur.offsetTop, h = cur.offsetHeight;
|
||||||
|
if (top < code.scrollTop || top + h > code.scrollTop + code.clientHeight) code.scrollTop = Math.max(0, top - code.clientHeight / 3);
|
||||||
|
}
|
||||||
|
var vals = last ? last.c : data.c0;
|
||||||
|
var wrote = last ? last.cw : [];
|
||||||
|
for (var c = 0; c < cells.length; c++) {
|
||||||
|
var v = vals[c];
|
||||||
|
text(cells[c], v == null ? '—' : v);
|
||||||
|
rows[c] && rows[c].classList.toggle('is-wrote', wrote.indexOf(c) >= 0);
|
||||||
|
}
|
||||||
|
text(now, t === 0 ? (data.count ? 'Before the first step.' : 'The program takes no steps.')
|
||||||
|
: 'Step ' + t + ': ' + last.x + (last.w.length ? ' — writes ' + last.w.join(', ') : ''));
|
||||||
|
var printed = [];
|
||||||
|
for (var r = 0; r < t; r++) printed.push.apply(printed, data.rows[r].o);
|
||||||
|
if (out) { text(out, printed.join('\n')); out.scrollTop = out.scrollHeight; }
|
||||||
|
if (slider) slider.value = String(t);
|
||||||
|
if (count) text(count, t + ' / ' + data.count);
|
||||||
|
root.setAttribute('data-t', String(t));
|
||||||
|
for (var b = 0; b < buttons.length; b++) {
|
||||||
|
var go = buttons[b].getAttribute('data-go');
|
||||||
|
if (go === 'first' || go === 'back') buttons[b].disabled = t === 0;
|
||||||
|
if (go === 'next' || go === 'last') buttons[b].disabled = t >= data.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function goto(n) { t = Math.max(0, Math.min(n, data.count)); show(); }
|
||||||
|
function stop() { if (timer) { clearInterval(timer); timer = null; } var p = root.querySelector('[data-go="play"]'); if (p) text(p, 'Play'); }
|
||||||
|
function play() {
|
||||||
|
if (t >= data.count) t = 0;
|
||||||
|
var p = root.querySelector('[data-go="play"]');
|
||||||
|
if (p) text(p, 'Pause');
|
||||||
|
timer = setInterval(function () { if (t >= data.count) return stop(); goto(t + 1); }, 450);
|
||||||
|
}
|
||||||
|
for (var b = 0; b < buttons.length; b++) {
|
||||||
|
buttons[b].addEventListener('click', function (ev) {
|
||||||
|
var go = ev.currentTarget.getAttribute('data-go');
|
||||||
|
if (go !== 'play') stop();
|
||||||
|
if (go === 'first') goto(0);
|
||||||
|
else if (go === 'back') goto(t - 1);
|
||||||
|
else if (go === 'next') goto(t + 1);
|
||||||
|
else if (go === 'last') goto(data.count);
|
||||||
|
else if (go === 'play') { if (timer) stop(); else play(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (slider) slider.addEventListener('input', function () { stop(); goto(Number(slider.value)); });
|
||||||
|
root.setAttribute('tabindex', root.getAttribute('tabindex') || '0');
|
||||||
|
root.addEventListener('keydown', function (ev) {
|
||||||
|
if (ev.target && ev.target.tagName === 'INPUT') return;
|
||||||
|
if (ev.key === 'ArrowRight') { stop(); goto(t + 1); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'ArrowLeft') { stop(); goto(t - 1); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'Home') { stop(); goto(0); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'End') { stop(); goto(data.count); ev.preventDefault(); }
|
||||||
|
});
|
||||||
|
show();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the machine (pplus-hw) ---------- */
|
||||||
|
|
||||||
|
// A machine board's cards, drawn at render time at every step: each card's distinct drawings, and which one each
|
||||||
|
// step shows. Compressed by render.mjs (deflate, base64); the app's gallery hands them over as plain JSON.
|
||||||
|
function readHwData(holder) {
|
||||||
|
var text = holder.textContent || '';
|
||||||
|
if (holder.getAttribute('type') !== 'application/x-pplus-deflate') return Promise.resolve(JSON.parse(text));
|
||||||
|
if (typeof DecompressionStream === 'undefined') return Promise.reject(new Error('this browser cannot decompress the run'));
|
||||||
|
var bin = atob(text), bytes = new Uint8Array(bin.length);
|
||||||
|
for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||||
|
var stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'));
|
||||||
|
return new Response(stream).text().then(JSON.parse);
|
||||||
|
}
|
||||||
|
|
||||||
|
function wireHw(root) {
|
||||||
|
if (root.__pplus) return;
|
||||||
|
var holder = root.querySelector('script.pplus-hw-data');
|
||||||
|
if (!holder) return;
|
||||||
|
root.__pplus = true;
|
||||||
|
readHwData(holder).then(function (data) {
|
||||||
|
var lines = root.querySelectorAll('.pplus-hw-listing .pplus-ln');
|
||||||
|
var byLine = {};
|
||||||
|
for (var i = 0; i < lines.length; i++) byLine[lines[i].getAttribute('data-line')] = lines[i];
|
||||||
|
var hosts = {};
|
||||||
|
var cardEls = root.querySelectorAll('[data-hw]');
|
||||||
|
for (var c = 0; c < cardEls.length; c++) hosts[cardEls[c].getAttribute('data-hw')] = cardEls[c].querySelector('[data-hw-frame]');
|
||||||
|
var slider = root.querySelector('.pplus-steps-slider');
|
||||||
|
var count = root.querySelector('.pplus-steps-count');
|
||||||
|
var now = root.querySelector('.pplus-hw-now');
|
||||||
|
var nowText = now && now.firstChild && now.firstChild.nodeType === 3 ? now.firstChild : null;
|
||||||
|
var code = root.querySelector('.pplus-hw-listing .pplus-code');
|
||||||
|
var buttons = root.querySelectorAll('[data-go]');
|
||||||
|
var last = data.shown.length - 1;
|
||||||
|
var k = Math.max(0, data.shown.indexOf(data.t));
|
||||||
|
var shownFrame = {};
|
||||||
|
var timer = null;
|
||||||
|
function mark(cls, line) {
|
||||||
|
var old = root.querySelectorAll('.pplus-hw-listing .pplus-ln.' + cls);
|
||||||
|
for (var j = 0; j < old.length; j++) old[j].classList.remove(cls);
|
||||||
|
var e = line != null ? byLine[String(line)] : null;
|
||||||
|
if (e) e.classList.add(cls);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
function show() {
|
||||||
|
var t = data.shown[k], s = data.steps[k];
|
||||||
|
mark('is-last', s.l);
|
||||||
|
var cur = mark('is-next', s.n);
|
||||||
|
if (cur && code) {
|
||||||
|
var top = cur.offsetTop, h = cur.offsetHeight;
|
||||||
|
if (top < code.scrollTop || top + h > code.scrollTop + code.clientHeight) code.scrollTop = Math.max(0, top - code.clientHeight / 3);
|
||||||
|
}
|
||||||
|
for (var j = 0; j < data.cards.length; j++) {
|
||||||
|
var card = data.cards[j], host = hosts[card.id];
|
||||||
|
if (!host) continue;
|
||||||
|
var f = card.at[k];
|
||||||
|
if (shownFrame[card.id] === f) continue;
|
||||||
|
shownFrame[card.id] = f;
|
||||||
|
host.innerHTML = card.frames[f];
|
||||||
|
// a card keeps the tallest height it has reached, so the cards under it stay put while stepping
|
||||||
|
var hgt = host.offsetHeight;
|
||||||
|
if (hgt > (parseFloat(host.style.minHeight) || 0)) host.style.minHeight = hgt + 'px';
|
||||||
|
}
|
||||||
|
if (nowText) nowText.textContent = t === 0 ? 'Before the first instruction.' : 'Step ' + t + ': ' + s.x;
|
||||||
|
if (slider) slider.value = String(k);
|
||||||
|
if (count) text(count, t + ' / ' + data.count);
|
||||||
|
root.setAttribute('data-t', String(t));
|
||||||
|
for (var b = 0; b < buttons.length; b++) {
|
||||||
|
var go = buttons[b].getAttribute('data-go');
|
||||||
|
if (go === 'first' || go === 'back') buttons[b].disabled = k === 0;
|
||||||
|
if (go === 'next' || go === 'last') buttons[b].disabled = k >= last;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function goto(n) { k = Math.max(0, Math.min(n, last)); show(); }
|
||||||
|
function stop() { if (timer) { clearInterval(timer); timer = null; } var p = root.querySelector('[data-go="play"]'); if (p) text(p, 'Play'); }
|
||||||
|
function play() {
|
||||||
|
if (k >= last) k = 0;
|
||||||
|
var p = root.querySelector('[data-go="play"]');
|
||||||
|
if (p) text(p, 'Pause');
|
||||||
|
timer = setInterval(function () { if (k >= last) return stop(); goto(k + 1); }, 450);
|
||||||
|
}
|
||||||
|
for (var b = 0; b < buttons.length; b++) {
|
||||||
|
buttons[b].addEventListener('click', function (ev) {
|
||||||
|
var go = ev.currentTarget.getAttribute('data-go');
|
||||||
|
if (go !== 'play') stop();
|
||||||
|
if (go === 'first') goto(0);
|
||||||
|
else if (go === 'back') goto(k - 1);
|
||||||
|
else if (go === 'next') goto(k + 1);
|
||||||
|
else if (go === 'last') goto(last);
|
||||||
|
else if (go === 'play') { if (timer) stop(); else play(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (slider) slider.addEventListener('input', function () { stop(); goto(Number(slider.value)); });
|
||||||
|
root.setAttribute('tabindex', root.getAttribute('tabindex') || '0');
|
||||||
|
root.addEventListener('keydown', function (ev) {
|
||||||
|
if (ev.target && ev.target.tagName === 'INPUT') return;
|
||||||
|
if (ev.key === 'ArrowRight') { stop(); goto(k + 1); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'ArrowLeft') { stop(); goto(k - 1); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'Home') { stop(); goto(0); ev.preventDefault(); }
|
||||||
|
else if (ev.key === 'End') { stop(); goto(last); ev.preventDefault(); }
|
||||||
|
});
|
||||||
|
// the frame in the markup is the step the page opened on; mark it shown, and hold every card's height
|
||||||
|
for (var j = 0; j < data.cards.length; j++) shownFrame[data.cards[j].id] = data.cards[j].at[k];
|
||||||
|
show();
|
||||||
|
}).catch(function (e) {
|
||||||
|
var bar = root.querySelector('.pplus-steps-bar');
|
||||||
|
if (bar) bar.replaceWith(Object.assign(document.createElement('p'), { className: 'pplus-note', textContent: 'This page shows one step of the run: ' + e.message + '.' }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- make it live ---------- */
|
||||||
|
|
||||||
|
function wireLive(btn) {
|
||||||
|
if (btn.__pplus) return;
|
||||||
|
btn.__pplus = true;
|
||||||
|
btn.addEventListener('click', function () {
|
||||||
|
var fig = btn.closest('.pplus-figure');
|
||||||
|
if (!fig) return;
|
||||||
|
var frame = document.createElement('iframe');
|
||||||
|
frame.className = 'pplus-frame';
|
||||||
|
frame.src = btn.getAttribute('data-src');
|
||||||
|
frame.height = btn.getAttribute('data-height') || '520';
|
||||||
|
frame.title = 'Programming+';
|
||||||
|
frame.setAttribute('allow', 'clipboard-write');
|
||||||
|
var view = fig.querySelector('.pplus-static');
|
||||||
|
if (view) view.replaceWith(frame); else fig.insertBefore(frame, fig.firstChild);
|
||||||
|
var code = fig.querySelector('.pplus-figcode');
|
||||||
|
if (code) code.remove(); // the live view has the code in it
|
||||||
|
fig.classList.add('is-live');
|
||||||
|
btn.remove();
|
||||||
|
send(frame);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function wire(root) {
|
||||||
|
root = root || document;
|
||||||
|
var steppers = root.querySelectorAll ? root.querySelectorAll('.pplus-v-steps') : [];
|
||||||
|
for (var i = 0; i < steppers.length; i++) wireStepper(steppers[i]);
|
||||||
|
if (root.classList && root.classList.contains('pplus-v-steps')) wireStepper(root);
|
||||||
|
var boards = root.querySelectorAll ? root.querySelectorAll('.pplus-v-hw') : [];
|
||||||
|
for (var h = 0; h < boards.length; h++) wireHw(boards[h]);
|
||||||
|
if (root.classList && root.classList.contains('pplus-v-hw')) wireHw(root);
|
||||||
|
var live = root.querySelectorAll ? root.querySelectorAll('button.pplus-golive') : [];
|
||||||
|
for (var j = 0; j < live.length; j++) wireLive(live[j]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- live frames ---------- */
|
||||||
|
|
||||||
|
// Quarto marks the page quarto-dark or quarto-light (and moves between them when the reader uses
|
||||||
|
// the toggle). A site with a single theme has neither, and the frames keep their own default.
|
||||||
|
function siteTheme() {
|
||||||
|
var b = document.body, de = document.documentElement;
|
||||||
|
if (b.classList.contains('quarto-dark')) return 'dark';
|
||||||
|
if (b.classList.contains('quarto-light')) return 'light';
|
||||||
|
var bs = b.getAttribute('data-bs-theme') || de.getAttribute('data-bs-theme');
|
||||||
|
return bs === 'dark' || bs === 'light' ? bs : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(frame) {
|
||||||
|
var theme = siteTheme();
|
||||||
|
if (theme && frame.contentWindow) frame.contentWindow.postMessage({ type: 'pplus:theme', theme: theme }, '*');
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendAll() {
|
||||||
|
var frames = document.querySelectorAll('iframe.pplus-frame');
|
||||||
|
for (var i = 0; i < frames.length; i++) send(frames[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A frame says how tall it would like to be. Whatever a frame says, the page grows it to between 120px and
|
||||||
|
// MAX_FRAME px: the app never asks for more than a view's height, and a page should not let a frame (another
|
||||||
|
// site's, if a page points pplus-url elsewhere) make it miles long. Anything but a finite number is ignored.
|
||||||
|
var MAX_FRAME = 4000;
|
||||||
|
function frameHeight(h) {
|
||||||
|
if (typeof h !== 'number' || !isFinite(h)) return null;
|
||||||
|
return Math.min(MAX_FRAME, Math.max(120, Math.ceil(h) + 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('message', function (ev) {
|
||||||
|
var d = ev.data;
|
||||||
|
if (!d) return;
|
||||||
|
var frames = document.querySelectorAll('iframe.pplus-frame');
|
||||||
|
for (var i = 0; i < frames.length; i++) {
|
||||||
|
if (frames[i].contentWindow !== ev.source) continue;
|
||||||
|
if (d.type === 'pplus:height' && frames[i].hasAttribute('data-pplus-auto')) {
|
||||||
|
var h = frameHeight(d.height);
|
||||||
|
if (h !== null) frames[i].style.height = h + 'px';
|
||||||
|
} else if (d.type === 'pplus:ready') {
|
||||||
|
send(frames[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The toggle changes a class on <body> (or an attribute on <html>/<body>); tell every frame.
|
||||||
|
function start() {
|
||||||
|
var obs = new MutationObserver(sendAll);
|
||||||
|
obs.observe(document.body, { attributes: true, attributeFilter: ['class', 'data-bs-theme'] });
|
||||||
|
obs.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-bs-theme'] });
|
||||||
|
sendAll();
|
||||||
|
wire(document);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.PPlus = { wire: wire, frameHeight: frameHeight };
|
||||||
|
if (document.body) start(); else document.addEventListener('DOMContentLoaded', start);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,781 @@
|
|||||||
|
-- pplus.lua: the shortcodes of the Programming+ Quarto extension. See README.md beside _extensions/.
|
||||||
|
--
|
||||||
|
-- Two kinds of shortcode, over the same program files beside the page (count.pseudo, count.lingo, mean.tex,
|
||||||
|
-- spec.speco, demo.mojo, demo.asm):
|
||||||
|
--
|
||||||
|
-- Rendered with the page. The program runs while Quarto renders, through the app's own engines and views
|
||||||
|
-- (render.mjs, with a built Programming+), and the result is part of the page: no iframe, no network, and it
|
||||||
|
-- prints. A run that does not print its EXPECT lines is reported as the page renders.
|
||||||
|
-- pplus-run what it prints and returns, checked against its EXPECT lines
|
||||||
|
-- pplus-steps the listing with a stepper: every step, its line, the values after it
|
||||||
|
-- pplus-table the table of values
|
||||||
|
-- pplus-flow the flowchart, shaded by how often each line ran
|
||||||
|
-- pplus-dataflow the data-flow graph
|
||||||
|
-- pplus-lifetimes each Mojo value made, copied, moved and destroyed
|
||||||
|
-- pplus-proof every claim of the specification: proved, broken or open
|
||||||
|
-- pplus-tests the fuzzer's report, every routine
|
||||||
|
-- pplus-check what the checker says about each file
|
||||||
|
-- pplus-translate the procedure in every notation, Mojo generated from the pseudo
|
||||||
|
-- pplus-machine the x86-64 run on the model machine: cycles, misses, branches
|
||||||
|
-- pplus-view any of these by name: view="flow"
|
||||||
|
--
|
||||||
|
-- The machine, rendered with the page: the Hardware area's board over an x86-64 file (asm=, setup=), the course's
|
||||||
|
-- own views drawn at every step of the run, with a stepper that moves through them.
|
||||||
|
-- pplus-hw the board: preset="regs" (default) | "caches" | "pipeline" | "chip", or views="registers,cache"
|
||||||
|
-- pplus-hw-<view> one view: code, explain, registers, flags, address, memory, stack, dataflow, alu, branches,
|
||||||
|
-- vectors, lines (cache lines), cache, hierarchy, paging (virtual memory, switched on), pipeline,
|
||||||
|
-- uops, timeline, bottleneck, counters, chip (the whole core), core (out of order), encoding
|
||||||
|
--
|
||||||
|
-- Live. An <iframe> of the app (pplus.scient.ing by default), with the program in its URL: the reader edits,
|
||||||
|
-- steps and runs it on the page.
|
||||||
|
-- pplus-playground the whole playground
|
||||||
|
-- pplus-embed one view of it: view="trace" (and every view= of the original {{< pplus >}})
|
||||||
|
-- pplus the original shortcode: a live embed, a listing, or both (show=)
|
||||||
|
--
|
||||||
|
-- And plain:
|
||||||
|
-- pplus-listing the files as highlighted listings (matho typeset as equations)
|
||||||
|
-- pplus-tabs the files as a tabset, one tab per notation
|
||||||
|
-- pplus-link a link that opens the program in the app
|
||||||
|
--
|
||||||
|
-- Every rendered view also takes live="click": a button under it puts the live view in its place.
|
||||||
|
--
|
||||||
|
-- Options shared by all
|
||||||
|
-- lingo, matho, pseudo, speco, mojo, asm files next to the page whose text fills that pane
|
||||||
|
-- setup a file next to the page holding the x86-64 pane's setup block (registers, memory)
|
||||||
|
-- lang the pane that runs (default: the first of lingo, matho, pseudo, mojo, asm given)
|
||||||
|
-- call the call to run (default: the file's own `// CALL:` line, else the engine's choice)
|
||||||
|
-- input lines INPUT reads, separated by | (default: the file's `// INPUT:` lines)
|
||||||
|
-- machine the x86-64 machine model preset
|
||||||
|
-- t the step the stepper starts on (or is parked at, live)
|
||||||
|
-- title a title over the view (and the iframe's title, for accessibility)
|
||||||
|
-- caption a sentence under the view, before the Programming+ links
|
||||||
|
-- collapse 1 folds it into a <details> block titled with `title` (or "Show the program")
|
||||||
|
-- area bridge (default), dev or hw: the area the "open in Programming+" link (and the live playground) opens in
|
||||||
|
--
|
||||||
|
-- Options of the rendered views
|
||||||
|
-- code 1 prints the program's listing above the view (run, table, flow, dataflow, proof, tests)
|
||||||
|
-- numbers 1 numbers the lines of a listing
|
||||||
|
-- follow steps, table: the variables to show, comma-separated (default: those of the routine that does the most work)
|
||||||
|
-- max steps: the most steps kept (default 400)
|
||||||
|
-- to translate: the notations to show, comma-separated (lingo,matho,pseudo,speco,mojo)
|
||||||
|
-- layout translate: tabs (default) | columns | grid (the app's own panes side by side)
|
||||||
|
-- compiler run, for a Mojo file: auto (default: the real `mojo` when one is on the PATH) | on (it must be) | off
|
||||||
|
-- preset, views pplus-hw: the board's arrangement, or the views (comma-separated) to show
|
||||||
|
-- listing pplus-hw: 0 leaves out the x86-64 listing beside the cards
|
||||||
|
-- column body | page | screen | ...: Quarto's column for the figure (pplus-hw's board is page-wide by default)
|
||||||
|
-- stepper pplus-hw: 0 draws only step t (no stepper); max: the most steps drawn (a longer run is sampled)
|
||||||
|
-- live click: a button that puts the live view in place of the rendered one
|
||||||
|
-- height the live frame's height in px when live="click" is pressed (default 520)
|
||||||
|
--
|
||||||
|
-- Options of the live views: see `live_embed` below (view, panel, build, dock, docktab, editor, side, dockheight,
|
||||||
|
-- theme, ro, showcall, split, height, mode, text, show, state, problem).
|
||||||
|
--
|
||||||
|
-- Project metadata (_quarto.yml or the page's front matter)
|
||||||
|
-- pplus-url where the live views point (default https://pplus.scient.ing)
|
||||||
|
-- pplus-engine a built Programming+ (its folder, or its dist/) for the rendered views; see README.md for where it is
|
||||||
|
-- looked for. none: render nothing with the page (each rendered view shows its listing and the live view)
|
||||||
|
-- pplus-node the node to run it with (default: node on the PATH)
|
||||||
|
-- pplus-strict true: a view that cannot be rendered, or a run that does not print its EXPECT lines (a program with EXPECT lines that does not run at all among them), stops the render
|
||||||
|
-- pplus-cache false: render every view again each time (by default results are kept in .quarto/pplus/)
|
||||||
|
|
||||||
|
local str = pandoc.utils.stringify
|
||||||
|
|
||||||
|
local function esc(s)
|
||||||
|
s = tostring(s or "")
|
||||||
|
s = s:gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """)
|
||||||
|
return s
|
||||||
|
end
|
||||||
|
|
||||||
|
local function warn(msg) io.stderr:write("pplus: " .. msg .. "\n") end
|
||||||
|
|
||||||
|
local function raw(html) return pandoc.RawBlock("html", html) end
|
||||||
|
|
||||||
|
local function is_html() return quarto.doc.is_format("html") end
|
||||||
|
|
||||||
|
-- A shortcode argument cannot hold a literal double quote inside double quotes, so " stands for one.
|
||||||
|
local function kwarg(kwargs, name)
|
||||||
|
local v = kwargs[name]
|
||||||
|
if v == nil then return nil end
|
||||||
|
local s = str(v):gsub(""", '"')
|
||||||
|
return s ~= "" and s or nil
|
||||||
|
end
|
||||||
|
|
||||||
|
local function meta_str(meta, name)
|
||||||
|
local v = meta and meta[name]
|
||||||
|
if v == nil then return nil end
|
||||||
|
local s = str(v)
|
||||||
|
return s ~= "" and s or nil
|
||||||
|
end
|
||||||
|
|
||||||
|
local function meta_bool(meta, name, default)
|
||||||
|
local v = meta and meta[name]
|
||||||
|
if v == nil then return default end
|
||||||
|
if type(v) == "boolean" then return v end
|
||||||
|
local s = str(v)
|
||||||
|
if s == "true" or s == "1" or s == "yes" then return true end
|
||||||
|
if s == "false" or s == "0" or s == "no" then return false end
|
||||||
|
return default
|
||||||
|
end
|
||||||
|
|
||||||
|
-- Absolute path of the file being rendered, with forward slashes.
|
||||||
|
local function input_path()
|
||||||
|
local f = quarto and quarto.doc and quarto.doc.input_file or ""
|
||||||
|
return (tostring(f):gsub("\\", "/"))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function page_dir() return input_path():match("^(.*)/[^/]*$") or "." end
|
||||||
|
|
||||||
|
-- This file's folder: the extension, where render.mjs and the stylesheets are.
|
||||||
|
local EXT_DIR = (function()
|
||||||
|
local src = debug.getinfo(1, "S").source or ""
|
||||||
|
src = src:gsub("^@", ""):gsub("\\", "/")
|
||||||
|
return src:match("^(.*)/[^/]*$") or "."
|
||||||
|
end)()
|
||||||
|
|
||||||
|
local function exists(path)
|
||||||
|
local f = io.open(path, "r")
|
||||||
|
if f then f:close() return true end
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The extension's stylesheets and script, attached once per page that uses a shortcode.
|
||||||
|
local deps_added = false
|
||||||
|
local function ensure_deps()
|
||||||
|
if deps_added or not is_html() then return end
|
||||||
|
deps_added = true
|
||||||
|
quarto.doc.add_html_dependency({ name = "pplus", version = "2.1.0", stylesheets = { "pplus-views.css", "pplus.css" }, scripts = { "pplus.js" } })
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The machine views' stylesheets: the course's own (course/, written for Quarto pages) and the board's adjustments
|
||||||
|
-- to them; attached only to a page that shows the machine.
|
||||||
|
local hw_deps_added = false
|
||||||
|
local function ensure_hw_deps()
|
||||||
|
if hw_deps_added or not is_html() then return end
|
||||||
|
hw_deps_added = true
|
||||||
|
quarto.doc.add_html_dependency({ name = "pplus-hw", version = "2.1.0", stylesheets = { "course/tokens.css", "course/kit.css", "course/asm86.css", "pplus-hw.css" } })
|
||||||
|
end
|
||||||
|
|
||||||
|
local PPLUS_DEFAULT_URL = "https://pplus.scient.ing"
|
||||||
|
|
||||||
|
local function pplus_url(meta)
|
||||||
|
return ((meta_str(meta, "pplus-url") or PPLUS_DEFAULT_URL):gsub("/+$", ""))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function read_beside_page(name)
|
||||||
|
local f = io.open(page_dir() .. "/" .. name, "r")
|
||||||
|
if not f then return nil end
|
||||||
|
local s = f:read("a"); f:close()
|
||||||
|
return (s:gsub("\n+$", ""))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function base64url(s)
|
||||||
|
local b = quarto.base64.encode(s)
|
||||||
|
return (b:gsub("%+", "-"):gsub("/", "_"):gsub("=+$", ""))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function json_encode(v) return quarto.json.encode(v) end
|
||||||
|
local function json_decode(s)
|
||||||
|
if quarto.json and quarto.json.decode then return quarto.json.decode(s) end
|
||||||
|
return pandoc.json.decode(s, false)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The call and input lines a program file carries for scripts/check-pages.mjs (// CALL: ..., // INPUT: ...),
|
||||||
|
-- so the embed runs exactly what the checker verified.
|
||||||
|
local function header_of(text)
|
||||||
|
local h = { input = {} }
|
||||||
|
for line in (text .. "\n"):gmatch("(.-)\n") do
|
||||||
|
local call = line:match("^%s*//%s*CALL:%s*(.-)%s*$") or line:match("^%s*%%%s*CALL:%s*(.-)%s*$") or line:match("^%s*#%s*CALL:%s*(.-)%s*$")
|
||||||
|
if call then h.call = call end
|
||||||
|
local inp = line:match("^%s*//%s*INPUT:%s?(.*)$") or line:match("^%s*%%%s*INPUT:%s?(.*)$") or line:match("^%s*#%s*INPUT:%s?(.*)$")
|
||||||
|
if inp then h.input[#h.input + 1] = inp end
|
||||||
|
end
|
||||||
|
return h
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The file as a page shows it: the checker's header lines (// CALL:, // EXPECT:, ...) removed. A Mojo
|
||||||
|
-- file's header is its leading block of `# key: value` comments (mojo/local/'s origin, probe, mode, args,
|
||||||
|
-- expect...; check-pages' EXPECT), so only that block goes: a `# note:` further down is the program's.
|
||||||
|
-- (src/quarto/program.ts listingText does the same for the rendered views; tests/quarto.test.mjs holds them together.)
|
||||||
|
local function listing_text(text, pane)
|
||||||
|
local out = {}
|
||||||
|
local head = pane == "mojo"
|
||||||
|
for line in (text .. "\n"):gmatch("(.-)\n") do
|
||||||
|
if head then
|
||||||
|
if line:match("^#%s*[%w%-]+:") then goto continue end
|
||||||
|
if line:match("^%s*$") and #out == 0 then goto continue end
|
||||||
|
head = false
|
||||||
|
end
|
||||||
|
if pane ~= "mojo" and (line:match("^%s*//%s*[A-Z]+:") or line:match("^%s*%%%s*[A-Z]+:")) then goto continue end
|
||||||
|
out[#out + 1] = line
|
||||||
|
::continue::
|
||||||
|
end
|
||||||
|
local s = table.concat(out, "\n")
|
||||||
|
return (s:gsub("^\n+", ""):gsub("\n+$", ""))
|
||||||
|
end
|
||||||
|
|
||||||
|
-- A LaTeX file as display mathematics: one block per equation, where an equation continues while a
|
||||||
|
-- brace or \begin{cases} is open or the next line starts with an operator.
|
||||||
|
local function math_blocks(text)
|
||||||
|
local eqs, cur, depth, cases = {}, nil, 0, 0
|
||||||
|
local function flush() if cur and cur:match("%S") then eqs[#eqs + 1] = cur end cur = nil end
|
||||||
|
for raw_line in (text .. "\n"):gmatch("(.-)\n") do
|
||||||
|
local line = raw_line:gsub("%%.*$", "")
|
||||||
|
if not line:match("%S") then
|
||||||
|
if depth <= 0 and cases <= 0 then flush() end
|
||||||
|
else
|
||||||
|
local continues = depth > 0 or cases > 0 or line:match("^%s*[=+%-&]") or line:match("^%s*\\cdot") or (cur and cur:match("[=+%-{]%s*$"))
|
||||||
|
if not continues then flush() end
|
||||||
|
cur = cur and (cur .. "\n" .. line) or line
|
||||||
|
for ch in line:gmatch("[{}]") do depth = depth + (ch == "{" and 1 or -1) end
|
||||||
|
for _ in line:gmatch("\\begin{cases}") do cases = cases + 1 end
|
||||||
|
for _ in line:gmatch("\\end{cases}") do cases = cases - 1 end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
flush()
|
||||||
|
local blocks = pandoc.Blocks({})
|
||||||
|
for _, eq in ipairs(eqs) do
|
||||||
|
blocks:insert(pandoc.Para({ pandoc.Math("DisplayMath", (eq:gsub("%s*\\\\%s*$", ""))) }))
|
||||||
|
end
|
||||||
|
return blocks
|
||||||
|
end
|
||||||
|
|
||||||
|
local function split_on(s, sep)
|
||||||
|
local out = {}
|
||||||
|
for piece in (s .. sep):gmatch("(.-)" .. sep:gsub("%p", "%%%0")) do out[#out + 1] = piece end
|
||||||
|
return out
|
||||||
|
end
|
||||||
|
local function split_bar(s) return split_on(s, "|") end
|
||||||
|
local function split_list(s)
|
||||||
|
local out = {}
|
||||||
|
for piece in s:gmatch("[^,%s]+") do out[#out + 1] = piece end
|
||||||
|
return out
|
||||||
|
end
|
||||||
|
|
||||||
|
local PANES = { "lingo", "matho", "pseudo", "speco", "mojo", "asm" }
|
||||||
|
local PANE_LABEL = { lingo = "lingo", matho = "matho", pseudo = "pseudo", speco = "speco", mojo = "Mojo", asm = "x86-64" }
|
||||||
|
local function set_of(list) local t = {} for _, k in ipairs(list) do t[k] = true end return t end
|
||||||
|
-- what view= can show (src/core/state.ts EMBED_VIEWS) and what the state's own view (the open tab) can be
|
||||||
|
local VIEWS = set_of({ "playground", "trace", "table", "flow", "data", "life", "problems", "proof", "tests", "compiler", "asm", "lingo", "matho", "pseudo", "speco", "mojo" })
|
||||||
|
local TABS = set_of({ "trace", "table", "flow", "data", "life", "problems", "proof", "tests", "compiler", "asm" })
|
||||||
|
local DOCK_TABS = set_of({ "setup", "output", "problems", "compiler", "asm" })
|
||||||
|
-- the options that arrange the example; the app reads them from the embed's query (applyEmbedParams)
|
||||||
|
local ARRANGE = { "area", "lang", "panel", "build", "machine", "dock", "docktab", "editor", "side", "dockheight", "theme" }
|
||||||
|
-- the rendered views (src/quarto/render.ts STATIC_VIEWS), and the live view each one opens as
|
||||||
|
local STATIC = { run = "trace", steps = "trace", table = "table", flow = "flow", data = "data", life = "life", proof = "proof", tests = "tests", check = "problems", translate = "playground", machine = "asm", hw = "playground" }
|
||||||
|
-- the machine's views, as pplus-hw-<name> names them (src/quarto/machine.ts HW_NAMES)
|
||||||
|
local HW_VIEWS = { "code", "explain", "registers", "flags", "address", "memory", "stack", "dataflow", "alu", "branches", "vectors",
|
||||||
|
"lines", "cache", "hierarchy", "paging", "pipeline", "uops", "timeline", "bottleneck", "counters", "chip", "core", "encoding" }
|
||||||
|
|
||||||
|
local function urlencode(v)
|
||||||
|
return (tostring(v):gsub("[^%w%-%._~,]", function(c) return string.format("%%%02X", string.byte(c)) end))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function fraction(v)
|
||||||
|
local n = tonumber(v)
|
||||||
|
return (n and n > 0 and n < 1) and n or nil
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The program files the shortcode names, read from beside the page: { pane = text } in pane order, the panes given,
|
||||||
|
-- and the name of a file that could not be read.
|
||||||
|
local function read_files(kwargs)
|
||||||
|
local files, given = {}, {}
|
||||||
|
for _, pane in ipairs(PANES) do
|
||||||
|
local file = kwarg(kwargs, pane)
|
||||||
|
if file then
|
||||||
|
local text = read_beside_page(file)
|
||||||
|
if not text then return nil, nil, file end
|
||||||
|
files[pane] = text
|
||||||
|
given[#given + 1] = pane
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return files, given, nil
|
||||||
|
end
|
||||||
|
|
||||||
|
local function missing(file)
|
||||||
|
warn("cannot read " .. file .. " next to " .. input_path())
|
||||||
|
return pandoc.Blocks({ pandoc.Para({ pandoc.Str("[pplus: missing file " .. file .. "]") }) })
|
||||||
|
end
|
||||||
|
|
||||||
|
local function wrap_collapse(kwargs, blocks)
|
||||||
|
if kwarg(kwargs, "collapse") ~= "1" or not is_html() then return blocks end
|
||||||
|
local out = pandoc.Blocks({ raw('<details class="pplus-details"><summary>' .. esc(kwarg(kwargs, "title") or "Show the program") .. '</summary>') })
|
||||||
|
out:extend(blocks)
|
||||||
|
out:insert(raw('</details>'))
|
||||||
|
return out
|
||||||
|
end
|
||||||
|
|
||||||
|
-- One file as a listing: a highlighted code block, or (matho) its equations typeset.
|
||||||
|
local function listing_blocks(pane, text, kwargs)
|
||||||
|
local shown = listing_text(text, pane)
|
||||||
|
if pane == "matho" and kwarg(kwargs, "math") ~= "0" then return math_blocks(shown) end
|
||||||
|
local attr = kwarg(kwargs, "numbers") == "1" and { ["code-line-numbers"] = "true" } or {}
|
||||||
|
-- matho is written in LaTeX: give its listing the class pandoc highlights as LaTeX
|
||||||
|
return pandoc.Blocks({ pandoc.CodeBlock(shown, pandoc.Attr("", { pane == "matho" and "latex" or pane }, attr)) })
|
||||||
|
end
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
-- Live: the app in an <iframe>
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- {{< pplus pseudo="count-base.pseudo" >}}
|
||||||
|
-- {{< pplus lingo="count-base.lingo" pseudo="count-base.pseudo" lang="lingo" view="trace" t=7 >}}
|
||||||
|
-- {{< pplus problem="count-base" view="trace" >}}
|
||||||
|
-- {{< pplus pseudo="x.pseudo" mode="link" text="Open it in the playground" >}}
|
||||||
|
-- {{< pplus mojo="demo.mojo" asm="demo.asm" setup="demo.setup" view="playground" area="hw" >}}
|
||||||
|
-- {{< pplus problem="demo" view="playground" panel="compiler" build="default" >}}
|
||||||
|
-- {{< pplus state="<blob from Share>" view="playground" >}}
|
||||||
|
--
|
||||||
|
-- Options (beside the shared ones at the top of this file)
|
||||||
|
-- problem a catalog problem id instead of files (its embed URL is #/embed/<view>/p/<id>)
|
||||||
|
-- state a state from the playground's Share dialog (the part of the link after #/<area>/s/): the
|
||||||
|
-- example exactly as it was arranged there, panes, layout, build and step included.
|
||||||
|
-- Share also writes this shortcode for you. (Pane files cannot be combined with it.)
|
||||||
|
-- view playground | trace | table | flow | data | life | problems | proof | tests | compiler | asm,
|
||||||
|
-- or a pane name to show just that editor (default trace). playground is the whole
|
||||||
|
-- playground in the frame: every pane, the stepper, the variables, every inspect tab and
|
||||||
|
-- the dock, arranged by the options below.
|
||||||
|
-- panel the tab the playground opens on: trace table flow data life proof tests (beside the
|
||||||
|
-- editor) or output problems compiler asm setup (the dock)
|
||||||
|
-- build O0 (as written, every function kept; the default) | default (as `mojo build` does)
|
||||||
|
-- dock open | closed: the dock under the editors; docktab picks its tab
|
||||||
|
-- editor 0.25-0.8: the editor column's share of the width
|
||||||
|
-- side the variables panel's share of the right column
|
||||||
|
-- dockheight 0.3-0.9: the editors' share of the height above the dock
|
||||||
|
-- theme light | dark (default: follow the page's own switch)
|
||||||
|
-- ro 1 makes the embedded editors read-only (and the frame keeps no save)
|
||||||
|
-- showcall 0 hides the run box above a flow, data or table view
|
||||||
|
-- height iframe height in px (default 520, or 720 for view="playground"), or auto: the frame
|
||||||
|
-- grows to fit its content (not for the playground, which fills its frame)
|
||||||
|
-- split the share of a fixed-height frame the code takes above the panel (default 0.7)
|
||||||
|
-- mode embed (default) | link: only a link to the full playground
|
||||||
|
-- text the link text (mode=link)
|
||||||
|
-- show embed (default) | listing | both: the file(s) as listings, the embed, or the listings then the embed
|
||||||
|
--
|
||||||
|
-- The state travels in the URL as `~` + base64url(JSON), which the app reads without decompression,
|
||||||
|
-- so no script of the app runs on this site: the page holds a plain <iframe>. In non-HTML output the
|
||||||
|
-- embed becomes a link.
|
||||||
|
|
||||||
|
-- Where the example opens: { embed = the iframe's src, open = the app link }, or nil and blocks to show instead.
|
||||||
|
local function live_target(kwargs, meta, view, listings, default_area)
|
||||||
|
local base = pplus_url(meta)
|
||||||
|
local playground = view == "playground"
|
||||||
|
local area = kwarg(kwargs, "area") or default_area or "bridge"
|
||||||
|
if area ~= "bridge" and area ~= "dev" and area ~= "hw" then
|
||||||
|
warn("unknown area=\"" .. area .. "\" (use bridge, dev or hw); using bridge")
|
||||||
|
area = "bridge"
|
||||||
|
end
|
||||||
|
local height = kwarg(kwargs, "height")
|
||||||
|
local query = {}
|
||||||
|
local function q_add(k, v) query[#query + 1] = k .. "=" .. urlencode(v) end
|
||||||
|
for _, k in ipairs({ "t", "ro", "showcall", "split" }) do
|
||||||
|
if kwarg(kwargs, k) then q_add(k, kwarg(kwargs, k)) end
|
||||||
|
end
|
||||||
|
for _, k in ipairs(ARRANGE) do
|
||||||
|
local v = kwarg(kwargs, k)
|
||||||
|
if v then q_add(k, v) end
|
||||||
|
end
|
||||||
|
-- a view of the machine opens in the Hardware area unless the page says otherwise
|
||||||
|
if default_area and not kwarg(kwargs, "area") then q_add("area", default_area) end
|
||||||
|
if height == "auto" and not playground then query[#query + 1] = "autosize=1" end
|
||||||
|
local q = #query > 0 and ("?" .. table.concat(query, "&")) or ""
|
||||||
|
|
||||||
|
local problem = kwarg(kwargs, "problem")
|
||||||
|
local given_state = kwarg(kwargs, "state")
|
||||||
|
if given_state then
|
||||||
|
-- a state made in the playground: Share -> Quarto writes this shortcode; the blob is opaque here
|
||||||
|
local blob = given_state:gsub("^.*#/%a+/s/", ""):gsub("^.*#/embed/[^/]+/", ""):gsub("%?.*$", "")
|
||||||
|
for _, pane in ipairs(PANES) do
|
||||||
|
if kwarg(kwargs, pane) then warn("state= already holds every pane; " .. pane .. "= is ignored (drop state= to build the example from files)") end
|
||||||
|
end
|
||||||
|
return { embed = base .. "/#/embed/" .. view .. "/" .. blob .. q, open = base .. "/#/" .. area .. "/s/" .. blob }
|
||||||
|
elseif problem then
|
||||||
|
local embed = base .. "/#/embed/" .. view .. "/p/" .. problem .. q
|
||||||
|
-- the arranged example, whole, in a tab of its own
|
||||||
|
return { embed = embed, open = playground and embed or (base .. "/#/" .. area .. "/p/" .. problem) }
|
||||||
|
end
|
||||||
|
|
||||||
|
local files, given, bad = read_files(kwargs)
|
||||||
|
if bad then return nil, missing(bad) end
|
||||||
|
if #given == 0 then
|
||||||
|
warn("give at least one of lingo=, matho=, pseudo=, speco=, mojo=, asm=, or problem= or state=")
|
||||||
|
return nil, pandoc.Blocks({})
|
||||||
|
end
|
||||||
|
local sources, file_call, file_input = {}, nil, nil
|
||||||
|
for _, pane in ipairs(given) do
|
||||||
|
local text = files[pane]
|
||||||
|
sources[pane] = listing_text(text, pane)
|
||||||
|
local h = header_of(text)
|
||||||
|
file_call = file_call or h.call
|
||||||
|
if #h.input > 0 and not file_input then file_input = table.concat(h.input, "\n") end
|
||||||
|
if listings then listings:extend(listing_blocks(pane, text, kwargs)) end
|
||||||
|
end
|
||||||
|
local panel = kwarg(kwargs, "panel")
|
||||||
|
local state = {
|
||||||
|
v = 3,
|
||||||
|
sources = sources,
|
||||||
|
lang = kwarg(kwargs, "lang") or given[1],
|
||||||
|
view = (TABS[panel or ""] and panel) or (TABS[view] and view) or "trace",
|
||||||
|
}
|
||||||
|
local setup_file = kwarg(kwargs, "setup")
|
||||||
|
if setup_file then
|
||||||
|
local text = read_beside_page(setup_file)
|
||||||
|
if text then state.setup = text else warn("cannot read " .. setup_file .. " next to " .. input_path()) end
|
||||||
|
end
|
||||||
|
if kwarg(kwargs, "build") == "O0" or kwarg(kwargs, "build") == "default" then state.build = kwarg(kwargs, "build") end
|
||||||
|
if kwarg(kwargs, "machine") then state.machine = kwarg(kwargs, "machine") end
|
||||||
|
local layout = {}
|
||||||
|
local dock = kwarg(kwargs, "dock")
|
||||||
|
if dock == "open" or dock == "closed" then layout.dockCollapsed = dock == "closed" end
|
||||||
|
local tab = kwarg(kwargs, "docktab") or ((panel == "output" or panel == "setup") and panel) or nil
|
||||||
|
if tab and DOCK_TABS[tab] then layout.dockTab = tab end
|
||||||
|
layout.split = fraction(kwarg(kwargs, "editor"))
|
||||||
|
layout.right = fraction(kwarg(kwargs, "side"))
|
||||||
|
layout.dock = fraction(kwarg(kwargs, "dockheight"))
|
||||||
|
if next(layout) then state.layout = { [area] = layout } end
|
||||||
|
local call = kwarg(kwargs, "call") or file_call
|
||||||
|
if call then state.call = call end
|
||||||
|
local input = kwarg(kwargs, "input") and table.concat(split_bar(kwarg(kwargs, "input")), "\n") or file_input
|
||||||
|
if input then state.input = input end
|
||||||
|
if kwarg(kwargs, "t") then state.t = tonumber(kwarg(kwargs, "t")) end
|
||||||
|
if kwarg(kwargs, "title") then state.title = kwarg(kwargs, "title") end
|
||||||
|
local blob = "~" .. base64url(json_encode(state))
|
||||||
|
return { embed = base .. "/#/embed/" .. view .. "/" .. blob .. q, open = base .. "/#/" .. area .. "/s/" .. blob }
|
||||||
|
end
|
||||||
|
|
||||||
|
local function figcaption(caption, links)
|
||||||
|
return '<figcaption>' .. (caption and ('<span class="pplus-caption">' .. esc(caption) .. '</span> · ') or '')
|
||||||
|
.. '<span class="pplus-brand">Programming+</span>' .. links .. '</figcaption>'
|
||||||
|
end
|
||||||
|
|
||||||
|
local function live_embed(kwargs, meta, view_override)
|
||||||
|
ensure_deps()
|
||||||
|
local view = view_override or kwarg(kwargs, "view") or "trace"
|
||||||
|
if not VIEWS[view] then
|
||||||
|
if STATIC[view] then
|
||||||
|
warn("view=\"" .. view .. "\" is a rendered view: use {{< pplus-view view=\"" .. view .. "\" >}} (or {{< pplus-" .. view .. " >}}); showing the live " .. STATIC[view])
|
||||||
|
view = STATIC[view]
|
||||||
|
else
|
||||||
|
warn("unknown view=\"" .. view .. "\" (use playground, trace, table, flow, data, life, problems, proof, tests, compiler, asm, or a pane name); showing trace")
|
||||||
|
view = "trace"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
local playground = view == "playground"
|
||||||
|
local mode = kwarg(kwargs, "mode") or "embed"
|
||||||
|
local show = kwarg(kwargs, "show") or "embed"
|
||||||
|
local height = kwarg(kwargs, "height") or (playground and "720" or "520")
|
||||||
|
if playground and height == "auto" then
|
||||||
|
warn("height=\"auto\" does not apply to view=\"playground\", which fills its frame; using 720")
|
||||||
|
height = "720"
|
||||||
|
end
|
||||||
|
local listings = pandoc.Blocks({})
|
||||||
|
local target, instead = live_target(kwargs, meta, view, show ~= "embed" and listings or nil)
|
||||||
|
if not target then return instead end
|
||||||
|
local title = kwarg(kwargs, "title")
|
||||||
|
local caption = kwarg(kwargs, "caption")
|
||||||
|
|
||||||
|
if show == "listing" or mode == "link" or not is_html() then
|
||||||
|
local text = kwarg(kwargs, "text") or "Open this in Programming+"
|
||||||
|
listings:insert(pandoc.Para({ pandoc.Link({ pandoc.Str(text) }, target.open, "", pandoc.Attr("", { "pplus-link" })) }))
|
||||||
|
return wrap_collapse(kwargs, listings)
|
||||||
|
end
|
||||||
|
local auto = height == "auto"
|
||||||
|
local label = title or ("Programming+: " .. view)
|
||||||
|
local html = '<figure class="pplus-embed' .. (auto and ' pplus-auto' or '') .. (playground and ' pplus-playground' or '') .. '">'
|
||||||
|
.. '<iframe class="pplus-frame" src="' .. esc(target.embed) .. '" height="' .. esc(auto and "360" or height)
|
||||||
|
.. '" loading="lazy" title="' .. esc(label) .. '"' .. (auto and ' data-pplus-auto="1"' or '')
|
||||||
|
.. ' allow="clipboard-write"></iframe>'
|
||||||
|
.. figcaption(caption, ' · <a href="' .. esc(target.open) .. '" target="_blank" rel="noopener">open in the playground</a>'
|
||||||
|
.. ' · <a href="' .. esc(target.embed) .. '" target="_blank" rel="noopener">full screen</a>')
|
||||||
|
.. '</figure>'
|
||||||
|
listings:insert(raw(html))
|
||||||
|
return wrap_collapse(kwargs, listings)
|
||||||
|
end
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
-- Rendered with the page: render.mjs runs the app's views on the files
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
-- A built Programming+ for render.mjs, looked for in this order: pplus-engine (project or page metadata), the
|
||||||
|
-- PPLUS_ENGINE environment variable, an engine/ folder in this extension (`pixi run quarto-engine <dir>` puts one
|
||||||
|
-- there), and the repository this extension sits in (quarto/_extensions/pplus inside a Programming+ checkout).
|
||||||
|
local function engine_dir(meta)
|
||||||
|
local function built(dir)
|
||||||
|
if not dir then return nil end
|
||||||
|
dir = dir:gsub("\\", "/"):gsub("/+$", "")
|
||||||
|
if exists(dir .. "/quarto/render.js") then return dir end
|
||||||
|
if exists(dir .. "/dist/quarto/render.js") then return dir .. "/dist" end
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
local configured = meta_str(meta, "pplus-engine")
|
||||||
|
-- none: render nothing with the page; every rendered view becomes its listing and the live view
|
||||||
|
if configured == "none" or configured == "false" then return nil end
|
||||||
|
if configured and not configured:match("^/") and not configured:match("^%a:") then
|
||||||
|
-- relative to the project (or, without one, to the page)
|
||||||
|
local root = (quarto.project and quarto.project.directory) or page_dir()
|
||||||
|
configured = root .. "/" .. configured
|
||||||
|
end
|
||||||
|
return built(configured) or built(os.getenv("PPLUS_ENGINE")) or built(EXT_DIR .. "/engine") or built(EXT_DIR .. "/../../..")
|
||||||
|
end
|
||||||
|
|
||||||
|
local engine_warned = false
|
||||||
|
local function cache_dir(meta)
|
||||||
|
if not meta_bool(meta, "pplus-cache", true) then return nil end
|
||||||
|
local root = (quarto.project and quarto.project.directory) or page_dir()
|
||||||
|
return root .. "/.quarto/pplus"
|
||||||
|
end
|
||||||
|
|
||||||
|
-- Run one view. Returns the result (a table), or nil and why not.
|
||||||
|
local function render_view(req, meta)
|
||||||
|
local engine = engine_dir(meta)
|
||||||
|
if not engine then
|
||||||
|
local off = meta_str(meta, "pplus-engine")
|
||||||
|
if off == "none" or off == "false" then return nil, "pplus-engine is none" end
|
||||||
|
return nil, "no built Programming+ found (set pplus-engine in _quarto.yml, or see README.md)"
|
||||||
|
end
|
||||||
|
req.cache = cache_dir(meta)
|
||||||
|
local node = meta_str(meta, "pplus-node") or os.getenv("PPLUS_NODE") or "node"
|
||||||
|
local ok, out = pcall(pandoc.pipe, node, { EXT_DIR .. "/render.mjs", engine }, json_encode(req))
|
||||||
|
if not ok then return nil, "could not run " .. node .. " (" .. tostring(out):gsub("%s+$", "") .. ")" end
|
||||||
|
local ok2, res = pcall(json_decode, out)
|
||||||
|
if not ok2 or type(res) ~= "table" then return nil, "render.mjs answered something that is not JSON: " .. tostring(out):sub(1, 300) end
|
||||||
|
if res.error then return nil, res.error end
|
||||||
|
return res
|
||||||
|
end
|
||||||
|
|
||||||
|
local function strict_fail(meta, what)
|
||||||
|
if meta_bool(meta, "pplus-strict", false) then error("pplus: " .. what .. " (pplus-strict is on)") end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- The tabs of a translate view, or of pplus-tabs: one per notation, a code block (matho typeset) in each.
|
||||||
|
local function tabset(panes, kwargs)
|
||||||
|
if not is_html() then
|
||||||
|
local out = pandoc.Blocks({})
|
||||||
|
for _, p in ipairs(panes) do
|
||||||
|
out:insert(pandoc.Para({ pandoc.Strong({ pandoc.Str(p.label) }), pandoc.Str(p.generated and " (generated)" or "") }))
|
||||||
|
if p.text ~= "" then out:extend(listing_blocks(p.lang, p.text, kwargs)) else out:insert(pandoc.Para({ pandoc.Emph({ pandoc.Str(p.note or "") }) })) end
|
||||||
|
end
|
||||||
|
return out
|
||||||
|
end
|
||||||
|
local tabs = {}
|
||||||
|
for _, p in ipairs(panes) do
|
||||||
|
local content = pandoc.Blocks({})
|
||||||
|
if p.text ~= "" then
|
||||||
|
if p.lang == "matho" and kwarg(kwargs, "math") ~= "0" then
|
||||||
|
content:extend(math_blocks(p.text))
|
||||||
|
content:extend(listing_blocks("matho", p.text, { math = pandoc.Str("0") }))
|
||||||
|
else
|
||||||
|
local attr = kwarg(kwargs, "numbers") == "1" and { ["code-line-numbers"] = "true" } or {}
|
||||||
|
content:insert(pandoc.CodeBlock(p.text, pandoc.Attr("", { p.lang == "matho" and "latex" or p.lang }, attr)))
|
||||||
|
end
|
||||||
|
if p.generated and p.lang == "mojo" then
|
||||||
|
content:insert(raw('<p class="pplus-tab-note"><span class="pplus-tag-generated">generated</span> ' .. esc(p.note or "Generated from the pseudo.") .. '</p>'))
|
||||||
|
elseif p.generated then
|
||||||
|
content:insert(raw('<p class="pplus-tab-note"><span class="pplus-tag-generated">generated</span> Written by Programming+ from the ' .. esc(PANE_LABEL[p.from or "pseudo"] or "pseudo") .. '.</p>'))
|
||||||
|
end
|
||||||
|
else
|
||||||
|
content:insert(raw('<p class="pplus-tab-note">' .. esc(p.note or "") .. '</p>'))
|
||||||
|
end
|
||||||
|
tabs[#tabs + 1] = { title = p.label, content = content }
|
||||||
|
end
|
||||||
|
local attr = pandoc.Attr("", { "panel-tabset", "pplus-tabs" })
|
||||||
|
-- Quarto turns a .panel-tabset div into tabs before shortcodes run, so a shortcode makes the tabset node itself
|
||||||
|
if quarto.Tabset and quarto.Tab then
|
||||||
|
local list = pandoc.List({})
|
||||||
|
for _, t in ipairs(tabs) do list:insert(quarto.Tab({ title = pandoc.Inlines({ pandoc.Str(t.title) }), content = t.content })) end
|
||||||
|
return pandoc.Blocks({ quarto.Tabset({ level = 3, tabs = list, attr = attr }) })
|
||||||
|
end
|
||||||
|
local inner = pandoc.Blocks({})
|
||||||
|
for _, t in ipairs(tabs) do
|
||||||
|
inner:insert(pandoc.Header(3, { pandoc.Str(t.title) }))
|
||||||
|
inner:extend(t.content)
|
||||||
|
end
|
||||||
|
return pandoc.Blocks({ pandoc.Div(inner, attr) })
|
||||||
|
end
|
||||||
|
|
||||||
|
local function static_view(view, kwargs, meta, extra)
|
||||||
|
ensure_deps()
|
||||||
|
if view == "hw" then ensure_hw_deps() end
|
||||||
|
local files, given, bad = read_files(kwargs)
|
||||||
|
if bad then return missing(bad) end
|
||||||
|
if #given == 0 then
|
||||||
|
warn("pplus-" .. view .. ": give a program file: lingo=, matho=, pseudo=, speco=, mojo= or asm=")
|
||||||
|
return pandoc.Blocks({})
|
||||||
|
end
|
||||||
|
local req = { view = view, files = files }
|
||||||
|
req.lang = kwarg(kwargs, "lang")
|
||||||
|
if kwarg(kwargs, "call") then req.call = kwarg(kwargs, "call") end
|
||||||
|
if kwarg(kwargs, "input") then req.input = split_bar(kwarg(kwargs, "input")) end
|
||||||
|
local setup_file = kwarg(kwargs, "setup")
|
||||||
|
if setup_file then
|
||||||
|
local text = read_beside_page(setup_file)
|
||||||
|
if text then req.setup = text else warn("cannot read " .. setup_file .. " next to " .. input_path()) end
|
||||||
|
end
|
||||||
|
req.machine = kwarg(kwargs, "machine")
|
||||||
|
req.t = tonumber(kwarg(kwargs, "t") or "")
|
||||||
|
req.title = kwarg(kwargs, "title")
|
||||||
|
req.max = tonumber(kwarg(kwargs, "max") or "")
|
||||||
|
if kwarg(kwargs, "follow") then req.follow = split_list(kwarg(kwargs, "follow")) end
|
||||||
|
if kwarg(kwargs, "to") then req.to = split_list(kwarg(kwargs, "to")) end
|
||||||
|
req.compiler = kwarg(kwargs, "compiler") or "auto"
|
||||||
|
if view == "hw" then
|
||||||
|
req.hw = (extra and extra.hw) or (kwarg(kwargs, "views") and split_list(kwarg(kwargs, "views"))) or (kwarg(kwargs, "view") and kwarg(kwargs, "view") ~= "hw" and { kwarg(kwargs, "view") }) or nil
|
||||||
|
req.preset = kwarg(kwargs, "preset")
|
||||||
|
req.listing = kwarg(kwargs, "listing") ~= "0"
|
||||||
|
req.stepper = kwarg(kwargs, "stepper") ~= "0"
|
||||||
|
end
|
||||||
|
|
||||||
|
local name = (extra and extra.name) or ("pplus-" .. view)
|
||||||
|
local where = name .. " in " .. (input_path():match("[^/]*$") or "")
|
||||||
|
local res, why = render_view(req, meta)
|
||||||
|
local blocks = pandoc.Blocks({})
|
||||||
|
local title = kwarg(kwargs, "title")
|
||||||
|
local caption = kwarg(kwargs, "caption")
|
||||||
|
local target = live_target(kwargs, meta, STATIC[view], nil, view == "hw" and "hw" or nil)
|
||||||
|
|
||||||
|
if not res then
|
||||||
|
-- no engine (or it failed): the page still renders, with the program and the live view in its place
|
||||||
|
if not engine_warned then warn(where .. ": " .. why .. "; showing the live view instead") engine_warned = true end
|
||||||
|
strict_fail(meta, where .. ": " .. why)
|
||||||
|
for _, pane in ipairs(given) do blocks:extend(listing_blocks(pane, files[pane], kwargs)) end
|
||||||
|
if target then blocks:extend(live_embed(kwargs, meta, STATIC[view])) end
|
||||||
|
return wrap_collapse(kwargs, blocks)
|
||||||
|
end
|
||||||
|
for _, w in ipairs(res.warnings or {}) do warn(where .. ": " .. w) end
|
||||||
|
if res.expect and not res.expect.ok then strict_fail(meta, where .. ": the run does not print its EXPECT lines") end
|
||||||
|
|
||||||
|
local code = pandoc.Blocks({})
|
||||||
|
if kwarg(kwargs, "code") == "1" then
|
||||||
|
for _, pane in ipairs(given) do
|
||||||
|
local shows = pane == res.lang or #given == 1
|
||||||
|
or (res.lang == "pseudo" and (pane == "lingo" or pane == "matho" or (pane == "speco" and view == "proof")))
|
||||||
|
if shows then code:extend(listing_blocks(pane, files[pane], kwargs)) end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- translate, as tabs: Quarto's own tabset over pandoc code blocks (highlighted by the syntax definitions)
|
||||||
|
local layout = kwarg(kwargs, "layout") or "tabs"
|
||||||
|
if view == "translate" and (layout == "tabs" or layout == "columns" or not is_html()) and res.panes then
|
||||||
|
if layout == "columns" and is_html() then
|
||||||
|
local cols = pandoc.Blocks({})
|
||||||
|
for _, p in ipairs(res.panes) do
|
||||||
|
local col = pandoc.Blocks({ pandoc.Para({ pandoc.Strong({ pandoc.Str(p.label) }), pandoc.Str(p.generated and " (generated)" or "") }) })
|
||||||
|
if p.text ~= "" then col:extend(listing_blocks(p.lang, p.text, kwargs)) else col:insert(pandoc.Para({ pandoc.Emph({ pandoc.Str(p.note or "") }) })) end
|
||||||
|
cols:insert(pandoc.Div(col, pandoc.Attr("", { "pplus-col" })))
|
||||||
|
end
|
||||||
|
blocks:insert(pandoc.Div(cols, pandoc.Attr("", { "pplus-columns" })))
|
||||||
|
else
|
||||||
|
blocks:extend(tabset(res.panes, kwargs))
|
||||||
|
end
|
||||||
|
if is_html() and (caption or target) then
|
||||||
|
blocks:insert(raw('<div class="pplus-under">' .. figcaption(caption, target and (' · <a href="' .. esc(target.open) .. '" target="_blank" rel="noopener">open in the playground</a>') or '') .. '</div>'))
|
||||||
|
end
|
||||||
|
return wrap_collapse(kwargs, blocks)
|
||||||
|
end
|
||||||
|
|
||||||
|
if not is_html() then
|
||||||
|
if title then blocks:insert(pandoc.Para({ pandoc.Strong({ pandoc.Str(title) }) })) end
|
||||||
|
blocks:extend(code)
|
||||||
|
blocks:extend(pandoc.read(res.markdown or "", "markdown").blocks)
|
||||||
|
if caption then blocks:insert(pandoc.Para({ pandoc.Emph({ pandoc.Str(caption) }) })) end
|
||||||
|
if target then blocks:insert(pandoc.Para({ pandoc.Link({ pandoc.Str(kwarg(kwargs, "text") or "Open this in Programming+") }, target.open, "", pandoc.Attr("", { "pplus-link" })) })) end
|
||||||
|
return wrap_collapse(kwargs, blocks)
|
||||||
|
end
|
||||||
|
|
||||||
|
local live = kwarg(kwargs, "live")
|
||||||
|
local links = ''
|
||||||
|
if target then
|
||||||
|
if live == "click" then
|
||||||
|
links = links .. ' · <button type="button" class="pplus-golive" data-src="' .. esc(target.embed) .. '" data-height="' .. esc(kwarg(kwargs, "height") or (STATIC[view] == "playground" and "720" or "520")) .. '">make it live</button>'
|
||||||
|
end
|
||||||
|
links = links .. ' · <a href="' .. esc(target.open) .. '" target="_blank" rel="noopener">open in the playground</a>'
|
||||||
|
end
|
||||||
|
-- a div, not a raw <figure>, so a listing inside it is still pandoc's (highlighted, numbered)
|
||||||
|
local fig = pandoc.Blocks({})
|
||||||
|
if title then fig:insert(raw('<div class="pplus-figtitle">' .. esc(title) .. '</div>')) end
|
||||||
|
if #code > 0 then fig:insert(pandoc.Div(code, pandoc.Attr("", { "pplus-figcode" }))) end
|
||||||
|
fig:insert(raw(res.html))
|
||||||
|
fig:insert(raw(figcaption(caption, links)))
|
||||||
|
local classes = { "pplus-figure", "pplus-figure-" .. view }
|
||||||
|
-- column= widens the figure into Quarto's page grid (body, page, screen, margin...); the whole machine board is page-wide
|
||||||
|
local column = kwarg(kwargs, "column") or ((view == "hw" and not (extra and extra.name)) and "page" or nil)
|
||||||
|
if column and column ~= "body" then classes[#classes + 1] = "column-" .. column end
|
||||||
|
blocks:insert(pandoc.Div(fig, pandoc.Attr("", classes)))
|
||||||
|
return wrap_collapse(kwargs, blocks)
|
||||||
|
end
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
-- Plain: listings, tabs, a link
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
local function listing(kwargs, meta)
|
||||||
|
ensure_deps()
|
||||||
|
local files, given, bad = read_files(kwargs)
|
||||||
|
if bad then return missing(bad) end
|
||||||
|
local blocks = pandoc.Blocks({})
|
||||||
|
for _, pane in ipairs(given) do blocks:extend(listing_blocks(pane, files[pane], kwargs)) end
|
||||||
|
if kwarg(kwargs, "link") == "1" then
|
||||||
|
local target = live_target(kwargs, meta, kwarg(kwargs, "view") or "trace", nil)
|
||||||
|
if target then blocks:insert(pandoc.Para({ pandoc.Link({ pandoc.Str(kwarg(kwargs, "text") or "Open this in Programming+") }, target.open, "", pandoc.Attr("", { "pplus-link" })) })) end
|
||||||
|
end
|
||||||
|
return wrap_collapse(kwargs, blocks)
|
||||||
|
end
|
||||||
|
|
||||||
|
local function tabs(kwargs, meta)
|
||||||
|
ensure_deps()
|
||||||
|
local files, given, bad = read_files(kwargs)
|
||||||
|
if bad then return missing(bad) end
|
||||||
|
local panes = {}
|
||||||
|
for _, pane in ipairs(given) do panes[#panes + 1] = { lang = pane, label = PANE_LABEL[pane], text = listing_text(files[pane], pane), generated = false } end
|
||||||
|
return wrap_collapse(kwargs, tabset(panes, kwargs))
|
||||||
|
end
|
||||||
|
|
||||||
|
local function link(kwargs, meta)
|
||||||
|
ensure_deps()
|
||||||
|
local view = kwarg(kwargs, "view") or "playground"
|
||||||
|
local target, instead = live_target(kwargs, meta, VIEWS[view] and view or "playground", nil)
|
||||||
|
if not target then return instead end
|
||||||
|
-- the whole playground opens in its area; a single view opens as that embed, full screen
|
||||||
|
local href = view == "playground" and target.open or target.embed
|
||||||
|
return pandoc.Para({ pandoc.Link({ pandoc.Str(kwarg(kwargs, "text") or "Open this in Programming+") }, href, "", pandoc.Attr("", { "pplus-link" })) })
|
||||||
|
end
|
||||||
|
|
||||||
|
------------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
local function static(view) return function(args, kwargs, meta) return static_view(view, kwargs, meta) end end
|
||||||
|
|
||||||
|
local shortcodes = {
|
||||||
|
["pplus"] = function(args, kwargs, meta) return live_embed(kwargs, meta) end,
|
||||||
|
["pplus-embed"] = function(args, kwargs, meta) return live_embed(kwargs, meta) end,
|
||||||
|
["pplus-playground"] = function(args, kwargs, meta) return live_embed(kwargs, meta, "playground") end,
|
||||||
|
["pplus-view"] = function(args, kwargs, meta)
|
||||||
|
local view = kwarg(kwargs, "view") or (args[1] and str(args[1])) or "steps"
|
||||||
|
if view == "dataflow" then view = "data" elseif view == "lifetimes" then view = "life" end
|
||||||
|
if not STATIC[view] then
|
||||||
|
warn("pplus-view: unknown view=\"" .. view .. "\" (use run, steps, table, flow, data, life, proof, tests, check, translate, machine)")
|
||||||
|
return pandoc.Blocks({})
|
||||||
|
end
|
||||||
|
return static_view(view, kwargs, meta)
|
||||||
|
end,
|
||||||
|
["pplus-run"] = static("run"),
|
||||||
|
["pplus-steps"] = static("steps"),
|
||||||
|
["pplus-table"] = static("table"),
|
||||||
|
["pplus-flow"] = static("flow"),
|
||||||
|
["pplus-dataflow"] = static("data"),
|
||||||
|
["pplus-lifetimes"] = static("life"),
|
||||||
|
["pplus-proof"] = static("proof"),
|
||||||
|
["pplus-tests"] = static("tests"),
|
||||||
|
["pplus-check"] = static("check"),
|
||||||
|
["pplus-translate"] = static("translate"),
|
||||||
|
["pplus-machine"] = static("machine"),
|
||||||
|
-- the machine: the Hardware board over an x86-64 run, every card steppable
|
||||||
|
["pplus-hw"] = function(args, kwargs, meta) return static_view("hw", kwargs, meta) end,
|
||||||
|
["pplus-listing"] = function(args, kwargs, meta) return listing(kwargs, meta) end,
|
||||||
|
["pplus-tabs"] = function(args, kwargs, meta) return tabs(kwargs, meta) end,
|
||||||
|
["pplus-link"] = function(args, kwargs, meta) return link(kwargs, meta) end,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name in ipairs(HW_VIEWS) do
|
||||||
|
shortcodes["pplus-hw-" .. name] = function(args, kwargs, meta) return static_view("hw", kwargs, meta, { hw = { name }, name = "pplus-hw-" .. name }) end
|
||||||
|
end
|
||||||
|
|
||||||
|
return shortcodes
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// render.mjs: runs one static view for the Programming+ shortcodes (pplus.lua calls it while Quarto renders).
|
||||||
|
//
|
||||||
|
// node render.mjs <engine> a request as JSON on stdin; the result as JSON on stdout
|
||||||
|
//
|
||||||
|
// <engine> is a built Programming+ (a folder holding dist/, or dist/ itself): the extension finds it as
|
||||||
|
// quarto/README.md describes. The views run the app's own engines, from dist/quarto/render.js, under a small
|
||||||
|
// document (dist/quarto/dom.js): nothing here knows how a program runs.
|
||||||
|
//
|
||||||
|
// A Mojo file asked to run is also given to a real compiler when one is on the PATH (`mojo`; inside pixi, the
|
||||||
|
// pinned one), and the page shows that compiler's output; without one, Programming+'s interpreter runs it and
|
||||||
|
// the page says so. `"compiler": "off"` in the request skips the compiler.
|
||||||
|
//
|
||||||
|
// Results are cached by the request and the engine's build, in the folder the request names (`cache`).
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
// written synchronously: process.exit() would cut an asynchronous write to a pipe short
|
||||||
|
const write = (text) => { const b = Buffer.from(text); let o = 0; while (o < b.length) o += fs.writeSync(1, b, o); };
|
||||||
|
const out = (obj) => write(JSON.stringify(obj));
|
||||||
|
function fail(message) { out({ error: message }); process.exit(0); }
|
||||||
|
|
||||||
|
const arg = process.argv[2];
|
||||||
|
if (!arg) fail('usage: node render.mjs <Programming+ folder or its dist/>');
|
||||||
|
const dist = fs.existsSync(path.join(arg, 'quarto', 'render.js')) ? arg : path.join(arg, 'dist');
|
||||||
|
const entry = path.join(dist, 'quarto', 'render.js');
|
||||||
|
if (!fs.existsSync(entry)) fail(`no built Programming+ at ${arg} (looked for ${entry}); build it with \`pixi run build\``);
|
||||||
|
|
||||||
|
let req;
|
||||||
|
try { req = JSON.parse(fs.readFileSync(0, 'utf8')); } catch (e) { fail(`the request is not JSON: ${e.message}`); }
|
||||||
|
|
||||||
|
// the cache key: the request, and the build of every file the views read (a rebuilt engine renders again)
|
||||||
|
let key = null;
|
||||||
|
if (req.cache) {
|
||||||
|
const h = crypto.createHash('sha256').update(JSON.stringify({ ...req, cache: undefined }));
|
||||||
|
// the app's files in dist/, pplus-core's beside it in ../core/dist/ (a checkout, or the engine folder quarto-engine writes)
|
||||||
|
for (const f of ['quarto/render.js', 'quarto/machine.js', 'quarto/dom.js', 'core/session.js', 'ui/views/viz.js']) {
|
||||||
|
try { h.update(f + fs.statSync(path.join(dist, f)).mtimeMs); } catch { /* absent: not part of the key */ }
|
||||||
|
}
|
||||||
|
for (const f of ['common/workspace.js', 'engines/asm86/hwviews.js', 'engines/asm86/views.js', 'mojo/generated/pin.js']) {
|
||||||
|
try { h.update('core/' + f + fs.statSync(path.join(dist, '..', 'core', 'dist', f)).mtimeMs); } catch { /* absent: not part of the key */ }
|
||||||
|
}
|
||||||
|
key = h.digest('hex').slice(0, 24);
|
||||||
|
try { write(fs.readFileSync(path.join(req.cache, key + '.json'), 'utf8')); process.exit(0); } catch { /* not cached yet */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// a real Mojo compiler, for a run of a Mojo file
|
||||||
|
let compiled = null;
|
||||||
|
if (req.view === 'run' && typeof req.files?.mojo === 'string' && req.compiler !== 'off') {
|
||||||
|
const v = spawnSync('mojo', ['--version'], { encoding: 'utf8' });
|
||||||
|
if (v.status === 0) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-mojo-'));
|
||||||
|
const file = path.join(dir, 'main.mojo');
|
||||||
|
fs.writeFileSync(file, req.files.mojo);
|
||||||
|
const input = (req.input ?? []).map((l) => l + '\n').join('');
|
||||||
|
// built as Programming+ builds everywhere (pplus-core's pin: a stated target CPU, and a multiply never fused
|
||||||
|
// with an add), so the page shows what the app's Compile & run would, on whatever machine renders it
|
||||||
|
const { mojoBuildArgs } = await import(pathToFileURL(path.join(dist, '..', 'core', 'dist', 'services', 'godbolt.js')).href);
|
||||||
|
const args = mojoBuildArgs('', { x86_64: process.arch === 'x64' }).split(/\s+/).filter(Boolean);
|
||||||
|
const r = spawnSync('mojo', ['run', ...args, file], { input, encoding: 'utf8', timeout: 180000 });
|
||||||
|
compiled = { stdout: r.stdout ?? '', stderr: r.stderr ?? '', status: r.status, version: v.stdout.trim(), args: args.join(' ') };
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
} else if (req.compiler === 'on') fail('compiler="on", and there is no `mojo` on the PATH');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { installDocument } = await import(pathToFileURL(path.join(dist, 'quarto', 'dom.js')).href);
|
||||||
|
installDocument();
|
||||||
|
const { renderStatic } = await import(pathToFileURL(entry).href);
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = renderStatic({ ...req, compiled });
|
||||||
|
} catch (e) {
|
||||||
|
fail(`the ${req.view} view failed: ${e?.stack || e}`);
|
||||||
|
}
|
||||||
|
const { node, ...rest } = res;
|
||||||
|
// a machine board keeps every step's drawing of every card: they repeat from step to step, so deflate (which
|
||||||
|
// pplus.js undoes with the browser's DecompressionStream) makes them a few kilobytes a card
|
||||||
|
if (rest.html) {
|
||||||
|
const zlib = await import('node:zlib');
|
||||||
|
rest.html = rest.html.replace(/<script type="application\/json" class="pplus-hw-data">([^<]*)<\/script>/g, (_, json) =>
|
||||||
|
`<script type="application/x-pplus-deflate" class="pplus-hw-data">${zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 }).toString('base64')}</script>`);
|
||||||
|
}
|
||||||
|
const text = JSON.stringify(rest);
|
||||||
|
if (key) { try { fs.mkdirSync(req.cache, { recursive: true }); fs.writeFileSync(path.join(req.cache, key + '.json'), text); } catch { /* a cache that cannot be written is no cache */ } }
|
||||||
|
write(text);
|
||||||
|
// the views leave timers behind (a deferred scroll, a tooltip); the answer is written, so do not wait for them
|
||||||
|
process.exit(0);
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!-- lingo: the controlled English of Programming+ (pplus.scient.ing). A reader knows a fixed set of
|
||||||
|
sentence shapes; this definition colors those shapes so a page can show which words carry the
|
||||||
|
meaning. Hand-written, like pseudo.xml. -->
|
||||||
|
<language name="Lingo"
|
||||||
|
section="Sources"
|
||||||
|
version="1"
|
||||||
|
kateversion="5.0"
|
||||||
|
extensions="*.lingo"
|
||||||
|
mimetype="text/x-lingo"
|
||||||
|
author="BIOSC 1540"
|
||||||
|
license="Apache-2.0">
|
||||||
|
|
||||||
|
<highlighting>
|
||||||
|
<!-- sentence openers that start a block or end the routine -->
|
||||||
|
<list name="flow">
|
||||||
|
<item>If</item>
|
||||||
|
<item>Otherwise</item>
|
||||||
|
<item>Repeat</item>
|
||||||
|
<item>Stop</item>
|
||||||
|
<item>Skip</item>
|
||||||
|
</list>
|
||||||
|
<!-- steps that create or change a value -->
|
||||||
|
<list name="steps">
|
||||||
|
<item>Start</item>
|
||||||
|
<item>Set</item>
|
||||||
|
<item>Add</item>
|
||||||
|
<item>Subtract</item>
|
||||||
|
<item>Count</item>
|
||||||
|
<item>Swap</item>
|
||||||
|
<item>Check</item>
|
||||||
|
</list>
|
||||||
|
<!-- comparison and connective words -->
|
||||||
|
<list name="glue">
|
||||||
|
<item>is</item>
|
||||||
|
<item>are</item>
|
||||||
|
<item>not</item>
|
||||||
|
<item>and</item>
|
||||||
|
<item>or</item>
|
||||||
|
<item>neither</item>
|
||||||
|
<item>nor</item>
|
||||||
|
<item>at</item>
|
||||||
|
<item>of</item>
|
||||||
|
<item>in</item>
|
||||||
|
<item>to</item>
|
||||||
|
<item>from</item>
|
||||||
|
<item>with</item>
|
||||||
|
<item>when</item>
|
||||||
|
<item>where</item>
|
||||||
|
<item>otherwise</item>
|
||||||
|
<item>plus</item>
|
||||||
|
<item>minus</item>
|
||||||
|
<item>times</item>
|
||||||
|
<item>less</item>
|
||||||
|
<item>more</item>
|
||||||
|
<item>than</item>
|
||||||
|
<item>least</item>
|
||||||
|
<item>most</item>
|
||||||
|
<item>one</item>
|
||||||
|
<item>every</item>
|
||||||
|
<item>each</item>
|
||||||
|
<item>called</item>
|
||||||
|
<item>empty</item>
|
||||||
|
<item>contains</item>
|
||||||
|
</list>
|
||||||
|
<!-- kinds of thing -->
|
||||||
|
<list name="kinds">
|
||||||
|
<item>text</item>
|
||||||
|
<item>letter</item>
|
||||||
|
<item>number</item>
|
||||||
|
<item>whole</item>
|
||||||
|
<item>list</item>
|
||||||
|
<item>tally</item>
|
||||||
|
<item>position</item>
|
||||||
|
<item>positions</item>
|
||||||
|
<item>length</item>
|
||||||
|
<item>letters</item>
|
||||||
|
<item>window</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<contexts>
|
||||||
|
<context name="Normal" attribute="Normal Text" lineEndContext="#stay">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<Detect2Chars attribute="Comment" char="/" char1="/" context="Comment"/>
|
||||||
|
<DetectChar attribute="String" char=""" context="StringDouble"/>
|
||||||
|
<DetectChar attribute="Char" char="'" context="CharSingle"/>
|
||||||
|
|
||||||
|
<!-- the routine's first line and its last -->
|
||||||
|
<RegExpr attribute="Function" String="^\s*To\b" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="The answer is" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="Stop and answer" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="Stop the loop" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="Skip to the next" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="For each" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="For every" context="#stay"/>
|
||||||
|
<StringDetect attribute="Control Flow" String="Repeat while" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="up to but not including" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="up to and including" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="the number of" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="the letter of" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="the length of" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="starting at" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="to the end of" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="an empty list called" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="an empty tally called" context="#stay"/>
|
||||||
|
<StringDetect attribute="Keyword" String="an empty text called" context="#stay"/>
|
||||||
|
|
||||||
|
<keyword attribute="Control Flow" String="flow"/>
|
||||||
|
<keyword attribute="Keyword" String="steps"/>
|
||||||
|
<keyword attribute="Data Type" String="kinds"/>
|
||||||
|
<keyword attribute="Operator" String="glue"/>
|
||||||
|
|
||||||
|
<RegExpr attribute="Decimal" String="\b[0-9]+\b" context="#stay"/>
|
||||||
|
<!-- a name: a capitalized word or a single lowercase letter that is not a glue word -->
|
||||||
|
<RegExpr attribute="Variable" String="\b[A-Z][A-Za-z0-9_]*\b" context="#stay"/>
|
||||||
|
<RegExpr attribute="Variable" String="\b[a-z]\b" context="#stay"/>
|
||||||
|
<AnyChar attribute="Operator" String=":.,+-()"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="Comment" attribute="Comment" lineEndContext="#pop">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<DetectIdentifier/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="StringDouble" attribute="String" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="String" char=""" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="CharSingle" attribute="Char" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="Char" char="'" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
</contexts>
|
||||||
|
|
||||||
|
<itemDatas>
|
||||||
|
<itemData name="Normal Text" defStyleNum="dsNormal"/>
|
||||||
|
<itemData name="Control Flow" defStyleNum="dsControlFlow"/>
|
||||||
|
<itemData name="Keyword" defStyleNum="dsKeyword"/>
|
||||||
|
<itemData name="Data Type" defStyleNum="dsDataType"/>
|
||||||
|
<itemData name="Operator" defStyleNum="dsOperator"/>
|
||||||
|
<itemData name="Function" defStyleNum="dsFunction"/>
|
||||||
|
<itemData name="Variable" defStyleNum="dsVariable"/>
|
||||||
|
<itemData name="String" defStyleNum="dsString"/>
|
||||||
|
<itemData name="Char" defStyleNum="dsChar"/>
|
||||||
|
<itemData name="Decimal" defStyleNum="dsDecVal"/>
|
||||||
|
<itemData name="Comment" defStyleNum="dsComment"/>
|
||||||
|
</itemDatas>
|
||||||
|
</highlighting>
|
||||||
|
|
||||||
|
<general>
|
||||||
|
<keywords casesensitive="1" weakDeliminator="'"/>
|
||||||
|
<comments>
|
||||||
|
<comment name="singleLine" start="//"/>
|
||||||
|
</comments>
|
||||||
|
</general>
|
||||||
|
</language>
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!-- Generated by scripts/mojo/corpus.py emit from modular/modular@527d069ee11a (Mojo 1.2.0). Do not edit. -->
|
||||||
|
<language name="Mojo"
|
||||||
|
section="Sources"
|
||||||
|
version="1"
|
||||||
|
kateversion="5.0"
|
||||||
|
extensions="*.mojo;*.🔥"
|
||||||
|
mimetype="text/x-mojo"
|
||||||
|
author="Programming+"
|
||||||
|
license="Apache-2.0">
|
||||||
|
|
||||||
|
<highlighting>
|
||||||
|
<list name="keywords">
|
||||||
|
<item>False</item>
|
||||||
|
<item>None</item>
|
||||||
|
<item>Self</item>
|
||||||
|
<item>True</item>
|
||||||
|
<item>_</item>
|
||||||
|
<item>abi</item>
|
||||||
|
<item>and</item>
|
||||||
|
<item>as</item>
|
||||||
|
<item>assert</item>
|
||||||
|
<item>break</item>
|
||||||
|
<item>capturing</item>
|
||||||
|
<item>case</item>
|
||||||
|
<item>class</item>
|
||||||
|
<item>comptime</item>
|
||||||
|
<item>conforms_to</item>
|
||||||
|
<item>continue</item>
|
||||||
|
<item>def</item>
|
||||||
|
<item>del</item>
|
||||||
|
<item>elif</item>
|
||||||
|
<item>else</item>
|
||||||
|
<item>escaping</item>
|
||||||
|
<item>except</item>
|
||||||
|
<item>finally</item>
|
||||||
|
<item>for</item>
|
||||||
|
<item>from</item>
|
||||||
|
<item>global</item>
|
||||||
|
<item>if</item>
|
||||||
|
<item>import</item>
|
||||||
|
<item>in</item>
|
||||||
|
<item>is</item>
|
||||||
|
<item>lambda</item>
|
||||||
|
<item>match</item>
|
||||||
|
<item>nonlocal</item>
|
||||||
|
<item>not</item>
|
||||||
|
<item>or</item>
|
||||||
|
<item>origin_of</item>
|
||||||
|
<item>pass</item>
|
||||||
|
<item>raise</item>
|
||||||
|
<item>raises</item>
|
||||||
|
<item>return</item>
|
||||||
|
<item>struct</item>
|
||||||
|
<item>thin</item>
|
||||||
|
<item>trait</item>
|
||||||
|
<item>try</item>
|
||||||
|
<item>type_of</item>
|
||||||
|
<item>where</item>
|
||||||
|
<item>while</item>
|
||||||
|
<item>with</item>
|
||||||
|
<item>yield</item>
|
||||||
|
</list>
|
||||||
|
<list name="conventions">
|
||||||
|
<item>deinit</item>
|
||||||
|
<item>imm</item>
|
||||||
|
<item>mut</item>
|
||||||
|
<item>out</item>
|
||||||
|
<item>ref</item>
|
||||||
|
<item>var</item>
|
||||||
|
</list>
|
||||||
|
<list name="removed">
|
||||||
|
<item>fn</item>
|
||||||
|
<item>read</item>
|
||||||
|
</list>
|
||||||
|
<list name="builtins">
|
||||||
|
<item>Absable</item>
|
||||||
|
<item>AddressSpace</item>
|
||||||
|
<item>AnyOrigin</item>
|
||||||
|
<item>AnyType</item>
|
||||||
|
<item>Array</item>
|
||||||
|
<item>BFloat16</item>
|
||||||
|
<item>Bool</item>
|
||||||
|
<item>Boolable</item>
|
||||||
|
<item>Byte</item>
|
||||||
|
<item>Codepoint</item>
|
||||||
|
<item>Comparable</item>
|
||||||
|
<item>Copyable</item>
|
||||||
|
<item>DType</item>
|
||||||
|
<item>Defaultable</item>
|
||||||
|
<item>Deinitable</item>
|
||||||
|
<item>Dict</item>
|
||||||
|
<item>EnumLike</item>
|
||||||
|
<item>Equatable</item>
|
||||||
|
<item>Error</item>
|
||||||
|
<item>FileHandle</item>
|
||||||
|
<item>Float16</item>
|
||||||
|
<item>Float32</item>
|
||||||
|
<item>Float4_e2m1fn</item>
|
||||||
|
<item>Float64</item>
|
||||||
|
<item>Float8_e4m3fn</item>
|
||||||
|
<item>Float8_e4m3fnuz</item>
|
||||||
|
<item>Float8_e5m2</item>
|
||||||
|
<item>Float8_e5m2fnuz</item>
|
||||||
|
<item>Float8_e8m0fnu</item>
|
||||||
|
<item>FloatLiteral</item>
|
||||||
|
<item>Floatable</item>
|
||||||
|
<item>FloatableRaising</item>
|
||||||
|
<item>Hashable</item>
|
||||||
|
<item>Identifiable</item>
|
||||||
|
<item>ImmOpaquePointer</item>
|
||||||
|
<item>ImmOrigin</item>
|
||||||
|
<item>ImmPointer</item>
|
||||||
|
<item>ImmSpan</item>
|
||||||
|
<item>ImmStaticOrigin</item>
|
||||||
|
<item>ImmStringSlice</item>
|
||||||
|
<item>ImmStringSpan</item>
|
||||||
|
<item>ImmUnsafeAnyOrigin</item>
|
||||||
|
<item>ImmUntrackedOrigin</item>
|
||||||
|
<item>ImmutAnyOrigin</item>
|
||||||
|
<item>ImplicitlyCopyable</item>
|
||||||
|
<item>Indexer</item>
|
||||||
|
<item>InlineLevel</item>
|
||||||
|
<item>Int</item>
|
||||||
|
<item>Int128</item>
|
||||||
|
<item>Int16</item>
|
||||||
|
<item>Int256</item>
|
||||||
|
<item>Int32</item>
|
||||||
|
<item>Int64</item>
|
||||||
|
<item>Int8</item>
|
||||||
|
<item>IntLiteral</item>
|
||||||
|
<item>Intable</item>
|
||||||
|
<item>IntableRaising</item>
|
||||||
|
<item>Iterable</item>
|
||||||
|
<item>IterableOwned</item>
|
||||||
|
<item>Iterator</item>
|
||||||
|
<item>KeyElement</item>
|
||||||
|
<item>List</item>
|
||||||
|
<item>Movable</item>
|
||||||
|
<item>MutAnyOrigin</item>
|
||||||
|
<item>MutOpaquePointer</item>
|
||||||
|
<item>MutOrigin</item>
|
||||||
|
<item>MutPointer</item>
|
||||||
|
<item>MutSpan</item>
|
||||||
|
<item>MutUnsafeAnyOrigin</item>
|
||||||
|
<item>MutUntrackedOrigin</item>
|
||||||
|
<item>Never</item>
|
||||||
|
<item>NoneType</item>
|
||||||
|
<item>OpaquePointer</item>
|
||||||
|
<item>Optional</item>
|
||||||
|
<item>OptionalImmPointer</item>
|
||||||
|
<item>OptionalMutPointer</item>
|
||||||
|
<item>OptionalPointer</item>
|
||||||
|
<item>Origin</item>
|
||||||
|
<item>OriginSet</item>
|
||||||
|
<item>ParameterList</item>
|
||||||
|
<item>Pointer</item>
|
||||||
|
<item>Powable</item>
|
||||||
|
<item>RawFileDescriptor</item>
|
||||||
|
<item>RegisterPassable</item>
|
||||||
|
<item>ReversibleRange</item>
|
||||||
|
<item>Roundable</item>
|
||||||
|
<item>SIMD</item>
|
||||||
|
<item>SIMDLength</item>
|
||||||
|
<item>Scalar</item>
|
||||||
|
<item>Sized</item>
|
||||||
|
<item>SizedRaising</item>
|
||||||
|
<item>Slice</item>
|
||||||
|
<item>Some</item>
|
||||||
|
<item>SomeTypeList</item>
|
||||||
|
<item>Span</item>
|
||||||
|
<item>StaticString</item>
|
||||||
|
<item>StopIteration</item>
|
||||||
|
<item>String</item>
|
||||||
|
<item>StringLiteral</item>
|
||||||
|
<item>StringSlice</item>
|
||||||
|
<item>StringSpan</item>
|
||||||
|
<item>TrivialRegisterPassable</item>
|
||||||
|
<item>Tuple</item>
|
||||||
|
<item>TypeList</item>
|
||||||
|
<item>UInt</item>
|
||||||
|
<item>UInt128</item>
|
||||||
|
<item>UInt16</item>
|
||||||
|
<item>UInt256</item>
|
||||||
|
<item>UInt32</item>
|
||||||
|
<item>UInt64</item>
|
||||||
|
<item>UInt8</item>
|
||||||
|
<item>UnsafeAnyOrigin</item>
|
||||||
|
<item>UnsafePointer</item>
|
||||||
|
<item>UntrackedOrigin</item>
|
||||||
|
<item>VariadicList</item>
|
||||||
|
<item>VariadicPack</item>
|
||||||
|
<item>Writable</item>
|
||||||
|
<item>Writer</item>
|
||||||
|
<item>abs</item>
|
||||||
|
<item>all</item>
|
||||||
|
<item>alloc</item>
|
||||||
|
<item>any</item>
|
||||||
|
<item>ascii</item>
|
||||||
|
<item>atof</item>
|
||||||
|
<item>atol</item>
|
||||||
|
<item>bin</item>
|
||||||
|
<item>breakpoint</item>
|
||||||
|
<item>chr</item>
|
||||||
|
<item>debug_assert</item>
|
||||||
|
<item>deinit</item>
|
||||||
|
<item>divmod</item>
|
||||||
|
<item>doc_hidden</item>
|
||||||
|
<item>enumerate</item>
|
||||||
|
<item>hash</item>
|
||||||
|
<item>hash_bytes</item>
|
||||||
|
<item>hex</item>
|
||||||
|
<item>index</item>
|
||||||
|
<item>input</item>
|
||||||
|
<item>iter</item>
|
||||||
|
<item>len</item>
|
||||||
|
<item>map</item>
|
||||||
|
<item>materialize</item>
|
||||||
|
<item>max</item>
|
||||||
|
<item>min</item>
|
||||||
|
<item>next</item>
|
||||||
|
<item>oct</item>
|
||||||
|
<item>open</item>
|
||||||
|
<item>ord</item>
|
||||||
|
<item>partition</item>
|
||||||
|
<item>pow</item>
|
||||||
|
<item>print</item>
|
||||||
|
<item>range</item>
|
||||||
|
<item>rebind</item>
|
||||||
|
<item>rebind_var</item>
|
||||||
|
<item>reflect</item>
|
||||||
|
<item>repr</item>
|
||||||
|
<item>reversed</item>
|
||||||
|
<item>round</item>
|
||||||
|
<item>slice</item>
|
||||||
|
<item>sort</item>
|
||||||
|
<item>swap</item>
|
||||||
|
<item>zip</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<contexts>
|
||||||
|
<context name="Normal" attribute="Normal Text" lineEndContext="#stay">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<DetectChar attribute="Comment" char="#" context="Comment"/>
|
||||||
|
<RegExpr attribute="String" String="[rRtT]{0,2}"""" context="TripleDouble"/>
|
||||||
|
<RegExpr attribute="String" String="[rRtT]{0,2}'''" context="TripleSingle"/>
|
||||||
|
<RegExpr attribute="String" String="[rRtT]{0,2}"" context="StringDouble"/>
|
||||||
|
<RegExpr attribute="String" String="[rRtT]{0,2}'" context="StringSingle"/>
|
||||||
|
<RegExpr attribute="Decorator" String="@[A-Za-z_][A-Za-z0-9_.]*" context="#stay" firstNonSpace="true"/>
|
||||||
|
<keyword attribute="Removed" String="removed"/>
|
||||||
|
<keyword attribute="Convention" String="conventions"/>
|
||||||
|
<keyword attribute="Keyword" String="keywords"/>
|
||||||
|
<keyword attribute="Builtin" String="builtins"/>
|
||||||
|
<RegExpr attribute="Transfer" String="(?<=[A-Za-z0-9_\)\]])\^(?=\s*[\),\]\}:]|\s*$)" context="#stay"/>
|
||||||
|
<RegExpr attribute="Float" String="\b[0-9][0-9_]*\.[0-9_]*(?:[eE][+-]?[0-9]+)?|\b[0-9][0-9_]*[eE][+-]?[0-9]+\b" context="#stay"/>
|
||||||
|
<RegExpr attribute="Decimal" String="\b(?:0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|[0-9][0-9_]*)\b" context="#stay"/>
|
||||||
|
<RegExpr attribute="Function" String="\b[A-Za-z_][A-Za-z0-9_]*(?=\s*[\(\[])" context="#stay"/>
|
||||||
|
<AnyChar attribute="Operator" String="+-*/%<>=!^~&|:,.@[](){}"/>
|
||||||
|
</context>
|
||||||
|
<context name="Comment" attribute="Comment" lineEndContext="#pop">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<RegExpr attribute="Alert" String="\b(TODO|FIXME|NOTE)\b" context="#stay"/>
|
||||||
|
<DetectIdentifier/>
|
||||||
|
</context>
|
||||||
|
<context name="TripleDouble" attribute="String" lineEndContext="#stay">
|
||||||
|
<DetectChar attribute="String" char="\" context="Escape"/>
|
||||||
|
<StringDetect attribute="String" String=""""" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
<context name="TripleSingle" attribute="String" lineEndContext="#stay">
|
||||||
|
<DetectChar attribute="String" char="\" context="Escape"/>
|
||||||
|
<StringDetect attribute="String" String="'''" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
<context name="StringDouble" attribute="String" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="String" char="\" context="Escape"/>
|
||||||
|
<DetectChar attribute="String" char=""" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
<context name="StringSingle" attribute="String" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="String" char="\" context="Escape"/>
|
||||||
|
<DetectChar attribute="String" char="'" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
<context name="Escape" attribute="String" lineEndContext="#pop">
|
||||||
|
<RegExpr attribute="String" String="." context="#pop"/>
|
||||||
|
</context>
|
||||||
|
</contexts>
|
||||||
|
|
||||||
|
<itemDatas>
|
||||||
|
<itemData name="Normal Text" defStyleNum="dsNormal"/>
|
||||||
|
<itemData name="Keyword" defStyleNum="dsKeyword"/>
|
||||||
|
<itemData name="Convention" defStyleNum="dsAttribute" bold="1" italic="1"/>
|
||||||
|
<itemData name="Transfer" defStyleNum="dsSpecialChar" bold="1"/>
|
||||||
|
<itemData name="Removed" defStyleNum="dsError"/>
|
||||||
|
<itemData name="Builtin" defStyleNum="dsBuiltIn"/>
|
||||||
|
<itemData name="Decorator" defStyleNum="dsAttribute"/>
|
||||||
|
<itemData name="Function" defStyleNum="dsFunction"/>
|
||||||
|
<itemData name="Decimal" defStyleNum="dsDecVal"/>
|
||||||
|
<itemData name="Float" defStyleNum="dsFloat"/>
|
||||||
|
<itemData name="String" defStyleNum="dsString"/>
|
||||||
|
<itemData name="Comment" defStyleNum="dsComment"/>
|
||||||
|
<itemData name="Alert" defStyleNum="dsAlert"/>
|
||||||
|
<itemData name="Operator" defStyleNum="dsOperator"/>
|
||||||
|
</itemDatas>
|
||||||
|
</highlighting>
|
||||||
|
|
||||||
|
<general>
|
||||||
|
<comments>
|
||||||
|
<comment name="singleLine" start="#"/>
|
||||||
|
</comments>
|
||||||
|
<keywords casesensitive="1"/>
|
||||||
|
</general>
|
||||||
|
</language>
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
|
||||||
|
<language name="Pseudo"
|
||||||
|
section="Sources"
|
||||||
|
version="1"
|
||||||
|
kateversion="5.0"
|
||||||
|
extensions="*.pseudo;*.pcode"
|
||||||
|
mimetype="text/x-pseudocode"
|
||||||
|
author="BIOSC 1540"
|
||||||
|
license="Apache-2.0">
|
||||||
|
|
||||||
|
<highlighting>
|
||||||
|
<list name="controlflow">
|
||||||
|
<item>IF</item>
|
||||||
|
<item>THEN</item>
|
||||||
|
<item>ELSE</item>
|
||||||
|
<item>ELSEIF</item>
|
||||||
|
<item>ENDIF</item>
|
||||||
|
<item>CASE</item>
|
||||||
|
<item>OTHERWISE</item>
|
||||||
|
<item>ENDCASE</item>
|
||||||
|
<item>FOR</item>
|
||||||
|
<item>TO</item>
|
||||||
|
<item>STEP</item>
|
||||||
|
<item>NEXT</item>
|
||||||
|
<item>EACH</item>
|
||||||
|
<item>REPEAT</item>
|
||||||
|
<item>UNTIL</item>
|
||||||
|
<item>WHILE</item>
|
||||||
|
<item>ENDWHILE</item>
|
||||||
|
<item>RETURN</item>
|
||||||
|
<item>BREAK</item>
|
||||||
|
<item>CONTINUE</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="keywords">
|
||||||
|
<item>AND</item>
|
||||||
|
<item>OR</item>
|
||||||
|
<item>NOT</item>
|
||||||
|
<item>DIV</item>
|
||||||
|
<item>MOD</item>
|
||||||
|
<item>OF</item>
|
||||||
|
<item>CALL</item>
|
||||||
|
<item>IN</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="io">
|
||||||
|
<item>INPUT</item>
|
||||||
|
<item>OUTPUT</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="declarations">
|
||||||
|
<item>DECLARE</item>
|
||||||
|
<item>CONSTANT</item>
|
||||||
|
<item>DEFINE</item>
|
||||||
|
<item>TYPE</item>
|
||||||
|
<item>ENDTYPE</item>
|
||||||
|
<item>RETURNS</item>
|
||||||
|
<item>CLASS</item>
|
||||||
|
<item>ENDCLASS</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="modifiers">
|
||||||
|
<item>BYVAL</item>
|
||||||
|
<item>BYREF</item>
|
||||||
|
<item>PUBLIC</item>
|
||||||
|
<item>PRIVATE</item>
|
||||||
|
<item>INHERITS</item>
|
||||||
|
<item>SUPER</item>
|
||||||
|
<item>NEW</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="types">
|
||||||
|
<item>INTEGER</item>
|
||||||
|
<item>FLOAT</item>
|
||||||
|
<item>CHAR</item>
|
||||||
|
<item>STRING</item>
|
||||||
|
<item>BOOL</item>
|
||||||
|
<item>BOOLEAN</item>
|
||||||
|
<item>ARRAY</item>
|
||||||
|
<item>SET</item>
|
||||||
|
<item>HASHMAP</item>
|
||||||
|
<item>LIST</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="reasoning">
|
||||||
|
<item>REQUIRE</item>
|
||||||
|
<item>ENSURE</item>
|
||||||
|
<item>INVARIANT</item>
|
||||||
|
<item>DECREASES</item>
|
||||||
|
<item>ASSERT</item>
|
||||||
|
<item>FORALL</item>
|
||||||
|
<item>EXISTS</item>
|
||||||
|
<item>RESULT</item>
|
||||||
|
<item>OLD</item>
|
||||||
|
</list>
|
||||||
|
<list name="constants">
|
||||||
|
<item>TRUE</item>
|
||||||
|
<item>FALSE</item>
|
||||||
|
<item>NULL</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<list name="builtins">
|
||||||
|
<item>LENGTH</item>
|
||||||
|
<item>APPEND</item>
|
||||||
|
<item>INT</item>
|
||||||
|
<item>RAND</item>
|
||||||
|
<item>ABS</item>
|
||||||
|
<item>ROUND</item>
|
||||||
|
<item>MIN</item>
|
||||||
|
<item>MAX</item>
|
||||||
|
<item>ROWS</item>
|
||||||
|
<item>COLUMNS</item>
|
||||||
|
<item>SQRT</item>
|
||||||
|
<item>EXP</item>
|
||||||
|
<item>LOG</item>
|
||||||
|
<item>LOG2</item>
|
||||||
|
<item>RANDINT</item>
|
||||||
|
<item>SLICE</item>
|
||||||
|
<item>UPPER</item>
|
||||||
|
<item>LOWER</item>
|
||||||
|
<item>ORD</item>
|
||||||
|
<item>CHR</item>
|
||||||
|
<item>TO_STRING</item>
|
||||||
|
<item>TO_INTEGER</item>
|
||||||
|
<item>TO_FLOAT</item>
|
||||||
|
<item>KEYS</item>
|
||||||
|
<item>SORTED</item>
|
||||||
|
<item>INSERT</item>
|
||||||
|
<item>REMOVE</item>
|
||||||
|
<item>ADD</item>
|
||||||
|
<item>DELETE</item>
|
||||||
|
<item>SORT</item>
|
||||||
|
</list>
|
||||||
|
|
||||||
|
<contexts>
|
||||||
|
|
||||||
|
<context name="Normal" attribute="Normal Text" lineEndContext="#stay">
|
||||||
|
<DetectSpaces/>
|
||||||
|
|
||||||
|
<Detect2Chars attribute="Comment" char="/" char1="/" context="Comment"/>
|
||||||
|
|
||||||
|
<StringDetect attribute="Assignment" String="<-" context="#stay"/>
|
||||||
|
<RegExpr attribute="Assignment" String="\x{2190}" context="#stay"/>
|
||||||
|
|
||||||
|
<Detect2Chars attribute="Operator" char="=" char1="=" context="#stay"/>
|
||||||
|
<Detect2Chars attribute="Operator" char="!" char1="=" context="#stay"/>
|
||||||
|
<Detect2Chars attribute="Operator" char="<" char1="=" context="#stay"/>
|
||||||
|
<Detect2Chars attribute="Operator" char=">" char1="=" context="#stay"/>
|
||||||
|
|
||||||
|
<DetectChar attribute="String" char=""" context="StringDouble"/>
|
||||||
|
<DetectChar attribute="Char" char="'" context="CharSingle"/>
|
||||||
|
|
||||||
|
<WordDetect attribute="Declaration" String="FUNCTION" context="FunctionName"/>
|
||||||
|
<WordDetect attribute="Declaration" String="PROCEDURE" context="FunctionName"/>
|
||||||
|
<WordDetect attribute="Declaration" String="ENDFUNCTION" context="#stay"/>
|
||||||
|
<WordDetect attribute="Declaration" String="ENDPROCEDURE" context="#stay"/>
|
||||||
|
<WordDetect attribute="Declaration" String="DECLARE" context="DeclName"/>
|
||||||
|
|
||||||
|
<keyword attribute="Control Flow" String="controlflow"/>
|
||||||
|
<keyword attribute="Keyword" String="keywords"/>
|
||||||
|
<keyword attribute="IO" String="io"/>
|
||||||
|
<keyword attribute="Declaration" String="declarations"/>
|
||||||
|
<keyword attribute="Modifier" String="modifiers"/>
|
||||||
|
<keyword attribute="Data Type" String="types"/>
|
||||||
|
<keyword attribute="Constant" String="constants"/>
|
||||||
|
<keyword attribute="Reasoning" String="reasoning"/>
|
||||||
|
<keyword attribute="Builtin" String="builtins"/>
|
||||||
|
|
||||||
|
<RegExpr attribute="Float" String="\b[0-9]+\.[0-9]+\b" context="#stay"/>
|
||||||
|
<RegExpr attribute="Decimal" String="\b[0-9]+\b" context="#stay"/>
|
||||||
|
|
||||||
|
<RegExpr attribute="Function" String="\b[A-Za-z][A-Za-z0-9_]*(?=\s*\()" context="#stay"/>
|
||||||
|
|
||||||
|
<AnyChar attribute="Operator" String="+-*/<>=!^:,.[](){}&"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="Comment" attribute="Comment" lineEndContext="#pop">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<RegExpr attribute="Alert" String="\b(TODO|FIXME|NOTE)\b" context="#stay"/>
|
||||||
|
<DetectIdentifier/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="FunctionName" attribute="Normal Text" lineEndContext="#pop">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<RegExpr attribute="Function" String="[A-Za-z][A-Za-z0-9_]*" context="#pop"/>
|
||||||
|
<RegExpr attribute="Normal Text" String="." context="#pop"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="DeclName" attribute="Normal Text" lineEndContext="#pop">
|
||||||
|
<DetectSpaces/>
|
||||||
|
<RegExpr attribute="Variable" String="[A-Za-z][A-Za-z0-9_]*" context="#pop"/>
|
||||||
|
<RegExpr attribute="Normal Text" String="." context="#pop"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="StringDouble" attribute="String" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="String" char=""" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<context name="CharSingle" attribute="Char" lineEndContext="#pop">
|
||||||
|
<DetectChar attribute="Char" char="'" context="#pop"/>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
</contexts>
|
||||||
|
|
||||||
|
<itemDatas>
|
||||||
|
<itemData name="Normal Text" defStyleNum="dsNormal"/>
|
||||||
|
<itemData name="Keyword" defStyleNum="dsKeyword"/>
|
||||||
|
<itemData name="Control Flow" defStyleNum="dsControlFlow" bold="1"/>
|
||||||
|
<itemData name="Declaration" defStyleNum="dsImport"/> <!-- .im -->
|
||||||
|
<itemData name="Modifier" defStyleNum="dsAttribute"/>
|
||||||
|
<itemData name="IO" defStyleNum="dsExtension"/> <!-- .ex -->
|
||||||
|
<itemData name="Data Type" defStyleNum="dsDataType"/>
|
||||||
|
<itemData name="Builtin" defStyleNum="dsBuiltIn"/>
|
||||||
|
<itemData name="Function" defStyleNum="dsFunction"/>
|
||||||
|
<itemData name="Variable" defStyleNum="dsVariable"/>
|
||||||
|
<itemData name="Constant" defStyleNum="dsConstant"/>
|
||||||
|
<itemData name="Reasoning" defStyleNum="dsPreprocessor" bold="1"/> <!-- .pp -->
|
||||||
|
<itemData name="Decimal" defStyleNum="dsDecVal"/>
|
||||||
|
<itemData name="Float" defStyleNum="dsFloat"/>
|
||||||
|
<itemData name="String" defStyleNum="dsString"/>
|
||||||
|
<itemData name="Char" defStyleNum="dsChar"/>
|
||||||
|
<itemData name="Comment" defStyleNum="dsComment"/>
|
||||||
|
<itemData name="Alert" defStyleNum="dsAlert"/>
|
||||||
|
<itemData name="Assignment" defStyleNum="dsSpecialChar"/>
|
||||||
|
<itemData name="Operator" defStyleNum="dsOperator"/>
|
||||||
|
</itemDatas>
|
||||||
|
|
||||||
|
</highlighting>
|
||||||
|
|
||||||
|
<general>
|
||||||
|
<comments>
|
||||||
|
<comment name="singleLine" start="//"/>
|
||||||
|
</comments>
|
||||||
|
<keywords casesensitive="1"/>
|
||||||
|
</general>
|
||||||
|
|
||||||
|
</language>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# The example site: every shortcode of the extension, on real pages (quarto/README.md).
|
||||||
|
# quarto render quarto (build Programming+ first: pixi run build; or: pixi run quarto-example)
|
||||||
|
project:
|
||||||
|
type: website
|
||||||
|
output-dir: _site
|
||||||
|
render:
|
||||||
|
- example/*.qmd
|
||||||
|
|
||||||
|
website:
|
||||||
|
title: "Programming+ with Quarto"
|
||||||
|
navbar:
|
||||||
|
left:
|
||||||
|
- href: example/index.qmd
|
||||||
|
text: Rendered views
|
||||||
|
- href: example/machine.qmd
|
||||||
|
text: The machine
|
||||||
|
- href: example/live.qmd
|
||||||
|
text: Live views and listings
|
||||||
|
|
||||||
|
format:
|
||||||
|
html:
|
||||||
|
theme:
|
||||||
|
light: cosmo
|
||||||
|
dark: darkly
|
||||||
|
toc: true
|
||||||
|
|
||||||
|
syntax-definitions:
|
||||||
|
- _extensions/pplus/syntax/pseudo.xml
|
||||||
|
- _extensions/pplus/syntax/lingo.xml
|
||||||
|
- _extensions/pplus/syntax/mojo.xml
|
||||||
|
|
||||||
|
# the app the live views and the "open in the playground" links point at
|
||||||
|
pplus-url: "https://pplus.scient.ing"
|
||||||
|
# a rendered view that fails stops the render: every example on these pages must run as its header says
|
||||||
|
pplus-strict: true
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
---
|
||||||
|
title: "Rendered views"
|
||||||
|
subtitle: "Programs beside the page, run while the page renders"
|
||||||
|
---
|
||||||
|
|
||||||
|
Every view on this page was made by `quarto render`: the shortcode handed the files beside the page to Programming+'s own engines, ran them, and wrote what its views drew into the page. There is no iframe here and nothing to load. The views print, and they work offline. A program that stops printing what its `EXPECT` lines say fails the render (this site sets `pplus-strict: true`).
|
||||||
|
|
||||||
|
The programs are in the `programs/` folder beside this page, one file per notation: `count-base.pseudo`, `count-base.lingo`, `mean.tex` and the others. Each one starts with the lines the checker reads:
|
||||||
|
|
||||||
|
```pseudo
|
||||||
|
// CALL: COUNT_BASE('A', "GATTACA")
|
||||||
|
// EXPECT: COUNT_BASE returned 3
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
`pplus-run` runs the program and shows what it printed. When the program has `EXPECT` lines, the view checks the output against them.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-run pseudo="programs/count-base.pseudo" code="1" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-run pseudo="programs/count-base.pseudo" code="1" >}}
|
||||||
|
|
||||||
|
A Mojo file runs on the real `mojo` compiler when the machine that renders the page has one (inside `pixi`, the pinned one). Without one, Programming+'s interpreter runs it, and the view says which of the two printed the output.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-run mojo="programs/count-base.mojo" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-run mojo="programs/count-base.mojo" >}}
|
||||||
|
|
||||||
|
## Step through it
|
||||||
|
|
||||||
|
`pplus-steps` puts the listing beside a stepper. Each step shows the line it ran, what it wrote, and the values after it. The run happened at render time, so the page only moves through it: drag the slider, or click into the view and use ← and →.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-steps pseudo="programs/count-base.pseudo" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-steps pseudo="programs/count-base.pseudo" >}}
|
||||||
|
|
||||||
|
The same procedure in plain English. `lingo` runs as written, with the stepper on its own lines:
|
||||||
|
|
||||||
|
{{< pplus-steps lingo="programs/count-base.lingo" t="6" title="count_base, in lingo, parked at step 6" >}}
|
||||||
|
|
||||||
|
Down at the machine, the stepper follows the registers each instruction writes:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-steps asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" max="40" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-steps asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" max="40" >}}
|
||||||
|
|
||||||
|
## Pictures of the run
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-table pseudo="programs/count-base.pseudo" >}}}
|
||||||
|
{{{< pplus-flow pseudo="programs/binary-search.pseudo" >}}}
|
||||||
|
{{{< pplus-dataflow pseudo="programs/count-base.pseudo" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
The table of values is the one you would draw by hand: a column for each step that changed something, and a row for each name.
|
||||||
|
|
||||||
|
{{< pplus-table pseudo="programs/count-base.pseudo" >}}
|
||||||
|
|
||||||
|
The flowchart is drawn from the program's structure. Each box is shaded by how often its line ran, and each arrow is labeled with how often it was taken.
|
||||||
|
|
||||||
|
{{< pplus-flow pseudo="programs/binary-search.pseudo" caption="CONTAINS_SORTED([2, 5, 8, 13, 21], 13): three passes of the loop." >}}
|
||||||
|
|
||||||
|
The data-flow graph shows which names feed which:
|
||||||
|
|
||||||
|
{{< pplus-dataflow pseudo="programs/count-base.pseudo" >}}
|
||||||
|
|
||||||
|
Every rendered view can also go live. `live="click"` adds a button that swaps in the interactive view, so a reader can edit the program and run it again:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-flow pseudo="programs/count-base.pseudo" live="click" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-flow pseudo="programs/count-base.pseudo" live="click" >}}
|
||||||
|
|
||||||
|
## Mojo values, made and destroyed
|
||||||
|
|
||||||
|
`pplus-lifetimes` gives each value its own row. The row shows when the value is made, copied, moved and destroyed, as Programming+'s interpreter records it. The file's `# expect-stdout:` lines hold what the real compiler printed for it on Compiler Explorer, so the run below is checked against that.
|
||||||
|
|
||||||
|
{{< pplus-run mojo="programs/lifecycle.mojo" >}}
|
||||||
|
|
||||||
|
{{< pplus-lifetimes mojo="programs/lifecycle.mojo" >}}
|
||||||
|
|
||||||
|
## Say what must be true
|
||||||
|
|
||||||
|
`pplus-proof` checks the claims a specification makes: a pseudo program's `ENSURE` and `INVARIANT` lines, or a `.speco` file woven into it.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-proof pseudo="programs/count-base.pseudo" speco="programs/count-base.speco" code="1" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-proof pseudo="programs/count-base.pseudo" speco="programs/count-base.speco" code="1" >}}
|
||||||
|
|
||||||
|
`pplus-tests` shows the fuzzer's report for every routine. It lists the inputs it tried, the failures it found, and each failure shrunk to the smallest input that still fails.
|
||||||
|
|
||||||
|
{{< pplus-tests pseudo="programs/match-off-by-one.pseudo" >}}
|
||||||
|
|
||||||
|
## What the checker says
|
||||||
|
|
||||||
|
`pplus-check` lists what Programming+ finds in each file before anything runs, on the file's own line numbers:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-check pseudo="programs/five-bugs.pseudo" code="1" numbers="1" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-check pseudo="programs/five-bugs.pseudo" code="1" numbers="1" >}}
|
||||||
|
|
||||||
|
## One procedure, every notation
|
||||||
|
|
||||||
|
`pplus-translate` takes one file and writes the procedure in every notation it can be written in. The Mojo is generated from the pseudo and labeled as generated. With one equation:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-translate matho="programs/mean.tex" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-translate matho="programs/mean.tex" >}}
|
||||||
|
|
||||||
|
`layout="grid"` shows the same panes side by side, highlighted the way the app highlights them:
|
||||||
|
|
||||||
|
{{< pplus-translate lingo="programs/count-base.lingo" layout="grid" to="lingo,pseudo,mojo" >}}
|
||||||
|
|
||||||
|
## The machine
|
||||||
|
|
||||||
|
`pplus-machine` runs the x86-64 on the model machine and counts what it cost: instructions, cycles on two kinds of core, cache misses and branches.
|
||||||
|
|
||||||
|
{{< pplus-machine asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" >}}
|
||||||
|
|
||||||
|
## Every view by name
|
||||||
|
|
||||||
|
`pplus-view` takes the view as an option, for templates that choose it:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-view view="table" lingo="programs/count-base.lingo" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-view view="table" lingo="programs/count-base.lingo" >}}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
---
|
||||||
|
title: "Live views and listings"
|
||||||
|
subtitle: "The app in the page, and the programs as text"
|
||||||
|
---
|
||||||
|
|
||||||
|
A live view is the app itself, in an `<iframe>`, with the program carried in its URL. The reader can edit the program, step it and run it again. Their edits stay in their own browser, and **Reset** brings back the page's version. Live views need the network, where rendered views do not (see [Rendered views](index.qmd)).
|
||||||
|
|
||||||
|
## The whole playground
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-playground lingo="programs/count-base.lingo" pseudo="programs/count-base.pseudo" panel="flow" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-playground lingo="programs/count-base.lingo" pseudo="programs/count-base.pseudo" panel="flow" >}}
|
||||||
|
|
||||||
|
Arrange it the way the playground's own controls do: the area, the tab it opens on, the build, the dock and the splits.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-playground mojo="programs/count-base.mojo" area="dev" panel="compiler" dock="open" editor="0.6" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
## One view of it
|
||||||
|
|
||||||
|
`pplus-embed` shows one view with the code it reads. The views are `trace`, `table`, `flow`, `data`, `life`, `problems`, `proof`, `tests`, `compiler` and `asm`, or the name of a pane to show only that editor.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-embed pseudo="programs/count-base.pseudo" view="trace" t="9" >}}}
|
||||||
|
{{{< pplus-embed pseudo="programs/binary-search.pseudo" view="flow" height="auto" showcall="0" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-embed pseudo="programs/count-base.pseudo" view="trace" t="9" >}}
|
||||||
|
|
||||||
|
The original shortcode, `{{{< pplus >}}}`, still works as it did. It takes the same options as `pplus-embed`, plus `show="listing"` and `show="both"`.
|
||||||
|
|
||||||
|
## Listings
|
||||||
|
|
||||||
|
`pplus-listing` prints the files as code blocks, highlighted by the syntax definitions the extension ships. The header lines (`// CALL:`, `// EXPECT:`) are left out, and a `.tex` file is typeset as equations.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-listing pseudo="programs/count-base.pseudo" numbers="1" >}}}
|
||||||
|
{{{< pplus-listing matho="programs/mean.tex" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-listing pseudo="programs/count-base.pseudo" numbers="1" >}}
|
||||||
|
|
||||||
|
{{< pplus-listing matho="programs/mean.tex" >}}
|
||||||
|
|
||||||
|
`pplus-tabs` gives the files one tab each:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-tabs lingo="programs/count-base.lingo" pseudo="programs/count-base.pseudo" mojo="programs/count-base.mojo" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-tabs lingo="programs/count-base.lingo" pseudo="programs/count-base.pseudo" mojo="programs/count-base.mojo" >}}
|
||||||
|
|
||||||
|
## A link
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-link pseudo="programs/count-base.pseudo" text="Open count_base in Programming+" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-link pseudo="programs/count-base.pseudo" text="Open count_base in Programming+" >}}
|
||||||
|
|
||||||
|
## Folded away
|
||||||
|
|
||||||
|
Any shortcode takes `collapse="1"`, which folds it into a block the reader opens:
|
||||||
|
|
||||||
|
{{< pplus-steps pseudo="programs/binary-search.pseudo" collapse="1" title="Show the binary search, step by step" >}}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
---
|
||||||
|
title: "The machine"
|
||||||
|
subtitle: "x86-64 on a model machine, every step drawn with the page"
|
||||||
|
---
|
||||||
|
|
||||||
|
These shortcodes show what the Hardware area's board shows: the registers, memory, the caches, the pipeline and the core, running an x86-64 file beside the page. While Quarto renders, the extension runs the program on the model machine and draws each view at every step of the run. The page carries those drawings, compressed, and the stepper moves through them. Nothing runs in the reader's browser, and the page opens on the step you choose, so it prints too.
|
||||||
|
|
||||||
|
The program is `programs/two-pointers.asm`: it counts the values two sorted lists have in common. Its registers and memory are set by `programs/two-pointers.setup`:
|
||||||
|
|
||||||
|
```
|
||||||
|
rdi = 0x1000 rsi = 6 rdx = 0x2000 rcx = 7
|
||||||
|
memory 0x1000 bytes 1 0 0 0 0 0 0 0 4 0 ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## The board
|
||||||
|
|
||||||
|
`pplus-hw` puts the listing beside a set of cards. With no options, it uses the board's first arrangement: registers, flags, address arithmetic, memory and the stack.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-hw asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-hw asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" >}}
|
||||||
|
|
||||||
|
`preset=` picks one of the board's other arrangements: `caches`, `pipeline` or `chip`. `views=` names the cards yourself, in order, and `t=` is the step the page opens on:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-hw asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" preset="caches" t="12" >}}}
|
||||||
|
{{{< pplus-hw asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" views="explain,registers,encoding" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-hw asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" preset="caches" t="12" title="The caches, at step 12" >}}
|
||||||
|
|
||||||
|
## One view at a time
|
||||||
|
|
||||||
|
Each card of the board is also a shortcode of its own, `pplus-hw-<view>`:
|
||||||
|
|
||||||
|
| shortcode | shows |
|
||||||
|
|---|---|
|
||||||
|
| `pplus-hw-code` | the machine code: each instruction with its address and bytes |
|
||||||
|
| `pplus-hw-explain` | the last instruction in words: what it read, computed and wrote |
|
||||||
|
| `pplus-hw-registers`, `pplus-hw-flags` | the registers the program touches, and ZF, SF, CF, OF, PF |
|
||||||
|
| `pplus-hw-address` | base + index × scale + displacement, part by part |
|
||||||
|
| `pplus-hw-memory`, `pplus-hw-stack` | memory byte by byte, and the stack's slots |
|
||||||
|
| `pplus-hw-dataflow`, `pplus-hw-alu` | where the last instruction's values came from, and the ALU at bit level |
|
||||||
|
| `pplus-hw-branches`, `pplus-hw-vectors` | each branch and the predictor's guess, and the xmm registers lane by lane |
|
||||||
|
| `pplus-hw-lines`, `pplus-hw-cache`, `pplus-hw-hierarchy` | the cache line each access touched, the L1 data cache, and the path through L1, L2, L3 and memory |
|
||||||
|
| `pplus-hw-paging` | the page walk and the TLB (it switches virtual memory on) |
|
||||||
|
| `pplus-hw-pipeline`, `pplus-hw-uops`, `pplus-hw-timeline`, `pplus-hw-bottleneck` | the five-stage pipeline, micro-ops and ports, the out-of-order timeline, and what limits the speed |
|
||||||
|
| `pplus-hw-counters` | the run as totals, in the style of `perf stat` |
|
||||||
|
| `pplus-hw-chip`, `pplus-hw-core`, `pplus-hw-encoding` | the whole core lit up, inside the out-of-order core, and the instruction's bytes field by field |
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
{{{< pplus-hw-pipeline asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" listing="0" max="40" >}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
{{< pplus-hw-pipeline asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" listing="0" max="40" >}}
|
||||||
|
|
||||||
|
The whole core, with the parts the last instruction used lit up:
|
||||||
|
|
||||||
|
{{< pplus-hw-chip asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" t="9" >}}
|
||||||
|
|
||||||
|
Virtual memory: the page walk and the TLB. `pplus-hw-paging` turns virtual memory on for the run.
|
||||||
|
|
||||||
|
{{< pplus-hw-paging asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" t="10" >}}
|
||||||
|
|
||||||
|
`stepper="0"` draws one step and nothing else, which suits a figure in a printed handout:
|
||||||
|
|
||||||
|
{{< pplus-hw-encoding asm="programs/two-pointers.asm" setup="programs/two-pointers.setup" t="9" stepper="0" listing="0" caption="Step 9, mov r11, qword ptr [rdx + r9*8], byte by byte." >}}
|
||||||
|
|
||||||
|
## From Mojo to the machine
|
||||||
|
|
||||||
|
`pixi run quarto-export demo <folder>` writes a Mojo program's x86-64, from the real compiler's listing, beside a page, along with a setup for its arguments. Here it is the `cell` function of the demo's Smith-Waterman alignment (`programs/cell.asm`): the best of three scores, with three branch-free `cmovg`s. Each instruction's comment names the Mojo line it came from.
|
||||||
|
|
||||||
|
{{< pplus-hw asm="programs/cell.asm" setup="programs/cell.setup" views="explain,registers,flags" >}}
|
||||||
|
|
||||||
|
{{< pplus-hw-counters asm="programs/cell.asm" setup="programs/cell.setup" listing="0" stepper="0" >}}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// CALL: CONTAINS_SORTED([2, 5, 8, 13, 21], 13)
|
||||||
|
// EXPECT: CONTAINS_SORTED returned TRUE
|
||||||
|
// Is X in the sorted list L? Halve the range that could hold it each time.
|
||||||
|
FUNCTION CONTAINS_SORTED(L : LIST OF INTEGER, X : INTEGER) RETURNS BOOL
|
||||||
|
REQUIRE FORALL K IN [0, LENGTH(L) - 1) : L[K] <= L[K + 1]
|
||||||
|
DECLARE Lo : INTEGER
|
||||||
|
DECLARE Hi : INTEGER
|
||||||
|
DECLARE Mid : INTEGER
|
||||||
|
Lo <- 0
|
||||||
|
Hi <- LENGTH(L)
|
||||||
|
WHILE Lo < Hi
|
||||||
|
INVARIANT 0 <= Lo AND Lo <= Hi AND Hi <= LENGTH(L)
|
||||||
|
DECREASES Hi - Lo
|
||||||
|
Mid <- (Lo + Hi) DIV 2
|
||||||
|
IF L[Mid] == X THEN
|
||||||
|
RETURN TRUE
|
||||||
|
ELSEIF L[Mid] < X THEN
|
||||||
|
Lo <- Mid + 1
|
||||||
|
ELSE
|
||||||
|
Hi <- Mid
|
||||||
|
ENDIF
|
||||||
|
ENDWHILE
|
||||||
|
RETURN FALSE
|
||||||
|
ENDFUNCTION
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
cell: ; cell(Int, Int, Int)
|
||||||
|
xor eax, eax ; mojo line 9
|
||||||
|
cmp rdi, 0 ; mojo line 9
|
||||||
|
cmovg rax, rdi ; mojo line 9
|
||||||
|
cmp rsi, rax ; mojo line 11
|
||||||
|
cmovg rax, rsi ; mojo line 11
|
||||||
|
cmp rdx, rax ; mojo line 13
|
||||||
|
cmovg rax, rdx ; mojo line 13
|
||||||
|
ret ; mojo line 15
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# cell(Int, Int, Int): the arguments arrive in rdi, rsi, rdx (System V)
|
||||||
|
# the diagonal 4, a gap in the reference 9, a gap in the read -2: the cell keeps 9
|
||||||
|
rdi = 4
|
||||||
|
rsi = 9
|
||||||
|
rdx = -2
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// CALL: COUNT_BASES('A', "GATTACA")
|
||||||
|
// EXPECT: COUNT_BASES returned 3
|
||||||
|
To count the B bases in T:
|
||||||
|
Start with Count at 0.
|
||||||
|
For each letter c of T:
|
||||||
|
If c is B, add 1 to Count.
|
||||||
|
The answer is Count.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# origin: Programming+ exercise count-base (was translations.mojo, by course staff)
|
||||||
|
# status: unverified; Stage 1 verifies it on the pinned compiler
|
||||||
|
# probe: does the course's hand-written count_base compile and agree with the pseudo?
|
||||||
|
# expect-stdout: 3
|
||||||
|
def count_base(b: String, t: String) -> Int:
|
||||||
|
var total = 0
|
||||||
|
for i in range(t.count_codepoints()):
|
||||||
|
if String(t[codepoint=i]) == b:
|
||||||
|
total += 1
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(count_base("A", "GATTACA"))
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// CALL: COUNT_BASE('A', "GATTACA")
|
||||||
|
// EXPECT: COUNT_BASE returned 3
|
||||||
|
// How many positions of T hold the base B.
|
||||||
|
FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER
|
||||||
|
|
||||||
|
// Set up
|
||||||
|
DECLARE N : INTEGER
|
||||||
|
DECLARE Total : INTEGER
|
||||||
|
N <- LENGTH(T)
|
||||||
|
Total <- 0
|
||||||
|
|
||||||
|
// Visit each position
|
||||||
|
FOR I <- 0 TO N
|
||||||
|
|
||||||
|
// Test this position
|
||||||
|
IF T[I] == B THEN
|
||||||
|
|
||||||
|
// Update the running total
|
||||||
|
Total <- Total + 1
|
||||||
|
|
||||||
|
ENDIF
|
||||||
|
NEXT I
|
||||||
|
|
||||||
|
// Report
|
||||||
|
RETURN Total
|
||||||
|
ENDFUNCTION
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
SPEC COUNT_BASE(B, T)
|
||||||
|
ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|
|
||||||
|
LOOP FOR I
|
||||||
|
INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// CALL: COUNT_GC("GATTACA")
|
||||||
|
// ERRORS: 2
|
||||||
|
// Count the G and C bases in T. This version has five mistakes;
|
||||||
|
// the coach finds all of them before anything runs.
|
||||||
|
FUNCTION COUNT_GC(T : STRING) RETURNS INTEGER
|
||||||
|
DECLARE Total : INTEGER
|
||||||
|
DECLARE Unused : FLOAT
|
||||||
|
FOR I <- 0 TO LENGTH(T) - 1
|
||||||
|
Total <- 0
|
||||||
|
IF T[I] == "G" OR T[I] == 'C' THEN
|
||||||
|
Total = Total + 1
|
||||||
|
ENDIF
|
||||||
|
NEXT I
|
||||||
|
RETURN Total
|
||||||
|
ENDFUNCTION
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# probe: copy and move constructors through var arguments and transfers
|
||||||
|
# status: the expected output is Programming+'s interpreter's prediction; corpus.py verify confirms or refutes it on godbolt
|
||||||
|
# expect-stdout: new a
|
||||||
|
# expect-stdout: copy a
|
||||||
|
# expect-stdout: consumed a+
|
||||||
|
# expect-stdout: free a+
|
||||||
|
# expect-stdout: move a
|
||||||
|
# expect-stdout: holding a
|
||||||
|
# expect-stdout: free a
|
||||||
|
struct Box(Copyable, Movable):
|
||||||
|
var label: String
|
||||||
|
|
||||||
|
def __init__(out self, label: String):
|
||||||
|
self.label = label
|
||||||
|
print("new", label)
|
||||||
|
|
||||||
|
def __init__(out self, *, copy: Self):
|
||||||
|
self.label = copy.label + "+"
|
||||||
|
print("copy", copy.label)
|
||||||
|
|
||||||
|
def __init__(out self, *, deinit move: Self):
|
||||||
|
self.label = move.label^
|
||||||
|
print("move", self.label)
|
||||||
|
|
||||||
|
def __deinit__(deinit self):
|
||||||
|
print("free", self.label)
|
||||||
|
|
||||||
|
|
||||||
|
def consume(var b: Box):
|
||||||
|
print("consumed", b.label)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
var a = Box("a")
|
||||||
|
var b = a.copy()
|
||||||
|
consume(b^)
|
||||||
|
var c = a^
|
||||||
|
print("holding", c.label)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// CALL: MATCH("ATT", "GATTACA")
|
||||||
|
// STOPS: index
|
||||||
|
// One bound is wrong. Every position where pattern P occurs exactly in text T.
|
||||||
|
FUNCTION MATCH(P : STRING, T : STRING) RETURNS LIST OF INTEGER
|
||||||
|
|
||||||
|
// Set up
|
||||||
|
DECLARE N : INTEGER
|
||||||
|
DECLARE M : INTEGER
|
||||||
|
DECLARE Matched : BOOL
|
||||||
|
DECLARE Answer : LIST OF INTEGER
|
||||||
|
N <- LENGTH(T)
|
||||||
|
M <- LENGTH(P)
|
||||||
|
|
||||||
|
// Visit each legal start
|
||||||
|
FOR I <- 0 TO N
|
||||||
|
|
||||||
|
// Test: does the pattern match here?
|
||||||
|
Matched <- TRUE
|
||||||
|
FOR J <- 0 TO M
|
||||||
|
IF T[I + J] != P[J] THEN
|
||||||
|
Matched <- FALSE
|
||||||
|
BREAK
|
||||||
|
ENDIF
|
||||||
|
NEXT J
|
||||||
|
|
||||||
|
// Update
|
||||||
|
IF Matched THEN
|
||||||
|
APPEND(Answer, I)
|
||||||
|
ENDIF
|
||||||
|
NEXT I
|
||||||
|
|
||||||
|
RETURN Answer
|
||||||
|
ENDFUNCTION
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
% CALL: X_BAR(3, [1.0, 2.0, 6.0])
|
||||||
|
% EXPECT: X_BAR returned 3.0
|
||||||
|
\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
; rdi = list A rsi = |A| rdx = list B rcx = |B|
|
||||||
|
; rax = how many values appear in both
|
||||||
|
xor eax, eax
|
||||||
|
xor r8, r8
|
||||||
|
xor r9, r9
|
||||||
|
.step:
|
||||||
|
cmp r8, rsi
|
||||||
|
jae .done
|
||||||
|
cmp r9, rcx
|
||||||
|
jae .done
|
||||||
|
mov r10, qword ptr [rdi + r8*8]
|
||||||
|
mov r11, qword ptr [rdx + r9*8]
|
||||||
|
cmp r10, r11
|
||||||
|
je .both
|
||||||
|
jb .advanceA
|
||||||
|
add r9, 1 ; the second list is behind
|
||||||
|
jmp .step
|
||||||
|
.advanceA:
|
||||||
|
add r8, 1 ; the first list is behind
|
||||||
|
jmp .step
|
||||||
|
.both:
|
||||||
|
add rax, 1
|
||||||
|
add r8, 1
|
||||||
|
add r9, 1
|
||||||
|
jmp .step
|
||||||
|
.done:
|
||||||
|
ret
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
rdi = 0x1000
|
||||||
|
rsi = 6
|
||||||
|
rdx = 0x2000
|
||||||
|
rcx = 7
|
||||||
|
memory 0x1000 bytes 1 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 13 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0
|
||||||
|
memory 0x2000 bytes 2 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
*
|
||||||
|
!.gitignore
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
// The assembled site's index.html, from the one in the repository: scripts/assemble.sh runs this on site/.
|
||||||
|
// node scripts/assemble-page.mjs <site-dir>
|
||||||
|
// It adds two things a checkout served as it is (pixi run dev) does without:
|
||||||
|
// - <meta name="pplus-version">, the commit in site/VERSION, which the footer shows (no request needed);
|
||||||
|
// - a <link rel="modulepreload"> for every module the page's static import graph reaches. Without a bundler the
|
||||||
|
// browser finds the modules one level of imports at a time, so a first visit waits for a chain of round trips
|
||||||
|
// (six levels today); with the list it asks for them all at once. The links go after the import map, which a
|
||||||
|
// browser must have read before it loads any module.
|
||||||
|
// Nothing else in the page changes, so the hashes of its inline scripts (docs/Caddyfile's CSP) still hold.
|
||||||
|
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
|
||||||
|
import { resolve, dirname, relative, join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const IMPORT = /(?:^|[;\n}])\s*(?:import|export)\s*(?:[\w*{}\s,$]*?\sfrom\s*)?['"]([^'"]+)['"]/g;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every module the page's entry imports, directly or through others, as hrefs relative to the page ('./dist/…',
|
||||||
|
* './core/dist/…'), shallowest first; the entry itself is not listed (its own <script> loads it).
|
||||||
|
* @param {string} root the directory that holds index.html, dist/ and core/dist/
|
||||||
|
* @param {string} [entry] the entry module, relative to root
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function modulePreloads(root, entry = 'dist/main.js') {
|
||||||
|
const coreDist = resolve(root, 'core/dist');
|
||||||
|
const target = (from, spec) => spec.startsWith('#core/') ? join(coreDist, spec.slice('#core/'.length)) : spec.startsWith('.') ? resolve(dirname(from), spec) : null;
|
||||||
|
const start = resolve(root, entry);
|
||||||
|
const depth = new Map([[start, 0]]);
|
||||||
|
const queue = [start];
|
||||||
|
while (queue.length) {
|
||||||
|
const file = queue.shift();
|
||||||
|
const src = readFileSync(file, 'utf8');
|
||||||
|
for (const m of src.matchAll(IMPORT)) {
|
||||||
|
const t = target(file, m[1]);
|
||||||
|
if (!t || depth.has(t)) continue;
|
||||||
|
if (!existsSync(t)) throw new Error(`${relative(root, file)} imports ${m[1]}, which is not in ${root}`);
|
||||||
|
depth.set(t, depth.get(file) + 1);
|
||||||
|
queue.push(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...depth].filter(([f]) => f !== start).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1)).map(([f]) => `./${relative(root, f).split('\\').join('/')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The page with the version and the preloads in it.
|
||||||
|
* @param {string} html index.html as the repository has it
|
||||||
|
* @param {{ version?: string | null, preloads?: string[] }} parts
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function assemblePage(html, { version = null, preloads = [] } = {}) {
|
||||||
|
let out = html;
|
||||||
|
if (version && /^[0-9a-f]{7,40}$/.test(version)) out = out.replace(/\n<\/head>/, `\n <meta name="pplus-version" content="${version}">\n</head>`);
|
||||||
|
const map = /<script type="importmap">[^<]*<\/script>\n/.exec(out);
|
||||||
|
if (!map) throw new Error('index.html has no import map: the preloads go after it');
|
||||||
|
const links = preloads.map((h) => ` <link rel="modulepreload" href="${h}">\n`).join('');
|
||||||
|
return out.slice(0, map.index + map[0].length) + links + out.slice(map.index + map[0].length);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const site = resolve(process.argv[2] ?? 'site');
|
||||||
|
const page = join(site, 'index.html');
|
||||||
|
const versionFile = join(site, 'VERSION');
|
||||||
|
const version = existsSync(versionFile) ? readFileSync(versionFile, 'utf8').trim() : null;
|
||||||
|
const preloads = modulePreloads(site);
|
||||||
|
writeFileSync(page, assemblePage(readFileSync(page, 'utf8'), { version, preloads }));
|
||||||
|
console.log(`index.html: ${preloads.length} module preloads${version ? `, version ${version.slice(0, 12)}` : ''}`);
|
||||||
|
}
|
||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
# Assemble the deployable site into ./site: what a static host needs (the page, its styles and fonts, dist/, pplus-core's
|
||||||
|
# core/dist/ that the page's import map points at, and the Quarto extension).
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
rm -rf site && mkdir -p site
|
||||||
|
cp -r index.html styles.css styles fonts dist site/
|
||||||
|
rm -f site/styles/course/README.md # the provenance notes stay in the repository (the fonts' LICENSE.txt goes with them)
|
||||||
|
# the license and the third-party notices go with the files they cover (CodeMirror's MIT notices among them)
|
||||||
|
cp LICENSE.md NOTICE.md THIRD_PARTY.md site/
|
||||||
|
# pplus-core's built modules, without source maps, declarations, or the lesson corpus (a test fixture)
|
||||||
|
mkdir -p site/core
|
||||||
|
cp -r core/dist site/core/
|
||||||
|
find site/core/dist \( -name '*.map' -o -name '*.d.ts' \) -delete
|
||||||
|
rm -rf site/core/dist/curriculum
|
||||||
|
# the Quarto extension, which the "With Quarto" page loads (pplus.css, pplus.js) and links to, file by file
|
||||||
|
mkdir -p site/quarto/_extensions
|
||||||
|
cp -r quarto/_extensions/pplus site/quarto/_extensions/
|
||||||
|
rm -rf site/quarto/_extensions/pplus/engine
|
||||||
|
printf '%s\n' "${GITHUB_SHA:-$(git rev-parse HEAD 2>/dev/null || echo dev)}" > site/VERSION
|
||||||
|
# the three commits it was built from (web, core, library), their versions and the pinned Mojo (scripts/build-info.mjs)
|
||||||
|
node scripts/build-info.mjs > site/build.json
|
||||||
|
# the page names the commit (the footer shows it) and preloads every module its imports reach (scripts/assemble-page.mjs)
|
||||||
|
node scripts/assemble-page.mjs site
|
||||||
|
echo "site/ assembled ($(du -sh site | cut -f1))"
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* What a built site is made of, as JSON: the version and commit of each of the three repositories, and the Mojo the
|
||||||
|
* corpus is pinned to. scripts/assemble.sh writes it to site/build.json beside VERSION (which stays the site's own
|
||||||
|
* commit, for the deploy's smoke test), so the live site can say exactly which commits it was built from.
|
||||||
|
*
|
||||||
|
* node scripts/build-info.mjs print it
|
||||||
|
*
|
||||||
|
* A version is the one package.json states (pplus-library has none: its commit is its version); `describe` is
|
||||||
|
* `git describe --tags --always --dirty`, so a tagged release reads as its tag and a change not yet committed says
|
||||||
|
* so. Outside a git checkout a commit is null. GITHUB_SHA, when CI sets it, is the site's commit.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const WEB = fileURLToPath(new URL('..', import.meta.url));
|
||||||
|
|
||||||
|
function git(dir, ...args) {
|
||||||
|
const r = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8' });
|
||||||
|
return r.status === 0 ? r.stdout.trim() : null;
|
||||||
|
}
|
||||||
|
const version = (dir) => { try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version ?? null; } catch { return null; } };
|
||||||
|
|
||||||
|
/** One repository's entry. */
|
||||||
|
function repo(dir, name) {
|
||||||
|
return { name, version: version(dir), commit: git(dir, 'rev-parse', 'HEAD'), describe: git(dir, 'describe', '--tags', '--always', '--dirty') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The build's description: web, core and library, and the pinned Mojo. */
|
||||||
|
export function buildInfo(web = WEB) {
|
||||||
|
const core = path.join(web, 'core');
|
||||||
|
const lib = path.join(core, 'library');
|
||||||
|
const site = repo(web, 'pplus-web');
|
||||||
|
if (process.env.GITHUB_SHA && !site.commit) site.commit = process.env.GITHUB_SHA;
|
||||||
|
let mojo = null;
|
||||||
|
try { mojo = JSON.parse(fs.readFileSync(path.join(lib, 'mojo', 'pin.json'), 'utf8')).mojo.version; } catch { /* no library checked out */ }
|
||||||
|
return { web: site, core: repo(core, 'pplus-core'), library: repo(lib, 'pplus-library'), mojo };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
process.stdout.write(`${JSON.stringify(buildInfo(), null, 2)}\n`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
// Serve an assembled site/ with a real Caddy under docs/Caddyfile's own rules, and hold what it answers: the
|
||||||
|
// security headers on every answer, what a browser may keep, and where a path that is not a file goes. The tests
|
||||||
|
// read the Caddyfile as text (tests/csp.test.mjs); only Caddy says what it does with it.
|
||||||
|
//
|
||||||
|
// pixi run caddy-check assemble site/ first (pixi run site), then this
|
||||||
|
//
|
||||||
|
// Caddy comes from `pixi exec` (conda-forge), so the first run needs the network; nothing else does. The site block
|
||||||
|
// is the document's own, with two lines changed: the host (localhost, plain HTTP) and the root (./site).
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
const PORT = Number(process.env.CADDY_CHECK_PORT || 8767);
|
||||||
|
const base = `http://127.0.0.1:${PORT}`;
|
||||||
|
if (!fs.existsSync('site/index.html')) { console.error('site/ is not assembled: run `pixi run site` (or scripts/assemble.sh) first'); process.exit(2); }
|
||||||
|
const doc = fs.readFileSync('docs/Caddyfile', 'utf8');
|
||||||
|
const host = /^[a-z0-9.-]+\.[a-z]+ \{$/m.exec(doc);
|
||||||
|
if (!host || !doc.includes('root * /srv/www/pplus')) { console.error('docs/Caddyfile no longer has the site block this script rewrites'); process.exit(2); }
|
||||||
|
const local = `{\n admin off\n auto_https off\n}\n${doc.replace(host[0], `http://127.0.0.1:${PORT} {`).replace('root * /srv/www/pplus', `root * ${path.resolve('site')}`)}`;
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-caddy-'));
|
||||||
|
const file = path.join(dir, 'Caddyfile');
|
||||||
|
fs.writeFileSync(file, local);
|
||||||
|
|
||||||
|
const caddy = spawn('pixi', ['exec', '-s', 'caddy>=2.8', '--', 'caddy', 'run', '--config', file, '--adapter', 'caddyfile'], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||||
|
let log = '';
|
||||||
|
caddy.stderr.on('data', (d) => { log += d; });
|
||||||
|
const stop = () => { try { caddy.kill('SIGTERM'); } catch { /* already gone */ } fs.rmSync(dir, { recursive: true, force: true }); };
|
||||||
|
process.on('exit', stop);
|
||||||
|
|
||||||
|
const get = (p, headers = {}) => fetch(base + p, { redirect: 'manual', headers });
|
||||||
|
let up = false;
|
||||||
|
for (let i = 0; i < 120 && !up; i++) { try { await get('/VERSION'); up = true; } catch { await new Promise((r) => setTimeout(r, 500)); } }
|
||||||
|
if (!up) { console.error(`Caddy did not start:\n${log.slice(-2000)}`); process.exit(2); }
|
||||||
|
|
||||||
|
const problems = [];
|
||||||
|
const SECURITY = ['content-security-policy', 'referrer-policy', 'x-content-type-options', 'permissions-policy'];
|
||||||
|
/** One request, held to a status and to headers (a string must equal; a RegExp must match; null must be absent). */
|
||||||
|
async function check(what, p, status, want = {}, reqHeaders = {}) {
|
||||||
|
const r = await get(p, reqHeaders);
|
||||||
|
await r.arrayBuffer();
|
||||||
|
if (r.status !== status) problems.push(`${what}: ${p} answered ${r.status}, not ${status}`);
|
||||||
|
for (const h of SECURITY) if (!r.headers.get(h)) problems.push(`${what}: ${p} has no ${h}`);
|
||||||
|
for (const [h, v] of Object.entries(want)) {
|
||||||
|
const got = r.headers.get(h);
|
||||||
|
const ok = v === null ? got === null : v instanceof RegExp ? v.test(got ?? '') : got === v;
|
||||||
|
if (!ok) problems.push(`${what}: ${p} has ${h}: ${got}, not ${v}`);
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
const font = fs.readdirSync('site/fonts').find((f) => f.endsWith('.woff2'));
|
||||||
|
const page = await check('the page', '/', 200, { 'cache-control': 'no-cache', 'content-type': /^text\/html/, etag: /./ });
|
||||||
|
await check('the page by name', '/index.html', 200, { 'cache-control': 'no-cache' });
|
||||||
|
const js = await check('a module', '/dist/main.js', 200, { 'cache-control': 'no-cache', 'content-type': /javascript/, etag: /./ });
|
||||||
|
await check('a module, unchanged', '/dist/main.js', 304, { 'cache-control': 'no-cache' }, { 'if-none-match': js.headers.get('etag') });
|
||||||
|
await check('a module of core', '/core/dist/services/pseudo.js', 200, { 'cache-control': 'no-cache' });
|
||||||
|
await check('the stylesheet', '/styles.css', 200, { 'cache-control': 'no-cache', 'content-type': /^text\/css/ });
|
||||||
|
await check('a font', `/fonts/${font}`, 200, { 'cache-control': 'public, max-age=2592000', 'content-type': 'font/woff2' });
|
||||||
|
await check('VERSION', '/VERSION', 200, { 'cache-control': 'no-store' });
|
||||||
|
await check('build.json', '/build.json', 200, { 'cache-control': 'no-cache', 'content-type': /json/ });
|
||||||
|
for (const f of ['LICENSE.md', 'NOTICE.md', 'THIRD_PARTY.md']) await check('a notice', `/${f}`, 200, { 'content-type': 'text/plain; charset=utf-8' });
|
||||||
|
// a path that is not a file: a page goes to /, a file is a plain 404, and neither is kept
|
||||||
|
for (const p of ['/no/such/page', '/bridge', '/old/link?x=1']) await check('a missing page', p, 302, { location: '/', 'cache-control': 'no-store' });
|
||||||
|
for (const p of ['/dist/gone.js', '/fonts/gone.woff2', '/styles/gone.css']) await check('a missing file', p, 404, { 'cache-control': 'no-store', 'content-type': /^text\/plain/ });
|
||||||
|
// the CSP the server sends is the one the tests hold to index.html's inline scripts
|
||||||
|
const csp = page.headers.get('content-security-policy') ?? '';
|
||||||
|
for (const part of ["default-src 'self'", "frame-ancestors", 'https://godbolt.org']) if (!csp.includes(part)) problems.push(`the CSP Caddy sends has no ${part}`);
|
||||||
|
|
||||||
|
stop();
|
||||||
|
if (problems.length) { console.error(problems.join('\n')); console.error(`\n${problems.length} thing(s) wrong`); process.exit(1); }
|
||||||
|
console.log(`Caddy serves site/ as docs/Caddyfile says: security headers on every answer, caching per kind of file, a missing page sent to /, a missing file a plain 404`);
|
||||||
|
process.exit(0);
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
// Check every program a Quarto site embeds with the extension's shortcodes ({{< pplus-run >}}, {{< pplus >}}, ...):
|
||||||
|
// the .lingo, .pseudo, .speco, .tex and .mojo files next to the pages, and the shortcodes that name them, run
|
||||||
|
// through this repository's own engines (build first: pixi run build).
|
||||||
|
//
|
||||||
|
// node scripts/check-pages.mjs /path/to/site/programmingplus [more folders ...]
|
||||||
|
//
|
||||||
|
// Set PPLUS_DIR to use another checkout's dist/ (and its core/dist/); set CHECK_FILES_ONLY=1 to only check that the files
|
||||||
|
// the shortcodes name exist (no engine needed).
|
||||||
|
//
|
||||||
|
// A program file may carry expectations in comment lines at the top:
|
||||||
|
// // CALL: COUNT_BASE('A', "GATTACA") the call to run (pseudo and lingo; otherwise the engine's default)
|
||||||
|
// // INPUT: 4000 a line INPUT reads (repeatable)
|
||||||
|
// // EXPECT: 3 a line of output, in order (repeatable; a Mojo file may write # expect-stdout:); the call's result
|
||||||
|
// counts as "<NAME> returned <value>"
|
||||||
|
// // ERRORS: 1 the program is meant to be refused with this many errors
|
||||||
|
// // STOPS: race the run is meant to stop with this kind of error (race, contract, bounds, ...)
|
||||||
|
// // QUESTION: range-ends lingo: the reader is meant to ask this question
|
||||||
|
// A lingo file is also lowered to pseudo, and that pseudo must check. A .tex file (LaTeX equations) uses
|
||||||
|
// % instead of // for its header lines, is translated to pseudo, and that pseudo must check and run.
|
||||||
|
// A .mojo file uses # for its header lines. It must be free of syntax the pinned Mojo removed (fn, read),
|
||||||
|
// and when a `mojo` compiler is on the PATH (inside pixi, which pins it) it is built and run for real:
|
||||||
|
// it must exit 0 and print its EXPECT lines, or, with ERRORS, fail to compile.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
|
||||||
|
const here = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
|
||||||
|
const root = process.cwd();
|
||||||
|
const folders = process.argv.slice(2);
|
||||||
|
if (!folders.length) { console.error('usage: node scripts/check-pages.mjs <folder with .qmd pages> [...]'); process.exit(2); }
|
||||||
|
const pplusDir = process.env.CHECK_FILES_ONLY ? null : (process.env.PPLUS_DIR || here);
|
||||||
|
|
||||||
|
function walk(dir, out = []) {
|
||||||
|
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
if (e.name.startsWith('_') || e.name.startsWith('.')) continue;
|
||||||
|
const p = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) walk(p, out); else out.push(p);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the live shortcodes' view= values (src/core/state.ts EMBED_VIEWS), and pplus-view's (src/quarto/render.ts
|
||||||
|
// STATIC_VIEWS), kept here so CHECK_FILES_ONLY needs no build; tests/quarto.test.mjs holds them to the app's
|
||||||
|
const EMBED_VIEWS = new Set(['playground', 'trace', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'problems', 'compiler', 'asm', 'lingo', 'matho', 'pseudo', 'speco', 'mojo']);
|
||||||
|
const STATIC_VIEWS = new Set(['run', 'steps', 'table', 'flow', 'data', 'dataflow', 'life', 'lifetimes', 'proof', 'tests', 'check', 'translate', 'machine', 'hw']);
|
||||||
|
// the machine's views, pplus-hw-<view> (src/quarto/machine.ts HW_NAMES), also what pplus-hw's views= may name
|
||||||
|
const HW_VIEWS = ['code', 'explain', 'registers', 'flags', 'address', 'memory', 'stack', 'dataflow', 'alu', 'branches', 'vectors', 'lines', 'cache', 'hierarchy', 'paging', 'pipeline', 'uops', 'timeline', 'bottleneck', 'counters', 'chip', 'core', 'encoding'];
|
||||||
|
// every shortcode of the extension (src/quarto/shortcodes.ts SHORTCODE_NAMES)
|
||||||
|
const SHORTCODES = new Set(['pplus', 'pplus-embed', 'pplus-playground', 'pplus-view', 'pplus-run', 'pplus-steps', 'pplus-table', 'pplus-flow', 'pplus-dataflow', 'pplus-lifetimes', 'pplus-proof', 'pplus-tests', 'pplus-check', 'pplus-translate', 'pplus-machine', 'pplus-hw', ...HW_VIEWS.map((v) => `pplus-hw-${v}`), 'pplus-listing', 'pplus-tabs', 'pplus-link']);
|
||||||
|
|
||||||
|
const files = folders.flatMap((f) => walk(path.resolve(root, f)));
|
||||||
|
const pages = files.filter((f) => f.endsWith('.qmd'));
|
||||||
|
const programs = files.filter((f) => /\.(lingo|pseudo|speco|tex|mojo)$/.test(f));
|
||||||
|
let failures = 0;
|
||||||
|
const fail = (where, msg) => { failures++; console.log(`✗ ${path.relative(root, where)}: ${msg}`); };
|
||||||
|
|
||||||
|
// 1. shortcodes name files that exist
|
||||||
|
const referenced = new Set();
|
||||||
|
for (const page of pages) {
|
||||||
|
const text = fs.readFileSync(page, 'utf8');
|
||||||
|
// {{< pplus-name ... >}}, but not an escaped {{{< ... >}}} (a page showing the shortcode as text)
|
||||||
|
for (const m of text.matchAll(/(?<!\{)\{\{<\s*(pplus(?:-[a-z]+)*)(\s+[^>]*)?>\}\}(?!\})/g)) {
|
||||||
|
const name = m[1], args = m[2] ?? '';
|
||||||
|
if (!SHORTCODES.has(name)) { fail(page, `{{< ${name} >}} is not a shortcode of the extension; they are ${[...SHORTCODES].join(', ')}`); continue; }
|
||||||
|
const view = /\bview="([^"]+)"/.exec(args)?.[1];
|
||||||
|
const views = name === 'pplus-view' ? STATIC_VIEWS : name === 'pplus-hw' ? new Set(HW_VIEWS) : EMBED_VIEWS;
|
||||||
|
if (view && !name.startsWith('pplus-hw-') && !views.has(view)) fail(page, `{{< ${name} >}} has view="${view}"; the views are ${[...views].join(', ')}`);
|
||||||
|
for (const v of (/\bviews="([^"]+)"/.exec(args)?.[1] ?? '').split(/[\s,]+/).filter(Boolean)) if (!HW_VIEWS.includes(v)) fail(page, `{{< ${name} >}} names the machine view "${v}"; the views are ${HW_VIEWS.join(', ')}`);
|
||||||
|
for (const a of args.matchAll(/\b(lingo|matho|pseudo|speco|mojo|asm|setup)="([^"]+)"/g)) {
|
||||||
|
const f = path.join(path.dirname(page), a[2]);
|
||||||
|
if (!fs.existsSync(f)) fail(page, `{{< ${name} >}} names ${a[2]}, which does not exist`);
|
||||||
|
else referenced.add(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const p of programs) if (!referenced.has(p) && !/\.(speco)$/.test(p)) console.log(` (note) ${path.relative(root, p)} is not embedded by any page`);
|
||||||
|
|
||||||
|
if (!pplusDir) {
|
||||||
|
console.log(`check-pages: ${programs.length} program files, ${failures} problems (files only; unset CHECK_FILES_ONLY to run them)`);
|
||||||
|
process.exit(failures ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. every program parses, runs, and prints what it says
|
||||||
|
const dist = path.join(pplusDir, 'dist');
|
||||||
|
const coreDist = path.join(pplusDir, 'core', 'dist'); // pplus-core, built beside the app
|
||||||
|
const { studyOf, runPseudo } = await import(pathToFileURL(path.join(coreDist, 'services/pseudo.js')));
|
||||||
|
const { removedSyntax } = await import(pathToFileURL(path.join(coreDist, 'mojo/check.js')));
|
||||||
|
const { MOJO_VERSION } = await import(pathToFileURL(path.join(coreDist, 'mojo/generated/pin.js')));
|
||||||
|
// a Mojo file is run as Programming+ builds everywhere: the pin's arguments (core's mojoBuildArgs), without the
|
||||||
|
// x86-64 target on a machine that is not one
|
||||||
|
const { mojoBuildArgs } = await import(pathToFileURL(path.join(coreDist, 'services/godbolt.js')));
|
||||||
|
const MOJO_RUN_ARGS = mojoBuildArgs('', { x86_64: process.arch === 'x64' }).split(/\s+/).filter(Boolean);
|
||||||
|
const mojoVersion = (() => { const r = spawnSync('mojo', ['--version'], { encoding: 'utf8' }); return r.status === 0 ? r.stdout.trim() : null; })();
|
||||||
|
if (programs.some((f) => f.endsWith('.mojo'))) {
|
||||||
|
if (!mojoVersion) console.log(' (note) no mojo compiler on the PATH: .mojo files are checked for removed syntax only. Run inside pixi to build and run them.');
|
||||||
|
else if (!mojoVersion.includes(MOJO_VERSION)) console.log(` (warning) ${mojoVersion} is not the pinned Mojo ${MOJO_VERSION}; results may not match the site`);
|
||||||
|
}
|
||||||
|
const { readLingo, lowerLingo, runLingo } = await import(pathToFileURL(path.join(coreDist, 'services/lingo.js')));
|
||||||
|
const { parseMatho, lowerMatho, runMatho } = await import(pathToFileURL(path.join(coreDist, 'services/matho.js')));
|
||||||
|
|
||||||
|
function header(text) {
|
||||||
|
const h = { expect: [], input: [], questions: [], stops: null };
|
||||||
|
for (const line of text.split('\n')) {
|
||||||
|
const m = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT|EXPECT|ERRORS|QUESTION|STOPS|expect-stdout):\s?(.*)$/.exec(line);
|
||||||
|
if (!m) continue;
|
||||||
|
if (m[1] === 'CALL') h.call = m[2].trim();
|
||||||
|
else if (m[1] === 'INPUT') h.input.push(m[2]);
|
||||||
|
else if (m[1] === 'EXPECT' || m[1] === 'expect-stdout') h.expect.push(m[2]);
|
||||||
|
else if (m[1] === 'ERRORS') h.errors = Number(m[2]);
|
||||||
|
else if (m[1] === 'QUESTION') h.questions.push(m[2].trim());
|
||||||
|
else if (m[1] === 'STOPS') h.stops = m[2].trim();
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkRun(file, tr, h) {
|
||||||
|
if (h.stops) { if (!tr.error) fail(file, `was meant to stop with a ${h.stops} error and ran to the end`); else if (tr.error.kind !== h.stops) fail(file, `was meant to stop with a ${h.stops} error and stopped with ${tr.error.kind}: ${tr.error.message}`); return; }
|
||||||
|
if (tr.error) { fail(file, `stopped: ${tr.error.message}`); return; }
|
||||||
|
if (h.expect.length) {
|
||||||
|
const got = tr.output;
|
||||||
|
const want = h.expect;
|
||||||
|
if (JSON.stringify(got) !== JSON.stringify(want)) fail(file, `printed ${JSON.stringify(got)}, expected ${JSON.stringify(want)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const file of programs) {
|
||||||
|
const text = fs.readFileSync(file, 'utf8');
|
||||||
|
const h = header(text);
|
||||||
|
if (file.endsWith('.pseudo')) {
|
||||||
|
const st = studyOf(text);
|
||||||
|
const errs = st.diagnostics.filter((d) => d.severity === 'error');
|
||||||
|
if (h.errors !== undefined) { if (errs.length !== h.errors) fail(file, `expected ${h.errors} errors, got ${errs.length}: ${errs.map((d) => `L${d.line} ${d.id}`).join(', ')}`); continue; }
|
||||||
|
if (errs.length) { fail(file, errs.map((d) => `L${d.line} ${d.id}: ${d.message}`).join(' | ')); continue; }
|
||||||
|
if (h.expect.length || h.call) checkRun(file, runPseudo(st, { call: h.call ?? null, input: h.input, maxSteps: 200000 }), h);
|
||||||
|
} else if (file.endsWith('.tex')) {
|
||||||
|
const r = parseMatho(text);
|
||||||
|
const errs = r.diagnostics.filter((d) => d.severity === 'error');
|
||||||
|
if (h.errors !== undefined) { if (errs.length !== h.errors) fail(file, `expected ${h.errors} errors, got ${errs.length}: ${errs.map((d) => `L${d.line} ${d.id}`).join(', ')}`); continue; }
|
||||||
|
if (errs.length) { fail(file, errs.map((d) => `L${d.line} ${d.id}: ${d.message}`).join(' | ')); continue; }
|
||||||
|
const low = lowerMatho(r, 'pseudo');
|
||||||
|
if (!low) { fail(file, 'does not translate to pseudo'); continue; }
|
||||||
|
if (h.expect.length || h.call) {
|
||||||
|
try { checkRun(file, runMatho(r, { call: h.call ?? null, input: h.input, maxSteps: 200000 }), h); }
|
||||||
|
catch (e) { fail(file, `run failed: ${e.message}`); }
|
||||||
|
}
|
||||||
|
} else if (file.endsWith('.mojo')) {
|
||||||
|
const removed = removedSyntax(text);
|
||||||
|
if (removed.length && h.errors == null) { fail(file, removed.map((d) => `L${d.line} ${d.message}`).join(' | ')); continue; }
|
||||||
|
if (!mojoVersion) continue;
|
||||||
|
const r = spawnSync('mojo', ['run', ...MOJO_RUN_ARGS, file], { input: h.input.map((l) => l + '\n').join(''), encoding: 'utf8', timeout: 120000 });
|
||||||
|
if (h.errors != null) { if (r.status === 0) fail(file, 'was meant to fail to compile, and ran'); continue; }
|
||||||
|
if (r.status !== 0) { fail(file, `mojo run exited ${r.status ?? r.signal}: ${(r.stderr || '').trim().split('\n').slice(0, 4).join(' | ')}`); continue; }
|
||||||
|
if (h.expect.length) {
|
||||||
|
const got = r.stdout.replace(/\n$/, '').split('\n');
|
||||||
|
if (JSON.stringify(got) !== JSON.stringify(h.expect)) fail(file, `printed ${JSON.stringify(got)}, expected ${JSON.stringify(h.expect)}`);
|
||||||
|
}
|
||||||
|
} else if (file.endsWith('.lingo')) {
|
||||||
|
const r = readLingo(text);
|
||||||
|
const errs = r.diagnostics.filter((d) => d.severity === 'error');
|
||||||
|
if (h.questions.length) {
|
||||||
|
for (const q of h.questions) if (!r.diagnostics.some((d) => d.id === q)) fail(file, `the reader did not ask "${q}" (asked: ${r.diagnostics.map((d) => d.id).join(', ') || 'nothing'})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (errs.length) { fail(file, errs.map((d) => `L${d.line} ${d.id}: ${d.message}`).join(' | ')); continue; }
|
||||||
|
const low = lowerLingo(r, 'pseudo');
|
||||||
|
if (!low) { fail(file, 'does not lower to pseudo'); continue; }
|
||||||
|
const st = studyOf(low.source);
|
||||||
|
const perrs = st.diagnostics.filter((d) => d.severity === 'error');
|
||||||
|
if (perrs.length) { fail(file, 'lowered pseudo has errors: ' + perrs.map((d) => `L${d.line} ${d.message}`).join(' | ')); continue; }
|
||||||
|
if (h.expect.length || h.call) {
|
||||||
|
try { checkRun(file, runLingo(r, { call: h.call ?? null, input: h.input, maxSteps: 200000 }), h); }
|
||||||
|
catch (e) { fail(file, `run failed: ${e.message}`); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`check-pages: ${programs.length} program files, ${failures} problems`);
|
||||||
|
process.exit(failures ? 1 : 0);
|
||||||
Executable
+57
@@ -0,0 +1,57 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
# Publish ./site to /srv/www/<slug> as an atomic release (DEPLOY_ROOT overrides /srv/www).
|
||||||
|
#
|
||||||
|
# scripts/deploy.sh <slug> [host]
|
||||||
|
#
|
||||||
|
# Without a host, the script runs on the server itself (the Gitea runner lives
|
||||||
|
# on the droplet). With a host (user@droplet), it rsyncs over SSH. Either way
|
||||||
|
# the layout on the server is:
|
||||||
|
#
|
||||||
|
# /srv/www/<slug> -> symlink to the live release
|
||||||
|
# /srv/www/<slug>.releases/ one directory per deployed commit, last 5 kept
|
||||||
|
#
|
||||||
|
# The symlink swap is one rename, so visitors never see a half-copied site, and
|
||||||
|
# rolling back is `ln -sfn /srv/www/<slug>.releases/<sha> /srv/www/<slug>`.
|
||||||
|
set -euo pipefail
|
||||||
|
slug="${1:?usage: deploy.sh <slug> [user@host]}"
|
||||||
|
host="${2:-}"
|
||||||
|
sha="${GITHUB_SHA:-$(git rev-parse HEAD 2>/dev/null || date +%s)}"
|
||||||
|
root="${DEPLOY_ROOT:-/srv/www}"
|
||||||
|
releases="$root/$slug.releases"
|
||||||
|
release="$releases/${sha:0:12}"
|
||||||
|
live="$root/$slug"
|
||||||
|
|
||||||
|
[ -f site/index.html ] || { echo "site/ is missing; run scripts/assemble.sh first" >&2; exit 1; }
|
||||||
|
|
||||||
|
# Everything that touches the server, as one script, so the SSH path and the local path stay identical.
|
||||||
|
remote_script=$(cat <<EOS
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p "$releases"
|
||||||
|
rm -rf "$release.tmp"
|
||||||
|
mv "$release.incoming" "$release.tmp"
|
||||||
|
# a rebuilt commit replaces its earlier release
|
||||||
|
rm -rf "$release"
|
||||||
|
mv "$release.tmp" "$release"
|
||||||
|
# a plain directory from before releases existed is kept aside, once
|
||||||
|
if [ -d "$live" ] && [ ! -L "$live" ]; then mv "$live" "$releases/before-releases"; fi
|
||||||
|
# swap in one rename
|
||||||
|
ln -sfn "$release" "$live.next"
|
||||||
|
mv -Tf "$live.next" "$live"
|
||||||
|
# keep the five newest releases
|
||||||
|
ls -1dt "$releases"/*/ 2>/dev/null | tail -n +6 | xargs -r rm -rf
|
||||||
|
echo "live: $live -> \$(readlink "$live")"
|
||||||
|
EOS
|
||||||
|
)
|
||||||
|
|
||||||
|
if [ -z "$host" ]; then
|
||||||
|
mkdir -p "$releases"
|
||||||
|
rm -rf "$release.incoming"
|
||||||
|
if command -v rsync >/dev/null; then rsync -a --delete site/ "$release.incoming/"; else cp -a site "$release.incoming"; fi
|
||||||
|
bash -c "$remote_script"
|
||||||
|
else
|
||||||
|
ssh -o BatchMode=yes "$host" "mkdir -p '$releases'"
|
||||||
|
rsync -a --delete -e "ssh -o BatchMode=yes" site/ "$host:$release.incoming/"
|
||||||
|
ssh -o BatchMode=yes "$host" "$remote_script"
|
||||||
|
fi
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
"""Zip the repository for sharing: the files git tracks, plus new files it does not ignore.
|
||||||
|
|
||||||
|
pixi run package # writes package/programming-plus-<commit>.zip
|
||||||
|
|
||||||
|
pplus-core (the core/ submodule, with its own submodule library/) goes in as its checkouts track it. Nothing git ignores goes in: no .DS_Store, __pycache__, scratch/, dist/, site/, node_modules/ or
|
||||||
|
.pixi/. Files are stored under a top folder named programming-plus/, as the shared zips were.
|
||||||
|
Standard library only, like the corpus pipeline.
|
||||||
|
"""
|
||||||
|
import pathlib
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
def git(*args: str) -> str:
|
||||||
|
return subprocess.run(["git", *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
try:
|
||||||
|
commit = git("rev-parse", "--short", "HEAD").strip()
|
||||||
|
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||||
|
print("package: this needs a git checkout (git init and commit first)", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
dirty = bool(git("status", "--porcelain").strip())
|
||||||
|
names = sorted(set(git("ls-files", "-z", "--cached", "--others", "--exclude-standard").split("\0")) - {""})
|
||||||
|
# pplus-core (core/) is a submodule: take the files its checkout tracks, so the zip builds on its own.
|
||||||
|
subs = git("config", "-f", ".gitmodules", "--get-regexp", r"\.path$").split() if (ROOT / ".gitmodules").exists() else []
|
||||||
|
for sub in subs[1::2]:
|
||||||
|
if (ROOT / sub / ".git").exists():
|
||||||
|
tracked = subprocess.run(["git", "ls-files", "-z", "--recurse-submodules"], cwd=ROOT / sub, check=True, capture_output=True, text=True).stdout
|
||||||
|
names += [f"{sub}/{n}" for n in tracked.split("\0") if n]
|
||||||
|
names = sorted(n for n in set(names) if (ROOT / n).is_file())
|
||||||
|
out_dir = ROOT / "package"
|
||||||
|
out_dir.mkdir(exist_ok=True)
|
||||||
|
out = out_dir / f"programming-plus-{commit}{'-dirty' if dirty else ''}.zip"
|
||||||
|
with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
||||||
|
for n in names:
|
||||||
|
z.write(ROOT / n, f"programming-plus/{n}")
|
||||||
|
size = out.stat().st_size / 1e6
|
||||||
|
print(f"wrote {out.relative_to(ROOT)}: {len(names)} files, {size:.1f} MB{' (with uncommitted changes)' if dirty else ''}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Write quarto/_extensions/pplus/pplus-views.css: the app's own rules for what the static views draw, so a Quarto
|
||||||
|
* page shows the flowchart, the table of values, the proof and the rest exactly as the app does.
|
||||||
|
*
|
||||||
|
* pixi run quarto-css (build first; `pixi run test` fails while the file is out of date)
|
||||||
|
*
|
||||||
|
* It renders every static view of a few catalog problems (src/quarto/render.ts, as `quarto render` would), collects
|
||||||
|
* the classes they use, and copies from styles.css every rule whose selectors use only those classes, each selector
|
||||||
|
* scoped under `.pplus-static`. The app's color tokens come along: light by default, dark when the Quarto page is
|
||||||
|
* dark (`body.quarto-dark`, or Bootstrap's `data-bs-theme="dark"`); the paper and ink follow the page's own.
|
||||||
|
*
|
||||||
|
* It also copies the course's stylesheets for the machine views (course/*.css), writes pplus-hw.css from
|
||||||
|
* styles/course/bridge.css, and copies pplus-core's KDE syntax for Mojo (core/library/syntax/mojo.xml, which core's corpus
|
||||||
|
* pipeline writes) to syntax/mojo.xml, for the listings Pandoc highlights.
|
||||||
|
*
|
||||||
|
* node scripts/quarto-css.mjs --check exit 1 if a file is not what this would write
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
||||||
|
const OUT = path.join(ROOT, 'quarto/_extensions/pplus/pplus-views.css');
|
||||||
|
const dist = (p) => pathToFileURL(path.join(ROOT, 'dist', p)).href;
|
||||||
|
if (!fs.existsSync(path.join(ROOT, 'dist/quarto/render.js'))) { console.error('quarto-css: dist/ is missing; run `pixi run build` first'); process.exit(1); }
|
||||||
|
|
||||||
|
const { installDocument } = await import(dist('quarto/dom.js'));
|
||||||
|
installDocument();
|
||||||
|
const { renderStatic, STATIC_VIEWS } = await import(dist('quarto/render.js'));
|
||||||
|
const { problemById } = await import(dist('core/catalog.js'));
|
||||||
|
|
||||||
|
/* ---------- the classes the views use ---------- */
|
||||||
|
|
||||||
|
const samples = [];
|
||||||
|
for (const id of ['count-base', 'count-base-proved', 'match-off-by-one', 'five-bugs', 'binary-search', 'asm-two-pointers', 'demo']) {
|
||||||
|
const p = problemById(id);
|
||||||
|
const files = Object.fromEntries(Object.entries(p.sources).filter(([, v]) => typeof v === 'string' && v.trim()));
|
||||||
|
for (const lang of Object.keys(files)) samples.push({ files, lang, call: p.call ?? null, setup: p.setup, machine: p.machine });
|
||||||
|
}
|
||||||
|
samples.push({ files: { mojo: fs.readFileSync(path.join(ROOT, 'core/library/mojo/stress/lifecycle-moves.mojo'), 'utf8') }, lang: 'mojo' });
|
||||||
|
const used = new Set();
|
||||||
|
for (const s of samples) for (const view of STATIC_VIEWS.filter((v) => v !== 'hw')) {
|
||||||
|
let html = '';
|
||||||
|
try { html = renderStatic({ ...s, view }).html; } catch { continue; }
|
||||||
|
for (const m of html.matchAll(/class="([^"]*)"/g)) for (const c of m[1].split(/\s+/)) if (c) used.add(c);
|
||||||
|
}
|
||||||
|
// the editor's token colors and the step colors, whichever a sample happened to show
|
||||||
|
for (const c of ['tok-keyword', 'tok-builtin', 'tok-string', 'tok-number', 'tok-comment', 'tok-label', 'tok-op', 'tok-error', 'tok-punct', 'tok-convention', 'tok-transfer', 'tok-name']) used.add(c);
|
||||||
|
|
||||||
|
/* ---------- styles.css as rules ---------- */
|
||||||
|
|
||||||
|
/** Top-level rules and @media blocks: { selector, body } or { media, rules }. Comments are dropped. */
|
||||||
|
function parse(css) {
|
||||||
|
css = css.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||||
|
const out = [];
|
||||||
|
let i = 0;
|
||||||
|
const block = (from) => { let depth = 0; for (let k = from; k < css.length; k++) { if (css[k] === '{') depth++; else if (css[k] === '}' && --depth === 0) return k; } return css.length; };
|
||||||
|
while (i < css.length) {
|
||||||
|
const open = css.indexOf('{', i);
|
||||||
|
if (open < 0) break;
|
||||||
|
const prelude = css.slice(i, open).trim();
|
||||||
|
const close = block(open);
|
||||||
|
const body = css.slice(open + 1, close);
|
||||||
|
if (prelude.startsWith('@media')) out.push({ media: prelude, rules: parse(body) });
|
||||||
|
else if (!prelude.startsWith('@')) out.push({ selector: prelude, body: body.trim() });
|
||||||
|
i = close + 1;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokens = { light: new Map(), dark: new Map() };
|
||||||
|
const LIGHT = /^:root$/, DARK = /^:root\[data-theme="dark"\]$/;
|
||||||
|
const SKIP_TOKENS = new Set(['--paper', '--paper-2', '--paper-3', '--ink', '--ink-2', '--ink-3', '--line', '--line-2', '--mono', '--sans', 'color-scheme']);
|
||||||
|
|
||||||
|
/** A selector the static views can use: every class in it is one they emit, and nothing in it names the app's page. */
|
||||||
|
function keep(sel) {
|
||||||
|
if (/(^|[\s>+~(,])(html|body|:root)\b/.test(sel) || /\[data-theme|\.is-embed|\.shell|\.home|::?-webkit|:hover|:focus|:active/.test(sel)) return false;
|
||||||
|
const classes = [...sel.matchAll(/\.([\w-]+)/g)].map((m) => m[1]);
|
||||||
|
if (!classes.length) return false;
|
||||||
|
return classes.every((c) => used.has(c));
|
||||||
|
}
|
||||||
|
|
||||||
|
function scoped(rules, indent = '') {
|
||||||
|
const lines = [];
|
||||||
|
for (const r of rules) {
|
||||||
|
if (r.media) {
|
||||||
|
// the app's narrow-screen rearrangements are for its workspace; a page keeps the view's own layout
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const sels = r.selector.split(',').map((s) => s.trim());
|
||||||
|
if (sels.length === 1 && LIGHT.test(sels[0])) { collect(r.body, tokens.light); continue; }
|
||||||
|
if (sels.length === 1 && DARK.test(sels[0])) { collect(r.body, tokens.dark); continue; }
|
||||||
|
const kept = sels.filter(keep);
|
||||||
|
if (!kept.length || !r.body) continue;
|
||||||
|
lines.push(`${indent}${kept.map((s) => `.pplus-static ${s}`).join(',\n' + indent)} {\n${r.body.split('\n').map((l) => `${indent} ${l.trim()}`).filter((l) => l.trim()).join('\n')}\n${indent}}`);
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
function collect(body, into) {
|
||||||
|
for (const decl of body.split(';')) {
|
||||||
|
const k = decl.slice(0, decl.indexOf(':')).trim();
|
||||||
|
const v = decl.slice(decl.indexOf(':') + 1).trim();
|
||||||
|
if (k.startsWith('--') && v && !SKIP_TOKENS.has(k)) into.set(k, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rules = scoped(parse(fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8')));
|
||||||
|
const decls = (m) => [...m].map(([k, v]) => ` ${k}: ${v};`).join('\n');
|
||||||
|
const text = `/* pplus-views.css: GENERATED by \`pixi run quarto-css\` (scripts/quarto-css.mjs) from styles.css. Do not edit.
|
||||||
|
The app's own rules for what the static views draw, scoped under .pplus-static, with the app's color tokens;
|
||||||
|
the paper and ink follow the Quarto page (Bootstrap's variables). */
|
||||||
|
.pplus-static {
|
||||||
|
--paper: var(--bs-body-bg, #ffffff);
|
||||||
|
--paper-2: color-mix(in srgb, var(--bs-body-bg, #ffffff) 94%, var(--bs-body-color, #16191f));
|
||||||
|
--paper-3: color-mix(in srgb, var(--bs-body-bg, #ffffff) 88%, var(--bs-body-color, #16191f));
|
||||||
|
--ink: var(--bs-body-color, #16191f);
|
||||||
|
--ink-2: color-mix(in srgb, var(--bs-body-color, #16191f) 68%, var(--bs-body-bg, #ffffff));
|
||||||
|
--ink-3: color-mix(in srgb, var(--bs-body-color, #16191f) 48%, var(--bs-body-bg, #ffffff));
|
||||||
|
--line: color-mix(in srgb, var(--bs-body-color, #16191f) 14%, var(--bs-body-bg, #ffffff));
|
||||||
|
--line-2: color-mix(in srgb, var(--bs-body-color, #16191f) 24%, var(--bs-body-bg, #ffffff));
|
||||||
|
--mono: var(--bs-font-monospace, "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace);
|
||||||
|
--sans: inherit;
|
||||||
|
--bg: var(--paper); --bg-2: var(--paper-2); --bg-3: var(--paper-3); --fg: var(--ink); --fg-2: var(--ink-2); --note: var(--ink-3);
|
||||||
|
--current: var(--marker-bg); --last: var(--last-bg); --radius: var(--r-lg);
|
||||||
|
${decls(tokens.light)}
|
||||||
|
}
|
||||||
|
body.quarto-dark .pplus-static,
|
||||||
|
[data-bs-theme="dark"] .pplus-static {
|
||||||
|
${decls(tokens.dark)}
|
||||||
|
}
|
||||||
|
|
||||||
|
${rules.join('\n\n')}
|
||||||
|
`;
|
||||||
|
|
||||||
|
/* ---------- the machine views: the course's stylesheets, as the board uses them ---------- */
|
||||||
|
|
||||||
|
// tokens.css, kit.css and asm86.css are the course site's own, written for Quarto pages: they go in unchanged
|
||||||
|
// (styles/course/README.md). bridge.css's :root block maps the app's tokens onto the ones a Quarto page already
|
||||||
|
// has, so a page gets the rest of it: the board's adjustments to the course views.
|
||||||
|
const EXT = path.join(ROOT, 'quarto/_extensions/pplus');
|
||||||
|
const outputs = [[OUT, text]];
|
||||||
|
for (const f of ['tokens.css', 'kit.css', 'asm86.css']) outputs.push([path.join(EXT, 'course', f), fs.readFileSync(path.join(ROOT, 'styles/course', f), 'utf8')]);
|
||||||
|
const bridge = fs.readFileSync(path.join(ROOT, 'styles/course/bridge.css'), 'utf8');
|
||||||
|
const afterRoot = bridge.slice(bridge.indexOf('}', bridge.indexOf(':root {')) + 1).replace(/^\s+/, '');
|
||||||
|
outputs.push([path.join(EXT, 'pplus-hw.css'), `/* pplus-hw.css: GENERATED by \`pixi run quarto-css\` (scripts/quarto-css.mjs) from styles/course/bridge.css. Do not edit.
|
||||||
|
The Hardware board's adjustments to the course's machine views (course/*.css), for the pplus-hw shortcodes. A Quarto
|
||||||
|
page already has the colors and fonts those files read (--bs-body-bg, --bs-body-color, body.quarto-dark). */
|
||||||
|
${afterRoot}`]);
|
||||||
|
|
||||||
|
outputs.push([path.join(EXT, 'syntax', 'mojo.xml'), fs.readFileSync(path.join(ROOT, 'core/library/syntax/mojo.xml'), 'utf8')]);
|
||||||
|
|
||||||
|
if (process.argv.includes('--check')) {
|
||||||
|
const stale = outputs.filter(([file, want]) => !fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== want).map(([file]) => path.relative(ROOT, file));
|
||||||
|
if (stale.length) { console.error(`quarto-css: out of date: ${stale.join(', ')}; run \`pixi run quarto-css\``); process.exit(1); }
|
||||||
|
console.log('quarto-css: up to date');
|
||||||
|
} else {
|
||||||
|
for (const [file, want] of outputs) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, want); }
|
||||||
|
console.log(`quarto-css: wrote ${outputs.map(([f]) => path.relative(ROOT, f)).join(', ')} (${rules.length} rules, ${used.size} classes)`);
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Put a built Programming+ inside a copy of the Quarto extension, so a site renders the rendered views
|
||||||
|
* ({{< pplus-run >}}, {{< pplus-steps >}}, ...) without a checkout of this repository beside it:
|
||||||
|
*
|
||||||
|
* pixi run quarto-engine ../my-site/_extensions/pplus
|
||||||
|
*
|
||||||
|
* copies dist/ (without the source maps and the interpreter's test fixture) to <dir>/engine/dist, where pplus.lua
|
||||||
|
* looks for it after pplus-engine and PPLUS_ENGINE (quarto/README.md), pplus-core's core/dist/ to
|
||||||
|
* <dir>/engine/core/dist, and a package.json that maps the app's #core/ imports to it. Run it again after rebuilding. The copy is
|
||||||
|
* the app's compiled JavaScript; the site still needs Node 20 or later on the machine that renders it.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
||||||
|
const dir = process.argv[2];
|
||||||
|
const die = (m) => { console.error(`quarto-engine: ${m}`); process.exit(1); };
|
||||||
|
if (!dir) die('usage: pixi run quarto-engine <a site\'s _extensions/pplus folder>');
|
||||||
|
if (!fs.existsSync(path.join(dir, 'pplus.lua'))) die(`${dir} is not the extension's folder (no pplus.lua in it); copy quarto/_extensions/pplus there first`);
|
||||||
|
const dist = path.join(ROOT, 'dist');
|
||||||
|
if (!fs.existsSync(path.join(dist, 'quarto', 'render.js'))) die('dist/ is missing; run `pixi run build` first');
|
||||||
|
const out = path.join(dir, 'engine', 'dist');
|
||||||
|
fs.rmSync(path.join(dir, 'engine'), { recursive: true, force: true });
|
||||||
|
let files = 0, bytes = 0;
|
||||||
|
fs.cpSync(dist, out, {
|
||||||
|
recursive: true,
|
||||||
|
filter: (src) => {
|
||||||
|
const rel = path.relative(dist, src);
|
||||||
|
if (rel.endsWith('.map') || rel === 'curriculum' || rel.startsWith('curriculum' + path.sep)) return false;
|
||||||
|
if (fs.statSync(src).isFile()) { files++; bytes += fs.statSync(src).size; }
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// pplus-core's modules, which the app's modules import as #core/...: Node finds the mapping in engine/package.json
|
||||||
|
const coreDist = path.join(ROOT, 'core', 'dist');
|
||||||
|
if (!fs.existsSync(path.join(coreDist, 'common', 'workspace.js'))) die('core/dist/ is missing; run `pixi run build` first');
|
||||||
|
fs.cpSync(coreDist, path.join(dir, 'engine', 'core', 'dist'), {
|
||||||
|
recursive: true,
|
||||||
|
filter: (src) => {
|
||||||
|
const rel = path.relative(coreDist, src);
|
||||||
|
if (rel.endsWith('.map') || rel.endsWith('.d.ts') || rel === 'curriculum' || rel.startsWith('curriculum' + path.sep)) return false;
|
||||||
|
if (fs.statSync(src).isFile()) { files++; bytes += fs.statSync(src).size; }
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
fs.writeFileSync(path.join(dir, 'engine', 'package.json'), JSON.stringify({ private: true, type: 'module', imports: { '#core/*': './core/dist/*' } }, null, 2) + '\n');
|
||||||
|
// the extension's own copy of the version, so a page can say which Programming+ rendered it
|
||||||
|
let version = 'dev';
|
||||||
|
try { version = fs.readFileSync(path.join(ROOT, '.git', 'HEAD'), 'utf8').trim(); } catch { /* not a checkout */ }
|
||||||
|
fs.writeFileSync(path.join(dir, 'engine', 'VERSION'), version + '\n');
|
||||||
|
console.log(`quarto-engine: copied ${files} files (${(bytes / 1e6).toFixed(1)} MB) to ${out}`);
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Put a program from mojo/local/ next to a Quarto page, with everything the playground shows for it:
|
||||||
|
*
|
||||||
|
* pixi run quarto-export demo ../site/programmingplus/demo
|
||||||
|
*
|
||||||
|
* writes into that folder
|
||||||
|
* demo.mojo the program, header and all (the shortcode leaves the header out of the pane and listing)
|
||||||
|
* demo.asm the compiler's x86-64 for it, as the x86-64 pane shows it (from src/mojo/generated/listings.ts)
|
||||||
|
* demo.setup the setup block that goes with it: the arguments' registers and the listing's data
|
||||||
|
* and prints the shortcodes that embed the whole playground with them, and that run it with the page. Run `pixi run --manifest-path core/pixi.toml play demo` first so
|
||||||
|
* the listing is current; without one (no godbolt answer yet, or the program has no function of its own
|
||||||
|
* left at this build), only the .mojo is written and the shortcode says so.
|
||||||
|
*
|
||||||
|
* Every option the shortcode takes is at the top of quarto/_extensions/pplus/pplus.lua.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
||||||
|
const [name, outDir] = process.argv.slice(2).filter((a) => !a.startsWith('--'));
|
||||||
|
const die = (m) => { console.error(`quarto:export: ${m}`); process.exit(1); };
|
||||||
|
if (!name || !outDir) die('usage: pixi run quarto-export <program in mojo/local/> <folder beside the .qmd page>');
|
||||||
|
|
||||||
|
const src = path.join(ROOT, 'core/library/mojo/local', `${name}.mojo`);
|
||||||
|
if (!fs.existsSync(src)) die(`core/library/mojo/local/${name}.mojo does not exist`);
|
||||||
|
const listingsJs = path.join(ROOT, 'core/dist/mojo/generated/listings.js');
|
||||||
|
if (!fs.existsSync(listingsJs)) die('core/dist/ is missing; run `pixi run build` first');
|
||||||
|
const { MOJO_LISTINGS } = await import(pathToFileURL(listingsJs).href);
|
||||||
|
|
||||||
|
fs.mkdirSync(outDir, { recursive: true });
|
||||||
|
const wrote = [];
|
||||||
|
const put = (file, text) => { fs.writeFileSync(path.join(outDir, file), text.endsWith('\n') ? text : text + '\n'); wrote.push(file); };
|
||||||
|
put(`${name}.mojo`, fs.readFileSync(src, 'utf8'));
|
||||||
|
const listing = MOJO_LISTINGS[name];
|
||||||
|
if (listing) { put(`${name}.asm`, listing.asm); put(`${name}.setup`, listing.setup); }
|
||||||
|
|
||||||
|
const attrs = [`mojo="${name}.mojo"`];
|
||||||
|
if (listing) attrs.push(`asm="${name}.asm"`, `setup="${name}.setup"`);
|
||||||
|
attrs.push(`area="${listing ? 'hw' : 'dev'}"`, `title="${name}"`);
|
||||||
|
console.log(`wrote ${wrote.map((f) => path.join(outDir, f)).join(', ')}`);
|
||||||
|
if (!listing) console.log(`no x86-64 listing for ${name} yet: run \`pixi run --manifest-path core/pixi.toml play ${name}\` (with # mode: both and -O0 in its header), then export again`);
|
||||||
|
console.log(`\nin the page, the whole playground:\n\n{{< pplus-playground ${attrs.join(' ')} >}}\n`);
|
||||||
|
console.log(`or, rendered with the page (no iframe):\n\n{{< pplus-run mojo="${name}.mojo" code="1" >}}\n{{< pplus-lifetimes mojo="${name}.mojo" >}}\n`);
|
||||||
|
console.log('Other arrangements: panel="compiler" (open on the compiler\'s answer), build="default", dock="closed", editor="0.6"; {{< pplus-embed view="life" >}} for one live view. The gallery at #/quarto shows them all.');
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The chain of the three repositories, checked and moved in order. pplus-web pins pplus-core (core/) by commit, and
|
||||||
|
* core pins pplus-library (core/library/) by commit; a change at the bottom reaches the site only when both pointers
|
||||||
|
* move, in that order, and each repository has pushed the commit the one above names. When that was first done by
|
||||||
|
* hand it broke twice and nobody saw it for five weeks (a pointer to a commit from before a move, a pointer to a
|
||||||
|
* commit that existed only on one machine). This script is the order written down.
|
||||||
|
*
|
||||||
|
* node scripts/release.mjs check [--offline] [--quick] [--json]
|
||||||
|
* Is the chain consistent? For each pointer (web -> core, core -> library):
|
||||||
|
* - the commit it names is in the submodule's checkout, the checkout is at it, and has no uncommitted change
|
||||||
|
* - it is on the submodule's branch (.gitmodules, `main`) on its remote: asked with `git ls-remote` unless
|
||||||
|
* --offline, else read from the last fetch; "cannot tell" when neither can say. A pointer to a commit only
|
||||||
|
* this machine has is the failure this exists for.
|
||||||
|
* and, unless --quick: the generated files are current (core's `library.mjs emit --check`, `corpus.py emit`
|
||||||
|
* writes nothing new, web's `quarto-css.mjs --check`), and Mojo, Node and Python are pinned alike in
|
||||||
|
* library/mojo/pin.json, both pixi.toml files and both pixi.lock files. --quick is what tests/chain.test.mjs
|
||||||
|
* runs: the pointers and the checkouts only, no network, no build.
|
||||||
|
* Exit status 1 when something is wrong (each line says what to run), 0 otherwise ("cannot tell" included).
|
||||||
|
*
|
||||||
|
* node scripts/release.mjs bump [--commit] [--no-gate]
|
||||||
|
* After a change in core/library (committed there) or in core: move core's pointer to the library checkout's
|
||||||
|
* commit and regenerate what core derives from the library (library-emit, mojo-emit), run core's gate; then
|
||||||
|
* move web's pointer, regenerate what web derives from core (quarto-css), run web's gate; print the commits
|
||||||
|
* to push, in order. Without --commit it stages core's new pointer and leaves the regenerated files in the
|
||||||
|
* working trees, and prints the commits to make; with --commit it makes them. It never pushes, tags or fetches.
|
||||||
|
*
|
||||||
|
* Needs a build for everything but --quick (pixi run release-check and release-bump build first). Commands run with
|
||||||
|
* the node and python on the PATH, which under pixi are the pinned ones.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
export const WEB = fileURLToPath(new URL('..', import.meta.url));
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* git */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const NO_PROMPT = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND || 'ssh -o BatchMode=yes -o ConnectTimeout=10' };
|
||||||
|
|
||||||
|
/** Run git in dir; the trimmed stdout, or null when it fails. */
|
||||||
|
function git(dir, args, { timeout = 30000 } = {}) {
|
||||||
|
const r = spawnSync('git', ['-C', dir, ...args], { encoding: 'utf8', env: NO_PROMPT, timeout });
|
||||||
|
return r.status === 0 ? r.stdout.trim() : null;
|
||||||
|
}
|
||||||
|
const hasGit = () => spawnSync('git', ['--version']).status === 0;
|
||||||
|
const isCheckout = (dir) => fs.existsSync(path.join(dir, '.git')) && git(dir, ['rev-parse', '--is-inside-work-tree']) === 'true';
|
||||||
|
const short = (sha) => (sha ? sha.slice(0, 10) : '?');
|
||||||
|
|
||||||
|
/** The submodules a repository's .gitmodules names: path, url and branch (main when it names none). */
|
||||||
|
function submodules(dir) {
|
||||||
|
const file = path.join(dir, '.gitmodules');
|
||||||
|
if (!fs.existsSync(file)) return [];
|
||||||
|
const out = [];
|
||||||
|
let cur = null;
|
||||||
|
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
||||||
|
const head = /^\s*\[submodule "([^"]+)"\]/.exec(line);
|
||||||
|
if (head) { cur = { name: head[1], branch: 'main' }; out.push(cur); continue; }
|
||||||
|
const kv = /^\s*(\w+)\s*=\s*(.+?)\s*$/.exec(line);
|
||||||
|
if (cur && kv) cur[kv[1]] = kv[2];
|
||||||
|
}
|
||||||
|
return out.filter((s) => s.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The commit a repository's index records for a submodule path (what the next commit will pin). */
|
||||||
|
function pointer(dir, sub) {
|
||||||
|
const line = git(dir, ['ls-files', '--stage', '--', sub]);
|
||||||
|
const m = line && /^160000 ([0-9a-f]{40}) /.exec(line);
|
||||||
|
return m ? m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A repository's name: its package.json's, else its remote's (pplus-library has no package.json). */
|
||||||
|
function repoName(dir, url = null) {
|
||||||
|
const pkg = path.join(dir, 'package.json');
|
||||||
|
if (fs.existsSync(pkg)) { try { return JSON.parse(fs.readFileSync(pkg, 'utf8')).name; } catch { /* below */ } }
|
||||||
|
return path.basename(url || git(dir, ['remote', 'get-url', 'origin']) || dir).replace(/\.git$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The links of the chain from a root: web -> core -> library, each a parent, a submodule path and the child dir. */
|
||||||
|
export function chain(root = WEB) {
|
||||||
|
const links = [];
|
||||||
|
const walk = (dir, label) => {
|
||||||
|
for (const s of submodules(dir)) {
|
||||||
|
const child = path.join(dir, s.path);
|
||||||
|
const childLabel = repoName(child, s.url);
|
||||||
|
links.push({ parent: dir, parentLabel: label, path: s.path, child, childLabel, branch: s.branch, url: s.url });
|
||||||
|
walk(child, childLabel);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(root, repoName(root));
|
||||||
|
return links;
|
||||||
|
}
|
||||||
|
const rel = (dir) => path.relative(WEB, dir) || '.';
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* check */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cheap half of check: every pointer names a commit its checkout has, and the checkout is at it. Returns a list
|
||||||
|
* of { level: 'problem' | 'note', text, unread? } (unread: there were no pointers to read). Used by tests/chain.test.mjs, so `npm test` says when a pointer is broken.
|
||||||
|
* @param {string} [root] the repository at the top of the chain (default: this one)
|
||||||
|
*/
|
||||||
|
export function quickCheck(root = WEB) {
|
||||||
|
const out = [];
|
||||||
|
if (!hasGit()) return [{ level: 'note', unread: true, text: 'git is not on the PATH: the pointers cannot be read' }];
|
||||||
|
if (!isCheckout(root)) return [{ level: 'note', unread: true, text: `${root} is not a git checkout (a package, say): no pointers to read` }];
|
||||||
|
for (const l of chain(root)) {
|
||||||
|
const name = `${l.parentLabel} -> ${l.childLabel} (${rel(l.child)})`;
|
||||||
|
const sha = pointer(l.parent, l.path);
|
||||||
|
if (!sha) { out.push({ level: 'problem', text: `${name}: ${l.parentLabel} records no commit for ${l.path}` }); continue; }
|
||||||
|
if (!isCheckout(l.child)) {
|
||||||
|
out.push({ level: 'problem', text: `${name}: ${rel(l.child)} is not checked out. Fix: git submodule update --init --recursive` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const head = git(l.child, ['rev-parse', 'HEAD']);
|
||||||
|
if (git(l.child, ['cat-file', '-e', `${sha}^{commit}`]) === null) {
|
||||||
|
out.push({ level: 'problem', text: `${name}: ${l.parentLabel} pins ${short(sha)}, and ${rel(l.child)} does not have that commit. Fix: git submodule update --init --recursive (it fetches the pinned commit); if no remote has it either, it was never pushed: push ${l.childLabel} from the machine that made it, then this` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (head === sha) continue;
|
||||||
|
if (git(l.child, ['merge-base', '--is-ancestor', head, sha]) !== null) {
|
||||||
|
out.push({ level: 'problem', text: `${name}: ${rel(l.child)} is at ${short(head)}, behind the pinned ${short(sha)}, so everything built and tested here uses an older ${l.childLabel}. Fix: git submodule update --recursive` });
|
||||||
|
} else if (git(l.child, ['merge-base', '--is-ancestor', sha, head]) !== null) {
|
||||||
|
const n = git(l.child, ['rev-list', '--count', `${sha}..${head}`]);
|
||||||
|
out.push({ level: 'note', text: `${name}: ${rel(l.child)} is ${n} commit(s) ahead of the pinned ${short(sha)}; when they are done, move the pointer (pixi run release-bump)` });
|
||||||
|
} else {
|
||||||
|
out.push({ level: 'problem', text: `${name}: ${rel(l.child)} is at ${short(head)}, which is neither the pinned ${short(sha)} nor after it. Fix: git submodule update --recursive, or, if ${short(head)} is the one wanted, pixi run release-bump` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Is a commit on the branch of the submodule's remote? { level, text } with level ok, problem or unknown. */
|
||||||
|
function onRemoteBranch(l, sha, offline) {
|
||||||
|
const dir = l.child;
|
||||||
|
const tracking = `origin/${l.branch}`;
|
||||||
|
if (!offline) {
|
||||||
|
const r = spawnSync('git', ['-C', dir, 'ls-remote', '--heads', 'origin', l.branch], { encoding: 'utf8', env: NO_PROMPT, timeout: 20000 });
|
||||||
|
if (r.status === 0) {
|
||||||
|
const remoteHead = r.stdout.split('\n')[0]?.split('\t')[0];
|
||||||
|
if (!remoteHead) return { level: 'problem', text: `the remote has no branch ${l.branch}` };
|
||||||
|
if (remoteHead === sha) return { level: 'ok', text: `${short(sha)} is the head of ${l.branch} on the remote` };
|
||||||
|
if (git(dir, ['cat-file', '-e', `${remoteHead}^{commit}`]) === null) return { level: 'unknown', text: `cannot tell: the remote's ${l.branch} is at ${short(remoteHead)}, which this checkout has not fetched (git -C ${rel(dir)} fetch, then check again)` };
|
||||||
|
if (git(dir, ['merge-base', '--is-ancestor', sha, remoteHead]) !== null) return { level: 'ok', text: `${short(sha)} is on ${l.branch} on the remote (at ${short(remoteHead)})` };
|
||||||
|
return { level: 'problem', text: `${short(sha)} is not on ${l.branch} on the remote (at ${short(remoteHead)}), so a clone of ${l.childLabel}'s ${l.branch} does not have it. Push ${l.childLabel} first; the order is library, core, web` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const why = offline ? '--offline' : 'the remote could not be asked';
|
||||||
|
if (git(dir, ['rev-parse', '--verify', '--quiet', `refs/remotes/${tracking}`]) === null) return { level: 'unknown', text: `cannot tell: ${why}, and there is no ${tracking} from an earlier fetch` };
|
||||||
|
if (git(dir, ['merge-base', '--is-ancestor', sha, `refs/remotes/${tracking}`]) !== null) return { level: 'ok', text: `${short(sha)} is on ${tracking} as of the last fetch (${why})` };
|
||||||
|
return { level: 'unknown', text: `cannot tell for sure (${why}): ${short(sha)} is not on ${tracking} as of the last fetch, so it is unpushed or was pushed after that fetch; if unpushed, push ${l.childLabel} to ${l.branch} first` };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run a command in dir; { ok, out }. */
|
||||||
|
function sh(dir, cmd, args, opts = {}) {
|
||||||
|
const r = spawnSync(cmd, args, { cwd: dir, encoding: 'utf8', maxBuffer: 64 << 20, ...opts });
|
||||||
|
return { ok: r.status === 0, status: r.status, out: `${r.stdout || ''}${r.stderr || ''}`.trim(), missing: r.error?.code === 'ENOENT' };
|
||||||
|
}
|
||||||
|
const python = () => (spawnSync('python3', ['--version']).status === 0 ? 'python3' : spawnSync('python', ['--version']).status === 0 ? 'python' : null);
|
||||||
|
|
||||||
|
/** Every file under the given directories of dir. */
|
||||||
|
function filesUnder(dir, watched) {
|
||||||
|
const out = [];
|
||||||
|
const walk = (p) => { if (!fs.existsSync(p)) return; if (fs.statSync(p).isDirectory()) for (const e of fs.readdirSync(p)) walk(path.join(p, e)); else out.push(p); };
|
||||||
|
for (const w of watched) walk(path.join(dir, w));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run a generator and say which files under `watched` it changed or added; then put them back as they were. */
|
||||||
|
function writesNothing(dir, watched, cmd, args) {
|
||||||
|
const before = new Map(filesUnder(dir, watched).map((f) => [f, fs.readFileSync(f)]));
|
||||||
|
const r = sh(dir, cmd, args);
|
||||||
|
const changed = [];
|
||||||
|
for (const [f, buf] of before) if (!fs.existsSync(f) || !fs.readFileSync(f).equals(buf)) { changed.push(path.relative(dir, f)); fs.writeFileSync(f, buf); }
|
||||||
|
for (const f of filesUnder(dir, watched)) if (!before.has(f)) { changed.push(path.relative(dir, f)); fs.rmSync(f); }
|
||||||
|
return { ...r, changed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The version a pixi.toml installs of a package, as written ("==1.2.0", ">=26.10.0,<26.11"). */
|
||||||
|
const pixiDep = (text, name) => new RegExp(`^${name} = "([^"]+)"`, 'm').exec(text)?.[1] ?? null;
|
||||||
|
|
||||||
|
/** Full check: the quick part, the remote, the generated files and the pins. */
|
||||||
|
export function fullCheck({ root = WEB, offline = false } = {}) {
|
||||||
|
const lines = [];
|
||||||
|
const add = (level, where, text) => lines.push({ level, where, text });
|
||||||
|
for (const q of quickCheck(root)) add(q.level, 'pointers', q.text);
|
||||||
|
const links = chain(root);
|
||||||
|
if (!hasGit() || !isCheckout(root)) return lines;
|
||||||
|
|
||||||
|
for (const l of links) {
|
||||||
|
const where = `${l.parentLabel} -> ${l.childLabel}`;
|
||||||
|
const sha = pointer(l.parent, l.path);
|
||||||
|
if (!sha || git(l.child, ['cat-file', '-e', `${sha}^{commit}`]) === null) continue;
|
||||||
|
add('ok', where, `${l.parentLabel} pins ${l.childLabel} at ${short(sha)}${git(l.child, ['rev-parse', 'HEAD']) === sha ? ', and the checkout is there' : ''}`);
|
||||||
|
const dirty = git(l.child, ['status', '--porcelain', '--untracked-files=no', '--ignore-submodules=dirty']);
|
||||||
|
if (dirty) add('problem', where, `${rel(l.child)} has uncommitted changes, so what is tested here is not what the pointer names: ${dirty.split('\n').slice(0, 5).map((s) => s.trim()).join('; ')}${dirty.split('\n').length > 5 ? '; ...' : ''}. Commit them in ${l.childLabel} (then pixi run release-bump) or put them aside`);
|
||||||
|
const untracked = git(l.child, ['ls-files', '--others', '--exclude-standard', '--directory']);
|
||||||
|
if (untracked) add('note', where, `${rel(l.child)} has untracked files: ${untracked.split('\n').slice(0, 5).join(', ')}${untracked.split('\n').length > 5 ? ', ...' : ''}`);
|
||||||
|
const r = onRemoteBranch(l, sha, offline);
|
||||||
|
add(r.level, where, r.text);
|
||||||
|
}
|
||||||
|
// the top of the chain: its own commit is what the push order ends with; say if it is not on its branch either
|
||||||
|
const top = { child: root, childLabel: repoName(root), branch: 'main' };
|
||||||
|
const head = git(root, ['rev-parse', 'HEAD']);
|
||||||
|
if (head) { const r = onRemoteBranch(top, head, offline); add(r.level === 'problem' ? 'note' : r.level, top.childLabel, `this checkout's own commit: ${r.text}`); }
|
||||||
|
|
||||||
|
// generated files
|
||||||
|
const core = links.find((l) => l.childLabel === 'pplus-core')?.child ?? (fs.existsSync(path.join(root, 'scripts/library.mjs')) ? root : null);
|
||||||
|
const lib = core ? path.join(core, 'library') : null;
|
||||||
|
if (core) {
|
||||||
|
if (!fs.existsSync(path.join(core, 'dist', 'library', 'registry.js'))) add('unknown', 'generated', `cannot tell whether core's registry is current: core is not built (pixi run build)`);
|
||||||
|
else {
|
||||||
|
const r = sh(core, process.execPath, ['scripts/library.mjs', 'emit', '--check']);
|
||||||
|
add(r.ok ? 'ok' : 'problem', 'generated', r.ok ? "core's registry (src/library/generated.ts) is current with the library" : `${r.out}`);
|
||||||
|
}
|
||||||
|
const py = python();
|
||||||
|
if (!py) add('unknown', 'generated', 'cannot tell whether corpus.py emit is current: no python on the PATH (run through pixi)');
|
||||||
|
else {
|
||||||
|
const r = writesNothing(core, ['src/mojo/generated', 'library/syntax'], py, ['scripts/mojo/corpus.py', 'emit']);
|
||||||
|
if (!r.ok) add('problem', 'generated', `corpus.py emit failed: ${r.out.split('\n').slice(-3).join(' ')}`);
|
||||||
|
else add(r.changed.length ? 'problem' : 'ok', 'generated', r.changed.length ? `corpus.py emit would change ${r.changed.join(', ')} (put back as they were): run core's mojo-emit task (pixi run --manifest-path core/pixi.toml mojo-emit) and commit the result in core` : 'corpus.py emit writes nothing new (src/mojo/generated/, library/syntax/mojo.xml)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fs.existsSync(path.join(root, 'scripts/quarto-css.mjs'))) {
|
||||||
|
if (!fs.existsSync(path.join(root, 'dist', 'quarto', 'render.js'))) add('unknown', 'generated', 'cannot tell whether the Quarto extension\'s generated files are current: the site is not built (pixi run build)');
|
||||||
|
else {
|
||||||
|
const r = sh(root, process.execPath, ['scripts/quarto-css.mjs', '--check']);
|
||||||
|
add(r.ok ? 'ok' : 'problem', 'generated', r.ok ? "the Quarto extension's generated files are current (quarto-css --check)" : `${r.out.split('\n').slice(-3).join(' ')}: run pixi run quarto-css and commit the result`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the pins: Mojo, Node and Python alike everywhere
|
||||||
|
if (lib && fs.existsSync(path.join(lib, 'mojo', 'pin.json'))) {
|
||||||
|
const want = JSON.parse(fs.readFileSync(path.join(lib, 'mojo', 'pin.json'), 'utf8')).mojo.version;
|
||||||
|
const wrong = [];
|
||||||
|
for (const dir of [core, root === core ? null : root].filter(Boolean)) {
|
||||||
|
const toml = fs.readFileSync(path.join(dir, 'pixi.toml'), 'utf8');
|
||||||
|
const name = rel(path.join(dir, 'pixi.toml'));
|
||||||
|
if (pixiDep(toml, 'mojo') !== `==${want}`) wrong.push(`${name} installs mojo ${pixiDep(toml, 'mojo')}`);
|
||||||
|
const lock = fs.existsSync(path.join(dir, 'pixi.lock')) ? fs.readFileSync(path.join(dir, 'pixi.lock'), 'utf8') : '';
|
||||||
|
const locked = [...new Set([...lock.matchAll(/\/mojo-(\d+\.\d+\.\d+)-[^/]*\.conda/g)].map((m) => m[1]))];
|
||||||
|
if (locked.length !== 1 || locked[0] !== want) wrong.push(`${rel(path.join(dir, 'pixi.lock'))} locks mojo ${locked.join(', ') || 'nowhere'}`);
|
||||||
|
}
|
||||||
|
const gen = path.join(core, 'src', 'mojo', 'generated', 'pin.ts');
|
||||||
|
const genVersion = fs.existsSync(gen) ? /MOJO_VERSION = "([^"]+)"/.exec(fs.readFileSync(gen, 'utf8'))?.[1] : null;
|
||||||
|
if (genVersion !== want) wrong.push(`core's src/mojo/generated/pin.ts says ${genVersion}`);
|
||||||
|
add(wrong.length ? 'problem' : 'ok', 'pins', wrong.length ? `library/mojo/pin.json pins Mojo ${want}, and ${wrong.join('; ')}` : `Mojo ${want} in library/mojo/pin.json, core's generated pin, every pixi.toml and pixi.lock`);
|
||||||
|
if (root !== core) {
|
||||||
|
const a = fs.readFileSync(path.join(core, 'pixi.toml'), 'utf8'); const b = fs.readFileSync(path.join(root, 'pixi.toml'), 'utf8');
|
||||||
|
const differ = ['nodejs', 'python'].filter((p) => pixiDep(a, p) !== pixiDep(b, p));
|
||||||
|
add(differ.length ? 'problem' : 'ok', 'pins', differ.length ? differ.map((p) => `${p}: core pins ${pixiDep(a, p)}, web pins ${pixiDep(b, p)}`).join('; ') : `Node ${pixiDep(a, 'nodejs')} and Python ${pixiDep(a, 'python')} alike in core and web`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* bump */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
function step(text) { console.log(`\n== ${text}`); }
|
||||||
|
function must(r, what) {
|
||||||
|
if (r.ok) return r;
|
||||||
|
console.error(r.out.split('\n').slice(-25).join('\n'));
|
||||||
|
console.error(`\nrelease bump: ${what} failed; nothing was committed. Fix it and run release-bump again.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const testFiles = (dir) => fs.readdirSync(path.join(dir, 'tests')).filter((f) => f.endsWith('.test.mjs')).sort().map((f) => `tests/${f}`);
|
||||||
|
const tsc = () => path.join(WEB, 'node_modules', 'typescript', 'bin', 'tsc');
|
||||||
|
/** The tracked files with changes in dir (porcelain lines are "XY path"; read untrimmed, X may be a space). */
|
||||||
|
const tracked = (dir) => (spawnSync('git', ['-C', dir, 'status', '--porcelain', '--untracked-files=no', '--ignore-submodules=dirty'], { encoding: 'utf8' }).stdout || '').split('\n').filter(Boolean).map((l) => l.slice(3));
|
||||||
|
|
||||||
|
/** Move the pointers bottom up; see the header. */
|
||||||
|
export function bump({ commit = false, gate = true } = {}) {
|
||||||
|
const links = chain(WEB);
|
||||||
|
const toCore = links.find((l) => l.childLabel === 'pplus-core');
|
||||||
|
const toLib = links.find((l) => l.childLabel === 'pplus-library');
|
||||||
|
if (!toCore || !toLib) { console.error('release bump: run it in pplus-web, with core/ and core/library/ checked out (git submodule update --init --recursive)'); process.exit(2); }
|
||||||
|
const core = toCore.child; const lib = toLib.child;
|
||||||
|
const py = python();
|
||||||
|
if (!py) { console.error('release bump: no python on the PATH; run it as pixi run release-bump'); process.exit(2); }
|
||||||
|
const push = [];
|
||||||
|
// with --commit, a commit must hold the pointer and what was regenerated, and nothing else someone was editing
|
||||||
|
const editing = [...tracked(core).filter((f) => f !== 'library').map((f) => `core/${f}`), ...tracked(WEB).filter((f) => f !== 'core')];
|
||||||
|
if (commit && editing.length) { console.error(`release bump --commit: there are uncommitted changes that are not the pointers (${editing.join(', ')}); commit or put them aside first, or run without --commit`); process.exit(1); }
|
||||||
|
|
||||||
|
// 1. the library: committed, and clean
|
||||||
|
const libHead = git(lib, ['rev-parse', 'HEAD']);
|
||||||
|
const libDirty = tracked(lib);
|
||||||
|
if (libDirty.length) { console.error(`release bump: core/library has uncommitted changes (${libDirty.join(', ')}). Commit them in pplus-library first.`); process.exit(1); }
|
||||||
|
const libPinned = pointer(core, 'library');
|
||||||
|
if (libHead !== libPinned) {
|
||||||
|
if (git(lib, ['merge-base', '--is-ancestor', libPinned, libHead]) === null) console.log(`note: the library checkout (${short(libHead)}) does not descend from the commit core pinned (${short(libPinned)})`);
|
||||||
|
step(`core: move library from ${short(libPinned)} to ${short(libHead)}, and regenerate what core derives from it`);
|
||||||
|
must(sh(core, 'git', ['add', 'library']), 'git add library in core');
|
||||||
|
} else step(`core already pins the library checkout (${short(libHead)}); regenerating to be sure`);
|
||||||
|
must(sh(WEB, process.execPath, [tsc(), '-p', 'core/tsconfig.json']), 'building core');
|
||||||
|
// what core derives from the library; library CI (pplus-library's .gitea/workflows/test.yml) runs the same two
|
||||||
|
console.log(must(sh(core, process.execPath, ['scripts/library.mjs', 'emit']), 'library-emit').out);
|
||||||
|
console.log(must(sh(core, py, ['scripts/mojo/corpus.py', 'emit']), 'mojo-emit').out.split('\n').slice(-2).join('\n'));
|
||||||
|
if (tracked(lib).length) { console.error(`release bump: mojo-emit changed the library (${tracked(lib).join(', ')}): commit that in pplus-library, then run release-bump again`); process.exit(1); }
|
||||||
|
must(sh(WEB, process.execPath, [tsc(), '-p', 'core/tsconfig.json']), 'building core again, with the regenerated sources');
|
||||||
|
if (gate) {
|
||||||
|
step("core's gate: every test, and no program of ours failing");
|
||||||
|
const t = must(sh(core, process.execPath, ['--test', ...testFiles(core)]), "core's tests");
|
||||||
|
console.log(t.out.split('\n').filter((l) => /^ℹ (tests|pass|fail|skipped)/.test(l)).join('\n'));
|
||||||
|
console.log(must(sh(core, py, ['scripts/mojo/corpus.py', 'status', '--strict']), 'mojo-status-strict').out.split('\n').slice(-2).join('\n'));
|
||||||
|
console.log(must(sh(core, process.execPath, ['scripts/library.mjs', 'check']), 'library-check').out.split('\n').slice(-1).join('\n'));
|
||||||
|
if (tracked(lib).length) { console.error(`release bump: library-check rewrote ${tracked(lib).join(', ')}: the library's records were not current. Commit them in pplus-library, then run release-bump again`); process.exit(1); }
|
||||||
|
}
|
||||||
|
const coreChanges = tracked(core);
|
||||||
|
const coreMsg = `Move pplus-library to ${short(libHead)}, and regenerate what core derives from it`;
|
||||||
|
const libBranch = toLib.branch;
|
||||||
|
push.push({ repo: 'pplus-library', dir: lib, sha: libHead, branch: libBranch });
|
||||||
|
let coreSha = git(core, ['rev-parse', 'HEAD']);
|
||||||
|
if (coreChanges.length) {
|
||||||
|
if (commit) {
|
||||||
|
must(sh(core, 'git', ['add', '--', ...coreChanges]), 'git add in core');
|
||||||
|
must(sh(core, 'git', ['commit', '-q', '-m', coreMsg]), 'git commit in core');
|
||||||
|
coreSha = git(core, ['rev-parse', 'HEAD']);
|
||||||
|
console.log(`committed core ${short(coreSha)}: ${coreMsg}`);
|
||||||
|
} else {
|
||||||
|
console.log(`\nto commit in core (or run again with --commit):\n git -C core add ${coreChanges.join(' ')}\n git -C core commit -m "${coreMsg}"`);
|
||||||
|
}
|
||||||
|
} else console.log('core: nothing to commit');
|
||||||
|
push.push({ repo: 'pplus-core', dir: core, sha: coreChanges.length && !commit ? null : coreSha, branch: toCore.branch });
|
||||||
|
|
||||||
|
// 2. web: pointer to core's commit, regenerate, gate
|
||||||
|
const corePinned = pointer(WEB, 'core');
|
||||||
|
const coreMoved = coreSha !== corePinned || (coreChanges.length && !commit);
|
||||||
|
if (commit && coreSha !== corePinned) { step(`web: move core from ${short(corePinned)} to ${short(coreSha)}`); must(sh(WEB, 'git', ['add', 'core']), 'git add core in web'); }
|
||||||
|
else if (!coreMoved) step(`web already pins core at ${short(coreSha)}`);
|
||||||
|
else step("web: built and tested against core's working tree (the pointer moves when core's commit exists)");
|
||||||
|
must(sh(WEB, process.execPath, [tsc(), '-p', 'tsconfig.json']), 'building the site');
|
||||||
|
console.log(must(sh(WEB, process.execPath, ['scripts/quarto-css.mjs']), 'quarto-css').out.split('\n').slice(-2).join('\n'));
|
||||||
|
if (gate) {
|
||||||
|
step("web's gate: every test of the site");
|
||||||
|
const t = must(sh(WEB, process.execPath, ['--test', ...testFiles(WEB)]), "the site's tests");
|
||||||
|
console.log(t.out.split('\n').filter((l) => /^ℹ (tests|pass|fail|skipped)/.test(l)).join('\n'));
|
||||||
|
}
|
||||||
|
const webChanges = tracked(WEB);
|
||||||
|
const webMsg = `Move pplus-core to ${short(coreSha)}`;
|
||||||
|
let webSha = git(WEB, ['rev-parse', 'HEAD']);
|
||||||
|
if (webChanges.length && commit) {
|
||||||
|
must(sh(WEB, 'git', ['add', '--', ...webChanges]), 'git add in web');
|
||||||
|
must(sh(WEB, 'git', ['commit', '-q', '-m', webMsg]), 'git commit in web');
|
||||||
|
webSha = git(WEB, ['rev-parse', 'HEAD']);
|
||||||
|
console.log(`committed web ${short(webSha)}: ${webMsg}`);
|
||||||
|
} else if (webChanges.length || coreMoved) {
|
||||||
|
console.log(`\nto commit in web, after core's commit:\n git add core${webChanges.filter((f) => f !== 'core').map((f) => ` ${f}`).join('')}\n git commit -m "Move pplus-core to <core's new commit>"`);
|
||||||
|
}
|
||||||
|
push.push({ repo: 'pplus-web', dir: WEB, sha: webChanges.length && !commit ? null : webSha, branch: 'main' });
|
||||||
|
|
||||||
|
console.log('\nPush in this order, each before the next (a pointer may only name a pushed commit); nothing was pushed:');
|
||||||
|
push.forEach((p, i) => console.log(` ${i + 1}. ${p.repo} ${p.sha ? short(p.sha) : '(the commit above, once made)'} to ${p.branch}: git -C ${rel(p.dir)} push origin ${p.sha ?? 'HEAD'}:refs/heads/${p.branch}`));
|
||||||
|
console.log('Then pixi run release-check should say every pointer is on its branch.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Command line */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const cmd = args[0];
|
||||||
|
if (cmd === 'check') {
|
||||||
|
const lines = args.includes('--quick') ? quickCheck().map((q) => ({ ...q, where: 'pointers' })) : fullCheck({ offline: args.includes('--offline') });
|
||||||
|
if (args.includes('--json')) console.log(JSON.stringify(lines, null, 2));
|
||||||
|
else {
|
||||||
|
const tag = { ok: 'ok ', problem: 'PROBLEM ', unknown: 'cannot tell', note: 'note ' };
|
||||||
|
for (const l of lines) console.log(`${tag[l.level]} [${l.where}] ${l.text}`);
|
||||||
|
const n = (lv) => lines.filter((l) => l.level === lv).length;
|
||||||
|
console.log(`\n${n('problem') ? `${n('problem')} problem(s)` : 'the chain is consistent'}${n('unknown') ? `; ${n('unknown')} thing(s) it cannot tell` : ''}`);
|
||||||
|
}
|
||||||
|
process.exit(lines.some((l) => l.level === 'problem') ? 1 : 0);
|
||||||
|
} else if (cmd === 'bump') {
|
||||||
|
bump({ commit: args.includes('--commit'), gate: !args.includes('--no-gate') });
|
||||||
|
} else {
|
||||||
|
console.error('usage: node scripts/release.mjs check [--offline] [--quick] [--json] | bump [--commit] [--no-gate]');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+17
@@ -0,0 +1,17 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
const esbuild = await import(process.env.ESBUILD_LIB || 'esbuild');
|
||||||
|
import path from 'node:path';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
|
||||||
|
const here = path.dirname(new URL(import.meta.url).pathname);
|
||||||
|
const map = {
|
||||||
|
'@codemirror/state': 'state/src/index.ts', '@codemirror/view': 'view/src/index.ts', '@codemirror/language': 'language/src/index.ts',
|
||||||
|
'@codemirror/commands': 'commands/src/index.ts', '@codemirror/search': 'search/src/index.ts',
|
||||||
|
'@lezer/common': 'common/src/index.ts', '@lezer/highlight': 'highlight/src/highlight.ts', '@lezer/lr': 'lr/src/index.ts',
|
||||||
|
'style-mod': 'style-mod/src/style-mod.js', 'w3c-keyname': 'w3c-keyname/index.js', 'crelt': 'crelt/index.js', '@marijn/find-cluster-break': 'find-cluster-break/src/index.js',
|
||||||
|
};
|
||||||
|
const alias = { name: 'alias', setup(b) { b.onResolve({ filter: /^(@codemirror|@lezer|@marijn)\/|^(style-mod|w3c-keyname|crelt)$/ }, (a) => ({ path: path.join(here, map[a.path]) })); } };
|
||||||
|
const versions = Object.entries(map).map(([k, v]) => `${k}@${JSON.parse(fs.readFileSync(path.join(here, v.split('/')[0], 'package.json'), 'utf8')).version}`);
|
||||||
|
const banner = `/* CodeMirror 6, bundled for Programming+ from the packages' sources (MIT; see CODEMIRROR-LICENSE next to this file).\n * ${versions.join(' ')}\n * Rebuild with scripts/vendor/codemirror.sh; do not edit by hand. */`;
|
||||||
|
await esbuild.build({ entryPoints: [path.join(here, 'entry.ts')], bundle: true, format: 'esm', outfile: path.join(here, 'codemirror.js'), plugins: [alias], target: 'es2022', minifyWhitespace: true, minifySyntax: true, legalComments: 'none', banner: { js: banner }, logLevel: 'info' });
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
# Rebuilds src/vendor/codemirror.js (one ES module) and src/vendor/cm-types/ (its
|
||||||
|
# declarations) from the CodeMirror packages' own sources on GitHub.
|
||||||
|
#
|
||||||
|
# Programming+ ships no bundler and no runtime dependency; CodeMirror is
|
||||||
|
# vendored the way the pseudo and asm86 engines are, as a built file checked
|
||||||
|
# into the repository. Rerun this to move to newer CodeMirror releases:
|
||||||
|
#
|
||||||
|
# scripts/vendor/codemirror.sh # the packages' main branches
|
||||||
|
# scripts/vendor/codemirror.sh @6.5.0 ... # (edit PINS below for exact tags)
|
||||||
|
#
|
||||||
|
# Needs: git, node >= 20, esbuild on the PATH or in ESBUILD, and tsc.
|
||||||
|
set -euo pipefail
|
||||||
|
here="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
root="$(cd "$here/../.." && pwd)"
|
||||||
|
work="${CM_WORK:-$(mktemp -d)}"
|
||||||
|
ESBUILD="${ESBUILD:-$(command -v esbuild || true)}"
|
||||||
|
[ -n "$ESBUILD" ] || { echo "esbuild not found: npm i -g esbuild, or ESBUILD=/path/to/esbuild"; exit 1; }
|
||||||
|
|
||||||
|
# repo -> directory name the build script expects
|
||||||
|
PINS=(
|
||||||
|
"codemirror/state state" "codemirror/view view" "codemirror/language language" "codemirror/commands commands" "codemirror/search search"
|
||||||
|
"marijnh/style-mod style-mod" "marijnh/w3c-keyname w3c-keyname" "marijnh/crelt crelt" "marijnh/find-cluster-break find-cluster-break"
|
||||||
|
"lezer-parser/common common" "lezer-parser/highlight highlight" "lezer-parser/lr lr"
|
||||||
|
)
|
||||||
|
cd "$work"
|
||||||
|
for pin in "${PINS[@]}"; do
|
||||||
|
set -- $pin
|
||||||
|
[ -d "$2" ] || git clone -q --depth 1 "https://github.com/$1" "$2"
|
||||||
|
done
|
||||||
|
# two packages have no src/index.ts of their own
|
||||||
|
printf 'export * from "./commands"\nexport * from "./history"\nexport * from "./comment"\n' > commands/src/index.ts
|
||||||
|
printf 'export * from "./search"\nexport * from "./cursor"\nexport * from "./regexp"\nexport * from "./goto-line"\nexport * from "./selection-match"\n' > search/src/index.ts
|
||||||
|
cp "$here/entry.ts" "$here/build.mjs" "$here/relink.mjs" "$here/tsconfig.cm.json" .
|
||||||
|
mv tsconfig.cm.json tsconfig.json
|
||||||
|
ESBUILD_LIB="$(node -e "console.log(require.resolve('esbuild', { paths: [process.cwd(), '$(dirname "$ESBUILD")/..', '$(npm root -g)'] }))")" node build.mjs
|
||||||
|
rm -rf types && (tsc -p tsconfig.json || true) # the packages' own sources have a few strict-mode complaints; the declarations still emit
|
||||||
|
node relink.mjs
|
||||||
|
rm -rf "$root/src/vendor/cm-types"
|
||||||
|
cp codemirror.js "$root/src/vendor/codemirror.js"
|
||||||
|
cp -r types "$root/src/vendor/cm-types"
|
||||||
|
rm "$root/src/vendor/cm-types/entry.d.ts"
|
||||||
|
sed 's#"\./#"./cm-types/#g' types/entry.d.ts > "$root/src/vendor/codemirror.d.ts"
|
||||||
|
cp state/LICENSE "$root/src/vendor/CODEMIRROR-LICENSE"
|
||||||
|
echo "vendored into $root/src/vendor from $work"
|
||||||
Vendored
+8
@@ -0,0 +1,8 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
// Programming+'s CodeMirror 6 bundle: the parts the editor uses, in one ES module.
|
||||||
|
export * from '@codemirror/state';
|
||||||
|
export * from '@codemirror/view';
|
||||||
|
export { history, historyKeymap, undo, redo, defaultKeymap, indentWithTab, insertNewlineAndIndent, toggleComment, selectAll, indentMore, indentLess } from '@codemirror/commands';
|
||||||
|
export { search, searchKeymap, highlightSelectionMatches, openSearchPanel, closeSearchPanel, gotoLine } from '@codemirror/search';
|
||||||
|
export { indentUnit, bracketMatching, foldGutter, foldKeymap, codeFolding, foldService, indentService, StreamLanguage, LanguageSupport, syntaxHighlighting, HighlightStyle, defaultHighlightStyle } from '@codemirror/language';
|
||||||
Vendored
+26
@@ -0,0 +1,26 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
import fs from 'node:fs'; import path from 'node:path';
|
||||||
|
const root = path.resolve('types');
|
||||||
|
const map = {
|
||||||
|
'@codemirror/state': 'state/src/index.d.ts', '@codemirror/view': 'view/src/index.d.ts', '@codemirror/language': 'language/src/index.d.ts',
|
||||||
|
'@codemirror/commands': 'commands/src/index.d.ts', '@codemirror/search': 'search/src/index.d.ts',
|
||||||
|
'@lezer/common': 'common/src/index.d.ts', '@lezer/highlight': 'highlight/src/highlight.d.ts', '@lezer/lr': 'lr/src/index.d.ts',
|
||||||
|
'style-mod': 'style-mod/src/style-mod.d.ts', 'w3c-keyname': 'w3c-keyname/index.d.ts', 'crelt': 'crelt/index.d.ts', '@marijn/find-cluster-break': 'find-cluster-break/src/index.d.ts',
|
||||||
|
};
|
||||||
|
// the plain-JS deps' hand-written d.ts files were not emitted by tsc; copy them in
|
||||||
|
for (const [k, v] of Object.entries(map)) { const dst = path.join(root, v); if (!fs.existsSync(dst)) { fs.mkdirSync(path.dirname(dst), { recursive: true }); fs.copyFileSync(path.join(k === '@marijn/find-cluster-break' ? 'find-cluster-break/src/index.d.ts' : v), dst); } }
|
||||||
|
const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(path.join(d, e.name)) : e.name.endsWith('.d.ts') ? [path.join(d, e.name)] : []);
|
||||||
|
let n = 0;
|
||||||
|
for (const f of walk(root)) {
|
||||||
|
let s = fs.readFileSync(f, 'utf8');
|
||||||
|
const before = s;
|
||||||
|
s = s.replace(/from ["']([^"']+)["']/g, (m, spec) => {
|
||||||
|
if (!map[spec]) return m;
|
||||||
|
let rel = path.relative(path.dirname(f), path.join(root, map[spec])).replace(/\\/g, '/').replace(/\.d\.ts$/, '.js');
|
||||||
|
if (!rel.startsWith('.')) rel = './' + rel;
|
||||||
|
return `from "${rel}"`;
|
||||||
|
});
|
||||||
|
if (s !== before) { fs.writeFileSync(f, s); n++; }
|
||||||
|
}
|
||||||
|
console.log('relinked', n, 'files');
|
||||||
Vendored
+64
@@ -0,0 +1,64 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"lib": [
|
||||||
|
"ES2022",
|
||||||
|
"DOM",
|
||||||
|
"DOM.Iterable"
|
||||||
|
],
|
||||||
|
"declaration": true,
|
||||||
|
"emitDeclarationOnly": true,
|
||||||
|
"outDir": "types",
|
||||||
|
"rootDir": ".",
|
||||||
|
"strict": false,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"allowJs": true,
|
||||||
|
"stripInternal": true,
|
||||||
|
"types": [],
|
||||||
|
"baseUrl": ".",
|
||||||
|
"ignoreDeprecations": "6.0",
|
||||||
|
"paths": {
|
||||||
|
"@codemirror/state": [
|
||||||
|
"state/src/index.ts"
|
||||||
|
],
|
||||||
|
"@codemirror/view": [
|
||||||
|
"view/src/index.ts"
|
||||||
|
],
|
||||||
|
"@codemirror/language": [
|
||||||
|
"language/src/index.ts"
|
||||||
|
],
|
||||||
|
"@codemirror/commands": [
|
||||||
|
"commands/src/index.ts"
|
||||||
|
],
|
||||||
|
"@codemirror/search": [
|
||||||
|
"search/src/index.ts"
|
||||||
|
],
|
||||||
|
"@lezer/common": [
|
||||||
|
"common/src/index.ts"
|
||||||
|
],
|
||||||
|
"@lezer/highlight": [
|
||||||
|
"highlight/src/highlight.ts"
|
||||||
|
],
|
||||||
|
"@lezer/lr": [
|
||||||
|
"lr/src/index.ts"
|
||||||
|
],
|
||||||
|
"style-mod": [
|
||||||
|
"style-mod/src/style-mod.d.ts"
|
||||||
|
],
|
||||||
|
"w3c-keyname": [
|
||||||
|
"w3c-keyname/index.d.ts"
|
||||||
|
],
|
||||||
|
"crelt": [
|
||||||
|
"crelt/index.d.ts"
|
||||||
|
],
|
||||||
|
"@marijn/find-cluster-break": [
|
||||||
|
"find-cluster-break/src/index.d.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"entry.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The three areas (restructure plan, section 2.1). A problem is one `PlayState` shared by all three, so moving
|
||||||
|
* from the Bridge to the Developer area to Hardware carries the work along; the area comes from the route, not
|
||||||
|
* the state. The names are placeholders in this one table: the owner renames an area with a one-line change
|
||||||
|
* here (and nowhere else), and the routes, which are ids, stay.
|
||||||
|
*/
|
||||||
|
import type { LangId } from '#core/common/types.js';
|
||||||
|
import type { DockTab, PlayState } from './state.js';
|
||||||
|
import { LINKED } from '#core/sync/hub.js';
|
||||||
|
|
||||||
|
export type { AreaId } from '#core/common/types.js';
|
||||||
|
import type { AreaId } from '#core/common/types.js';
|
||||||
|
|
||||||
|
/** The tabs beside the editor: the views that read a run. */
|
||||||
|
export type InspectId = 'trace' | 'table' | 'flow' | 'data' | 'life' | 'proof' | 'tests';
|
||||||
|
|
||||||
|
export interface AreaDef {
|
||||||
|
id: AreaId;
|
||||||
|
/** The path segment: `#/<route>/p/<problem>`. */
|
||||||
|
route: AreaId;
|
||||||
|
/** What the area is called on screen. */
|
||||||
|
name: string;
|
||||||
|
tagline: string;
|
||||||
|
/** The panes it offers, in tab order. */
|
||||||
|
panes: LangId[];
|
||||||
|
/** The inspect tabs it may offer (each also has to apply to the open pane). `trace` is the Run view: the run top to bottom, with the variables followed and their lifetimes. */
|
||||||
|
inspect: InspectId[];
|
||||||
|
/** The dock tabs it may offer. */
|
||||||
|
dock: DockTab[];
|
||||||
|
/** What the toolbar's main button does for the pane that is open: run it as written, or build it with the real compiler. */
|
||||||
|
primary: 'run' | 'compile';
|
||||||
|
/**
|
||||||
|
* How the workspace is laid out: `ide`, the code with the inspect panel beside it and the dock below; `board`, two
|
||||||
|
* panes only, the code on the left and on the right a board of cards the student arranges (src/ui/hw/board.ts),
|
||||||
|
* which holds what the dock and the inspect panel would (setup, output, problems, the compiler, the Run view).
|
||||||
|
*/
|
||||||
|
workspace: 'ide' | 'board';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AREAS: Record<AreaId, AreaDef> = {
|
||||||
|
bridge: {
|
||||||
|
id: 'bridge', route: 'bridge', name: 'Bridge',
|
||||||
|
tagline: 'Take a written problem or idea into Mojo: write it as plain-English steps (lingo), equations (matho) or pseudocode (pseudo), and Mojo is generated from the pseudo.',
|
||||||
|
panes: ['lingo', 'matho', 'pseudo', 'speco', 'mojo'],
|
||||||
|
inspect: ['trace', 'flow', 'data', 'proof', 'tests'],
|
||||||
|
dock: ['setup', 'output', 'problems', 'compiler', 'practices'],
|
||||||
|
primary: 'run', workspace: 'ide',
|
||||||
|
},
|
||||||
|
dev: {
|
||||||
|
id: 'dev', route: 'dev', name: 'Developer',
|
||||||
|
tagline: 'Write Mojo: the checker, the stepper, lifetimes, tests, and the real compiler.',
|
||||||
|
panes: ['mojo'],
|
||||||
|
inspect: ['trace', 'flow', 'data', 'tests'],
|
||||||
|
dock: ['setup', 'output', 'problems', 'compiler'],
|
||||||
|
primary: 'compile', workspace: 'ide',
|
||||||
|
},
|
||||||
|
hw: {
|
||||||
|
id: 'hw', route: 'hw', name: 'Hardware',
|
||||||
|
tagline: 'See the machine: Mojo and the x86-64 it compiles to, stepped on a model machine with its registers, memory and chip in view.',
|
||||||
|
panes: ['mojo', 'asm'],
|
||||||
|
// no inspect panel and no dock: their views are cards on the board
|
||||||
|
inspect: [],
|
||||||
|
dock: [],
|
||||||
|
primary: 'compile', workspace: 'board',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AREA_ORDER: AreaId[] = ['bridge', 'dev', 'hw'];
|
||||||
|
|
||||||
|
export const isAreaId = (x: unknown): x is AreaId => typeof x === 'string' && Object.prototype.hasOwnProperty.call(AREAS, x);
|
||||||
|
|
||||||
|
/** The area an exercise opens in when it does not say: Hardware for assembly problems, Developer for Mojo-only ones, Bridge for the rest. */
|
||||||
|
export function defaultAreaFor(e: { id: string; sources: Partial<Record<LangId, string>>; area?: AreaId; mojoProgram?: string }): AreaId {
|
||||||
|
if (e.area) return e.area;
|
||||||
|
const has = (l: LangId) => !!(e.sources[l] ?? '').trim();
|
||||||
|
if (e.id.startsWith('asm-')) return 'hw';
|
||||||
|
if ((has('mojo') || e.mojoProgram) && !has('pseudo') && !has('lingo') && !has('matho')) return 'dev';
|
||||||
|
return 'bridge';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a pane is one of the area's. */
|
||||||
|
export const areaHasPane = (area: AreaDef, lang: LangId): boolean => area.panes.includes(lang);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pane to show when a state opens in an area. A pane that belongs to the area is kept (a shared link points
|
||||||
|
* at one view on purpose); otherwise the area's own first choice. `fresh` is for a catalog problem opening: its
|
||||||
|
* authored default pane is Mojo for most, but the Bridge begins with the idea, not the generated code.
|
||||||
|
*/
|
||||||
|
export function paneForArea(area: AreaDef, state: PlayState, fresh = false): LangId {
|
||||||
|
const has = (l: LangId) => !!(state.sources[l] ?? '').trim();
|
||||||
|
switch (area.id) {
|
||||||
|
case 'dev': return 'mojo';
|
||||||
|
case 'hw': return areaHasPane(area, state.lang) ? state.lang : has('asm') ? 'asm' : 'mojo';
|
||||||
|
case 'bridge': {
|
||||||
|
if ((LINKED as readonly string[]).includes(state.lang)) return state.lang;
|
||||||
|
if (!fresh && areaHasPane(area, state.lang)) return state.lang;
|
||||||
|
return (['pseudo', 'lingo', 'matho', 'speco'] as LangId[]).find(has) ?? 'pseudo';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The areas the work can move to from `from` without changing what is on screen: the open pane exists there, and it
|
||||||
|
* shows the same text. In practice that is Developer and Hardware on the same Mojo; the Bridge's Mojo is the
|
||||||
|
* translation of its pseudo, so it matches the others only when the student's Mojo is that translation. The
|
||||||
|
* toolbar offers only these; every area is its own page in the nav and on the home page, so a learner moving
|
||||||
|
* between them never finds the work changed under them by the move itself.
|
||||||
|
*/
|
||||||
|
export function safeSwitches(from: AreaId, lang: LangId, shown: (area: AreaId, lang: LangId) => string): AreaId[] {
|
||||||
|
if (!areaHasPane(AREAS[from], lang)) return [];
|
||||||
|
const here = shown(from, lang);
|
||||||
|
// an empty pane carries nothing across: "the same" would be true of any area, and the move would show other work
|
||||||
|
if (!here.trim()) return [];
|
||||||
|
return AREA_ORDER.filter((to) => to !== from && areaHasPane(AREAS[to], lang) && shown(to, lang) === here);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The areas a catalog problem has something to show in, its own area first: the Bridge when it has an idea to
|
||||||
|
* translate (lingo, matho, pseudo or speco), Developer when it has Mojo, Hardware when it has x86-64. The home
|
||||||
|
* page's problem cards link to each and filter by them.
|
||||||
|
*/
|
||||||
|
export function areasFor(p: { area: AreaId; sources: Partial<Record<LangId, string>>; mojo?: { source?: string } | null }): AreaId[] {
|
||||||
|
const has = (l: LangId) => !!(p.sources[l] ?? '').trim();
|
||||||
|
const fits: Record<AreaId, boolean> = {
|
||||||
|
bridge: has('pseudo') || has('lingo') || has('matho') || has('speco'),
|
||||||
|
dev: has('mojo') || !!p.mojo?.source?.trim(),
|
||||||
|
hw: has('asm'),
|
||||||
|
};
|
||||||
|
return [p.area, ...AREA_ORDER.filter((a) => a !== p.area && fits[a])];
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The app's problem catalog: core's problems (core/problems.ts), each with the
|
||||||
|
* area it opens in, and the saved state a problem opens with.
|
||||||
|
*/
|
||||||
|
import { PROBLEMS as CORE_PROBLEMS, type Problem as CoreProblem } from '#core/common/problems.js';
|
||||||
|
import { defaultAreaFor, type AreaId } from './areas.js';
|
||||||
|
import { emptyState, type PlayState } from './state.js';
|
||||||
|
|
||||||
|
export interface Problem extends CoreProblem {
|
||||||
|
/** The area it opens in from the problem list. */
|
||||||
|
area: AreaId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PROBLEMS: Problem[] = CORE_PROBLEMS.map((p) => ({ ...p, area: defaultAreaFor({ id: p.id, sources: p.sources, area: p.area, mojoProgram: p.mojoProgram }) }));
|
||||||
|
|
||||||
|
export function problemById(id: string): Problem | undefined {
|
||||||
|
return PROBLEMS.find((p) => p.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function stateForProblem(p: Problem): PlayState {
|
||||||
|
const s = emptyState();
|
||||||
|
s.problem = p.id;
|
||||||
|
s.title = p.title;
|
||||||
|
s.sources = { ...p.sources };
|
||||||
|
s.lang = p.lang;
|
||||||
|
s.call = p.call ?? null;
|
||||||
|
s.setup = p.setup;
|
||||||
|
s.machine = p.machine;
|
||||||
|
s.view = p.view ?? 'trace';
|
||||||
|
return s;
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* godbolt's answers, kept across everything that rebuilds the page: switching panes or problems, following a
|
||||||
|
* link, reloading. An answer is only ever shown for exactly the source, input and build it answered, so a
|
||||||
|
* kept one is as good as a new one; asking again costs a network round trip and a slot in godbolt's rate limit.
|
||||||
|
*
|
||||||
|
* Kept in memory for this tab, and in localStorage (the newest few, smallest first to go when space runs out)
|
||||||
|
* so a reload or a new tab finds them too. A browser that refuses storage still keeps them for the tab.
|
||||||
|
*/
|
||||||
|
import type { BuildLevel, CompileOutcome } from '#core/services/godbolt.js';
|
||||||
|
|
||||||
|
export interface KeptCompile { source: string; stdin: string; level: BuildLevel; at: number; outcome: CompileOutcome }
|
||||||
|
|
||||||
|
const KEY = 'pplus.compiles';
|
||||||
|
const KEEP = 16;
|
||||||
|
let memory: KeptCompile[] | null = null;
|
||||||
|
|
||||||
|
function load(): KeptCompile[] {
|
||||||
|
if (memory) return memory;
|
||||||
|
memory = [];
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(KEY);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : [];
|
||||||
|
if (Array.isArray(parsed)) memory = parsed.filter((r) => r && typeof r.source === 'string' && typeof r.stdin === 'string' && (r.level === 'O0' || r.level === 'default') && r.outcome);
|
||||||
|
} catch { /* storage blocked or the entry is damaged: start empty */ }
|
||||||
|
return memory;
|
||||||
|
}
|
||||||
|
|
||||||
|
function save(list: KeptCompile[]): void {
|
||||||
|
// drop the oldest until it fits; a browser that refuses storage keeps them in memory only
|
||||||
|
for (let n = list.length; n > 0; n--) {
|
||||||
|
try { localStorage.setItem(KEY, JSON.stringify(list.slice(0, n))); return; } catch { /* over quota: keep fewer */ }
|
||||||
|
}
|
||||||
|
try { localStorage.removeItem(KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the summary index: what the godbolt badge reads ---------- */
|
||||||
|
|
||||||
|
/** What godbolt said about a build, in the few words a badge needs. */
|
||||||
|
export type CompiledOutcome = 'ran' | 'did-not-compile' | 'timed-out' | 'not-run';
|
||||||
|
export interface CompiledSummary { hash: string; level: BuildLevel; outcome: CompiledOutcome; exit: number | null; at: number }
|
||||||
|
export interface CompiledStatus { outcome: CompiledOutcome; exit: number | null; at: number; level: BuildLevel }
|
||||||
|
|
||||||
|
const INDEX_KEY = 'pplus.compiled';
|
||||||
|
const INDEX_KEEP = 300;
|
||||||
|
let index: CompiledSummary[] | null = null;
|
||||||
|
|
||||||
|
/** A content hash of exactly what was sent: the source, the input, and the build level (cyrb53, 53 bits, as hex). */
|
||||||
|
export function compileHash(source: string, stdin: string, level: BuildLevel): string {
|
||||||
|
const str = JSON.stringify([source, stdin, level]);
|
||||||
|
let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
const c = str.charCodeAt(i);
|
||||||
|
h1 = Math.imul(h1 ^ c, 2654435761);
|
||||||
|
h2 = Math.imul(h2 ^ c, 1597334677);
|
||||||
|
}
|
||||||
|
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
||||||
|
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
||||||
|
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0') + str.length.toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadIndex(): CompiledSummary[] {
|
||||||
|
if (index) return index;
|
||||||
|
index = [];
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(INDEX_KEY);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : [];
|
||||||
|
if (Array.isArray(parsed)) index = parsed.filter((r) => r && typeof r.hash === 'string' && (r.level === 'O0' || r.level === 'default') && typeof r.at === 'number'
|
||||||
|
&& (r.outcome === 'ran' || r.outcome === 'did-not-compile' || r.outcome === 'timed-out' || r.outcome === 'not-run'));
|
||||||
|
} catch { /* storage blocked or damaged: start empty */ }
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveIndex(list: CompiledSummary[]): void {
|
||||||
|
for (let n = list.length; n > 0; n = Math.floor(n / 2)) {
|
||||||
|
try { localStorage.setItem(INDEX_KEY, JSON.stringify(list.slice(0, n))); return; } catch { /* over quota: keep fewer */ }
|
||||||
|
}
|
||||||
|
try { localStorage.removeItem(INDEX_KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarize(rec: KeptCompile): CompiledSummary | null {
|
||||||
|
const a = rec.outcome.answer;
|
||||||
|
if (!a) return null;
|
||||||
|
const outcome: CompiledOutcome = !a.compiled ? 'did-not-compile' : a.timedOut ? 'timed-out' : !a.executed ? 'not-run' : 'ran';
|
||||||
|
return { hash: compileHash(rec.source, rec.stdin, rec.level), level: rec.level, outcome, exit: a.executed ? a.exitCode : null, at: rec.at };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What godbolt last said about exactly this source, input and build level, or null when this browser never
|
||||||
|
* asked. Only this browser's own compiles are in the index, never anything from a link or a file.
|
||||||
|
*/
|
||||||
|
export function compiledStatus(source: string, stdin: string, level: BuildLevel): CompiledStatus | null {
|
||||||
|
if (!source.trim()) return null;
|
||||||
|
const hash = compileHash(source, stdin, level);
|
||||||
|
const r = loadIndex().find((x) => x.hash === hash);
|
||||||
|
return r ? { outcome: r.outcome, exit: r.exit, at: r.at, level: r.level } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep an answer (a network failure is not worth keeping: asking again may well work). */
|
||||||
|
export function keepCompile(rec: KeptCompile): void {
|
||||||
|
if (!rec.outcome.answer) return;
|
||||||
|
const sum = summarize(rec);
|
||||||
|
if (sum) { index = [sum, ...loadIndex().filter((r) => r.hash !== sum.hash)].slice(0, INDEX_KEEP); saveIndex(index); }
|
||||||
|
const list = load().filter((r) => !(r.source === rec.source && r.stdin === rec.stdin && r.level === rec.level));
|
||||||
|
list.unshift({ source: rec.source, stdin: rec.stdin, level: rec.level, at: rec.at, outcome: rec.outcome });
|
||||||
|
memory = list.slice(0, KEEP);
|
||||||
|
save(memory);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every kept answer for this exact source, newest first. */
|
||||||
|
export function keptCompiles(source: string): KeptCompile[] {
|
||||||
|
return load().filter((r) => r.source === source);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forget every kept answer (the tests use this). */
|
||||||
|
export function forgetCompiles(): void {
|
||||||
|
memory = []; index = [];
|
||||||
|
try { localStorage.removeItem(KEY); localStorage.removeItem(INDEX_KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Text for a spreadsheet: the trace's CSV export (the stepper's CSV button) and the table of values' "copy as
|
||||||
|
* text". DOM-free, so a test holds it.
|
||||||
|
*
|
||||||
|
* A spreadsheet reads a cell that starts with =, +, - or @ (or a tab or a carriage return) as a formula, and a
|
||||||
|
* program's text and output are anyone's to write: a shared link can carry `OUTPUT "=HYPERLINK(...)"`. Such a cell
|
||||||
|
* is written with a leading apostrophe, which a spreadsheet shows as text and does not keep in the value. A cell that
|
||||||
|
* reads as a plain number (-3, +2.5, 1e-9) is not a formula and is left as it is.
|
||||||
|
*/
|
||||||
|
const NUMBER = /^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$/;
|
||||||
|
|
||||||
|
/** A cell's text, made safe to open in a spreadsheet. */
|
||||||
|
export function safeCell(v: unknown): string {
|
||||||
|
const s = String(v ?? '');
|
||||||
|
return /^[=+\-@\t\r]/.test(s) && !NUMBER.test(s) ? `'${s}` : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One CSV field: safe, quoted, with its quotes doubled. */
|
||||||
|
export function csvCell(v: unknown): string {
|
||||||
|
return `"${safeCell(v).replace(/"/g, '""')}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rows of cells as CSV text, one line per row. */
|
||||||
|
export function toCsv(rows: unknown[][]): string {
|
||||||
|
return rows.map((r) => r.map(csvCell).join(',')).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rows of cells as tab-separated text (what a spreadsheet takes from the clipboard): tabs and line breaks in a cell become spaces. */
|
||||||
|
export function toTsv(rows: unknown[][]): string {
|
||||||
|
return rows.map((r) => r.map((c) => safeCell(String(c ?? '').replace(/[\t\r\n]+/g, ' '))).join('\t')).join('\n');
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* A saved piece of work that takes the page down every time it opens must not lock the student out of it.
|
||||||
|
*
|
||||||
|
* The engines stop a program that runs too long, but a program can still exhaust the tab's memory before a limit
|
||||||
|
* is reached (in Mojo 1.2.0's interpreter, a string doubled in a loop), and the browser then kills the page. The
|
||||||
|
* work is saved on every edit, so without this the next visit would run it again and die again.
|
||||||
|
*
|
||||||
|
* Before work runs (an edit, or opening saved work), its save's id is marked busy in this tab; the mark is cleared
|
||||||
|
* once the page has been idle for a moment. A timer cannot fire while a synchronous run is going, so a run that
|
||||||
|
* ends with the page killed leaves the mark behind, and the reload finds it: that save is set aside as a version
|
||||||
|
* and the problem opens as written, with a note. DOM-free; the storage is a parameter.
|
||||||
|
*/
|
||||||
|
import { saveVersion, versionKey, type Store } from './versions.js';
|
||||||
|
import type { PlayState } from './state.js';
|
||||||
|
import type { AreaId } from './areas.js';
|
||||||
|
|
||||||
|
const KEY = 'pplus.busy';
|
||||||
|
/** How long after the last edit or open the page must stay alive before the mark is cleared (ms). */
|
||||||
|
export const SETTLE_MS = 1500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mark lives in sessionStorage: it belongs to this tab (another tab busy with the same work is not a crash), it
|
||||||
|
* survives the reload after the browser kills the page, and it never adds to the work kept in localStorage.
|
||||||
|
*/
|
||||||
|
const markStore = (): Store | null => { try { return typeof sessionStorage === 'undefined' ? null : sessionStorage; } catch { return null; } };
|
||||||
|
const workStore = (): Store | null => { try { return typeof localStorage === 'undefined' ? null : localStorage; } catch { return null; } };
|
||||||
|
|
||||||
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
/** Say that the work saved under `id` is about to run; cleared on its own once the page has settled. */
|
||||||
|
export function markBusy(id: string, store: Store | null = markStore()): void {
|
||||||
|
if (!store) return;
|
||||||
|
try { store.setItem(KEY, id); } catch { return; /* storage full or blocked: nothing to recover from later either */ }
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => { timer = null; clearBusy(id, store); }, SETTLE_MS);
|
||||||
|
(timer as any)?.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The work under `id` ran to the end (or was put aside): forget the mark if it is still this one's. */
|
||||||
|
export function clearBusy(id: string, store: Store | null = markStore()): void {
|
||||||
|
try { if (store?.getItem(KEY) === id) store.removeItem(KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The id whose work was running when the page last died, if any, and forget it: read once, at load. A page that
|
||||||
|
* closed normally, or was reloaded after its work settled, leaves nothing.
|
||||||
|
*/
|
||||||
|
export function takeCrashed(store: Store | null = markStore()): string | null {
|
||||||
|
try {
|
||||||
|
const id = store?.getItem(KEY) ?? null;
|
||||||
|
if (id !== null) store!.removeItem(KEY);
|
||||||
|
return id;
|
||||||
|
} catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The page is closing normally (pagehide): whatever was marked did not take it down. */
|
||||||
|
export function settle(store: Store | null = markStore()): void {
|
||||||
|
if (timer) { clearTimeout(timer); timer = null; }
|
||||||
|
try { store?.removeItem(KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Put a save that would not open aside as a named version of the same work, and remove the save, so the problem
|
||||||
|
* opens as written. Returns the version's name, or null when the browser would not store it (the save is then
|
||||||
|
* left where it is: nothing is deleted that is not kept somewhere else).
|
||||||
|
*/
|
||||||
|
export function setAside(id: string, saved: PlayState, area: AreaId, why: 'stopped' | 'failed', store: Store | null = workStore(), now = Date.now()): string | null {
|
||||||
|
const t = new Date(now).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
|
||||||
|
const name = why === 'stopped' ? `When the page stopped (${t})` : `When it would not open (${t})`;
|
||||||
|
const key = versionKey(saved) ?? versionKey({ problem: id });
|
||||||
|
const r = saveVersion(key, name, saved, area, { store, now });
|
||||||
|
if (!r.ok) return null;
|
||||||
|
try { store?.removeItem(`pplus.${id}`); } catch { /* ignore */ }
|
||||||
|
return name;
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The Hardware area's machine board, without the DOM (restructure plan, Stage 15). The views themselves are the
|
||||||
|
* course's (`src/engines/asm86/views.js` and `hwviews.js`), mounted by `src/ui/hw/board.ts`; this module decides
|
||||||
|
* what they are given: which views a preset shows and with what options, and the frame each one draws. Everything
|
||||||
|
* here runs under `node --test`, so the board's data steps are tested without a browser.
|
||||||
|
*/
|
||||||
|
import { REGS } from '#core/engines/asm86/interp.js';
|
||||||
|
|
||||||
|
/* ---------- the machine (core/machine.ts) ---------- */
|
||||||
|
|
||||||
|
export { MACHINE_PRESETS, parseMachine, machineName, machineSpec, machineLabel, type MachineChoice } from '#core/common/machine.js';
|
||||||
|
import { parseMachine, type MachineChoice } from '#core/common/machine.js';
|
||||||
|
|
||||||
|
/* ---------- the board ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything the Hardware area's board can show, one card each. Course views are mounted by name with options
|
||||||
|
* (`course`); the others are the app's own: the run setup, the output, the problems, the compiler, the Run view,
|
||||||
|
* the counters, and the cache-line view. `needs` is the pane whose run a view reads: the machine views read the
|
||||||
|
* x86-64 pane's run, the Run view and the compiler the Mojo pane's; a card whose pane is not open says so.
|
||||||
|
*/
|
||||||
|
export type BoardViewId =
|
||||||
|
| 'registers' | 'flags' | 'address' | 'memory' | 'stack' | 'explain' | 'dataflow' | 'bits' | 'branches' | 'vectors'
|
||||||
|
| 'lines' | 'cache' | 'hierarchy' | 'paging'
|
||||||
|
| 'pipeline' | 'uops' | 'timeline' | 'bottleneck' | 'core' | 'machine' | 'encoding' | 'code'
|
||||||
|
| 'setup' | 'output' | 'problems' | 'compiler' | 'run' | 'counters';
|
||||||
|
|
||||||
|
export interface BoardViewDef {
|
||||||
|
id: BoardViewId;
|
||||||
|
label: string;
|
||||||
|
group: string;
|
||||||
|
/** What it shows, in a line (the add menu, the card's tooltip). */
|
||||||
|
blurb: string;
|
||||||
|
needs: 'asm' | 'mojo' | 'any';
|
||||||
|
/** Takes the board's whole width unless the student narrows it. */
|
||||||
|
wide: boolean;
|
||||||
|
/** A course view: its name in views.js / hwviews.js and its options for a run. */
|
||||||
|
course?: { name: string; options?: (trace: any, machine: MachineChoice) => Record<string, unknown> };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BOARD_GROUPS = ['Program', 'Registers and memory', 'Memory system', 'Time', 'The chip'] as const;
|
||||||
|
|
||||||
|
export const BOARD_VIEWS: BoardViewDef[] = [
|
||||||
|
{ id: 'setup', label: 'Setup', group: 'Program', needs: 'any', wide: false, blurb: 'The run setup: registers, memory and input for x86-64; the build and input for Mojo; the machine.' },
|
||||||
|
{ id: 'output', label: 'Output', group: 'Program', needs: 'any', wide: false, blurb: 'What the run has printed so far.' },
|
||||||
|
{ id: 'problems', label: 'Problems', group: 'Program', needs: 'any', wide: false, blurb: 'Every message on the open pane, with its one-click fixes.' },
|
||||||
|
{ id: 'compiler', label: 'Compiler', group: 'Program', needs: 'mojo', wide: true, blurb: 'The real Mojo compiler on godbolt: its messages, the output, and the listing, with Open in Hardware for a function.' },
|
||||||
|
{ id: 'run', label: 'Run', group: 'Program', needs: 'mojo', wide: true, blurb: 'The Mojo run top to bottom, with the variables you follow and their lifetimes.' },
|
||||||
|
{ id: 'code', label: 'Machine code listing', group: 'Program', needs: 'asm', wide: false, blurb: 'Every instruction with its address and bytes, the one about to run marked.', course: { name: 'code', options: () => ({ addresses: true, bytes: true, heat: true }) } },
|
||||||
|
{ id: 'explain', label: 'What it did', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'The last instruction in words: what it read, computed and wrote.', course: { name: 'explain' } },
|
||||||
|
{ id: 'registers', label: 'Registers', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'A card per register the program touches, with the value before and every narrower name it uses.', course: { name: 'registers', options: (trace) => ({ widths: subRegisterWidths(trace.program) }) } },
|
||||||
|
{ id: 'flags', label: 'Flags', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'ZF, SF, CF, OF, PF, with the ones the last instruction set and read.', course: { name: 'flags' } },
|
||||||
|
{ id: 'address', label: 'Address arithmetic', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'base + index × scale + displacement, part by part.', course: { name: 'address' } },
|
||||||
|
{ id: 'memory', label: 'Memory', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'Each memory region byte by byte, the load (blue) or store (purple) highlighted.', course: { name: 'memory' } },
|
||||||
|
{ id: 'stack', label: 'Stack', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Eight-byte slots with rsp and rbp marked, and what put each there.', course: { name: 'stack' } },
|
||||||
|
{ id: 'dataflow', label: 'Data flow', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Where the last instruction\'s values came from and went.', course: { name: 'dataflow' } },
|
||||||
|
{ id: 'bits', label: 'Inside the ALU', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'The arithmetic unit at bit level for the last instruction.', course: { name: 'bits' } },
|
||||||
|
{ id: 'branches', label: 'Branches', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Each branch: taken or not, and whether the predictor guessed right.', course: { name: 'branches' } },
|
||||||
|
{ id: 'vectors', label: 'Vector registers', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'The xmm registers lane by lane.', course: { name: 'vectors' } },
|
||||||
|
{ id: 'lines', label: 'Cache lines', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The cache line each load and store touched, and how many of its bytes the program uses.' },
|
||||||
|
{ id: 'cache', label: 'L1d cache', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The L1 data cache as sets and ways: a hit green, a miss red, the evicted line named.', course: { name: 'cache', options: () => ({ level: 'L1d' }) } },
|
||||||
|
{ id: 'hierarchy', label: 'Memory hierarchy', group: 'Memory system', needs: 'asm', wide: false, blurb: 'L1, L2, L3 and memory: the path each access took, and running totals.', course: { name: 'hierarchy' } },
|
||||||
|
{ id: 'paging', label: 'Virtual memory', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The page walk and the TLB, with virtual memory on.', course: { name: 'paging' } },
|
||||||
|
{ id: 'pipeline', label: 'Five-stage pipeline', group: 'Time', needs: 'asm', wide: true, blurb: 'Cycle by cycle: stalls amber, wrong-path fetches red.', course: { name: 'pipeline' } },
|
||||||
|
{ id: 'uops', label: 'Micro-ops and ports', group: 'Time', needs: 'asm', wide: false, blurb: 'The micro-ops the last instruction became, and the ports each can run on.', course: { name: 'uops' } },
|
||||||
|
{ id: 'timeline', label: 'Out-of-order timeline', group: 'Time', needs: 'asm', wide: true, blurb: 'When each instruction entered the core, ran and retired.', course: { name: 'timeline' } },
|
||||||
|
{ id: 'bottleneck', label: 'What limits the speed', group: 'Time', needs: 'asm', wide: false, blurb: 'The dependency chain, the busiest ports and the front end, against the time taken.', course: { name: 'bottleneck' } },
|
||||||
|
{ id: 'counters', label: 'Counters', group: 'Time', needs: 'asm', wide: false, blurb: 'The run as the model machine counts it, in the style of perf stat, and what each Mojo line cost on it.' },
|
||||||
|
{ id: 'machine', label: 'The whole core', group: 'The chip', needs: 'asm', wide: true, blurb: 'From the branch predictor to memory, the parts the last instruction used lit up.', course: { name: 'machine' } },
|
||||||
|
{ id: 'core', label: 'Inside the out-of-order core', group: 'The chip', needs: 'asm', wide: true, blurb: 'The reorder buffer, the ports, and which physical register each name points at.', course: { name: 'core' } },
|
||||||
|
{ id: 'encoding', label: 'Instruction encoding', group: 'The chip', needs: 'asm', wide: false, blurb: 'The bytes of the last instruction, broken into prefix, REX, opcode, ModRM, SIB, displacement and immediate.', course: { name: 'encoding' } },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const boardView = (id: string): BoardViewDef | undefined => BOARD_VIEWS.find((v) => v.id === id);
|
||||||
|
|
||||||
|
/** One card on the board: which view, and its width when the student changed it. */
|
||||||
|
export interface BoardItem { id: BoardViewId; wide?: boolean }
|
||||||
|
|
||||||
|
export interface BoardPreset { id: string; label: string; blurb: string; items: BoardItem[] }
|
||||||
|
|
||||||
|
const items = (...ids: BoardViewId[]): BoardItem[] => ids.map((id) => ({ id }));
|
||||||
|
|
||||||
|
/** Arrangements that make sense to see at once; the student can change any of them. */
|
||||||
|
export const BOARD_PRESETS: BoardPreset[] = [
|
||||||
|
{ id: 'regs', label: 'Registers and memory', blurb: 'What each instruction does: the registers it writes, the flags, the address it computes, the bytes of memory it reads or writes, the stack.', items: items('registers', 'flags', 'address', 'memory', 'stack', 'output', 'setup') },
|
||||||
|
{ id: 'caches', label: 'Caches', blurb: 'What memory costs on the model machine: the cache line each access touches and how much of it is used, the L1 data cache, the hierarchy.', items: items('lines', 'cache', 'hierarchy', 'memory', 'output') },
|
||||||
|
{ id: 'pipeline', label: 'Pipeline', blurb: 'Time: the five-stage pipeline, the micro-ops and ports, what limits the speed, the out-of-order timeline.', items: items('pipeline', 'uops', 'bottleneck', 'timeline') },
|
||||||
|
// The listing and the encoding of the instruction it marks sit side by side; the out-of-order core, whose table
|
||||||
|
// grows and shrinks with what is in flight, goes last so that nothing below it moves while stepping.
|
||||||
|
{ id: 'chip', label: 'Whole chip', blurb: 'The whole core with the parts each instruction uses lit up, the machine code beside the encoding of the instruction it marks, and inside the out-of-order core.', items: items('machine', 'code', 'encoding', 'core') },
|
||||||
|
{ id: 'mojo', label: 'Mojo and the compiler', blurb: 'The Mojo side: the run with its variables and lifetimes, the real compiler\'s answer and listing, the output.', items: items('run', 'compiler', 'output', 'problems') },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const boardPreset = (id: string | undefined | null): BoardPreset => BOARD_PRESETS.find((p) => p.id === id) ?? BOARD_PRESETS[0];
|
||||||
|
|
||||||
|
/** A saved arrangement, cleaned: known views only, each once, at most 24. */
|
||||||
|
export function normalizeBoard(x: unknown): BoardItem[] | undefined {
|
||||||
|
if (!Array.isArray(x)) return undefined;
|
||||||
|
const out: BoardItem[] = [];
|
||||||
|
for (const it of x) {
|
||||||
|
const id = typeof it === 'string' ? it : it && typeof it === 'object' ? (it as any).id : null;
|
||||||
|
if (typeof id !== 'string' || !boardView(id) || out.some((o) => o.id === id)) continue;
|
||||||
|
const wide = it && typeof it === 'object' && typeof (it as any).wide === 'boolean' ? (it as any).wide : undefined;
|
||||||
|
out.push(wide === undefined ? { id: id as BoardViewId } : { id: id as BoardViewId, wide });
|
||||||
|
if (out.length >= 24) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a card is drawn at the board's whole width. */
|
||||||
|
export const isWide = (it: BoardItem): boolean => it.wide ?? boardView(it.id)!.wide;
|
||||||
|
|
||||||
|
/** The preset an arrangement is, or null when the student has made it their own. */
|
||||||
|
export function presetOf(list: BoardItem[]): string | null {
|
||||||
|
const same = (a: BoardItem[], b: BoardItem[]) => a.length === b.length && a.every((x, i) => x.id === b[i].id && isWide(x) === isWide(b[i]));
|
||||||
|
return BOARD_PRESETS.find((p) => same(p.items, list))?.id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The arrangement with the card at `from` moved to position `to` (drag and drop, or the move buttons). */
|
||||||
|
export function moveItem(list: BoardItem[], from: number, to: number): BoardItem[] {
|
||||||
|
if (from < 0 || from >= list.length) return list.slice();
|
||||||
|
const out = list.slice();
|
||||||
|
const [it] = out.splice(from, 1);
|
||||||
|
out.splice(Math.max(0, Math.min(to, out.length)), 0, it);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addItem(list: BoardItem[], id: BoardViewId, at = list.length): BoardItem[] {
|
||||||
|
if (!boardView(id) || list.some((x) => x.id === id)) return list.slice();
|
||||||
|
const out = list.slice();
|
||||||
|
out.splice(Math.max(0, Math.min(at, out.length)), 0, { id });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const removeItem = (list: BoardItem[], id: BoardViewId): BoardItem[] => list.filter((x) => x.id !== id);
|
||||||
|
|
||||||
|
export const toggleWide = (list: BoardItem[], id: BoardViewId): BoardItem[] => list.map((x) => (x.id === id ? { id, wide: !isWide(x) } : x));
|
||||||
|
|
||||||
|
/** The course views a set of cards mounts, with their options for this run (the board's data step). Paging only with virtual memory on. */
|
||||||
|
export function courseViews(list: BoardItem[], trace: any, machine: MachineChoice): Array<{ id: BoardViewId; name: string; options: Record<string, unknown> }> {
|
||||||
|
return list.flatMap((it) => {
|
||||||
|
const v = boardView(it.id)!;
|
||||||
|
if (!v.course) return [];
|
||||||
|
if (v.id === 'paging' && !machine.paging) return [];
|
||||||
|
return [{ id: v.id, name: v.course.name, options: v.course.options ? v.course.options(trace, machine) : {} }];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The 64-bit registers the program also uses under a narrower name (`eax`, `al`, `r8b`): their card shows every
|
||||||
|
* width, so `mov al, …` visibly changes only the low byte of `rax`. `rax` always does, since it holds the answer.
|
||||||
|
*/
|
||||||
|
export function subRegisterWidths(program: any): string[] {
|
||||||
|
const out = new Set<string>(['rax']);
|
||||||
|
for (const ins of program?.instrs ?? []) {
|
||||||
|
for (const o of ins.operands ?? []) {
|
||||||
|
const names = o.kind === 'reg' ? [o.name] : o.kind === 'mem' ? [o.base, o.index] : [];
|
||||||
|
for (const n of names) {
|
||||||
|
const r = n && (REGS as any)[n];
|
||||||
|
if (r && !r.vector && r.base !== n) out.add(r.base);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...out];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A frame is everything a course view needs to draw one moment (the same shape as `frameAt` in views.js). */
|
||||||
|
export interface BoardFrame { t: number; trace: any; state: any; last: any; next: any }
|
||||||
|
|
||||||
|
export function boardFrame(trace: any, t: number): BoardFrame {
|
||||||
|
const clamped = Math.max(0, Math.min(Math.floor(Number(t) || 0), trace.count));
|
||||||
|
const state = trace.states[clamped];
|
||||||
|
const last = clamped > 0 ? trace.steps[clamped - 1] : null;
|
||||||
|
const next = state.pc < trace.program.instrs.length && !state.halted ? trace.program.instrs[state.pc] : null;
|
||||||
|
return { t: clamped, trace, state, last, next };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- cache lines ---------- */
|
||||||
|
|
||||||
|
/** One cache line touched by one memory access of the step that just ran. */
|
||||||
|
export interface LineTouch {
|
||||||
|
kind: 'read' | 'write';
|
||||||
|
/** The access: its address as the program wrote it, the physical address the caches saw (the same without virtual memory), and its size in bytes. */
|
||||||
|
vaddr: number;
|
||||||
|
addr: number;
|
||||||
|
size: number;
|
||||||
|
/** The line: its address and size, and the bytes of it this access covered, as offsets [from, to). */
|
||||||
|
lineAddr: number;
|
||||||
|
lineSize: number;
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
/** Where the line was found: L1d (a hit), L2, L3, or memory. */
|
||||||
|
level: string;
|
||||||
|
hit: boolean;
|
||||||
|
/** Bytes of this line the program has used so far (this access included), and in the whole run, as sorted offsets. */
|
||||||
|
usedSoFar: number[];
|
||||||
|
usedInRun: number[];
|
||||||
|
/** What put the access there when it was not an instruction's own operand: a push, a call's return address, the kernel. */
|
||||||
|
stack: string | null;
|
||||||
|
kernel: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For each line, the step at which each of its bytes was first used. Computed once per hardware model. */
|
||||||
|
const firstUse = new WeakMap<object, Map<number, Map<number, number>>>();
|
||||||
|
|
||||||
|
function usesOf(hw: any): Map<number, Map<number, number>> {
|
||||||
|
const hit = firstUse.get(hw);
|
||||||
|
if (hit) return hit;
|
||||||
|
const mem = hw.memory();
|
||||||
|
const L: number = mem.hierarchy.line;
|
||||||
|
const lines = new Map<number, Map<number, number>>();
|
||||||
|
mem.steps.forEach((rec: any, k: number) => {
|
||||||
|
for (const r of rec.data) {
|
||||||
|
for (let b = r.addr; b < r.addr + Math.max(1, r.size); b++) {
|
||||||
|
const lineAddr = Math.floor(b / L) * L;
|
||||||
|
let m = lines.get(lineAddr);
|
||||||
|
if (!m) { m = new Map(); lines.set(lineAddr, m); }
|
||||||
|
if (!m.has(b - lineAddr)) m.set(b - lineAddr, k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
firstUse.set(hw, lines);
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cache lines the step that just ran (step t-1) touched with its loads and stores: which line, which bytes of
|
||||||
|
* it, where it was found, and how many of its bytes the program uses so far and in the whole run. A program that
|
||||||
|
* reads one byte of each 64-byte line moves 64 bytes for every one it uses; this is where that shows.
|
||||||
|
*/
|
||||||
|
export function lineTouches(hw: any, t: number): LineTouch[] {
|
||||||
|
const mem = hw.memory();
|
||||||
|
const k = Math.floor(Number(t) || 0) - 1;
|
||||||
|
if (k < 0 || k >= mem.steps.length) return [];
|
||||||
|
const L: number = mem.hierarchy.line;
|
||||||
|
const uses = usesOf(hw);
|
||||||
|
const out: LineTouch[] = [];
|
||||||
|
for (const r of mem.steps[k].data) {
|
||||||
|
for (const line of r.lines) {
|
||||||
|
const m = uses.get(line.lineAddr) ?? new Map<number, number>();
|
||||||
|
const soFar = [...m].filter(([, at]) => at <= k).map(([off]) => off).sort((a, b) => a - b);
|
||||||
|
out.push({
|
||||||
|
kind: r.kind === 'write' ? 'write' : 'read', vaddr: r.vaddr ?? r.addr, addr: r.addr, size: r.size,
|
||||||
|
lineAddr: line.lineAddr, lineSize: L,
|
||||||
|
from: Math.max(r.addr, line.lineAddr) - line.lineAddr,
|
||||||
|
to: Math.min(r.addr + Math.max(1, r.size), line.lineAddr + L) - line.lineAddr,
|
||||||
|
level: line.level, hit: !!line.trail[0]?.hit,
|
||||||
|
usedSoFar: soFar, usedInRun: [...m.keys()].sort((a, b) => a - b),
|
||||||
|
stack: r.stack ?? null, kernel: !!r.kernel,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Mojo beside x86-64 ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The line table of x86-64 sent from the Compiler view: `forSimulator` (mojo/att.ts) ends every instruction that
|
||||||
|
* came from a line of the Mojo program with `; mojo line N`, from godbolt's own line table. Map: x86-64 line (1-based)
|
||||||
|
* to Mojo line. Empty for x86-64 written by hand, which no Mojo line produced.
|
||||||
|
*/
|
||||||
|
export function asmMojoLines(asm: string): Map<number, number> {
|
||||||
|
const out = new Map<number, number>();
|
||||||
|
String(asm ?? '').split('\n').forEach((text, i) => {
|
||||||
|
const m = /;\s*mojo line (\d+)\s*$/.exec(text);
|
||||||
|
if (m) out.set(i + 1, Number(m[1]));
|
||||||
|
});
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The lines of the other pane that match `line` of pane `from`, through that table (sorted; empty when nothing matches). */
|
||||||
|
export function relateAsmMojo(asm: string, from: 'asm' | 'mojo', line: number): number[] {
|
||||||
|
const table = asmMojoLines(asm);
|
||||||
|
if (from === 'asm') { const m = table.get(line); return m == null ? [] : [m]; }
|
||||||
|
return [...table].filter(([, m]) => m === line).map(([a]) => a).sort((a, b) => a - b);
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Mojo 1.1.0 and 1.2.0 give every `input()` call a buffered reader of its own. When the input arrives all at once
|
||||||
|
* (a pipe, as on godbolt, where Compile & run sends the input box as the program's stdin), the first call reads
|
||||||
|
* every line into its buffer and keeps the rest, so the second call finds nothing left and raises EOF. Programming+'s
|
||||||
|
* Run view hands out one line per call, as a terminal does (core/docs/trust.md). The Compiler view says so when it
|
||||||
|
* matters: when a program that may call `input()` more than once was sent with input.
|
||||||
|
*
|
||||||
|
* "May call more than once" is decided from the text alone, erring toward saying it: more than one call site, a
|
||||||
|
* call inside a loop (or a comprehension), or a call inside any function other than `main`, which can be called
|
||||||
|
* any number of times. Strings and comments are not calls (core's Mojo lexer reads them). DOM-free.
|
||||||
|
*/
|
||||||
|
import { lex, type Tok } from '#core/mojo/lex.js';
|
||||||
|
|
||||||
|
export interface InputReads {
|
||||||
|
/** The lines with an `input(` call, in order. */
|
||||||
|
lines: number[];
|
||||||
|
/** Why the program may read input more than once, or null when it reads it at most once. */
|
||||||
|
why: 'several' | 'loop' | 'function' | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LOOPS = new Set(['for', 'while']);
|
||||||
|
|
||||||
|
export function inputReads(source: string): InputReads {
|
||||||
|
let toks: Tok[];
|
||||||
|
try { toks = lex(source).tokens; } catch { return { lines: [], why: null }; }
|
||||||
|
const lines: number[] = [];
|
||||||
|
let inLoop = false, inHelper = false;
|
||||||
|
// one entry per open block: whether it is a loop body, and whether it is a function other than main
|
||||||
|
const blocks: Array<{ loop: boolean; helper: boolean }> = [];
|
||||||
|
let lineLoop = false, lineHelper = false; // what the logical line now being read opens
|
||||||
|
let atStart = true;
|
||||||
|
const depthLoop = () => blocks.some((b) => b.loop);
|
||||||
|
const depthHelper = () => blocks.some((b) => b.helper);
|
||||||
|
let pending = 0; // calls on the logical line being read, settled at its end
|
||||||
|
const endLine = () => {
|
||||||
|
if (pending && (lineLoop || depthLoop())) inLoop = true;
|
||||||
|
if (pending && (lineHelper || depthHelper())) inHelper = true;
|
||||||
|
pending = 0;
|
||||||
|
};
|
||||||
|
for (let i = 0; i < toks.length; i++) {
|
||||||
|
const t = toks[i];
|
||||||
|
if (t.kind === 'newline' || t.kind === 'eof') { endLine(); atStart = true; continue; }
|
||||||
|
if (t.kind === 'indent') { endLine(); blocks.push({ loop: lineLoop, helper: lineHelper }); lineLoop = false; lineHelper = false; atStart = true; continue; }
|
||||||
|
if (t.kind === 'dedent') { endLine(); blocks.pop(); atStart = true; continue; }
|
||||||
|
if (atStart) { lineLoop = false; lineHelper = false; atStart = false; }
|
||||||
|
if (t.kind !== 'name') continue;
|
||||||
|
if (LOOPS.has(t.text)) lineLoop = true; // a loop statement, or a comprehension on this line
|
||||||
|
if (t.text === 'def' && toks[i + 1]?.kind === 'name' && toks[i + 1].text !== 'main') lineHelper = true;
|
||||||
|
if (t.text === 'input' && toks[i + 1]?.text === '(' && toks[i - 1]?.text !== '.' && toks[i - 1]?.text !== 'def') { lines.push(t.line); pending++; }
|
||||||
|
}
|
||||||
|
endLine();
|
||||||
|
const why = lines.length > 1 ? 'several' : inLoop ? 'loop' : inHelper ? 'function' : null;
|
||||||
|
return { lines, why };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The note the Compiler view shows for a program sent with `stdin`, or null when none is needed: no input was
|
||||||
|
* sent, or the program reads it at most once.
|
||||||
|
*/
|
||||||
|
export function inputNote(source: string, stdin: string): string | null {
|
||||||
|
if (!stdin.trim()) return null;
|
||||||
|
const r = inputReads(source);
|
||||||
|
if (!r.why) return null;
|
||||||
|
const where = r.why === 'several' ? `calls input() on lines ${listLines(r.lines)}` : r.why === 'loop' ? `calls input() in a loop (line ${r.lines[0]})` : `calls input() in a function that can run more than once (line ${r.lines[0]})`;
|
||||||
|
return `This program ${where}. In Mojo 1.2.0 each input() call reads through a buffer of its own, and here the input arrives all at once: the first call takes every line, and the next one stops with EOF. That is the compiler's run, not a mistake in your input. The Run view hands out one line per call, as typing at a terminal does.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function listLines(ns: number[]): string {
|
||||||
|
const u = [...new Set(ns)];
|
||||||
|
if (u.length <= 1) return String(u[0] ?? '');
|
||||||
|
const shown = u.slice(0, 4).map(String);
|
||||||
|
if (u.length > 4) return `${shown.join(', ')} and ${u.length - 4} more`;
|
||||||
|
return `${shown.slice(0, -1).join(', ')} and ${shown[shown.length - 1]}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The library (pplus-library, through core's registry) as the site shows it: a routine opened in the Bridge, and
|
||||||
|
* a summary of what its checks found. DOM-free; src/ui/library.ts draws it.
|
||||||
|
*
|
||||||
|
* A library routine opens like a catalog problem, under the id `lib:<module>.<Name>` (#/bridge/p/lib:md.LennardJones):
|
||||||
|
* its pseudo in the pseudo pane and its first case as the call, so it can be stepped through line by line, which
|
||||||
|
* a program that only calls it never does.
|
||||||
|
*/
|
||||||
|
import { libraryModules, libraryRoutine, type LibraryRoutine } from '#core/library/registry.js';
|
||||||
|
import type { LibraryCheck } from '#core/library/types.js';
|
||||||
|
import { emptyState, type PlayState } from './state.js';
|
||||||
|
|
||||||
|
export const LIBRARY_PREFIX = 'lib:';
|
||||||
|
|
||||||
|
export function isLibraryId(id: string): boolean { return id.startsWith(LIBRARY_PREFIX); }
|
||||||
|
|
||||||
|
/** The state a library routine opens in: its pseudo, and its first case as the call. */
|
||||||
|
export function stateForLibraryRoutine(r: LibraryRoutine): PlayState {
|
||||||
|
const s = emptyState();
|
||||||
|
s.problem = `${LIBRARY_PREFIX}${r.id}`;
|
||||||
|
s.title = `${r.id}, from the library`;
|
||||||
|
s.sources = { pseudo: r.source };
|
||||||
|
s.lang = 'pseudo';
|
||||||
|
s.call = r.cases[0]?.call ?? null;
|
||||||
|
s.view = 'trace';
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The state for a `lib:` problem id, or null when the library has no such routine. */
|
||||||
|
export function libraryState(id: string): PlayState | null {
|
||||||
|
if (!isLibraryId(id)) return null;
|
||||||
|
const r = libraryRoutine(id.slice(LIBRARY_PREFIX.length));
|
||||||
|
return r ? stateForLibraryRoutine(r) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every check of a routine, named as the page lists them: its own checks, each reference's runs, the proof. */
|
||||||
|
export function checksOf(r: LibraryRoutine): Array<{ name: string; check: LibraryCheck }> {
|
||||||
|
const out: Array<{ name: string; check: LibraryCheck }> = [];
|
||||||
|
const LABEL: Record<string, string> = { structure: 'One routine per file', pseudo: 'Cases run', prover: 'Prover', fuzz: 'Fuzzer', mojo: 'Generated Mojo' };
|
||||||
|
for (const k of ['structure', 'pseudo', 'prover', 'fuzz', 'mojo']) if (r.checks[k]) out.push({ name: LABEL[k], check: r.checks[k] });
|
||||||
|
for (const ref of r.references) for (const [how, c] of Object.entries(ref.checks)) out.push({ name: `${ref.lang} ${ref.level}, ${how}`, check: c });
|
||||||
|
if (r.proof) out.push({ name: `Proof (${r.proof.lang})`, check: r.proof.check });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How many checks of a routine ended each way. */
|
||||||
|
export function tally(r: LibraryRoutine): Record<LibraryCheck['status'], number> {
|
||||||
|
const t: Record<LibraryCheck['status'], number> = { pass: 0, fail: 0, open: 0, skipped: 0, unverified: 0 };
|
||||||
|
for (const { check } of checksOf(r)) t[check.status]++;
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { libraryModules, libraryRoutine };
|
||||||
|
export type { LibraryRoutine };
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Browser preferences that are not part of a piece of work: they live in localStorage, never in `PlayState`, so
|
||||||
|
* a share link or a file can never turn one on for someone else (restructure plan, section 2.6).
|
||||||
|
*
|
||||||
|
* The best-practices helper has one switch per area, off until the student turns it on. A browser that refuses
|
||||||
|
* storage still keeps the choice for the tab.
|
||||||
|
*/
|
||||||
|
import type { AreaId } from './areas.js';
|
||||||
|
|
||||||
|
/** The areas the helper runs in. */
|
||||||
|
export const PRACTICE_AREAS: readonly AreaId[] = ['bridge', 'dev'];
|
||||||
|
|
||||||
|
const key = (area: AreaId): string => `pplus.practices.${area}`;
|
||||||
|
const memory = new Map<AreaId, boolean>();
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
export function practicesOn(area: AreaId | null): boolean {
|
||||||
|
if (!area || !PRACTICE_AREAS.includes(area)) return false;
|
||||||
|
try { const v = localStorage.getItem(key(area)); if (v !== null) return v === '1'; } catch { /* blocked: fall back to this tab's choice */ }
|
||||||
|
return memory.get(area) ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPracticesOn(area: AreaId, on: boolean): void {
|
||||||
|
if (!PRACTICE_AREAS.includes(area)) return;
|
||||||
|
memory.set(area, on);
|
||||||
|
try { if (on) localStorage.setItem(key(area), '1'); else localStorage.removeItem(key(area)); } catch { /* the tab keeps it */ }
|
||||||
|
for (const fn of [...listeners]) fn();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Be told when a switch changes (so open workspaces can show or hide the helper). Returns the way to stop. */
|
||||||
|
export function onPracticesChange(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; }
|
||||||
|
|
||||||
|
/** Forget every choice (the tests use this). */
|
||||||
|
export function forgetPractices(): void {
|
||||||
|
memory.clear();
|
||||||
|
for (const a of PRACTICE_AREAS) { try { localStorage.removeItem(key(a)); } catch { /* ignore */ } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- sending a program to the compile backend ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compile & run sends the Mojo pane and the input box to a service run by others (godbolt.org). The first time,
|
||||||
|
* the app says so and asks; the answer is remembered in this browser only, like the switches above. A browser that
|
||||||
|
* refuses storage remembers it for the tab.
|
||||||
|
*/
|
||||||
|
const SEND_KEY = 'pplus.send.godbolt';
|
||||||
|
let sendMemory = false;
|
||||||
|
|
||||||
|
export function sendAllowed(): boolean {
|
||||||
|
try { if (localStorage.getItem(SEND_KEY) === '1') return true; } catch { /* blocked: this tab's answer */ }
|
||||||
|
return sendMemory;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function allowSend(): void {
|
||||||
|
sendMemory = true;
|
||||||
|
try { localStorage.setItem(SEND_KEY, '1'); } catch { /* the tab keeps it */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forget the answer (the tests use this). */
|
||||||
|
export function forgetSend(): void {
|
||||||
|
sendMemory = false;
|
||||||
|
try { localStorage.removeItem(SEND_KEY); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Where the Mojo on screen came from (restructure plan, section 2.4). One pure function answers for every view,
|
||||||
|
* so no screen has to work it out for itself: the Bridge's Mojo is always generated; anywhere else it is whatever
|
||||||
|
* `mojoOrigin` records (absent: written by hand, or an exercise's own program).
|
||||||
|
*/
|
||||||
|
import type { PlayState } from './state.js';
|
||||||
|
import type { AreaId } from './areas.js';
|
||||||
|
|
||||||
|
export type MojoProvenance = 'generated' | 'generated-edited' | null;
|
||||||
|
|
||||||
|
export function mojoProvenance(s: { area: AreaId | null; state: Pick<PlayState, 'mojoOrigin'> }, area: AreaId | null = s.area): MojoProvenance {
|
||||||
|
if (area === 'bridge') return 'generated';
|
||||||
|
return s.state.mojoOrigin ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* A session: the app's state plus everything derived from it. What the sources mean (the hub, parsing, runs,
|
||||||
|
* proofs, the fuzzer) is the Workspace's (core); a session adds the area the work is open in, where edits are
|
||||||
|
* saved, the saved versions, the real compiler's answers and the best-practices helper. Views read from here and
|
||||||
|
* never call an engine.
|
||||||
|
*/
|
||||||
|
import type { Diagnostic, LangId, ViewId } from '#core/common/types.js';
|
||||||
|
import { AREAS, type AreaId } from './areas.js';
|
||||||
|
import { type PlayState, type Layout, emptyState, saveLocal, clearLocal, editsFingerprint, editedFrom } from './state.js';
|
||||||
|
import { runMojo } from '#core/mojo/interp.js';
|
||||||
|
import { Workspace } from '#core/common/workspace.js';
|
||||||
|
import { compilerDiagnostics, listingFunctions, type BuildLevel, type CompileOptions, type CompileOutcome, type ListingFunction } from '#core/services/godbolt.js';
|
||||||
|
import { compileBackend } from '#core/services/compile-backend.js';
|
||||||
|
import { keepCompile, keptCompiles, compiledStatus, type CompiledStatus, type KeptCompile } from './compiles.js';
|
||||||
|
import { markBusy } from './guard.js';
|
||||||
|
import { mojoProvenance, type MojoProvenance } from './provenance.js';
|
||||||
|
import { practicesOn } from './prefs.js';
|
||||||
|
import { versionKey, listVersions, saveVersion, renameVersion, deleteVersion, restoreVersion, hasUnsavedEdits, currentVersion, newWorkspaceId, autoName, type SaveResult, type Version } from './versions.js';
|
||||||
|
import { findPractices, findingsToDiagnostics, applyPractices, type PracticeFinding } from '#core/mojo/practices.js';
|
||||||
|
import { checkMojo } from '#core/mojo/check.js';
|
||||||
|
import { GENERATED_HEADER } from '#core/sync/header.js';
|
||||||
|
import { SyncHub, isLinked, type Linked } from '#core/sync/hub.js';
|
||||||
|
|
||||||
|
/** One answer from godbolt, kept with exactly what it answered. */
|
||||||
|
export interface CompileRecord {
|
||||||
|
source: string;
|
||||||
|
stdin: string;
|
||||||
|
level: BuildLevel;
|
||||||
|
at: number;
|
||||||
|
outcome: CompileOutcome;
|
||||||
|
/** The service that answered (compileBackend().host when asked); absent in records kept before it was stored, which all came from godbolt.org. */
|
||||||
|
host?: string;
|
||||||
|
/** The compiler's messages, on the Mojo pane's lines. */
|
||||||
|
diagnostics: Diagnostic[];
|
||||||
|
/** The listing, one entry per function. */
|
||||||
|
functions: ListingFunction[];
|
||||||
|
}
|
||||||
|
|
||||||
|
type Listener = (what: 'state' | 'source' | 'run') => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The session for a shared state (`#/<area>/s/<blob>`): the sender's work, which is never saved over this browser's
|
||||||
|
* own save for the problem it names (a link that names `count-base` must not replace the reader's count-base work).
|
||||||
|
* Saved versions still go to that problem's list, which only ever adds.
|
||||||
|
*/
|
||||||
|
export function sharedSession(state: PlayState, area: AreaId): Session {
|
||||||
|
return new Session(state, { area, storageId: null });
|
||||||
|
}
|
||||||
|
|
||||||
|
const LANGS = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'] as const;
|
||||||
|
|
||||||
|
/** What to tell the student when an engine threw instead of answering. */
|
||||||
|
export function engineStopMessage(e: unknown): string {
|
||||||
|
if (e instanceof RangeError && /call stack/i.test(e.message)) return 'This is nested more deeply than Programming+ can read (brackets inside brackets, blocks inside blocks, or a chain of operators thousands long). Flatten it, or move the inner part into a routine of its own.';
|
||||||
|
return `Programming+ stopped reading this pane: ${(e as any)?.message || String(e)}. This is a fault in Programming+, not necessarily in the program.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Session extends Workspace {
|
||||||
|
declare state: PlayState;
|
||||||
|
private listeners = new Set<Listener>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `storageId` says where edits are saved: by default the problem's own save
|
||||||
|
* (the app), a given id for an embed's own save, or null for nowhere.
|
||||||
|
* `keep` decides whether a state is worth saving at all; when it says no,
|
||||||
|
* the save is removed (an embed keeps one only while it holds edits, so an
|
||||||
|
* unedited example always shows the author's current version).
|
||||||
|
*/
|
||||||
|
// `original` is copied: the session edits its state in place, and the problem's own version must not move with it
|
||||||
|
constructor(state: PlayState = emptyState(), opts: { storageId?: string | null; keep?: (state: PlayState) => boolean; original?: PlayState; stale?: boolean; area?: AreaId; practices?: typeof findPractices } = {}) {
|
||||||
|
super(state);
|
||||||
|
this.finder = opts.practices ?? findPractices;
|
||||||
|
this.area = opts.area ?? null; this.storageId = opts.storageId; this.keep = opts.keep; this.original = opts.original ? structuredClone(opts.original) : null; this.stale = !!opts.stale;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* The area the work is open in (from the route); the layout is kept per area. Null for a session that is not
|
||||||
|
* a workspace (a single-view embed, a test): every pane counts, and the Mojo pane is the state's own.
|
||||||
|
*/
|
||||||
|
readonly area: AreaId | null;
|
||||||
|
private readonly finder: typeof findPractices;
|
||||||
|
private readonly storageId: string | null | undefined;
|
||||||
|
/** A catalog problem's own version, so a save records which version it was made against and whether it differs. */
|
||||||
|
private original: PlayState | null;
|
||||||
|
/** The student's edits were made to an older version of the problem than the one the app now has. */
|
||||||
|
stale: boolean;
|
||||||
|
/** The problem's own version is shown again (Reset): later saves are made against it. */
|
||||||
|
resetTo(state: PlayState): void { this.original = structuredClone(state); this.stale = false; this.replace(state); }
|
||||||
|
private readonly keep: ((state: PlayState) => boolean) | undefined;
|
||||||
|
|
||||||
|
onChange(fn: Listener): () => void { this.listeners.add(fn); return () => this.listeners.delete(fn); }
|
||||||
|
|
||||||
|
/** The stepper moved to step `t`: cheap, frequent, not persisted. Views that follow the run listen here. */
|
||||||
|
private stepListeners = new Set<(t: number) => void>();
|
||||||
|
onStep(fn: (t: number) => void): () => void { this.stepListeners.add(fn); return () => this.stepListeners.delete(fn); }
|
||||||
|
notifyStep(t: number): void { for (const fn of this.stepListeners) fn(t); }
|
||||||
|
private emit(what: 'state' | 'source' | 'run') { for (const fn of this.listeners) fn(what); }
|
||||||
|
|
||||||
|
/* ---------- an engine that stops ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A pane that an engine cannot read without failing (a crafted link with brackets nested past what a parser's
|
||||||
|
* recursion can follow, or a fault in an engine) must not take the page down with it: the pane gets one error
|
||||||
|
* that says so, and everything else keeps working. Core's readers set their own limits (pseudo refuses more
|
||||||
|
* than 200 levels); this catches what is left, whatever the reason.
|
||||||
|
*/
|
||||||
|
protected override cached<T>(name: string, key: string, make: () => T): T {
|
||||||
|
return super.cached(name, key, () => {
|
||||||
|
try { return make(); } catch (e) {
|
||||||
|
const instead = this.stopped(name, e);
|
||||||
|
if (instead === undefined) throw e;
|
||||||
|
return instead as T;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a computation named `name` gives when its engine threw `e`, or undefined to let the error through. */
|
||||||
|
private stopped(name: string, e: unknown): unknown {
|
||||||
|
const why = engineStopMessage(e);
|
||||||
|
if ((LANGS as readonly string[]).includes(name)) return { program: null, ok: false, diagnostics: [{ lang: name as LangId, severity: 'error', id: 'engine-stop', line: 1, col: 1, message: why }] };
|
||||||
|
if (name === 'fill') {
|
||||||
|
const stale: Partial<Record<Linked, string>> = {};
|
||||||
|
for (const l of ['lingo', 'matho', 'pseudo', 'speco'] as Linked[]) if (this.state.sources[l] === undefined) stale[l] = why;
|
||||||
|
return { sources: this.state.sources, stale, maps: { up: {}, down: {} } };
|
||||||
|
}
|
||||||
|
if (name === 'mojo.derived') return { source: '', map: [], diagnostics: [{ lang: 'mojo', severity: 'error', id: 'engine-stop', line: 1, col: 1, message: why }] };
|
||||||
|
if (name === 'proof') return null;
|
||||||
|
if (name.startsWith('fuzz.')) return [];
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An edit the hub cannot carry to the other panes (it threw): the pane keeps the text, and the others say why they did not follow. */
|
||||||
|
override edit(lang: LangId, text: string, force = false): boolean {
|
||||||
|
try { return super.edit(lang, text, force); } catch (e) {
|
||||||
|
if (!isLinked(lang)) throw e;
|
||||||
|
const why = engineStopMessage(e);
|
||||||
|
this.state.sources[lang] = text;
|
||||||
|
const stale: Partial<Record<Linked, string>> = {};
|
||||||
|
for (const l of ['lingo', 'matho', 'pseudo', 'speco'] as Linked[]) if (l !== lang) stale[l] = `${lang} cannot be read: ${why}`;
|
||||||
|
this.state.sync = { authority: lang, stale, names: this.state.sync?.names ?? {} };
|
||||||
|
this.memo.clear();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In the Bridge the Mojo pane is always the literal translation of the pseudo, computed and never stored. */
|
||||||
|
protected override derivesMojo(): boolean { return this.area === 'bridge'; }
|
||||||
|
|
||||||
|
/* ---------- mutation ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The student typed in pane `lang`. For the four linked languages the hub makes the other panes follow in the
|
||||||
|
* same change (sync/hub.ts); Mojo and x86-64 are stored as they are. `force` runs the cascade even when the
|
||||||
|
* text is what the pane already shows (a stale pane the student chose to edit becomes the authority).
|
||||||
|
*/
|
||||||
|
setSource(lang: LangId, text: string, force = false): void {
|
||||||
|
// Mojo the student started from a generated program is theirs once they change it, and says so
|
||||||
|
const wasGenerated = lang === 'mojo' && this.state.mojoOrigin === 'generated' && this.state.sources.mojo !== text;
|
||||||
|
if (!this.edit(lang, text, force)) return;
|
||||||
|
if (wasGenerated) this.state.mojoOrigin = 'generated-edited';
|
||||||
|
this.persist(); this.emit('source');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Edit in Developer": the Bridge's generated Mojo becomes the Mojo pane's own text, recorded as generated so
|
||||||
|
* the Developer area can say so. The caller asks first when the pane already holds something else.
|
||||||
|
*/
|
||||||
|
adoptGeneratedMojo(): boolean {
|
||||||
|
const d = this.derivedMojo();
|
||||||
|
if (!d.source.trim()) return false;
|
||||||
|
this.state.sources.mojo = d.source;
|
||||||
|
this.state.mojoOrigin = 'generated';
|
||||||
|
this.state.lang = 'mojo';
|
||||||
|
this.memo.delete('mojo'); this.memo.delete('trace.mojo');
|
||||||
|
this.persist(); this.emit('source');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
/** Where the Mojo in the pane came from, for the labels (core/provenance.ts). */
|
||||||
|
provenance(): MojoProvenance { return mojoProvenance(this); }
|
||||||
|
/**
|
||||||
|
* "I've reviewed this": the only way generated Mojo stops being labeled. Takes the header comment off and forgets
|
||||||
|
* the origin; nothing else (not a successful compile, not an edit) does.
|
||||||
|
*/
|
||||||
|
clearMojoOrigin(): boolean {
|
||||||
|
if (!this.state.mojoOrigin || this.area === 'bridge') return false;
|
||||||
|
const lines = (this.state.sources.mojo ?? '').split('\n');
|
||||||
|
if (lines[0] === GENERATED_HEADER) lines.shift();
|
||||||
|
if (lines.length && lines[0].trim() === '' && (this.state.sources.mojo ?? '').startsWith(GENERATED_HEADER)) lines.shift();
|
||||||
|
this.state.sources.mojo = lines.join('\n');
|
||||||
|
delete this.state.mojoOrigin;
|
||||||
|
this.memo.delete('mojo'); this.memo.delete('trace.mojo');
|
||||||
|
this.persist(); this.emit('source');
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
/** Whether adopting the generated Mojo would replace Mojo the pane holds that is not already this program. */
|
||||||
|
wouldReplaceMojo(): boolean {
|
||||||
|
const have = (this.state.sources.mojo ?? '').trim();
|
||||||
|
return !!have && have !== this.derivedMojo().source.trim();
|
||||||
|
}
|
||||||
|
/** Make a stale pane the authority without changing its text: the others are regenerated from it. */
|
||||||
|
/** Make a stale pane the authority without changing its text (saved, and the views told). */
|
||||||
|
override takeAuthority(lang: Linked): boolean { this.setSource(lang, this.source(lang), true); return true; }
|
||||||
|
|
||||||
|
setLang(lang: LangId): void { if (this.state.lang !== lang) { this.state.lang = lang; this.persist(); this.emit('state'); } }
|
||||||
|
setView(view: ViewId): void { if (this.state.view !== view) { this.state.view = view; this.persist(); this.emit('state'); } }
|
||||||
|
setCall(call: string | null): void { this.state.call = call; this.persist(); this.emit('run'); }
|
||||||
|
setSetup(setup: string): void { this.state.setup = setup; this.persist(); this.emit('run'); }
|
||||||
|
setInput(input: string): void { this.state.input = input; this.persist(); this.emit('run'); }
|
||||||
|
setMachine(machine: string): void { this.state.machine = machine; this.persist(); this.emit('run'); }
|
||||||
|
setT(t: number): void { this.state.t = t; this.persist(); this.emit('state'); }
|
||||||
|
/** The workspace arrangement for the area that is open. */
|
||||||
|
layout(): Layout { return this.area ? this.state.layout?.[this.area] ?? {} : {}; }
|
||||||
|
setLayout(l: Layout): void { if (!this.area) return; this.state.layout = { ...(this.state.layout || {}), [this.area]: { ...(this.state.layout?.[this.area] || {}), ...l } }; this.persist(); }
|
||||||
|
/* ---------- saved versions (core/versions.ts) ---------- */
|
||||||
|
|
||||||
|
/** The list this work keeps its versions in; null until work from a link or a file is first saved. */
|
||||||
|
versionKey(): string | null { return versionKey(this.state); }
|
||||||
|
versions(): Version[] { return listVersions(this.versionKey()); }
|
||||||
|
/** Whether the work has edits that no saved version holds (and, for a catalog problem, that differ from the problem as written). */
|
||||||
|
hasUnsavedEdits(): boolean { return hasUnsavedEdits(this.versionKey(), this.state, this.original); }
|
||||||
|
/** The saved version the work is exactly, if it is one. */
|
||||||
|
currentVersion(): Version | null { return currentVersion(this.versionKey(), this.state); }
|
||||||
|
|
||||||
|
/** Save the work under a name. Work that came from a link or a file gets its workspace id the first time. */
|
||||||
|
saveVersion(name: string, auto = false): SaveResult {
|
||||||
|
if (!this.state.problem && !this.state.workspace) { this.state.workspace = newWorkspaceId(); this.persist(); this.emit('state'); }
|
||||||
|
return saveVersion(this.versionKey(), name, this.state, this.area ?? 'bridge', { auto });
|
||||||
|
}
|
||||||
|
renameVersion(id: string, name: string): boolean { return renameVersion(this.versionKey(), id, name); }
|
||||||
|
deleteVersion(id: string): boolean { return deleteVersion(this.versionKey(), id); }
|
||||||
|
|
||||||
|
/** Save the work as "Before switching (time)" when it holds edits nothing else holds. False when it could not be saved (the caller asks before going on). */
|
||||||
|
private keepBefore(why: 'switching' | 'reset'): boolean {
|
||||||
|
if (!this.hasUnsavedEdits()) return true;
|
||||||
|
return this.saveVersion(autoName(why), true).ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make a saved version the work. What the work held that no version does is saved first, so switching never loses
|
||||||
|
* it; the layout, the step and the open tab stay as they are. Returns false when that save was refused (and nothing changed).
|
||||||
|
*/
|
||||||
|
restoreVersion(id: string): boolean {
|
||||||
|
const key = this.versionKey();
|
||||||
|
if (!key || !this.versions().some((v) => v.id === id)) return false;
|
||||||
|
if (!this.keepBefore('switching')) return false;
|
||||||
|
const next = restoreVersion(key, id, this.state);
|
||||||
|
if (!next) return false;
|
||||||
|
this.replace(next);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Back to the exercise as written: the work is saved first as "Before reset (time)" when it holds edits. False when that save was refused. */
|
||||||
|
reset(fresh: PlayState): boolean {
|
||||||
|
if (!this.keepBefore('reset')) return false;
|
||||||
|
this.resetTo(fresh);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The problem changed under the student's edits (`stale`): keep the edits as a version and open the problem as it
|
||||||
|
* is now. False when there is nothing to open (no catalog problem) or the save was refused.
|
||||||
|
*/
|
||||||
|
seeNewVersion(): boolean {
|
||||||
|
if (!this.original || !this.state.problem) return false;
|
||||||
|
if (!this.saveVersion(autoName('new')).ok) return false;
|
||||||
|
this.resetTo(structuredClone(this.original));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Work that is not the problem this session opened with (a loaded file): the problem's own version no longer applies. */
|
||||||
|
adopt(state: PlayState): void { this.original = null; this.stale = false; this.replace(state); }
|
||||||
|
replace(state: PlayState): void { this.state = state; this.memo.clear(); this.maps = { up: {}, down: {} }; this.persist(); this.emit('source'); }
|
||||||
|
|
||||||
|
private persist(): void {
|
||||||
|
const id = this.storageId === undefined ? this.state.problem : this.storageId;
|
||||||
|
if (!id) return;
|
||||||
|
if (this.original && id === this.state.problem) { this.state.base = editsFingerprint(this.original); this.state.edited = editedFrom(this.state, this.original); }
|
||||||
|
if (this.keep && !this.keep(this.state)) { clearLocal(id); return; }
|
||||||
|
saveLocal(id, this.state);
|
||||||
|
// the work about to run is the work in this save: if running it takes the page down, the next load knows (core/guard.ts)
|
||||||
|
markBusy(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- derived ---------- */
|
||||||
|
|
||||||
|
/** What pane `lang` would show if this work were open in `area` (the Bridge's Mojo is the pseudo's translation; everywhere else it is the state's). */
|
||||||
|
shownIn(area: AreaId, lang: LangId): string {
|
||||||
|
if (lang === 'mojo') return area === 'bridge' ? this.derivedMojo().source : (this.state.sources.mojo ?? '');
|
||||||
|
return isLinked(lang) ? (this.fill().sources[lang] ?? '') : (this.state.sources[lang] ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the real compiler ---------- */
|
||||||
|
|
||||||
|
private compiles: CompileRecord[] = [];
|
||||||
|
/** A request in flight, so the button can say so and a second click waits. */
|
||||||
|
compiling: Promise<CompileRecord | null> | null = null;
|
||||||
|
|
||||||
|
buildLevel(): BuildLevel { return this.state.build ?? 'O0'; }
|
||||||
|
setBuildLevel(level: BuildLevel): void { this.state.build = level; this.persist(); this.emit('state'); }
|
||||||
|
|
||||||
|
/** Compile and run the Mojo pane on the compile backend (godbolt.org unless set otherwise); the answer is kept for the views that read it. This always asks: Compile & run asks only when `keptCompile()` has nothing. */
|
||||||
|
compile(fetchImpl?: (source: string, opts: CompileOptions) => Promise<CompileOutcome>, levelOverride?: BuildLevel): Promise<CompileRecord | null> {
|
||||||
|
if (this.compiling) return this.compiling;
|
||||||
|
this.reused = null;
|
||||||
|
const source = this.source('mojo');
|
||||||
|
if (!source.trim()) return Promise.resolve(null);
|
||||||
|
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||||
|
const level = levelOverride ?? this.buildLevel();
|
||||||
|
const backend = compileBackend();
|
||||||
|
const ask = fetchImpl ?? ((src: string, opts: CompileOptions) => backend.compile(src, opts));
|
||||||
|
this.compiling = ask(source, { stdin, level }).then((outcome) => {
|
||||||
|
const rec: CompileRecord = {
|
||||||
|
source, stdin, level, at: Date.now(), outcome, host: backend.host,
|
||||||
|
diagnostics: outcome.answer ? compilerDiagnostics(outcome.answer.buildStderr) : [],
|
||||||
|
functions: outcome.answer ? listingFunctions(outcome.answer.asm) : [],
|
||||||
|
};
|
||||||
|
this.compiles = [rec, ...this.compiles.filter((r) => !(r.source === source && r.stdin === stdin && r.level === level))].slice(0, 8);
|
||||||
|
keepCompile(rec);
|
||||||
|
return rec;
|
||||||
|
}).finally(() => { this.compiling = null; this.emit('run'); });
|
||||||
|
this.emit('run');
|
||||||
|
return this.compiling;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers godbolt gave earlier for exactly the source now in the Mojo pane, in this tab or another, before a
|
||||||
|
* reload or a change of problem (core/compiles.ts): they join this session's own, so nothing is asked twice.
|
||||||
|
*/
|
||||||
|
private recall(): void {
|
||||||
|
const src = this.source('mojo');
|
||||||
|
if (!src.trim() || this.recalledFor === src) return;
|
||||||
|
this.recalledFor = src;
|
||||||
|
const have = (k: KeptCompile) => this.compiles.some((r) => r.source === k.source && r.stdin === k.stdin && r.level === k.level);
|
||||||
|
const kept = keptCompiles(src).filter((k) => !have(k)).map((k): CompileRecord => ({
|
||||||
|
...k, diagnostics: k.outcome.answer ? compilerDiagnostics(k.outcome.answer.buildStderr) : [], functions: k.outcome.answer ? listingFunctions(k.outcome.answer.asm) : [],
|
||||||
|
}));
|
||||||
|
if (kept.length) this.compiles = [...this.compiles, ...kept].sort((a, b) => b.at - a.at).slice(0, 8);
|
||||||
|
}
|
||||||
|
private recalledFor: string | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The answer this browser already has for exactly the Mojo pane's source, its input and a build level (the chosen
|
||||||
|
* one unless named), if it is an answer: a request that failed is not one. Compile & run on unchanged work shows it
|
||||||
|
* again instead of sending the same program a second time (`reuseCompile`); asking again is a separate choice.
|
||||||
|
*/
|
||||||
|
keptCompile(level: BuildLevel = this.buildLevel()): CompileRecord | null {
|
||||||
|
const source = this.source('mojo');
|
||||||
|
if (!source.trim()) return null;
|
||||||
|
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||||
|
this.recall();
|
||||||
|
return this.compiles.find((r) => r.source === source && r.stdin === stdin && r.level === level && !!r.outcome.answer) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Show a kept answer as the newest, saying it was not asked again (`reusedCompile`); nothing is sent. */
|
||||||
|
reuseCompile(rec: CompileRecord): CompileRecord {
|
||||||
|
this.compiles = [rec, ...this.compiles.filter((r) => r !== rec)];
|
||||||
|
this.reused = rec;
|
||||||
|
this.emit('run');
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The kept answer the last Compile & run showed instead of asking, until the next real request. */
|
||||||
|
reusedCompile(): CompileRecord | null { return this.reused; }
|
||||||
|
private reused: CompileRecord | null = null;
|
||||||
|
|
||||||
|
/** The newest answer, and whether the pane still holds the source it answered. */
|
||||||
|
lastCompile(): { record: CompileRecord; fresh: boolean } | null {
|
||||||
|
this.recall();
|
||||||
|
// the build level the student chose; another level's answer (asked for to compare) does not replace it
|
||||||
|
const rec = this.compiles.find((r) => r.level === this.buildLevel()) ?? this.compiles[0];
|
||||||
|
return rec ? { record: rec, fresh: rec.source === this.source('mojo') } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The godbolt badge for the Mojo in the pane: 'compiled' when this browser asked godbolt about exactly this
|
||||||
|
* source, input and build level; 'edited' when this session compiled an earlier version; otherwise nothing.
|
||||||
|
*/
|
||||||
|
compileBadge(): { kind: 'compiled'; status: CompiledStatus } | { kind: 'edited' } | null {
|
||||||
|
const src = this.source('mojo');
|
||||||
|
if (!src.trim()) return null;
|
||||||
|
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||||
|
const status = compiledStatus(src, stdin, this.buildLevel());
|
||||||
|
if (status) return { kind: 'compiled', status };
|
||||||
|
this.recall();
|
||||||
|
return this.compiles.length && !this.compiles.some((r) => r.source === src) ? { kind: 'edited' } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The answer for this source at a given build level, if one has been asked for (the comparison of builds). */
|
||||||
|
compileAt(source: string, level: BuildLevel): CompileRecord | null {
|
||||||
|
this.recall();
|
||||||
|
return this.compiles.find((r) => r.source === source && r.level === level) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest answer for exactly the source in the pane (any input or build), for its diagnostics. */
|
||||||
|
private compileForSource(): CompileRecord | null {
|
||||||
|
this.recall();
|
||||||
|
const src = this.source('mojo');
|
||||||
|
return this.compiles.find((r) => r.source === src) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- best practices (off until the student turns it on, per area) ---------- */
|
||||||
|
|
||||||
|
/** Whether the helper is on for the area that is open. */
|
||||||
|
practicesOn(): boolean { return practicesOn(this.area); }
|
||||||
|
/**
|
||||||
|
* What the best-practices rules find in the Mojo on screen: nothing at all, and nothing is run, unless the helper is
|
||||||
|
* on for this area. In the Bridge that is the generated Mojo; in the Developer area, the student's own.
|
||||||
|
*/
|
||||||
|
practices(): PracticeFinding[] {
|
||||||
|
if (!this.practicesOn()) return [];
|
||||||
|
const src = this.source('mojo');
|
||||||
|
if (!src.trim()) return [];
|
||||||
|
return this.cached('practices', src, () => this.finder(src, this.parsedMojo()?.program?.module));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The pseudo lines a line of the Bridge's Mojo came from (empty when it came from none, or there is no pseudo). */
|
||||||
|
pseudoLinesOfMojo(line: number): number[] { return SyncHub.relate(this.lineMaps(), 'mojo', line, 'pseudo'); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Bridge's "Show idiomatic version": a copy of the generated Mojo with the safe best-practice rewrites applied,
|
||||||
|
* offered only when the result passes the checker as well as the literal one did and the interpreter prints exactly
|
||||||
|
* what it prints for the literal one (which the tests tie to the pseudo's own run). Otherwise the reason it was
|
||||||
|
* not offered. Asked for on demand; nothing runs until it is.
|
||||||
|
*/
|
||||||
|
idiomaticMojo(): { ok: true; source: string; applied: PracticeFinding[] } | { ok: false; reason: string } {
|
||||||
|
if (!this.practicesOn() || this.area !== 'bridge') return { ok: false, reason: 'Best practices are off.' };
|
||||||
|
const literal = this.source('mojo');
|
||||||
|
if (!literal.trim()) return { ok: false, reason: 'There is no Mojo yet.' };
|
||||||
|
return this.cached('idiomatic', literal, () => {
|
||||||
|
const { source, applied } = applyPractices(literal);
|
||||||
|
if (!applied.length) return { ok: false as const, reason: 'There is nothing to rewrite safely.' };
|
||||||
|
const errs = (t: string) => checkMojo(t).diagnostics.filter((d) => d.severity === 'error').length;
|
||||||
|
if (errs(source) > errs(literal)) return { ok: false as const, reason: 'The rewritten version did not pass the checker, so it is not shown.' };
|
||||||
|
const run = (t: string) => { const m = checkMojo(t); return runMojo(m.module, t, { input: this.inputLines() }); };
|
||||||
|
const a = run(literal), b = run(source);
|
||||||
|
if (a.refused !== null || b.refused !== null) return { ok: false as const, reason: `Programming+ could not run both versions to compare them (${a.refused ?? b.refused}), so it does not show the rewrite.` };
|
||||||
|
if (a.stdout !== b.stdout || a.exitCode !== b.exitCode) return { ok: false as const, reason: 'The rewritten version printed something different, so it is not shown.' };
|
||||||
|
return { ok: true as const, source, applied };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setViewsCollapsed(c: boolean): void { this.state.viewsCollapsed = c; this.persist(); this.emit('state'); }
|
||||||
|
|
||||||
|
override diagnostics(lang: LangId): Diagnostic[] {
|
||||||
|
if (lang !== 'mojo') return super.diagnostics(lang);
|
||||||
|
// the compiler's answer for this exact source replaces what Programming+ found by itself
|
||||||
|
const rec = this.compileForSource();
|
||||||
|
const base = rec?.outcome.answer ? rec.diagnostics : this.parsedMojo()?.diagnostics ?? [];
|
||||||
|
// in the Developer area the helper's findings are notes on the student's own lines (never errors or warnings)
|
||||||
|
return this.area === 'dev' && this.practicesOn() && !base.some((d) => d.severity === 'error') ? [...base, ...findingsToDiagnostics(this.practices())] : base;
|
||||||
|
}
|
||||||
|
|
||||||
|
override allDiagnostics(): Diagnostic[] {
|
||||||
|
return (this.area ? AREAS[this.area].panes : (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'] as LangId[])).flatMap((l) => this.diagnostics(l));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Facts about the site itself, for the footer and the note on what it stores and sends. DOM-free, so the tests hold
|
||||||
|
* the note to them.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where the source code is published. The public address is the owner's to set when the repositories go public;
|
||||||
|
* while it is empty the footer shows no link to it. Change it here and nowhere else.
|
||||||
|
*/
|
||||||
|
export const SOURCE_URL = '';
|
||||||
|
|
||||||
|
/** The one sentence that says what Programming+ is: the README, docs/app.md, index.html and the home page use it. */
|
||||||
|
export const DESCRIPTION = 'Programming+ takes a procedure from an idea to Mojo to the machine.';
|
||||||
|
|
||||||
|
/** The license and the notices `scripts/assemble.sh` copies into the site, beside index.html. */
|
||||||
|
export const LICENSE_FILES = [
|
||||||
|
{ href: './LICENSE.md', label: 'Apache-2.0 license' },
|
||||||
|
{ href: './NOTICE.md', label: 'Notice' },
|
||||||
|
{ href: './THIRD_PARTY.md', label: 'Third-party notices' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
/** NOTICE.md's disclaimer, as one line. */
|
||||||
|
export const DISCLAIMER = 'Programming+ is not affiliated with, sponsored by, or endorsed by Modular Inc. "Mojo" and "Modular" are trademarks of Modular Inc.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The build's commit, when the page has one: `scripts/assemble-page.mjs` writes it into the assembled index.html
|
||||||
|
* as `<meta name="pplus-version">` from the VERSION file `scripts/assemble.sh` writes, so showing it costs no request.
|
||||||
|
* A checkout served as it is (`pixi run dev`) has none.
|
||||||
|
*/
|
||||||
|
export function siteVersion(meta: string | null | undefined): string | null {
|
||||||
|
const v = (meta ?? '').trim();
|
||||||
|
return /^[0-9a-f]{7,40}$/.test(v) ? v.slice(0, 12) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What this site stores and sends, one statement per line. tests/site-data.test.mjs holds each one to the code:
|
||||||
|
* the storage the sources use, the one request they make to another origin, and the consent before it.
|
||||||
|
*/
|
||||||
|
export const SITE_DATA: readonly string[] = [
|
||||||
|
'No accounts, no cookies, no analytics.',
|
||||||
|
'Your work, its saved versions, the answers Compile & run brought back, and your settings (the theme, the best-practices switches, whether messages show in the editor, whether you agreed to send to godbolt.org) are kept in this browser\'s localStorage, under names that start with "pplus". While saved work runs, this tab also keeps a mark in its sessionStorage, so a page that stops can put that work aside. Nothing is kept on a server: clearing this site\'s data in the browser removes it all, and Share → Download keeps a copy as a file.',
|
||||||
|
'A shared link carries its work in the address after the #, which the browser does not send to any server. Opening one never saves over your own work on the same problem.',
|
||||||
|
'Compile & run sends the Mojo pane\'s text, the input box\'s lines and the build flags to godbolt.org (Compiler Explorer, a public service run by others, with its own privacy policy), and nothing else: no title, no other pane, nothing stored. The first time, it says so and asks; nothing is sent until you agree.',
|
||||||
|
'Nothing else leaves the browser. The page, its scripts and its fonts come from this site, and no other site is asked for anything. Links to other sites (the Mojo manual, where a method comes from) are followed only when you click them.',
|
||||||
|
];
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The whole playground is one state object. It lives in the URL hash (so a
|
||||||
|
* link opens exactly this state, in the app or as an embedded view) and in
|
||||||
|
* localStorage per problem (so a reload keeps a student's work).
|
||||||
|
*
|
||||||
|
* Routes (<area> is bridge, dev or hw: src/core/areas.ts; nothing else is a route):
|
||||||
|
* #/ home: the problem list
|
||||||
|
* #/<area>/p/<problemId> a catalog problem in an area, with the student's saved edits
|
||||||
|
* #/<area>/s/<blob> a shared state in an area, compressed into the URL
|
||||||
|
* #/embed/<view>/<blob> one view, no chrome, for an <iframe>
|
||||||
|
* #/embed/<view>/p/<id> one view of a catalog problem
|
||||||
|
* #/embed/playground/... the whole workspace, as the state lays it out (area=<area> picks the area)
|
||||||
|
* #/quarto "With Quarto": the Quarto extension's shortcodes, as a gallery (#/quarto#<section> scrolls)
|
||||||
|
*
|
||||||
|
* The blob is deflate-raw + base64url of the JSON below; `~` prefix marks
|
||||||
|
* plain base64url when compression is unavailable.
|
||||||
|
*/
|
||||||
|
import type { LangId, ViewId } from '#core/common/types.js';
|
||||||
|
import type { SyncInfo } from '#core/sync/hub.js';
|
||||||
|
import { isAreaId, type AreaId } from './areas.js';
|
||||||
|
import { normalizeBoard, type BoardItem } from './hardware.js';
|
||||||
|
|
||||||
|
export interface PlayState {
|
||||||
|
v: 3;
|
||||||
|
problem?: string;
|
||||||
|
title?: string;
|
||||||
|
sources: Partial<Record<LangId, string>>;
|
||||||
|
/** Which language pane is active. */
|
||||||
|
lang: LangId;
|
||||||
|
/** Which bottom view is open. */
|
||||||
|
view: ViewId;
|
||||||
|
/** The call used to run, e.g. `COUNT_BASE('A', "GATTACA")`. */
|
||||||
|
call?: string | null;
|
||||||
|
/** Lines INPUT reads, one per line, for pseudo, lingo and matho runs. */
|
||||||
|
input?: string;
|
||||||
|
/** Assembly setup block and machine preset. */
|
||||||
|
setup?: string;
|
||||||
|
machine?: string;
|
||||||
|
/** Step index the stepper is parked at. */
|
||||||
|
t?: number;
|
||||||
|
/** The bottom views pane, folded away. */
|
||||||
|
viewsCollapsed?: boolean;
|
||||||
|
/** How the Mojo pane is compiled: as written (-O0, every function kept) or as `mojo build` does by default. */
|
||||||
|
build?: 'O0' | 'default';
|
||||||
|
/** The workspace as the student arranged it, one arrangement per area: pane widths as fractions, which dock tab is open, what is folded. */
|
||||||
|
layout?: Partial<Record<AreaId, Layout>>;
|
||||||
|
/**
|
||||||
|
* Which linked pane (lingo, matho, pseudo, speco) was edited last, so the others follow it; which panes are
|
||||||
|
* not in step and why; and the student's own spelling of equation names. Absent until the first edit.
|
||||||
|
*/
|
||||||
|
sync?: SyncInfo;
|
||||||
|
/**
|
||||||
|
* Where `sources.mojo` came from when the student did not write it: `generated` for Mojo copied out of the
|
||||||
|
* Bridge (the literal translation of pseudo), `generated-edited` once the student has changed it. Absent for Mojo
|
||||||
|
* written by hand or an exercise's own program.
|
||||||
|
*/
|
||||||
|
mojoOrigin?: 'generated' | 'generated-edited';
|
||||||
|
/** Work that began from a share link or a file has no problem id: this names it, so its saved versions have a home. Added when such work is first saved. */
|
||||||
|
workspace?: string;
|
||||||
|
/** For a save of a catalog problem: the fingerprint of the problem as it was when the save was made. */
|
||||||
|
base?: string;
|
||||||
|
/** For a save of a catalog problem: whether it holds edits the problem did not. */
|
||||||
|
edited?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DockTab = 'setup' | 'output' | 'problems' | 'compiler' | 'asm' | 'practices';
|
||||||
|
|
||||||
|
export interface Layout {
|
||||||
|
/** Editor column width. */
|
||||||
|
split?: number;
|
||||||
|
/** The active pane's share of the editor column beside its companion. */
|
||||||
|
companion?: number;
|
||||||
|
/** The variables panel's share of the right column. */
|
||||||
|
right?: number;
|
||||||
|
/** The dock's share of the height. */
|
||||||
|
dock?: number;
|
||||||
|
dockTab?: DockTab;
|
||||||
|
dockCollapsed?: boolean;
|
||||||
|
setupCollapsed?: boolean;
|
||||||
|
/** The Hardware area's board: the cards it shows, in order (core/hardware.ts); absent means the first preset. */
|
||||||
|
board?: BoardItem[];
|
||||||
|
/** The variables the Run view follows, as `routine.name` (core/runview.ts); absent until the student chooses. */
|
||||||
|
follow?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What `#/embed/<view>/...` can show: the whole playground, one view with the code it reads, or one
|
||||||
|
* pane (a LangId). The Share dialog offers these, and the Quarto shortcode's `view=` takes them.
|
||||||
|
*/
|
||||||
|
export const EMBED_VIEWS = ['playground', 'trace', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'problems', 'compiler', 'asm', ...DEFAULT_PANES.filter((p) => p !== 'asm')] as const;
|
||||||
|
|
||||||
|
export function emptyState(): PlayState {
|
||||||
|
return { v: 3, sources: {}, lang: 'pseudo', view: 'problems' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Encoding */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const B64 = { enc: (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''), dec: (s: string) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)) };
|
||||||
|
|
||||||
|
async function pipe(bytes: Uint8Array, stream: any): Promise<Uint8Array> {
|
||||||
|
const ws = new Blob([bytes as BlobPart]).stream().pipeThrough(stream);
|
||||||
|
return new Uint8Array(await new Response(ws).arrayBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function encodeState(state: PlayState): Promise<string> {
|
||||||
|
const json = new TextEncoder().encode(JSON.stringify(state));
|
||||||
|
try {
|
||||||
|
if (typeof CompressionStream !== 'undefined') return B64.enc(await pipe(json, new CompressionStream('deflate-raw')));
|
||||||
|
} catch { /* fall through */ }
|
||||||
|
return '~' + B64.enc(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a link or a file may hold. A share link is read by anyone who follows it, so it is read with limits: a
|
||||||
|
* link longer than any the app writes, a blob that inflates past the size of any real piece of work (a
|
||||||
|
* decompression bomb), or a file larger than that, is refused with a message before anything else sees it.
|
||||||
|
* The largest state the app writes today (every catalog problem, every library routine) is a few tens of kB.
|
||||||
|
*/
|
||||||
|
export const LIMITS = {
|
||||||
|
/** Characters of the blob in a link. */
|
||||||
|
linkChars: 1_000_000,
|
||||||
|
/** Bytes of JSON a blob or a file may hold once inflated. */
|
||||||
|
stateBytes: 2 * 1024 * 1024,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/** A link or a file that does not hold a state the app will open; `message` says why, in words for the reader. */
|
||||||
|
export class StateError extends Error {
|
||||||
|
constructor(message: string) { super(message); this.name = 'StateError'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
const DAMAGED = 'This link is damaged (cut short, or changed on the way): it does not hold a Programming+ state.';
|
||||||
|
const tooLarge = (_bytes: number) => new StateError(`This link holds more than Programming+ opens: over ${Math.round(LIMITS.stateBytes / 1024).toLocaleString('en-US')} kB of work once unpacked, more than any program here.`);
|
||||||
|
|
||||||
|
/** Inflate with a cap: stop reading, and refuse, as soon as the output passes `max` bytes. */
|
||||||
|
async function inflateCapped(bytes: Uint8Array, max: number): Promise<Uint8Array> {
|
||||||
|
const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate-raw')).getReader();
|
||||||
|
const parts: Uint8Array[] = [];
|
||||||
|
let total = 0;
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
total += value.byteLength;
|
||||||
|
if (total > max) { void reader.cancel().catch(() => { /* already failed */ }); throw tooLarge(total); }
|
||||||
|
parts.push(value);
|
||||||
|
}
|
||||||
|
const out = new Uint8Array(total);
|
||||||
|
let at = 0;
|
||||||
|
for (const p of parts) { out.set(p, at); at += p.byteLength; }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state a link's blob holds. Throws a StateError with a message for the reader when the blob is too long,
|
||||||
|
* not base64url, cut short, inflates past LIMITS.stateBytes, or is not JSON; a state from another format is
|
||||||
|
* empty (normalize).
|
||||||
|
*/
|
||||||
|
export async function decodeState(blob: string): Promise<PlayState> {
|
||||||
|
if (blob.length > LIMITS.linkChars) throw new StateError(`This link is longer than any Programming+ makes (${blob.length.toLocaleString('en-US')} characters).`);
|
||||||
|
const plain = blob.startsWith('~');
|
||||||
|
const body = plain ? blob.slice(1) : blob;
|
||||||
|
if (!/^[A-Za-z0-9_-]*$/.test(body)) throw new StateError(DAMAGED);
|
||||||
|
let bytes: Uint8Array;
|
||||||
|
try { bytes = B64.dec(body); } catch { throw new StateError(DAMAGED); }
|
||||||
|
if (plain && bytes.byteLength > LIMITS.stateBytes) throw tooLarge(bytes.byteLength);
|
||||||
|
if (!plain) {
|
||||||
|
try { bytes = await inflateCapped(bytes, LIMITS.stateBytes); } catch (e) { throw e instanceof StateError ? e : new StateError(DAMAGED); }
|
||||||
|
}
|
||||||
|
let parsed: unknown;
|
||||||
|
try { parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { throw new StateError(DAMAGED); }
|
||||||
|
return normalize(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state a `.pplus.json` file holds, and the saved versions that came with it. Throws a StateError with a
|
||||||
|
* message for the reader when the file is too large, is not JSON, or is JSON that is not a Programming+ state
|
||||||
|
* (a file from an earlier state format opens empty, as a link does: normalize).
|
||||||
|
*/
|
||||||
|
export function readStateFile(text: string): { state: PlayState; versions: unknown[] } {
|
||||||
|
if (text.length > LIMITS.stateBytes) throw new StateError(`That file is larger than Programming+ opens (${Math.round(text.length / 1024).toLocaleString('en-US')} kB; the most is ${Math.round(LIMITS.stateBytes / 1024)} kB).`);
|
||||||
|
let parsed: any;
|
||||||
|
try { parsed = JSON.parse(text); } catch { throw new StateError('That file is not a Programming+ state: it is not JSON. Programming+ opens the .pplus.json files that Share → Download writes.'); }
|
||||||
|
const raw = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed.state ?? parsed) : null;
|
||||||
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('v' in raw) && !('sources' in raw))) throw new StateError('That file is not a Programming+ state. Programming+ opens the .pplus.json files that Share → Download writes.');
|
||||||
|
return { state: normalize(raw), versions: Array.isArray(parsed.versions) ? parsed.versions : [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLayout(l: any): Layout {
|
||||||
|
const num = (v: any) => (typeof v === 'number' && v > 0 && v < 1 ? v : undefined);
|
||||||
|
return { split: num(l.split), companion: num(l.companion), right: num(l.right), dock: num(l.dock),
|
||||||
|
dockTab: ['setup', 'output', 'problems', 'compiler', 'asm', 'practices'].includes(l.dockTab) ? l.dockTab : undefined,
|
||||||
|
dockCollapsed: typeof l.dockCollapsed === 'boolean' ? l.dockCollapsed : undefined, setupCollapsed: typeof l.setupCollapsed === 'boolean' ? l.setupCollapsed : undefined,
|
||||||
|
board: normalizeBoard(l.board),
|
||||||
|
follow: Array.isArray(l.follow) ? l.follow.filter((k: unknown) => typeof k === 'string' && k.includes('.')).slice(0, 40) : undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a problem id can look like: a catalog id (`count-base`) or a library routine (`lib:md.LennardJones`). */
|
||||||
|
export const PROBLEM_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
|
||||||
|
|
||||||
|
export function normalize(x: any): PlayState {
|
||||||
|
const s = emptyState();
|
||||||
|
// Programming+ is a new product: a state from any other version (an old link, an old save, no
|
||||||
|
// version at all) normalizes to empty rather than being migrated. No aliases, no legacy fields.
|
||||||
|
if (!x || typeof x !== 'object' || x.v !== 3) return s;
|
||||||
|
if (x.sources && typeof x.sources === 'object') for (const k of DEFAULT_PANES) if (typeof x.sources[k] === 'string') s.sources[k] = x.sources[k];
|
||||||
|
if (DEFAULT_PANES.includes(x.lang)) s.lang = x.lang;
|
||||||
|
if (['problems', 'trace', 'proof', 'tests', 'asm', 'flow', 'data', 'table', 'compiler', 'life'].includes(x.view)) s.view = x.view;
|
||||||
|
if (x.build === 'O0' || x.build === 'default') s.build = x.build;
|
||||||
|
if (typeof x.viewsCollapsed === 'boolean') s.viewsCollapsed = x.viewsCollapsed;
|
||||||
|
if (x.layout && typeof x.layout === 'object') {
|
||||||
|
const layouts: Partial<Record<AreaId, Layout>> = {};
|
||||||
|
for (const [k, v] of Object.entries(x.layout)) if (isAreaId(k) && v && typeof v === 'object') layouts[k] = normalizeLayout(v);
|
||||||
|
if (Object.keys(layouts).length) s.layout = layouts;
|
||||||
|
}
|
||||||
|
if (typeof x.call === 'string' || x.call === null) s.call = x.call;
|
||||||
|
if (typeof x.setup === 'string') s.setup = x.setup;
|
||||||
|
if (typeof x.input === 'string') s.input = x.input;
|
||||||
|
if (typeof x.machine === 'string') s.machine = x.machine;
|
||||||
|
if (typeof x.t === 'number' && x.t >= 0) s.t = Math.floor(x.t);
|
||||||
|
if (typeof x.problem === 'string' && PROBLEM_ID.test(x.problem)) s.problem = x.problem;
|
||||||
|
if (typeof x.title === 'string') s.title = x.title;
|
||||||
|
if (x.sync && typeof x.sync === 'object' && ['lingo', 'matho', 'pseudo', 'speco'].includes(x.sync.authority)) {
|
||||||
|
const stale: SyncInfo['stale'] = {};
|
||||||
|
if (x.sync.stale && typeof x.sync.stale === 'object') for (const k of ['lingo', 'matho', 'pseudo', 'speco'] as const) if (typeof x.sync.stale[k] === 'string') stale[k] = x.sync.stale[k];
|
||||||
|
const names: Record<string, string> = {};
|
||||||
|
if (x.sync.names && typeof x.sync.names === 'object') for (const [k, v] of Object.entries(x.sync.names)) if (typeof v === 'string') names[k] = v;
|
||||||
|
s.sync = { authority: x.sync.authority, stale, names };
|
||||||
|
}
|
||||||
|
if (x.mojoOrigin === 'generated' || x.mojoOrigin === 'generated-edited') s.mojoOrigin = x.mojoOrigin;
|
||||||
|
if (typeof x.workspace === 'string' && /^[a-z0-9-]{4,48}$/.test(x.workspace)) s.workspace = x.workspace;
|
||||||
|
if (typeof x.base === 'string') s.base = x.base;
|
||||||
|
if (typeof x.edited === 'boolean') s.edited = x.edited;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An embed's query can set up the example the way the playground's own controls do, so a catalog
|
||||||
|
* problem (`#/embed/playground/p/demo`) can be shown arranged for a page without a blob:
|
||||||
|
* lang=mojo the pane that is active
|
||||||
|
* panel=flow the inspect tab (trace table values flow data life proof tests) or dock tab
|
||||||
|
* (output problems compiler asm setup) the playground opens on
|
||||||
|
* build=O0|default how the Mojo pane is compiled
|
||||||
|
* machine=<preset> the x86-64 machine model
|
||||||
|
* dock=open|closed the dock under the editors; docktab=<tab> picks its tab
|
||||||
|
* area=dev the area the whole-workspace embed shows (bridge, dev, hw); the layout below is that area's
|
||||||
|
* editor=0.6 side=0.5 dockheight=0.7 the playground's split fractions (editor column, variables
|
||||||
|
* panel, and the dock's share of the height)
|
||||||
|
* t=12 the step the stepper is parked at
|
||||||
|
* Anything not given keeps what the state says; anything malformed is ignored.
|
||||||
|
*/
|
||||||
|
export function applyEmbedParams(state: PlayState, params: URLSearchParams, area: AreaId = 'bridge'): PlayState {
|
||||||
|
const s: PlayState = { ...state, layout: { ...(state.layout ?? {}), [area]: { ...(state.layout?.[area] ?? {}) } } };
|
||||||
|
const layout = s.layout![area]!;
|
||||||
|
const lang = params.get('lang');
|
||||||
|
if (lang && (DEFAULT_PANES as string[]).includes(lang)) s.lang = lang as LangId;
|
||||||
|
const panel = params.get('panel');
|
||||||
|
if (panel && ['trace', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'problems', 'compiler', 'asm'].includes(panel)) s.view = panel as ViewId;
|
||||||
|
if (panel === 'output' || panel === 'setup') layout.dockTab = panel;
|
||||||
|
const build = params.get('build');
|
||||||
|
if (build === 'O0' || build === 'default') s.build = build;
|
||||||
|
const machine = params.get('machine');
|
||||||
|
if (machine) s.machine = machine;
|
||||||
|
const dock = params.get('dock');
|
||||||
|
if (dock === 'open' || dock === 'closed') layout.dockCollapsed = dock === 'closed';
|
||||||
|
const tab = params.get('docktab');
|
||||||
|
if (tab && ['setup', 'output', 'problems', 'compiler', 'asm', 'practices'].includes(tab)) layout.dockTab = tab as DockTab;
|
||||||
|
const frac = (k: string) => { const v = Number(params.get(k)); return params.has(k) && v > 0 && v < 1 ? v : undefined; };
|
||||||
|
if (frac('editor') !== undefined) layout.split = frac('editor');
|
||||||
|
if (frac('side') !== undefined) layout.right = frac('side');
|
||||||
|
if (frac('dockheight') !== undefined) layout.dock = frac('dockheight');
|
||||||
|
const t = Number(params.get('t'));
|
||||||
|
if (params.has('t') && Number.isInteger(t) && t >= 0) s.t = t;
|
||||||
|
if (!Object.keys(layout).length) delete s.layout![area];
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Routes */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export type Route =
|
||||||
|
| { kind: 'home' }
|
||||||
|
| { kind: 'quarto'; anchor?: string }
|
||||||
|
| { kind: 'library'; id?: string }
|
||||||
|
| { kind: 'problem'; area: AreaId; id: string }
|
||||||
|
| { kind: 'shared'; area: AreaId; blob: string }
|
||||||
|
| { kind: 'embed'; view: ViewId | LangId; blob?: string; problem?: string; params: URLSearchParams };
|
||||||
|
|
||||||
|
/** A part of the address as written, decoded; a malformed escape (`%E0`) is kept as written rather than thrown. */
|
||||||
|
function decode(part: string): string {
|
||||||
|
try { return decodeURIComponent(part); } catch { return part; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an address names no page (`#/s/...`, `#/bridge/x`, an earlier form): it opens the home page, which then
|
||||||
|
* says so. A plain anchor (`#ref-pseudo`) and the home page's own anchors (`#/#problems`) are not that.
|
||||||
|
*/
|
||||||
|
export function isUnknownRoute(hash: string): boolean {
|
||||||
|
const h = (hash || '').replace(/^#/, '');
|
||||||
|
if (!h.startsWith('/')) return false;
|
||||||
|
if (/^\/(#[\w-]*)?(\?.*)?$/.test(h)) return false;
|
||||||
|
return parseRoute(hash).kind === 'home';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether going to `hash` only moves to an anchor of the page on screen (`#/#problems` on the home page, `#/quarto#setup`
|
||||||
|
* on With Quarto), so the page is scrolled rather than built again. `shown` is the class list of the page on screen:
|
||||||
|
* the library and a message page also have the class `home`, and from them `#/#problems` must open the home page.
|
||||||
|
*/
|
||||||
|
export function anchorOnly(hash: string, shown: readonly string[] | null): boolean {
|
||||||
|
const r = parseRoute(hash);
|
||||||
|
if (r.kind === 'home') return !isUnknownRoute(hash) && !!shown?.includes('home-page');
|
||||||
|
if (r.kind === 'quarto') return !!shown?.includes('qg');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Anything that is not one of the routes in the header is home; there are no aliases for old links. */
|
||||||
|
export function parseRoute(hash: string): Route {
|
||||||
|
const h = (hash || '').replace(/^#/, '');
|
||||||
|
const [pathPart, query = ''] = h.split('?');
|
||||||
|
const parts = pathPart.split('/').filter(Boolean);
|
||||||
|
const params = new URLSearchParams(query);
|
||||||
|
if (!parts.length) return { kind: 'home' };
|
||||||
|
if (parts.length === 1 && /^quarto(#[\w-]*)?$/.test(parts[0])) { const a = parts[0].split('#')[1]; return a ? { kind: 'quarto', anchor: a } : { kind: 'quarto' }; }
|
||||||
|
if (parts[0] === 'library') return parts[1] ? { kind: 'library', id: decode(parts[1]) } : { kind: 'library' };
|
||||||
|
if (isAreaId(parts[0]) && parts[1] === 'p' && parts[2]) return { kind: 'problem', area: parts[0], id: decode(parts[2]) };
|
||||||
|
if (isAreaId(parts[0]) && parts[1] === 's' && parts[2]) return { kind: 'shared', area: parts[0], blob: parts[2] };
|
||||||
|
if (parts[0] === 'embed' && parts[1]) {
|
||||||
|
// a view the app does not have shows the problems view, as mountEmbed does, under that one name
|
||||||
|
const view = ((EMBED_VIEWS as readonly string[]).includes(parts[1]) ? parts[1] : 'problems') as ViewId | LangId;
|
||||||
|
if (parts[2] === 'p' && parts[3]) return { kind: 'embed', view, problem: decode(parts[3]), params };
|
||||||
|
return { kind: 'embed', view, blob: parts[2], params };
|
||||||
|
}
|
||||||
|
return { kind: 'home' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function routeFor(r: Route): string {
|
||||||
|
switch (r.kind) {
|
||||||
|
case 'home': return '#/';
|
||||||
|
case 'quarto': return r.anchor ? `#/quarto#${r.anchor}` : '#/quarto';
|
||||||
|
case 'library': return r.id ? `#/library/${encodeURIComponent(r.id)}` : '#/library';
|
||||||
|
case 'problem': return `#/${r.area}/p/${encodeURIComponent(r.id)}`;
|
||||||
|
case 'shared': return `#/${r.area}/s/${r.blob}`;
|
||||||
|
case 'embed': {
|
||||||
|
const q = r.params.toString();
|
||||||
|
const base = r.problem ? `#/embed/${r.view}/p/${encodeURIComponent(r.problem)}` : `#/embed/${r.view}/${r.blob}`;
|
||||||
|
return q ? `${base}?${q}` : base;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Local persistence */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const KEY = (id: string) => `pplus.${id}`;
|
||||||
|
|
||||||
|
/** Saved work from before the rename lives under the old prefix; read it once, then it is re-saved under the new one. */
|
||||||
|
export function migrateLocal(): void {
|
||||||
|
try {
|
||||||
|
for (const k of Object.keys(localStorage)) {
|
||||||
|
if (k.startsWith('progo.') && localStorage.getItem('pplus.' + k.slice(6)) === null) localStorage.setItem('pplus.' + k.slice(6), localStorage.getItem(k)!);
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadLocal(id: string): PlayState | null {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(KEY(id));
|
||||||
|
if (!raw) return null;
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
// a save from another state format is dropped, not migrated: the problem opens as written
|
||||||
|
if (!parsed || parsed.v !== 3) { clearLocal(id); return null; }
|
||||||
|
return normalize(parsed);
|
||||||
|
} catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveLocal(id: string, state: PlayState): void {
|
||||||
|
try { localStorage.setItem(KEY(id), JSON.stringify(state)); } catch { /* private mode or quota */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an embed keeps the reader's edits: its own save, one per embedded
|
||||||
|
* example (the view, and the problem or the program's blob), never the
|
||||||
|
* app's save for the problem. Two pages that embed the same example share it.
|
||||||
|
*/
|
||||||
|
export function embedStorageId(view: string, problem?: string, blob?: string): string {
|
||||||
|
if (problem) return `embed.${view}.p.${problem}`;
|
||||||
|
let h = 0x811c9dc5; // FNV-1a: a short, stable name for a long blob
|
||||||
|
for (let i = 0; i < (blob ?? '').length; i++) { h ^= blob!.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||||
|
return `embed.${view}.b.${h.toString(16).padStart(8, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The parts of a state a reader edits; the rest (pane, view, step) is where they are looking. */
|
||||||
|
/* `sync` is bookkeeping (which pane the others follow, which are stale), not something the reader wrote: a state whose texts are the problem's own is unedited whatever it says. A saved version does keep it (core/versions.ts), because restoring one must bring the links back as they were. */
|
||||||
|
const EDITS = ['sources', 'input', 'call', 'setup', 'machine', 'build', 'mojoOrigin'] as const;
|
||||||
|
|
||||||
|
/** Whether `state` holds edits that `original` does not. */
|
||||||
|
export function editedFrom(state: PlayState, original: PlayState): boolean {
|
||||||
|
return EDITS.some((k) => JSON.stringify(state[k] ?? null) !== JSON.stringify(original[k] ?? null));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which fields count as the reader's edits, for code outside this file (saved versions add `sync`). */
|
||||||
|
export const EDIT_FIELDS: readonly (typeof EDITS[number])[] = EDITS;
|
||||||
|
|
||||||
|
/** A short, stable name for the edits of a state (FNV-1a over EDITS), to tell when a catalog problem has changed under a save. */
|
||||||
|
export function editsFingerprint(state: PlayState): string {
|
||||||
|
const text = JSON.stringify(EDITS.map((k) => state[k] ?? null));
|
||||||
|
let h = 0x811c9dc5;
|
||||||
|
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||||
|
return h.toString(16).padStart(8, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What to open for a catalog problem, given its save. A save made against an older version of the
|
||||||
|
* problem that holds no edits is dropped, so the reader sees the author's current version; a save
|
||||||
|
* that holds edits is kept, and marked stale so the app can say the problem changed underneath it.
|
||||||
|
*/
|
||||||
|
export function resolveSaved(original: PlayState, saved: PlayState | null): { state: PlayState; stale: boolean } {
|
||||||
|
if (!saved) return { state: original, stale: false };
|
||||||
|
const changed = saved.base !== undefined && saved.base !== editsFingerprint(original);
|
||||||
|
if (!changed) return { state: saved, stale: false };
|
||||||
|
return saved.edited ? { state: saved, stale: true } : { state: original, stale: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearLocal(id: string): void {
|
||||||
|
try { localStorage.removeItem(KEY(id)); } catch { /* ignore */ }
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Saved versions (restructure plan, section 2.7): a student can save the state of their work under a name and
|
||||||
|
* come back to any saved version. DOM-free; the storage is a parameter (localStorage when there is one), so the
|
||||||
|
* tests run it against a fake.
|
||||||
|
*
|
||||||
|
* A version holds what the student edits: every source, the link bookkeeping (`sync`), where the Mojo came from,
|
||||||
|
* the call, the input, the assembly setup and machine, the build level. It also records the area it was saved in,
|
||||||
|
* a name, and a time. It does not hold the layout, the step, or the open tab: those are where the student is
|
||||||
|
* looking, not what they made, so restoring a version never moves them.
|
||||||
|
*
|
||||||
|
* One list per piece of work: `pplus.versions.<problemId>` for a catalog problem, and
|
||||||
|
* `pplus.versions.ws.<workspaceId>` for work that began from a share link or a file.
|
||||||
|
*/
|
||||||
|
import { editedFrom, EDIT_FIELDS, normalize, type PlayState } from './state.js';
|
||||||
|
import { isAreaId, type AreaId } from './areas.js';
|
||||||
|
|
||||||
|
/** The most versions one piece of work keeps. */
|
||||||
|
export const MAX_VERSIONS = 50;
|
||||||
|
/** Characters of localStorage in use above which the drop-down says the browser is nearly full (most browsers hold about 5 million). */
|
||||||
|
export const PRESSURE_CHARS = 4_000_000;
|
||||||
|
|
||||||
|
const FIELDS = [...EDIT_FIELDS, 'sync'] as const;
|
||||||
|
export type VersionEdits = Partial<Pick<PlayState, typeof FIELDS[number]>>;
|
||||||
|
|
||||||
|
export interface Version {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
at: number;
|
||||||
|
area: AreaId;
|
||||||
|
/** Saved by Programming+ before a switch or a reset, not by the student. */
|
||||||
|
auto?: boolean;
|
||||||
|
edits: VersionEdits;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Store { getItem(k: string): string | null; setItem(k: string, v: string): void; removeItem(k: string): void; key?(i: number): string | null; readonly length?: number }
|
||||||
|
|
||||||
|
const defaultStore = (): Store | null => { try { return typeof localStorage === 'undefined' ? null : localStorage; } catch { return null; } };
|
||||||
|
|
||||||
|
/** The list a piece of work keeps its versions in, or null while it has neither a problem nor a workspace. */
|
||||||
|
export function versionKey(state: Pick<PlayState, 'problem' | 'workspace'>): string | null {
|
||||||
|
if (state.problem) return `pplus.versions.${state.problem}`;
|
||||||
|
if (state.workspace) return `pplus.versions.ws.${state.workspace}`;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A name for work that has none yet. Random, short, and safe in a key. */
|
||||||
|
export function newWorkspaceId(): string {
|
||||||
|
const bytes = new Uint8Array(8);
|
||||||
|
if (typeof crypto !== 'undefined' && crypto.getRandomValues) crypto.getRandomValues(bytes); else for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256);
|
||||||
|
return 'w' + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The edited fields of a state, and only those. */
|
||||||
|
export function editsOf(state: PlayState): VersionEdits {
|
||||||
|
const out: Record<string, unknown> = {};
|
||||||
|
for (const k of FIELDS) if (state[k] !== undefined) out[k] = structuredClone(state[k]);
|
||||||
|
return out as VersionEdits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A short, stable name for a state's edits (FNV-1a), `sync` included: two states with the same fingerprint restore to the same work. */
|
||||||
|
export function versionFingerprint(edits: VersionEdits | PlayState): string {
|
||||||
|
const text = canon(FIELDS.map((k) => (edits as Record<string, unknown>)[k] ?? null));
|
||||||
|
let h = 0x811c9dc5;
|
||||||
|
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||||
|
return h.toString(16).padStart(8, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSON with the keys in order, so the same edits read back from storage or a file name the same version. */
|
||||||
|
function canon(x: unknown): string {
|
||||||
|
if (Array.isArray(x)) return `[${x.map(canon).join(',')}]`;
|
||||||
|
if (x && typeof x === 'object') return `{${Object.keys(x).sort().filter((k) => (x as Record<string, unknown>)[k] !== undefined).map((k) => `${JSON.stringify(k)}:${canon((x as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||||
|
return JSON.stringify(x) ?? 'null';
|
||||||
|
}
|
||||||
|
|
||||||
|
function readList(key: string, store: Store | null): Version[] {
|
||||||
|
if (!store) return memoryLists.get(key) ?? [];
|
||||||
|
try {
|
||||||
|
const raw = store.getItem(key);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : [];
|
||||||
|
return Array.isArray(parsed) ? parsed.map(cleanVersion).filter((v): v is Version => !!v) : [];
|
||||||
|
} catch { return []; }
|
||||||
|
}
|
||||||
|
/** A browser with no storage still keeps versions for the tab. */
|
||||||
|
const memoryLists = new Map<string, Version[]>();
|
||||||
|
|
||||||
|
/** A version read back from storage or a file: only what is well formed; the edits go through `normalize`, so a damaged one cannot smuggle anything in. */
|
||||||
|
export function cleanVersion(v: any): Version | null {
|
||||||
|
if (!v || typeof v !== 'object' || typeof v.id !== 'string' || !/^[A-Za-z0-9_-]{1,40}$/.test(v.id) || typeof v.name !== 'string' || typeof v.at !== 'number' || !isAreaId(v.area)) return null;
|
||||||
|
const n = normalize({ v: 3, ...(v.edits && typeof v.edits === 'object' ? v.edits : {}) });
|
||||||
|
return { id: v.id, name: v.name.slice(0, 120), at: v.at, area: v.area, ...(v.auto ? { auto: true } : {}), edits: editsOf(n) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeList(key: string, list: Version[], store: Store | null): boolean {
|
||||||
|
if (!store) { memoryLists.set(key, list); return true; }
|
||||||
|
try { store.setItem(key, JSON.stringify(list)); return true; } catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saved versions, newest first. */
|
||||||
|
export function listVersions(key: string | null, store: Store | null = defaultStore()): Version[] {
|
||||||
|
if (!key) return [];
|
||||||
|
return readList(key, store).slice().sort((a, b) => b.at - a.at);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SaveResult = { ok: true; version: Version; dropped: Version[] } | { ok: false; reason: 'cap' | 'storage' | 'no-key' };
|
||||||
|
|
||||||
|
let counter = 0;
|
||||||
|
const newId = (at: number): string => `v${at.toString(36)}${(counter++ % 1296).toString(36)}${Math.floor(Math.random() * 1296).toString(36)}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save the state's edits as a version. When the list is full, the oldest automatic versions go first; if only
|
||||||
|
* named ones are left it refuses rather than delete something the student named.
|
||||||
|
*/
|
||||||
|
export function saveVersion(key: string | null, name: string, state: PlayState, area: AreaId, opts: { auto?: boolean; now?: number; store?: Store | null } = {}): SaveResult {
|
||||||
|
if (!key) return { ok: false, reason: 'no-key' };
|
||||||
|
const store = opts.store === undefined ? defaultStore() : opts.store;
|
||||||
|
const at = opts.now ?? Date.now();
|
||||||
|
let list = readList(key, store).slice().sort((a, b) => b.at - a.at);
|
||||||
|
const dropped: Version[] = [];
|
||||||
|
while (list.length >= MAX_VERSIONS) {
|
||||||
|
const oldestAuto = [...list].reverse().find((v) => v.auto);
|
||||||
|
if (!oldestAuto) return { ok: false, reason: 'cap' };
|
||||||
|
list = list.filter((v) => v !== oldestAuto); dropped.push(oldestAuto);
|
||||||
|
}
|
||||||
|
const version: Version = { id: newId(at), name: name.trim() || 'Untitled version', at, area, ...(opts.auto ? { auto: true } : {}), edits: editsOf(state) };
|
||||||
|
list.unshift(version);
|
||||||
|
return writeList(key, list, store) ? { ok: true, version, dropped } : { ok: false, reason: 'storage' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renameVersion(key: string | null, id: string, name: string, store: Store | null = defaultStore()): boolean {
|
||||||
|
if (!key || !name.trim()) return false;
|
||||||
|
const list = readList(key, store);
|
||||||
|
const v = list.find((x) => x.id === id);
|
||||||
|
if (!v) return false;
|
||||||
|
v.name = name.trim().slice(0, 120);
|
||||||
|
delete v.auto; // a version the student named is theirs: it is no longer the first to go
|
||||||
|
return writeList(key, list, store);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteVersion(key: string | null, id: string, store: Store | null = defaultStore()): boolean {
|
||||||
|
if (!key) return false;
|
||||||
|
const list = readList(key, store);
|
||||||
|
const rest = list.filter((x) => x.id !== id);
|
||||||
|
if (rest.length === list.length) return false;
|
||||||
|
if (!rest.length) { if (store) { try { store.removeItem(key); } catch { /* ignore */ } } else memoryLists.delete(key); return true; }
|
||||||
|
return writeList(key, rest, store);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state with a version's edits put in place of the current ones. Everything else (the layout, the step, the
|
||||||
|
* open tab and view, the title, the problem) is the current state's own, so restoring changes the work and not where
|
||||||
|
* the student is looking. A field the version does not have is removed, not left over from the work being replaced.
|
||||||
|
*/
|
||||||
|
export function restoreVersion(key: string | null, id: string, current: PlayState, store: Store | null = defaultStore()): PlayState | null {
|
||||||
|
const v = listVersions(key, store).find((x) => x.id === id);
|
||||||
|
if (!v) return null;
|
||||||
|
const next: PlayState = structuredClone(current);
|
||||||
|
for (const k of FIELDS) delete (next as unknown as Record<string, unknown>)[k];
|
||||||
|
Object.assign(next, structuredClone(v.edits));
|
||||||
|
if (!next.sources) next.sources = {};
|
||||||
|
delete next.edited; delete next.base;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the work has edits that no saved version holds. For a catalog problem, work that is the problem as
|
||||||
|
* written has none to lose (pass the problem's own state as `original`).
|
||||||
|
*/
|
||||||
|
export function hasUnsavedEdits(key: string | null, state: PlayState, original?: PlayState | null, store: Store | null = defaultStore()): boolean {
|
||||||
|
if (original && !editedFrom(state, original)) return false;
|
||||||
|
if (!original && !Object.values(state.sources).some((t) => (t ?? '').trim())) return false;
|
||||||
|
const fp = versionFingerprint(state);
|
||||||
|
return !listVersions(key, store).some((v) => versionFingerprint(v.edits) === fp);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which saved version, if any, the current work is exactly. */
|
||||||
|
export function currentVersion(key: string | null, state: PlayState, store: Store | null = defaultStore()): Version | null {
|
||||||
|
const fp = versionFingerprint(state);
|
||||||
|
return listVersions(key, store).find((v) => versionFingerprint(v.edits) === fp) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How full the browser's storage is, as a guess: characters held across every key against what browsers usually allow. */
|
||||||
|
export function storagePressure(store: Store | null = defaultStore()): { used: number; nearlyFull: boolean } {
|
||||||
|
let used = 0;
|
||||||
|
try {
|
||||||
|
const n = store?.length ?? 0;
|
||||||
|
for (let i = 0; i < n; i++) { const k = store!.key?.(i); if (k != null) used += k.length + (store!.getItem(k)?.length ?? 0); }
|
||||||
|
} catch { /* unreadable: say nothing */ }
|
||||||
|
return { used, nearlyFull: used >= PRESSURE_CHARS };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The versions for a file: every well-formed one in the list. */
|
||||||
|
export function exportVersions(key: string | null, store: Store | null = defaultStore()): Version[] { return listVersions(key, store); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Put versions from a file into a list: one with an id the list already has is left as it is (an import never
|
||||||
|
* overwrites), and the cap holds (the oldest automatic ones make room; otherwise the rest are not added).
|
||||||
|
*/
|
||||||
|
export function importVersions(key: string | null, incoming: unknown, store: Store | null = defaultStore()): { added: number; skipped: number } {
|
||||||
|
if (!key || !Array.isArray(incoming)) return { added: 0, skipped: Array.isArray(incoming) ? incoming.length : 0 };
|
||||||
|
let list = readList(key, store);
|
||||||
|
let added = 0, skipped = 0;
|
||||||
|
for (const raw of incoming) {
|
||||||
|
const v = cleanVersion(raw);
|
||||||
|
if (!v || list.some((x) => x.id === v.id)) { skipped++; continue; }
|
||||||
|
if (list.length >= MAX_VERSIONS) {
|
||||||
|
const oldestAuto = [...list].sort((a, b) => a.at - b.at).find((x) => x.auto);
|
||||||
|
if (!oldestAuto) { skipped++; continue; }
|
||||||
|
list = list.filter((x) => x !== oldestAuto);
|
||||||
|
}
|
||||||
|
list.push(v); added++;
|
||||||
|
}
|
||||||
|
if (added) writeList(key, list, store);
|
||||||
|
return { added, skipped };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The name of an automatic version: "Before switching (3:42 PM)". */
|
||||||
|
export function autoName(why: 'switching' | 'reset' | 'new', at = Date.now()): string {
|
||||||
|
const t = new Date(at).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
|
||||||
|
return why === 'new' ? 'My edits, before the problem changed' : `Before ${why === 'reset' ? 'reset' : 'switching'} (${t})`;
|
||||||
|
}
|
||||||
+170
@@ -0,0 +1,170 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* Entry point: a hash router over three screens (home, app, embed).
|
||||||
|
*/
|
||||||
|
import { el, clear, add } from './ui/dom.js';
|
||||||
|
import { Shell } from './ui/shell.js';
|
||||||
|
import { mountEmbed } from './ui/embed.js';
|
||||||
|
import { Session, sharedSession } from './core/session.js';
|
||||||
|
import { problemById, stateForProblem } from './core/catalog.js';
|
||||||
|
import { parseRoute, decodeState, loadLocal, migrateLocal, type PlayState, embedStorageId, clearLocal, editedFrom, applyEmbedParams, resolveSaved, isUnknownRoute, anchorOnly } from './core/state.js';
|
||||||
|
import { takeCrashed, settle, setAside, markBusy } from './core/guard.js';
|
||||||
|
import { notice, messagePage } from './ui/notice.js';
|
||||||
|
import { homeView } from './ui/home.js';
|
||||||
|
import { quartoView } from './ui/quarto.js';
|
||||||
|
import { libraryView } from './ui/library.js';
|
||||||
|
import { libraryState } from './core/library.js';
|
||||||
|
import { forceTheme, watchTheme } from './ui/theme.js';
|
||||||
|
|
||||||
|
/** The home page's title, as index.html has it before the app starts. */
|
||||||
|
const HOME_TITLE = 'Programming+: from an idea to Mojo to the machine';
|
||||||
|
import { AREAS, isAreaId, paneForArea, type AreaId } from './core/areas.js';
|
||||||
|
|
||||||
|
migrateLocal();
|
||||||
|
watchTheme();
|
||||||
|
const app = document.getElementById('app')!;
|
||||||
|
let shell: Shell | null = null;
|
||||||
|
/** The save whose work was running when the page last died (core/guard.ts): it is set aside, not opened again. */
|
||||||
|
let crashed = takeCrashed();
|
||||||
|
// a page that closes normally did not die of what it was running (the mark is this tab's: core/guard.ts)
|
||||||
|
window.addEventListener('pagehide', () => settle());
|
||||||
|
|
||||||
|
/** Where the route's work came from, so a failure to open it can offer to put a save aside. */
|
||||||
|
interface Opened { area: AreaId; state: PlayState; original?: PlayState; stale?: boolean; savedId?: string; embed?: { view: any; params: URLSearchParams; original: PlayState; storageId: string | null } }
|
||||||
|
type Resolved = Opened | { missing: { title: string; text: string } } | null;
|
||||||
|
|
||||||
|
const noProblem = (id: string) => ({ missing: { title: 'No such problem', text: `Programming+ has no problem called "${id.slice(0, 80)}". It may have been renamed, or the link may be cut short.` } });
|
||||||
|
|
||||||
|
async function stateForRoute(): Promise<Resolved> {
|
||||||
|
const r = parseRoute(location.hash);
|
||||||
|
if (r.kind === 'home' || r.kind === 'quarto' || r.kind === 'library') return null;
|
||||||
|
if (r.kind === 'problem') {
|
||||||
|
const p = problemById(r.id);
|
||||||
|
const original = p ? stateForProblem(p) : libraryState(r.id);
|
||||||
|
if (!original) return noProblem(r.id);
|
||||||
|
let saved = loadLocal(r.id);
|
||||||
|
if (saved && crashed === r.id) {
|
||||||
|
// this save was running when the page died: keep it as a version and open the problem as written
|
||||||
|
crashed = null;
|
||||||
|
const name = setAside(r.id, saved, r.area, 'stopped');
|
||||||
|
if (name) { saved = null; notice(`The last time this problem was open, the page stopped while it ran your program (it may have used up the browser's memory). Your work is kept as the version "${name}" in the Versions menu, and the problem opens as written.`); }
|
||||||
|
}
|
||||||
|
const { state, stale } = resolveSaved(original, saved);
|
||||||
|
state.lang = paneForArea(AREAS[r.area], state, true);
|
||||||
|
return { area: r.area, state, original, stale, savedId: saved ? r.id : undefined };
|
||||||
|
}
|
||||||
|
// a shared state is the sender's: it is never saved over this browser's own save for its problem
|
||||||
|
if (r.kind === 'shared') return { area: r.area, state: await decodeState(r.blob) };
|
||||||
|
if (r.kind === 'embed') {
|
||||||
|
let state: PlayState | null = null;
|
||||||
|
if (r.problem) { const p = problemById(r.problem); if (p) state = stateForProblem(p); else return noProblem(r.problem); }
|
||||||
|
else if (r.blob) state = await decodeState(r.blob);
|
||||||
|
if (!state) return { missing: { title: 'Nothing to show', text: 'This embed names no program: its address ends where the program should be.' } };
|
||||||
|
// the query arranges the example (pane, panel, panes, build, layout) as the page author asked
|
||||||
|
const asked = r.params.get('area');
|
||||||
|
const area: AreaId = isAreaId(asked) ? asked : r.problem && problemById(r.problem) ? problemById(r.problem)!.area : 'bridge';
|
||||||
|
state = applyEmbedParams(state, r.params, area);
|
||||||
|
// the reader's edits live in the embed's own save; a read-only embed has none to keep
|
||||||
|
const storageId = r.params.get('ro') === '1' ? null : embedStorageId(String(r.view), r.problem, r.blob);
|
||||||
|
// a reader's edits that were running when the page died are dropped: the author's example opens
|
||||||
|
if (storageId && crashed === storageId) { crashed = null; clearLocal(storageId); }
|
||||||
|
const saved = storageId ? loadLocal(storageId) : null;
|
||||||
|
// a copy: the session edits its state in place, and the original must stay the author's
|
||||||
|
return { area, state: saved ?? state, embed: { view: r.view, params: r.params, original: structuredClone(state), storageId } };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollToAnchor(): void {
|
||||||
|
const m = /#(problems|reference|quarto-teaser)$/.exec(location.hash) ?? /^#\/quarto#([\w-]+)$/.exec(location.hash);
|
||||||
|
if (m) requestAnimationFrame(() => document.getElementById(m[1])?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In a host page (the Quarto extension's pplus.js), follow its light/dark switch: the host posts
|
||||||
|
* {type:'pplus:theme', theme} whenever it changes, and answers our 'pplus:ready' with the current one. */
|
||||||
|
let following = false;
|
||||||
|
function followHostTheme(): void {
|
||||||
|
if (following || window.parent === window) return;
|
||||||
|
following = true;
|
||||||
|
window.addEventListener('message', (ev) => {
|
||||||
|
const d = ev.data;
|
||||||
|
if (ev.source === window.parent && d && d.type === 'pplus:theme' && (d.theme === 'light' || d.theme === 'dark')) forceTheme(d.theme);
|
||||||
|
});
|
||||||
|
window.parent.postMessage({ type: 'pplus:ready' }, '*');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function render(): Promise<void> {
|
||||||
|
try { await show(); } catch (e: any) {
|
||||||
|
// whatever went wrong, the page says so and offers a way on, rather than staying blank
|
||||||
|
shell?.destroy(); shell = null;
|
||||||
|
clear(app);
|
||||||
|
const r = (() => { try { return parseRoute(location.hash); } catch { return null; } })();
|
||||||
|
const saved = r?.kind === 'problem' ? loadLocal(r.id) : null;
|
||||||
|
const actions: Node[] = [];
|
||||||
|
if (r?.kind === 'problem' && saved) actions.push(el('button', { type: 'button', class: 'btn btn-primary', onClick: () => {
|
||||||
|
const name = setAside(r.id, saved, r.area, 'failed');
|
||||||
|
if (!name && !confirm('This browser would not keep a copy of your saved work as a version. Discard it, and open the problem as written?')) return;
|
||||||
|
if (!name) clearLocal(r.id);
|
||||||
|
void render();
|
||||||
|
} }, 'Keep my work as a version, and open the problem as written'));
|
||||||
|
add(app, messagePage('This did not open', `Programming+ could not show this page: ${String(e?.message || e).slice(0, 300)}`, ...actions));
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function show(): Promise<void> {
|
||||||
|
const route = parseRoute(location.hash);
|
||||||
|
// the same static page with only the anchor changed: scroll, do not rebuild
|
||||||
|
if (!shell && anchorOnly(location.hash, app.firstElementChild ? [...app.firstElementChild.classList] : null)) { scrollToAnchor(); return; }
|
||||||
|
shell?.destroy(); shell = null;
|
||||||
|
clear(app);
|
||||||
|
document.body.classList.remove('is-embed');
|
||||||
|
let resolved: Resolved;
|
||||||
|
try { resolved = await stateForRoute(); } catch (e: any) {
|
||||||
|
add(app, messagePage('That link did not open', String(e?.message || e)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (resolved && 'missing' in resolved) { add(app, messagePage(resolved.missing.title, resolved.missing.text)); document.title = `${resolved.missing.title} · Programming+`; return; }
|
||||||
|
if (!resolved && route.kind === 'library') { add(app, libraryView(route.id)); document.title = `${route.id ? `${route.id} · ` : ''}Library · Programming+`; window.scrollTo(0, 0); return; }
|
||||||
|
if (!resolved && route.kind === 'quarto') { add(app, quartoView()); document.title = 'With Quarto · Programming+'; if (route.anchor) scrollToAnchor(); else window.scrollTo(0, 0); return; }
|
||||||
|
if (!resolved) {
|
||||||
|
add(app, homeView()); document.title = HOME_TITLE; scrollToAnchor();
|
||||||
|
if (isUnknownRoute(location.hash)) notice('There is no page at that address, so this is the home page. Links from before the three areas open here too.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const embedded = resolved.embed;
|
||||||
|
const session = route.kind === 'shared' ? sharedSession(resolved.state, resolved.area) : new Session(resolved.state, embedded
|
||||||
|
? { storageId: embedded.storageId, keep: (st) => editedFrom(st, embedded.original), area: resolved.area }
|
||||||
|
: { original: resolved.original, stale: resolved.stale, area: resolved.area });
|
||||||
|
// saved work runs as the page opens: if it takes the page down, the next load sets it aside (core/guard.ts)
|
||||||
|
const busy = resolved.savedId ?? (embedded?.storageId && loadLocal(embedded.storageId) ? embedded.storageId : null);
|
||||||
|
if (busy) markBusy(busy);
|
||||||
|
document.title = `${resolved.state.title || 'Playground'} · Programming+`;
|
||||||
|
if (resolved.embed) {
|
||||||
|
document.body.classList.add('is-embed');
|
||||||
|
const th = resolved.embed.params.get('theme');
|
||||||
|
if (th === 'light' || th === 'dark') forceTheme(th);
|
||||||
|
followHostTheme();
|
||||||
|
const { original, storageId } = resolved.embed;
|
||||||
|
const reset = storageId ? () => { clearLocal(storageId); void render(); } : undefined;
|
||||||
|
if (resolved.embed.view === 'playground') {
|
||||||
|
// the whole playground in the frame, with the reader's edits in the embed's own save
|
||||||
|
document.body.classList.add('is-embed-playground');
|
||||||
|
shell = new Shell(session, AREAS[resolved.area], { embed: { reset, edited: () => editedFrom(session.state, original), readOnly: resolved.embed.params.get('ro') === '1' } });
|
||||||
|
add(app, shell.root);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
add(app, mountEmbed(session, resolved.embed.view, resolved.embed.params, {
|
||||||
|
original,
|
||||||
|
reset,
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
shell = new Shell(session, AREAS[resolved.area]);
|
||||||
|
add(app, shell.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('hashchange', () => void render());
|
||||||
|
window.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { const btn = document.querySelector<HTMLButtonElement>('.btn-primary'); btn?.click(); e.preventDefault(); } });
|
||||||
|
void render();
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* A small document for rendering the app's views outside a browser (`quarto render` runs them in Node).
|
||||||
|
*
|
||||||
|
* The views (src/ui/views/) build their output with `document.createElement` and friends; this is just enough of
|
||||||
|
* the DOM for them to do that, and to serialize what they built as HTML. It is not a browser: nothing is laid
|
||||||
|
* out (sizes are zero), events never fire, timers and animation frames are queued for `flushQueued()` to run.
|
||||||
|
* Only `installDocument()` touches the globals, and only when there is no real `document`.
|
||||||
|
*
|
||||||
|
* Selectors: what the views use and no more — a comma list of compound selectors (`tag`, `.class`, `#id`,
|
||||||
|
* `[attr]`, `[attr="v"]`, `[attr^="v"]`), joined by the descendant combinator only.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||||
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
||||||
|
const RAW_TEXT = new Set(['style', 'script']);
|
||||||
|
|
||||||
|
export const escapeText = (s: string): string => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
export const escapeAttr = (s: string): string => escapeText(s).replace(/"/g, '"');
|
||||||
|
|
||||||
|
/** `fontSize` → `font-size`; custom properties stay as they are. */
|
||||||
|
const kebab = (k: string): string => (k.startsWith('--') ? k : k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase()));
|
||||||
|
|
||||||
|
export class SNode {
|
||||||
|
parentNode: SElement | SFragment | null = null;
|
||||||
|
readonly childNodes: SNode[] = [];
|
||||||
|
nodeType = 0;
|
||||||
|
get parentElement(): SElement | null { return this.parentNode instanceof SElement ? this.parentNode : null; }
|
||||||
|
get firstChild(): SNode | null { return this.childNodes[0] ?? null; }
|
||||||
|
get lastChild(): SNode | null { return this.childNodes[this.childNodes.length - 1] ?? null; }
|
||||||
|
get nextSibling(): SNode | null { const p = this.parentNode; if (!p) return null; return p.childNodes[p.childNodes.indexOf(this) + 1] ?? null; }
|
||||||
|
get previousSibling(): SNode | null { const p = this.parentNode; if (!p) return null; return p.childNodes[p.childNodes.indexOf(this) - 1] ?? null; }
|
||||||
|
get textContent(): string { return this.childNodes.map((c) => c.textContent).join(''); }
|
||||||
|
set textContent(v: string) { for (const c of this.childNodes) c.parentNode = null; this.childNodes.length = 0; if (v !== '' && v != null) this.appendChild(new SText(String(v))); }
|
||||||
|
|
||||||
|
appendChild<T extends SNode>(c: T): T { return this.insertBefore(c, null); }
|
||||||
|
insertBefore<T extends SNode>(c: T, ref: SNode | null): T {
|
||||||
|
if (c instanceof SFragment) { for (const k of [...c.childNodes]) this.insertBefore(k, ref); return c; }
|
||||||
|
c.remove();
|
||||||
|
const at = ref ? this.childNodes.indexOf(ref) : -1;
|
||||||
|
if (at < 0) this.childNodes.push(c); else this.childNodes.splice(at, 0, c);
|
||||||
|
c.parentNode = this as any;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
removeChild<T extends SNode>(c: T): T { const i = this.childNodes.indexOf(c); if (i >= 0) { this.childNodes.splice(i, 1); c.parentNode = null; } return c; }
|
||||||
|
replaceChild(n: SNode, old: SNode): SNode { this.insertBefore(n, old); return this.removeChild(old); }
|
||||||
|
remove(): void { this.parentNode?.removeChild(this); }
|
||||||
|
append(...xs: Array<SNode | string>): void { for (const x of xs) this.appendChild(typeof x === 'string' ? new SText(x) : x); }
|
||||||
|
prepend(...xs: Array<SNode | string>): void { const first = this.firstChild; for (const x of xs) this.insertBefore(typeof x === 'string' ? new SText(x) : x, first); }
|
||||||
|
replaceChildren(...xs: Array<SNode | string>): void { this.textContent = ''; this.append(...xs); }
|
||||||
|
before(...xs: Array<SNode | string>): void { const p = this.parentNode; if (p) for (const x of xs) p.insertBefore(typeof x === 'string' ? new SText(x) : x, this); }
|
||||||
|
after(...xs: Array<SNode | string>): void { const p = this.parentNode; if (!p) return; const next = this.nextSibling; for (const x of xs) p.insertBefore(typeof x === 'string' ? new SText(x) : x, next); }
|
||||||
|
replaceWith(...xs: Array<SNode | string>): void { this.before(...xs); this.remove(); }
|
||||||
|
contains(n: SNode | null): boolean { for (let x: SNode | null = n; x; x = x.parentNode) if (x === this) return true; return false; }
|
||||||
|
hasChildNodes(): boolean { return this.childNodes.length > 0; }
|
||||||
|
cloneNode(deep = false): SNode { return this; }
|
||||||
|
addEventListener(): void { /* nothing fires here */ }
|
||||||
|
removeEventListener(): void { /* nothing fires here */ }
|
||||||
|
dispatchEvent(): boolean { return true; }
|
||||||
|
serialize(): string { return this.childNodes.map((c) => c.serialize()).join(''); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SText extends SNode {
|
||||||
|
constructor(public data: string) { super(); this.nodeType = 3; }
|
||||||
|
get textContent(): string { return this.data; }
|
||||||
|
set textContent(v: string) { this.data = String(v); }
|
||||||
|
get nodeValue(): string { return this.data; }
|
||||||
|
cloneNode(): SText { return new SText(this.data); }
|
||||||
|
serialize(): string { return this.parentNode instanceof SElement && RAW_TEXT.has(this.parentNode.localName) ? this.data : escapeText(this.data); }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SComment extends SNode {
|
||||||
|
constructor(public data: string) { super(); this.nodeType = 8; }
|
||||||
|
get textContent(): string { return ''; }
|
||||||
|
cloneNode(): SComment { return new SComment(this.data); }
|
||||||
|
serialize(): string { return `<!--${this.data}-->`; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SFragment extends SNode {
|
||||||
|
constructor() { super(); this.nodeType = 11; }
|
||||||
|
get children(): SElement[] { return this.childNodes.filter((c): c is SElement => c instanceof SElement); }
|
||||||
|
querySelector(sel: string): SElement | null { return this.querySelectorAll(sel)[0] ?? null; }
|
||||||
|
querySelectorAll(sel: string): SElement[] { const m = compile(sel); const out: SElement[] = []; for (const c of this.children) c.collect(m, out, true); return out; }
|
||||||
|
cloneNode(deep = false): SFragment { const f = new SFragment(); if (deep) for (const c of this.childNodes) f.appendChild(c.cloneNode(true)); return f; }
|
||||||
|
}
|
||||||
|
|
||||||
|
class ClassList {
|
||||||
|
constructor(private readonly owner: SElement) { }
|
||||||
|
private get list(): string[] { return (this.owner.getAttribute('class') ?? '').split(/\s+/).filter(Boolean); }
|
||||||
|
private set list(v: string[]) { this.owner.setAttribute('class', v.join(' ')); }
|
||||||
|
get length(): number { return this.list.length; }
|
||||||
|
contains(c: string): boolean { return this.list.includes(c); }
|
||||||
|
add(...cs: string[]): void { const l = this.list; for (const c of cs) if (!l.includes(c)) l.push(c); this.list = l; }
|
||||||
|
remove(...cs: string[]): void { this.list = this.list.filter((c) => !cs.includes(c)); }
|
||||||
|
toggle(c: string, force?: boolean): boolean { const on = force ?? !this.contains(c); if (on) this.add(c); else this.remove(c); return on; }
|
||||||
|
replace(a: string, b: string): void { if (this.contains(a)) { this.remove(a); this.add(b); } }
|
||||||
|
toString(): string { return this.list.join(' '); }
|
||||||
|
[Symbol.iterator](): Iterator<string> { return this.list[Symbol.iterator](); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `el.style`: properties set by name (`left`, `fontSize`) or with setProperty, written back as the style attribute. */
|
||||||
|
function styleOf(owner: SElement): any {
|
||||||
|
const props = new Map<string, string>();
|
||||||
|
const sync = () => { if (props.size) owner.attrs.set('style', [...props].map(([k, v]) => `${k}: ${v}`).join('; ')); else owner.attrs.delete('style'); };
|
||||||
|
const api = {
|
||||||
|
setProperty(k: string, v: string) { if (v == null || v === '') props.delete(kebab(k)); else props.set(kebab(k), String(v)); sync(); },
|
||||||
|
removeProperty(k: string) { props.delete(kebab(k)); sync(); },
|
||||||
|
getPropertyValue(k: string) { return props.get(kebab(k)) ?? ''; },
|
||||||
|
get cssText() { return owner.attrs.get('style') ?? ''; },
|
||||||
|
set cssText(v: string) { props.clear(); for (const part of String(v).split(';')) { const i = part.indexOf(':'); if (i > 0) props.set(part.slice(0, i).trim(), part.slice(i + 1).trim()); } sync(); },
|
||||||
|
};
|
||||||
|
return new Proxy(api, {
|
||||||
|
get: (t, k) => (k in t ? (t as any)[k] : typeof k === 'string' ? props.get(kebab(k)) ?? '' : undefined),
|
||||||
|
set: (t, k, v) => { if (k === 'cssText') t.cssText = v; else if (typeof k === 'string') t.setProperty(k, v); return true; },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function datasetOf(owner: SElement): any {
|
||||||
|
const attr = (k: string) => 'data-' + k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());
|
||||||
|
return new Proxy({}, {
|
||||||
|
get: (_t, k) => (typeof k === 'string' ? owner.getAttribute(attr(k)) ?? undefined : undefined),
|
||||||
|
set: (_t, k, v) => { if (typeof k === 'string') owner.setAttribute(attr(k), String(v)); return true; },
|
||||||
|
deleteProperty: (_t, k) => { if (typeof k === 'string') owner.removeAttribute(attr(k)); return true; },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Properties that reflect an attribute: a string, or a boolean (present or absent). */
|
||||||
|
const STRING_PROPS: Record<string, string> = { id: 'id', title: 'title', href: 'href', src: 'src', type: 'type', name: 'name', placeholder: 'placeholder', rel: 'rel', target: 'target', htmlFor: 'for', role: 'role', lang: 'lang', min: 'min', max: 'max', step: 'step', download: 'download', alt: 'alt' };
|
||||||
|
const BOOL_PROPS: Record<string, string> = { hidden: 'hidden', open: 'open', disabled: 'disabled', readOnly: 'readonly', multiple: 'multiple', required: 'required', spellcheck: 'spellcheck' };
|
||||||
|
|
||||||
|
export class SElement extends SNode {
|
||||||
|
readonly attrs = new Map<string, string>();
|
||||||
|
readonly localName: string;
|
||||||
|
private _classList?: ClassList;
|
||||||
|
private _style?: any;
|
||||||
|
private _dataset?: any;
|
||||||
|
/** Form state, which a browser keeps apart from the attributes; serialized as attributes. */
|
||||||
|
private _value: string | null = null;
|
||||||
|
private _checked: boolean | null = null;
|
||||||
|
private _selected: boolean | null = null;
|
||||||
|
scrollTop = 0; scrollLeft = 0;
|
||||||
|
readonly offsetWidth = 0; readonly offsetHeight = 0; readonly clientWidth = 0; readonly clientHeight = 0; readonly scrollWidth = 0; readonly scrollHeight = 0;
|
||||||
|
|
||||||
|
constructor(name: string, readonly namespaceURI: string | null = null) {
|
||||||
|
super();
|
||||||
|
this.nodeType = 1;
|
||||||
|
this.localName = namespaceURI === SVG_NS ? name : name.toLowerCase();
|
||||||
|
// the reflected properties, defined per instance so that `k in node` is true for them (src/ui/dom.ts el() asks)
|
||||||
|
for (const [prop, attr] of Object.entries(STRING_PROPS)) Object.defineProperty(this, prop, { configurable: true, enumerable: false, get: () => this.getAttribute(attr) ?? '', set: (v) => this.setAttribute(attr, String(v)) });
|
||||||
|
for (const [prop, attr] of Object.entries(BOOL_PROPS)) Object.defineProperty(this, prop, { configurable: true, enumerable: false, get: () => this.hasAttribute(attr), set: (v) => this.toggleAttribute(attr, !!v) });
|
||||||
|
}
|
||||||
|
get tagName(): string { return this.namespaceURI === SVG_NS ? this.localName : this.localName.toUpperCase(); }
|
||||||
|
get nodeName(): string { return this.tagName; }
|
||||||
|
get children(): SElement[] { return this.childNodes.filter((c): c is SElement => c instanceof SElement); }
|
||||||
|
get firstElementChild(): SElement | null { return this.children[0] ?? null; }
|
||||||
|
get lastElementChild(): SElement | null { const c = this.children; return c[c.length - 1] ?? null; }
|
||||||
|
get childElementCount(): number { return this.children.length; }
|
||||||
|
get className(): string { return this.getAttribute('class') ?? ''; }
|
||||||
|
set className(v: string) { this.setAttribute('class', String(v)); }
|
||||||
|
get classList(): ClassList { return (this._classList ??= new ClassList(this)); }
|
||||||
|
get style(): any { return (this._style ??= styleOf(this)); }
|
||||||
|
set style(v: any) { this.style.cssText = String(v); }
|
||||||
|
get dataset(): any { return (this._dataset ??= datasetOf(this)); }
|
||||||
|
|
||||||
|
get value(): string {
|
||||||
|
if (this.localName === 'select') { const opts = this.options; const sel = opts.find((o) => o.selected) ?? opts[0]; return sel ? sel.value : ''; }
|
||||||
|
if (this.localName === 'option') return this._value ?? this.getAttribute('value') ?? this.textContent;
|
||||||
|
if (this.localName === 'textarea') return this._value ?? this.textContent;
|
||||||
|
return this._value ?? this.getAttribute('value') ?? '';
|
||||||
|
}
|
||||||
|
set value(v: string) {
|
||||||
|
if (this.localName === 'select') { for (const o of this.options) o.selected = o.value === String(v); return; }
|
||||||
|
this._value = String(v);
|
||||||
|
}
|
||||||
|
get checked(): boolean { return this._checked ?? this.hasAttribute('checked'); }
|
||||||
|
set checked(v: boolean) { this._checked = !!v; }
|
||||||
|
get selected(): boolean { return this._selected ?? this.hasAttribute('selected'); }
|
||||||
|
set selected(v: boolean) {
|
||||||
|
if (v && this.parentElement?.localName === 'select') for (const o of this.parentElement.options) if (o !== this) o._selected = false;
|
||||||
|
this._selected = !!v;
|
||||||
|
}
|
||||||
|
get options(): SElement[] { const out: SElement[] = []; this.collect(compile('option'), out, true); return out; }
|
||||||
|
get selectedIndex(): number { return this.options.findIndex((o) => o.selected); }
|
||||||
|
set selectedIndex(i: number) { this.options.forEach((o, k) => { o.selected = k === i; }); }
|
||||||
|
|
||||||
|
getAttribute(k: string): string | null { return this.attrs.has(k) ? this.attrs.get(k)! : null; }
|
||||||
|
setAttribute(k: string, v: string): void { this.attrs.set(k, String(v)); }
|
||||||
|
setAttributeNS(_ns: string | null, k: string, v: string): void { this.setAttribute(k, v); }
|
||||||
|
removeAttribute(k: string): void { this.attrs.delete(k); }
|
||||||
|
hasAttribute(k: string): boolean { return this.attrs.has(k); }
|
||||||
|
toggleAttribute(k: string, force?: boolean): boolean { const on = force ?? !this.hasAttribute(k); if (on) this.attrs.set(k, ''); else this.attrs.delete(k); return on; }
|
||||||
|
get attributes(): Array<{ name: string; value: string }> { return [...this.attrs].map(([name, value]) => ({ name, value })); }
|
||||||
|
|
||||||
|
get innerHTML(): string { return super.serialize(); }
|
||||||
|
set innerHTML(v: string) {
|
||||||
|
// the views never parse markup; text is the safe reading of anything they might set
|
||||||
|
this.textContent = String(v).replace(/<[^>]*>/g, '');
|
||||||
|
}
|
||||||
|
get outerHTML(): string { return this.serialize(); }
|
||||||
|
|
||||||
|
matches(sel: string): boolean { return compile(sel)(this); }
|
||||||
|
closest(sel: string): SElement | null { const m = compile(sel); for (let e: SElement | null = this; e; e = e.parentElement) if (m(e)) return e; return null; }
|
||||||
|
querySelector(sel: string): SElement | null { return this.querySelectorAll(sel)[0] ?? null; }
|
||||||
|
querySelectorAll(sel: string): SElement[] { const out: SElement[] = []; for (const c of this.children) c.collect(compile(sel), out, true); return out; }
|
||||||
|
getElementsByTagName(name: string): SElement[] { return this.querySelectorAll(name); }
|
||||||
|
getElementsByClassName(name: string): SElement[] { return this.querySelectorAll('.' + name.trim().split(/\s+/).join('.')); }
|
||||||
|
collect(m: Matcher, out: SElement[], self: boolean): void { if (self && m(this)) out.push(this); for (const c of this.children) c.collect(m, out, true); }
|
||||||
|
|
||||||
|
cloneNode(deep = false): SElement {
|
||||||
|
const c = new SElement(this.localName, this.namespaceURI);
|
||||||
|
for (const [k, v] of this.attrs) c.attrs.set(k, v);
|
||||||
|
c._value = this._value; c._checked = this._checked; c._selected = this._selected;
|
||||||
|
if (deep) for (const k of this.childNodes) c.appendChild(k.cloneNode(true));
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
getBoundingClientRect() { return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0, toJSON() { return this; } }; }
|
||||||
|
getClientRects() { return []; }
|
||||||
|
scrollIntoView(): void { /* no layout */ }
|
||||||
|
scrollTo(): void { /* no layout */ }
|
||||||
|
focus(): void { /* no focus */ }
|
||||||
|
blur(): void { /* no focus */ }
|
||||||
|
click(): void { /* nothing fires */ }
|
||||||
|
select(): void { /* no selection */ }
|
||||||
|
getContext(): null { return null; }
|
||||||
|
|
||||||
|
serialize(): string {
|
||||||
|
const attrs = new Map(this.attrs);
|
||||||
|
// form state as markup, so the page shows what the view chose
|
||||||
|
if (this._value !== null && (this.localName === 'input' || this.localName === 'option')) attrs.set('value', this._value);
|
||||||
|
if (this._checked !== null) { if (this._checked) attrs.set('checked', ''); else attrs.delete('checked'); }
|
||||||
|
if (this._selected !== null) { if (this._selected) attrs.set('selected', ''); else attrs.delete('selected'); }
|
||||||
|
let open = '<' + this.localName;
|
||||||
|
for (const [k, v] of attrs) open += v === '' && (k in BOOL_ATTR) ? ` ${k}` : ` ${k}="${escapeAttr(v)}"`;
|
||||||
|
if (this.namespaceURI !== SVG_NS && VOID.has(this.localName)) return open + '>';
|
||||||
|
if (this.localName === 'textarea' && this._value !== null) return `${open}>${escapeText(this._value)}</textarea>`;
|
||||||
|
if (this.namespaceURI === SVG_NS && !this.childNodes.length) return open + '/>';
|
||||||
|
return `${open}>${super.serialize()}</${this.localName}>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const BOOL_ATTR: Record<string, true> = { hidden: true, open: true, disabled: true, readonly: true, checked: true, selected: true, multiple: true, required: true };
|
||||||
|
|
||||||
|
/* ---------- selectors ---------- */
|
||||||
|
|
||||||
|
type Matcher = (e: SElement) => boolean;
|
||||||
|
const compiled = new Map<string, Matcher>();
|
||||||
|
|
||||||
|
function compile(sel: string): Matcher {
|
||||||
|
const hit = compiled.get(sel);
|
||||||
|
if (hit) return hit;
|
||||||
|
const alts = sel.split(',').map((s) => s.trim()).filter(Boolean).map(descendant);
|
||||||
|
const m: Matcher = (e) => alts.some((a) => a(e));
|
||||||
|
compiled.set(sel, m);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `a b c`: c, inside a b, inside an a. */
|
||||||
|
function descendant(s: string): Matcher {
|
||||||
|
if (/[>+~]/.test(s.replace(/\[[^\]]*\]/g, ''))) throw new Error(`the render document does not handle the selector "${s}" (only the descendant combinator)`);
|
||||||
|
const parts = s.split(/\s+(?![^\[]*\])/).filter(Boolean).map(compound);
|
||||||
|
const last = parts.pop()!;
|
||||||
|
return (e) => {
|
||||||
|
if (!last(e)) return false;
|
||||||
|
let k = parts.length - 1;
|
||||||
|
for (let a = e.parentElement; a && k >= 0; a = a.parentElement) if (parts[k](a)) k--;
|
||||||
|
return k < 0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function compound(s: string): Matcher {
|
||||||
|
const tests: Matcher[] = [];
|
||||||
|
const re = /^([a-zA-Z][\w-]*|\*)|\.([\w-]+)|#([\w-]+)|\[([\w-]+)(?:([\^$*]?=)"?([^"\]]*)"?)?\]/g;
|
||||||
|
let m: RegExpExecArray | null;
|
||||||
|
let pos = 0;
|
||||||
|
while ((m = re.exec(s))) {
|
||||||
|
if (m.index !== pos) break;
|
||||||
|
pos = re.lastIndex;
|
||||||
|
const [, tag, cls, id, attr, op, val] = m;
|
||||||
|
if (tag && tag !== '*') tests.push((e) => e.localName.toLowerCase() === tag.toLowerCase());
|
||||||
|
else if (cls) tests.push((e) => e.classList.contains(cls));
|
||||||
|
else if (id) tests.push((e) => e.getAttribute('id') === id);
|
||||||
|
else if (attr) tests.push((e) => {
|
||||||
|
const v = e.getAttribute(attr);
|
||||||
|
if (v === null) return false;
|
||||||
|
if (!op) return true;
|
||||||
|
return op === '=' ? v === val : op === '^=' ? v.startsWith(val) : op === '$=' ? v.endsWith(val) : v.includes(val);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (pos !== s.length) throw new Error(`the render document does not handle the selector "${s}"`);
|
||||||
|
return (e) => tests.every((t) => t(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the document, and the globals ---------- */
|
||||||
|
|
||||||
|
export class SDocument extends SFragment {
|
||||||
|
readonly documentElement = new SElement('html');
|
||||||
|
readonly head = new SElement('head');
|
||||||
|
readonly body = new SElement('body');
|
||||||
|
constructor() { super(); this.nodeType = 9; this.appendChild(this.documentElement); this.documentElement.append(this.head, this.body); }
|
||||||
|
createElement(tag: string): SElement { return new SElement(tag); }
|
||||||
|
createElementNS(ns: string | null, tag: string): SElement { return new SElement(tag, ns); }
|
||||||
|
createTextNode(s: string): SText { return new SText(String(s)); }
|
||||||
|
createComment(s: string): SComment { return new SComment(String(s)); }
|
||||||
|
createDocumentFragment(): SFragment { return new SFragment(); }
|
||||||
|
getElementById(id: string): SElement | null { return this.querySelector('#' + id); }
|
||||||
|
execCommand(): boolean { return false; }
|
||||||
|
get activeElement(): null { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
const queued: Array<() => void> = [];
|
||||||
|
|
||||||
|
/** Run what the views put off to the next frame or a timer (a view that measures before drawing), until none is left. */
|
||||||
|
export function flushQueued(rounds = 8): void {
|
||||||
|
for (let i = 0; i < rounds && queued.length; i++) for (const fn of queued.splice(0)) { try { fn(); } catch { /* a view's late refinement, not its output */ } }
|
||||||
|
}
|
||||||
|
|
||||||
|
let installed: SDocument | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give this process a `document` (and the few other browser globals the views reach for). Does nothing where a
|
||||||
|
* real document exists, so the same render code runs in the app's gallery and under `quarto render`.
|
||||||
|
*/
|
||||||
|
export function installDocument(): boolean {
|
||||||
|
const g = globalThis as any;
|
||||||
|
if (g.document && !installed) return false;
|
||||||
|
if (installed) return true;
|
||||||
|
installed = new SDocument();
|
||||||
|
const store = new Map<string, string>();
|
||||||
|
g.document = installed;
|
||||||
|
g.Node = SNode; g.Element = SElement; g.HTMLElement = SElement; g.SVGElement = SElement; g.Text = SText; g.DocumentFragment = SFragment;
|
||||||
|
g.localStorage ??= { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, String(v)), removeItem: (k: string) => void store.delete(k), clear: () => store.clear(), key: (i: number) => [...store.keys()][i] ?? null, get length() { return store.size; } };
|
||||||
|
g.requestAnimationFrame ??= (fn: (t: number) => void) => { queued.push(() => fn(0)); return queued.length; };
|
||||||
|
g.cancelAnimationFrame ??= () => { /* queued work runs at most once */ };
|
||||||
|
g.ResizeObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } };
|
||||||
|
g.IntersectionObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } };
|
||||||
|
g.MutationObserver ??= class { observe() { /* nothing changes */ } disconnect() { /* nothing changes */ } takeRecords() { return []; } };
|
||||||
|
g.getComputedStyle ??= () => ({ getPropertyValue: () => '' });
|
||||||
|
g.matchMedia ??= () => ({ matches: false, addEventListener() { /* static */ }, removeEventListener() { /* static */ }, addListener() { /* static */ }, removeListener() { /* static */ } });
|
||||||
|
// a window whose timers are queued with the animation frames: the render reads the views once, after flushQueued()
|
||||||
|
g.window ??= g;
|
||||||
|
if (g.window === g) {
|
||||||
|
g.innerWidth ??= 1200; g.innerHeight ??= 800; g.devicePixelRatio ??= 1;
|
||||||
|
g.addEventListener ??= () => { /* nothing fires */ }; g.removeEventListener ??= () => { /* nothing fires */ };
|
||||||
|
g.location ??= { href: 'https://pplus.invalid/', hash: '', search: '', origin: 'https://pplus.invalid' };
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The HTML of what a view built: an element's children, as markup. */
|
||||||
|
export function htmlOf(node: unknown): string {
|
||||||
|
if (node instanceof SNode) return node.serialize();
|
||||||
|
return (node as any).innerHTML as string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
/**
|
||||||
|
* The machine, rendered with the page: the Hardware area's board views (registers, memory, the stack, the caches,
|
||||||
|
* virtual memory, the pipeline, the out-of-order core, the encoding...) over an x86-64 run, for the Quarto
|
||||||
|
* extension's `pplus-hw` shortcodes.
|
||||||
|
*
|
||||||
|
* The views are the course's own (src/engines/asm86/views.js and hwviews.js), mounted exactly as the board mounts
|
||||||
|
* them (`mountView`, `courseViews` in core/hardware.ts) and drawn at every step of the run. A page cannot run them,
|
||||||
|
* so each card keeps what it drew at each step: the distinct drawings once, and which one each step shows. pplus.js
|
||||||
|
* steps through them; render.mjs compresses them (they repeat from step to step, so deflate makes a run of a
|
||||||
|
* hundred steps a few kilobytes per card). The step the page opens on is in the markup itself, so the page reads,
|
||||||
|
* prints and works without script.
|
||||||
|
*/
|
||||||
|
import { el, add } from '../ui/dom.js';
|
||||||
|
import type { Session } from '../core/session.js';
|
||||||
|
import { BOARD_VIEWS, BOARD_PRESETS, boardFrame, boardView, courseViews, parseMachine, machineLabel, machineName, type BoardViewId } from '../core/hardware.js';
|
||||||
|
import { mountView } from '../ui/hw/board.js';
|
||||||
|
import { machineView } from '../ui/views/panels.js';
|
||||||
|
import { highlighted, freeze } from './render.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The machine's views as the shortcodes name them: `pplus-hw-<name>`. The name is the board's id, except where a
|
||||||
|
* shortcode of that name already means something else (the ALU is `bits` on the board, the whole core `machine`).
|
||||||
|
*/
|
||||||
|
export const HW_NAMES: Record<string, BoardViewId> = {
|
||||||
|
code: 'code', explain: 'explain', registers: 'registers', flags: 'flags', address: 'address', memory: 'memory', stack: 'stack',
|
||||||
|
dataflow: 'dataflow', alu: 'bits', branches: 'branches', vectors: 'vectors',
|
||||||
|
lines: 'lines', cache: 'cache', hierarchy: 'hierarchy', paging: 'paging',
|
||||||
|
pipeline: 'pipeline', uops: 'uops', timeline: 'timeline', bottleneck: 'bottleneck', counters: 'counters',
|
||||||
|
chip: 'machine', core: 'core', encoding: 'encoding',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The board's arrangements a page can ask for (`preset=`), without the Mojo one (the machine cards only). */
|
||||||
|
export const HW_PRESETS = BOARD_PRESETS.filter((p) => p.id !== 'mojo').map((p) => ({ id: p.id, label: p.label, blurb: p.blurb, views: p.items.map((x) => x.id).filter((id) => boardView(id)!.needs === 'asm') }));
|
||||||
|
|
||||||
|
/** A view by its shortcode name or its board id. */
|
||||||
|
export function hwView(name: string): BoardViewId | null {
|
||||||
|
const n = name.trim().toLowerCase();
|
||||||
|
if (HW_NAMES[n]) return HW_NAMES[n];
|
||||||
|
const v = boardView(n);
|
||||||
|
return v && v.needs === 'asm' ? v.id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What pplus.js reads: for each card, its distinct drawings, and which one each step shows. */
|
||||||
|
export interface HwData {
|
||||||
|
count: number;
|
||||||
|
t: number;
|
||||||
|
/** Per step: the line of the instruction about to run (`n`) and of the one that just ran (`l`), and that instruction's text. */
|
||||||
|
steps: Array<{ n: number | null; l: number | null; x: string }>;
|
||||||
|
cards: Array<{ id: string; frames: string[]; at: number[] }>;
|
||||||
|
/** Steps drawn: every one, or every `stride`-th when the run is longer than `max`. */
|
||||||
|
shown: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HwRequest { views?: string[]; preset?: string; t?: number; max?: number; listing?: boolean; stepper?: boolean }
|
||||||
|
|
||||||
|
export function machineBoard(session: Session, req: HwRequest): { node: HTMLElement; markdown: string; warnings: string[]; data: HwData | null } {
|
||||||
|
const warnings: string[] = [];
|
||||||
|
session.state.lang = 'asm';
|
||||||
|
// the views asked for, in order; unknown ones are reported, and paging turns virtual memory on
|
||||||
|
let ids: BoardViewId[] = [];
|
||||||
|
if (req.views?.length) {
|
||||||
|
for (const v of req.views) { const id = hwView(v); if (id) { if (!ids.includes(id)) ids.push(id); } else warnings.push(`hw: no machine view "${v}"; the views are ${Object.keys(HW_NAMES).join(', ')}`); }
|
||||||
|
}
|
||||||
|
if (!ids.length) ids = (HW_PRESETS.find((p) => p.id === req.preset) ?? HW_PRESETS[0]).views;
|
||||||
|
if (req.preset && !req.views?.length && !HW_PRESETS.some((p) => p.id === req.preset)) warnings.push(`hw: no preset "${req.preset}"; the presets are ${HW_PRESETS.map((p) => p.id).join(', ')}`);
|
||||||
|
if (ids.includes('paging') && !parseMachine(session.state.machine).paging) session.state.machine = machineName({ preset: parseMachine(session.state.machine).preset, paging: true });
|
||||||
|
|
||||||
|
const tr = session.trace();
|
||||||
|
const trace = tr && tr.lang === 'asm' ? (tr.raw as any)?.trace : null;
|
||||||
|
if (!session.source('asm').trim()) {
|
||||||
|
const why = 'The machine views run an x86-64 file (asm=, with its setup=). For a Mojo program, `pixi run quarto-export` writes the compiler\'s x86-64 and setup beside the page.';
|
||||||
|
return { node: el('div', {}, el('p', { class: 'pplus-err' }, why)), markdown: `*${why}*`, warnings: [...warnings, 'hw: no x86-64 file (asm=)'], data: null };
|
||||||
|
}
|
||||||
|
if (!trace) {
|
||||||
|
const why = session.runError ?? session.diagnostics('asm').find((d) => d.severity === 'error')?.message ?? 'The x86-64 file does not assemble.';
|
||||||
|
return { node: el('div', {}, el('p', { class: 'pplus-err' }, `It does not run: ${why}`)), markdown: `*It does not run: ${why}*`, warnings: [...warnings, `hw: ${why}`], data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const machine = parseMachine(session.state.machine);
|
||||||
|
const count: number = trace.count;
|
||||||
|
const max = Math.max(10, Math.min(req.max ?? 400, 5000));
|
||||||
|
const stride = Math.max(1, Math.ceil(count / max));
|
||||||
|
const shown: number[] = [];
|
||||||
|
for (let t = 0; t <= count; t += stride) shown.push(t);
|
||||||
|
if (shown[shown.length - 1] !== count) shown.push(count);
|
||||||
|
const t0 = Math.max(0, Math.min(req.t ?? 0, count));
|
||||||
|
// the step the page opens on is one of those drawn
|
||||||
|
const open = shown.reduce((best, t) => (Math.abs(t - t0) < Math.abs(best - t0) ? t : best), shown[0]);
|
||||||
|
const stepper = req.stepper !== false && count > 0;
|
||||||
|
|
||||||
|
const lineOf = (instr: any) => (instr && typeof instr.lineNo === 'number' ? instr.lineNo + 1 : null);
|
||||||
|
const steps = shown.map((t) => { const f = boardFrame(trace, t); return { n: lineOf(f.next), l: lineOf(f.last?.instr), x: String(f.last?.instr?.text ?? '').trim().replace(/\s+/g, ' ') }; });
|
||||||
|
|
||||||
|
const cards: HwData['cards'] = [];
|
||||||
|
const grid = el('div', { class: 'pplus-hw-grid' });
|
||||||
|
// the listing stands beside the cards (sticky while they scroll), unless the machine-code card is one of them
|
||||||
|
let listing: HTMLElement | null = null;
|
||||||
|
if (req.listing !== false && !ids.includes('code')) {
|
||||||
|
const code = highlighted(session.source('asm'), 'asm', { numbers: true });
|
||||||
|
const at = steps[shown.indexOf(open)];
|
||||||
|
for (const ln of [...code.querySelectorAll('.pplus-ln')]) {
|
||||||
|
const n = Number(ln.getAttribute('data-line'));
|
||||||
|
if (n === at.n) ln.classList.add('is-next');
|
||||||
|
if (n === at.l) ln.classList.add('is-last');
|
||||||
|
}
|
||||||
|
listing = el('section', { class: 'pplus-hw-card pplus-hw-listing', 'data-hw': 'listing' }, el('div', { class: 'pplus-hw-title' }, 'x86-64'), code);
|
||||||
|
}
|
||||||
|
for (const id of ids) {
|
||||||
|
const def = boardView(id)!;
|
||||||
|
const card = el('section', { class: `pplus-hw-card pplus-hw-${id}${def.wide ? ' is-wide' : ''}`, 'data-hw': id, title: def.blurb });
|
||||||
|
add(grid, card);
|
||||||
|
if (id === 'counters') {
|
||||||
|
// the run's totals: the same at every step
|
||||||
|
const box = el('div', { class: 'view view-asm' });
|
||||||
|
machineView(session, box);
|
||||||
|
freeze(box);
|
||||||
|
add(card, el('div', { class: 'pplus-hw-title' }, def.label), box);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const spec = id === 'lines' ? { name: 'lines', options: {} } : courseViews([{ id }], trace, machine)[0];
|
||||||
|
if (!spec) continue;
|
||||||
|
const view = mountView(spec.name, trace, spec.options);
|
||||||
|
const frames: string[] = [];
|
||||||
|
const index = new Map<string, number>();
|
||||||
|
const at: number[] = [];
|
||||||
|
let first = '';
|
||||||
|
for (const t of stepper ? shown : [open]) {
|
||||||
|
view.update(boardFrame(trace, t));
|
||||||
|
const html = inert(view.node.outerHTML);
|
||||||
|
if (!index.has(html)) { index.set(html, frames.length); frames.push(html); }
|
||||||
|
at.push(index.get(html)!);
|
||||||
|
if (t === open) first = html;
|
||||||
|
}
|
||||||
|
if (view.node.classList.contains('has-failed')) warnings.push(`hw: the ${def.label} view failed on this run`);
|
||||||
|
const holder = el('div', { class: 'a86 board-a86', 'data-hw-frame': '' });
|
||||||
|
// the drawing for the step the page opens on: the course view's own markup. In a browser (the gallery) it goes
|
||||||
|
// in directly; the small document has no parser, so there it is spliced into the serialized page (spliceFrames)
|
||||||
|
if (typeof DOMParser !== 'undefined') holder.innerHTML = first;
|
||||||
|
else (holder as any).__html = first;
|
||||||
|
add(card, holder);
|
||||||
|
cards.push({ id, frames, at });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: HwData = { count, t: open, steps, cards, shown };
|
||||||
|
const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label);
|
||||||
|
const node = el('div', { 'data-count': String(count), 'data-t': String(open) },
|
||||||
|
stepper ? el('div', { class: 'pplus-steps-bar' },
|
||||||
|
el('span', { class: 'pplus-chip pplus-chip-asm' }, 'x86-64'),
|
||||||
|
btn('first', '⏮', 'First step'), btn('back', '◀', 'Back one step'), btn('next', '▶', 'One step'), btn('last', '⏭', 'Last step'), btn('play', 'Play', 'Play the run'),
|
||||||
|
el('input', { type: 'range', class: 'pplus-steps-slider', min: '0', max: String(shown.length - 1), value: String(shown.indexOf(open)), 'aria-label': 'step' }),
|
||||||
|
el('span', { class: 'pplus-steps-count' }, `${open} / ${count}`)) : null,
|
||||||
|
el('div', { class: 'pplus-hw-now' }, nowText(steps[shown.indexOf(open)], open), el('span', { class: 'pplus-muted pplus-hw-machine' }, ` · ${machineLabel(session.state.machine)} machine`)),
|
||||||
|
el('div', { class: `pplus-hw-body${listing ? ' has-listing' : ''}` }, listing, grid),
|
||||||
|
stride > 1 ? el('p', { class: 'pplus-note' }, `The run takes ${count} steps; every ${stride}${stride === 2 ? 'nd' : stride === 3 ? 'rd' : 'th'} is drawn (max="${max}").`) : null,
|
||||||
|
stepper ? el('script', { type: 'application/json', class: 'pplus-hw-data' }, JSON.stringify(data).replace(/</g, '\\u003c')) : null);
|
||||||
|
|
||||||
|
const markdown = machineMarkdown(ids, trace, open);
|
||||||
|
return { node, markdown, warnings, data };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A course view's own controls (the core's "cycle ▸", a view's toggles) act on the live widget; in a drawing they
|
||||||
|
* would do nothing, so the drawing leaves them out. The view's markup is its own output: plain buttons, inputs and
|
||||||
|
* menus, never nested.
|
||||||
|
*/
|
||||||
|
export function inert(html: string): string {
|
||||||
|
return html.replace(/<button\b[^>]*>[\s\S]*?<\/button>/g, '').replace(/<select\b[^>]*>[\s\S]*?<\/select>/g, '').replace(/<input\b[^>]*>/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const nowText = (s: { x: string } | undefined, t: number): string => (t === 0 ? 'Before the first instruction.' : `Step ${t}: ${s?.x ?? ''}`);
|
||||||
|
|
||||||
|
/** Put each card's drawing for the opening step into the serialized markup (see machineBoard). */
|
||||||
|
export function spliceFrames(html: string, node: HTMLElement): string {
|
||||||
|
const holders = [...node.querySelectorAll('[data-hw-frame]')];
|
||||||
|
let i = 0;
|
||||||
|
return html.replace(/<div class="a86 board-a86" data-hw-frame=""><\/div>/g, (m) => {
|
||||||
|
const h = holders[i++] as any;
|
||||||
|
return h?.__html ? m.replace('></div>', `>${h.__html}</div>`) : m;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** In a format other than HTML: the registers the run wrote, at the step shown, and what each view is. */
|
||||||
|
function machineMarkdown(ids: BoardViewId[], trace: any, t: number): string {
|
||||||
|
const f = boardFrame(trace, t);
|
||||||
|
const regs = new Set<string>();
|
||||||
|
for (const s of trace.steps.slice(0, t)) for (const r of s.diff?.regs ?? []) regs.add(r.name);
|
||||||
|
const hex = (v: unknown) => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } };
|
||||||
|
const rows = [...regs].map((r) => `| ${r} | ${hex(f.state.regs[r])} |`);
|
||||||
|
return [`*The machine at step ${t} of ${trace.count}${f.last ? `, after \`${String(f.last.instr.text).trim().replace(/\s+/g, ' ')}\`` : ''}.*`, '',
|
||||||
|
rows.length ? ['| register | value |', '|---|---|', ...rows].join('\n') : '',
|
||||||
|
'', `*Drawn in the HTML version of this page: ${ids.map((id) => boardView(id)!.label).join(', ')}.*`].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const HW_VIEW_LIST = BOARD_VIEWS.filter((v) => v.needs === 'asm');
|
||||||
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user