feat: open-source release with Nox language and console
Public open-source release under MIT. Major addition: the Nox typed DSL for telescope and dome control, with parser, type checker, async runtime, CLI, HTTP API, and an in-browser IDE integrated into the Caelum web app. Nox language (nox/) - Parser, AST builder, type checker (Chevrotain) — units, coordinate frames, resources, capabilities, flow-sensitive narrowing - Async tree-walking interpreter with rollback semantics, edge-triggered policies, mock and real driver backends - CLI: nox check / run / ops / parse - 11-chapter "Nox for Dummies" tutorial + 8-doc API reference - 10 example programs covering imaging, focus runs, calibration, unattended sessions, weather policies, etc. - Test suites: parser (10/10 negative cases), runtime (9 mock examples plus rollback, policy edge, CLI, v0.4 features) Web client - /nox IDE: CodeMirror editor with live type-check linting, autocomplete, multi-tab workspace, streamed op log - /nox/docs: in-app docs viewer with sidebar nav and prev/next pager - /nox/examples: public example gallery with one-click "open in console" - Landing page Nox showcase with syntax-highlighted code preview Server - POST /api/nox/check, /run, /run-stream (SSE), GET /docs/*, /examples - Real driver factory binding to telescope-control and external-drivers - Self-contained docs file handler (no express.static quirks) Open-source infrastructure - LICENSE (MIT) - README rewritten for OSS audience - CONTRIBUTING, CODE_OF_CONDUCT, SECURITY, CHANGELOG - GitLab CI pipeline (parser/runtime tests, client build, deploy package) - Issue and MR templates - Hardened .gitignore (envs, SQLite WAL/journal, deploy zip, IDE junk) - Package metadata: license fields, repository URLs Deploy - Package script now stages nox/ workspace so file: deps resolve on the host. Fixes 503 on caelum.network after the Nox routes landed. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
2dfb2f66c7
commit
3c130b5d14
+48
-3
@@ -1,7 +1,52 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
server/data/
|
||||
.deploy-staging/
|
||||
caelum-deploy.zip
|
||||
|
||||
# Local environment + secrets
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
/env
|
||||
server/.env
|
||||
.DS_Store
|
||||
server/.env.local
|
||||
client/.env.local
|
||||
|
||||
# Local database dumps. Too large for the public repo (spacedb.sql is 1.2 GB)
|
||||
# and app.sql contains dev user records. Regenerate via the migrate script.
|
||||
/sql/
|
||||
|
||||
# Local data
|
||||
server/data/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.sqlite-journal
|
||||
*.sqlite3-journal
|
||||
*.sqlite-wal
|
||||
*.sqlite3-wal
|
||||
*.sqlite-shm
|
||||
*.sqlite3-shm
|
||||
|
||||
# Vite / build cache
|
||||
.vite/
|
||||
*.tsbuildinfo
|
||||
|
||||
# Test coverage
|
||||
coverage/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
db.sqlite3
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Editor / OS junk
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# GitLab CI for Caelum.
|
||||
#
|
||||
# - `nox` parser + runtime test suites
|
||||
# - `client` Vue/Vite production build (catches type/import errors)
|
||||
# - `package` deploy bundle smoke test on tagged pushes
|
||||
|
||||
default:
|
||||
image: node:20-alpine
|
||||
cache:
|
||||
key:
|
||||
files:
|
||||
- package-lock.json
|
||||
- server/package-lock.json
|
||||
- client/package-lock.json
|
||||
- nox/parser/package-lock.json
|
||||
- nox/runtime/package-lock.json
|
||||
paths:
|
||||
- node_modules/
|
||||
- server/node_modules/
|
||||
- client/node_modules/
|
||||
- nox/parser/node_modules/
|
||||
- nox/runtime/node_modules/
|
||||
|
||||
stages:
|
||||
- test
|
||||
- build
|
||||
- package
|
||||
|
||||
nox-parser:
|
||||
stage: test
|
||||
script:
|
||||
- cd nox/parser
|
||||
- npm ci --no-audit --no-fund
|
||||
- npm test
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
- if: $CI_COMMIT_TAG
|
||||
|
||||
nox-runtime:
|
||||
stage: test
|
||||
script:
|
||||
- cd nox/runtime
|
||||
- npm ci --no-audit --no-fund
|
||||
- npm test
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
- if: $CI_COMMIT_TAG
|
||||
|
||||
client-build:
|
||||
stage: build
|
||||
script:
|
||||
- cd client
|
||||
- npm ci --no-audit --no-fund
|
||||
- npx vite build
|
||||
artifacts:
|
||||
paths:
|
||||
- client/dist/
|
||||
expire_in: 1 week
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
- if: $CI_COMMIT_TAG
|
||||
|
||||
deploy-bundle:
|
||||
stage: package
|
||||
needs:
|
||||
- client-build
|
||||
script:
|
||||
- apk add --no-cache zip
|
||||
- npm ci --no-audit --no-fund
|
||||
- npm run package
|
||||
artifacts:
|
||||
paths:
|
||||
- caelum-deploy.zip
|
||||
expire_in: 30 days
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
when: manual
|
||||
@@ -0,0 +1,37 @@
|
||||
<!--
|
||||
Use this template for bug reports. Don't paste secrets, JWTs, or production
|
||||
data. Redact emails and IPs unless they're relevant to the issue.
|
||||
-->
|
||||
|
||||
### What happened
|
||||
|
||||
<!-- One paragraph describing the bug. -->
|
||||
|
||||
### Steps to reproduce
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
### What I expected
|
||||
|
||||
<!-- The intended behaviour. -->
|
||||
|
||||
### What I got
|
||||
|
||||
<!-- The actual behaviour. Include error messages, screenshots, or short log
|
||||
snippets. -->
|
||||
|
||||
### Environment
|
||||
|
||||
- Caelum version / commit SHA:
|
||||
- Node version (`node -v`):
|
||||
- Browser (if relevant):
|
||||
- OS:
|
||||
- MySQL version (if a DB-related issue):
|
||||
|
||||
### Additional context
|
||||
|
||||
<!-- Anything else. Linked issues, recent merges, network setup, etc. -->
|
||||
|
||||
/label ~bug
|
||||
@@ -0,0 +1,28 @@
|
||||
<!--
|
||||
Use this template to propose a new feature or improvement.
|
||||
For bugs, use the Bug template instead.
|
||||
-->
|
||||
|
||||
### The problem
|
||||
|
||||
<!-- What user need or pain point does this address? Concrete examples beat
|
||||
abstractions. -->
|
||||
|
||||
### The proposed change
|
||||
|
||||
<!-- What you want to build. Sketch the API, UI, or behaviour at a high level.
|
||||
A short example reads better than paragraphs of description. -->
|
||||
|
||||
### Why this design
|
||||
|
||||
<!-- Alternatives you considered and why this one wins. -->
|
||||
|
||||
### Out of scope
|
||||
|
||||
<!-- Things you specifically don't intend this change to do. -->
|
||||
|
||||
### Open questions
|
||||
|
||||
<!-- Anything you want feedback on before starting work. -->
|
||||
|
||||
/label ~feature
|
||||
@@ -0,0 +1,46 @@
|
||||
<!--
|
||||
Thanks for the contribution. Fill in the relevant sections; delete the rest.
|
||||
-->
|
||||
|
||||
## Summary
|
||||
|
||||
<!-- One paragraph: what does this MR change, and why? -->
|
||||
|
||||
## Related issues
|
||||
|
||||
<!-- Closes #123, refs #456 -->
|
||||
|
||||
## Type of change
|
||||
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
- [ ] Refactor (no behavioural change)
|
||||
- [ ] Documentation
|
||||
- [ ] Build / CI / tooling
|
||||
|
||||
## Testing
|
||||
|
||||
<!-- What did you run to verify this? Which suites pass? Any manual steps? -->
|
||||
|
||||
```sh
|
||||
cd nox/parser && npm test # if Nox parser/checker changed
|
||||
cd nox/runtime && npm test # if Nox runtime changed
|
||||
cd client && npx vite build # if SPA changed
|
||||
```
|
||||
|
||||
## Screenshots
|
||||
|
||||
<!-- For UI changes, paste before / after screenshots. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Tests added or updated where applicable
|
||||
- [ ] Docs updated where applicable
|
||||
- [ ] No secrets, tokens, or production data in the diff
|
||||
- [ ] Commits follow the [conventional commits](https://www.conventionalcommits.org/) style
|
||||
- [ ] The MR is rebased on latest `main`
|
||||
|
||||
## Notes for the reviewer
|
||||
|
||||
<!-- Anything that would help a reviewer understand the change. Risky areas,
|
||||
follow-up work, decisions you'd like a second opinion on. -->
|
||||
@@ -0,0 +1,20 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to Caelum are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning follows [SemVer](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Public open-source release. MIT license. Contributing, code of conduct, and security policy.
|
||||
- Nox language v0.4: typed DSL for telescope and dome control. Parser, type checker, interpreter, CLI, HTTP API, in-browser IDE, public docs and examples pages.
|
||||
- Pluggable Nox catalog files via `nox/runtime/catalogs/<name>.json`.
|
||||
|
||||
### Changed
|
||||
- Deploy bundle (`npm run package`) now ships the Nox workspace alongside the server so `file:` deps resolve on the host.
|
||||
|
||||
### Fixed
|
||||
- Nox docs route layout: dashboards sidebar no longer fights the docs sidebar; back arrow uses browser history.
|
||||
|
||||
## [0.1.0] - 2026-05-13
|
||||
|
||||
Initial private release. Web client, API server, MySQL migration from SQLite, telescope and dome integration. Not publicly released.
|
||||
@@ -0,0 +1,7 @@
|
||||
## Approach
|
||||
- Read existing files before writing. Don't re-read unless changed.
|
||||
- Thorough in reasoning, concise in output.
|
||||
- Skip files over 100KB unless required.
|
||||
- No sycophantic openers or closing fluff.
|
||||
- No emojis or em-dashes.
|
||||
- Do not guess APIs, versions, flags, commit SHAs, or package names. Verify by reading code or docs before asserting.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Code of Conduct
|
||||
|
||||
Caelum is built by and for observers, researchers, hobbyists, and developers. The project welcomes everyone. To keep that true, we expect contributors to follow a small set of behaviours.
|
||||
|
||||
## Be respectful
|
||||
|
||||
Disagree about technical decisions all you want. Don't attack the person making them. Focus on the work.
|
||||
|
||||
## Be welcoming
|
||||
|
||||
New contributors are the lifeblood of any project. Answer questions patiently. Point newcomers at the docs and the code rather than making them feel they should have known.
|
||||
|
||||
## Be inclusive
|
||||
|
||||
Harassment, discrimination, personal attacks, and unwelcome sexual attention are not tolerated. This applies in issues, merge requests, commit messages, chat, and any other project space.
|
||||
|
||||
## Be honest
|
||||
|
||||
Don't claim authorship of work you didn't do. Cite sources. Disclose conflicts of interest. If you make a mistake, own it.
|
||||
|
||||
## Scope
|
||||
|
||||
This code applies to anyone participating in Caelum project spaces: the GitLab repository, issues, merge requests, comments, the project website, and any related forums.
|
||||
|
||||
## Reporting
|
||||
|
||||
If you experience or witness behaviour that violates this code, contact the project maintainers privately at the email listed on the project's GitLab page. Reports are confidential. Reasonable steps will be taken to address the issue.
|
||||
|
||||
Maintainers reserve the right to remove comments, close issues, ban accounts, and otherwise act to enforce this code.
|
||||
|
||||
## Attribution
|
||||
|
||||
This code of conduct is based on the [Contributor Covenant](https://www.contributor-covenant.org/) version 2.1, adapted for Caelum's style. The original is licensed CC BY 4.0.
|
||||
@@ -0,0 +1,98 @@
|
||||
# Contributing to Caelum
|
||||
|
||||
Thanks for your interest. This document describes how to set up the project locally, the conventions we follow, and the merge-request workflow.
|
||||
|
||||
## Getting set up
|
||||
|
||||
See the quick start in [README.md](README.md). Once `npm run dev` works, you have everything you need to develop.
|
||||
|
||||
## Where things live
|
||||
|
||||
```
|
||||
client/ Vue 3 SPA. Pages in src/views/, components in src/components/.
|
||||
server/ Express API. Routes in src/routes/, services in src/services/.
|
||||
nox/ The Nox DSL. Self-contained — parser, runtime, docs, examples.
|
||||
sql/ Database dumps. Regenerate via `cd server && npm run migrate -- --dump ../sql`.
|
||||
scripts/ Tooling, including the deploy bundler.
|
||||
```
|
||||
|
||||
The Nox sub-project is intentionally decoupled from the rest of the codebase. Changes there should not require touching the server or client.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Fork the project on GitLab.
|
||||
2. Branch off `main`: `git checkout -b your-feature`.
|
||||
3. Make your changes.
|
||||
4. Run the test suites that cover what you touched.
|
||||
5. Open a merge request against `main` from your fork.
|
||||
|
||||
Small, focused changes merge faster than large ones. If a feature is big, propose it in an issue first.
|
||||
|
||||
## Commit style
|
||||
|
||||
We follow [Conventional Commits](https://www.conventionalcommits.org/) loosely. Example types:
|
||||
|
||||
- `feat:` new functionality
|
||||
- `fix:` bug fix
|
||||
- `docs:` documentation only
|
||||
- `refactor:` non-behavioral code change
|
||||
- `test:` test-only change
|
||||
- `chore:` build, deps, CI
|
||||
|
||||
Short subject line under 72 characters. Body paragraphs explain the why, not just the what.
|
||||
|
||||
## Code style
|
||||
|
||||
- **JavaScript / Vue:** stick to the existing style. No formatter is enforced; match the surrounding file. Two-space indent, single quotes, no semicolons in script blocks where they're already absent, semicolons elsewhere.
|
||||
- **Nox:** see [nox/docs/](nox/docs/) for syntax.
|
||||
- **No emojis or em-dashes** in code comments or docs. Plain text reads better in diffs.
|
||||
- **Verify before asserting.** Don't guess flag names, API versions, or commit SHAs. Check the actual code.
|
||||
- **Short sentences in human-facing text.** Long sentences hide assumptions.
|
||||
|
||||
## Tests
|
||||
|
||||
Each sub-project owns its tests.
|
||||
|
||||
```sh
|
||||
cd nox/parser && npm test # 5 scripts incl. parser, AST, type checker, negative cases
|
||||
cd nox/runtime && npm test # interpreter, rollback, policy edges, CLI smoke
|
||||
```
|
||||
|
||||
The client and server don't have automated tests yet. If you're adding meaningful logic, please include tests; if you're updating UI, manual screenshots in the MR are enough.
|
||||
|
||||
Type-check the SPA build by running `cd client && npx vite build`. The build fails on real errors.
|
||||
|
||||
## Working with Nox
|
||||
|
||||
The Nox parser, type checker, and runtime are pure ES modules with no external dependencies beyond Chevrotain. The interpreter is async and driver-agnostic, so you can plug in a mock driver, the bundled real driver, or your own.
|
||||
|
||||
To add a language feature:
|
||||
|
||||
1. Update [grammar.ebnf](nox/spec/grammar.ebnf).
|
||||
2. Update the lexer in [nox/parser/src/lexer.js](nox/parser/src/lexer.js).
|
||||
3. Update the parser rules and AST builder.
|
||||
4. Update the checker for type rules.
|
||||
5. Update the interpreter for runtime behavior.
|
||||
6. Add tests and update [nox/docs/](nox/docs/).
|
||||
|
||||
The IDE highlighter ([client/src/views/nox/language.js](client/src/views/nox/language.js)) and autocomplete table ([complete.js](client/src/views/nox/complete.js)) also need updates for any new keyword or method.
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
Open an issue on GitLab with:
|
||||
|
||||
- What you did
|
||||
- What you expected to happen
|
||||
- What actually happened
|
||||
- Steps to reproduce
|
||||
- Browser / Node version where relevant
|
||||
|
||||
Crash reports go in the body. Don't paste secrets.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). Be civil; assume good faith.
|
||||
|
||||
## License
|
||||
|
||||
By contributing, you agree that your contributions will be licensed under the MIT License. See [LICENSE](LICENSE).
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Paul Hitt and Caelum contributors
|
||||
|
||||
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.
|
||||
@@ -1,93 +1,196 @@
|
||||
# caelum
|
||||
# Caelum
|
||||
|
||||
A shared observatory network. Caelum lets observatories publish telescope time, coordinate live sessions, and share their imaging archive across a federation of operators. It ships with **Nox**, a typed DSL for telescope and dome control that runs both on the local CLI and inside a browser-based IDE.
|
||||
|
||||
- **Site:** [caelum.network](https://caelum.network)
|
||||
- **Source:** [gitlab.com/paulhitt/caelum](https://gitlab.com/paulhitt/caelum)
|
||||
- **License:** MIT — see [LICENSE](LICENSE)
|
||||
|
||||
## Getting started
|
||||
## What's in the box
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
| Area | Tech | What it does |
|
||||
| --- | --- | --- |
|
||||
| Web client | Vue 3 + Vite | Dashboards, scheduling, archive browser, Nox console |
|
||||
| API server | Node 20+, Express, Socket.IO | REST + realtime endpoints, auth, hardware drivers |
|
||||
| Telescope control | Stellarium protocol, Alpaca | Mount + dome integration |
|
||||
| App database | MySQL 8 | Users, sites, telescopes, bookings, proposals, frames |
|
||||
| Catalog database | MySQL 8 (SpaceDB) | 1.5M+ asteroids and comets from NASA/JPL |
|
||||
| **Nox language** | Custom DSL | Typed observation scripts with units, frames, and rollback |
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
## Quick start
|
||||
|
||||
## Add your files
|
||||
Requirements: Node 20+, MySQL 8+, `git`.
|
||||
|
||||
* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files
|
||||
* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
||||
```sh
|
||||
# 1. Clone
|
||||
git clone https://gitlab.com/paulhitt/caelum.git
|
||||
cd caelum
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://gitlab.com/paulhitt/caelum.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
# 2. Install everything (root, server, client)
|
||||
npm run install:all
|
||||
|
||||
# 3. Set up the databases — see "MySQL setup" below
|
||||
# 4. Seed sample data + admin user
|
||||
cd server && npm run seed && cd ..
|
||||
|
||||
# 5. Start in dev (server + client with HMR)
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
The Vue dev server runs on `http://localhost:5173`, the API on `http://localhost:3002`.
|
||||
|
||||
* [Set up project integrations](https://gitlab.com/paulhitt/caelum/-/settings/integrations)
|
||||
Default credentials from the seed: `admin@observatory.local` / `admin123` (admin), `observer@observatory.local` / `observer123` (observer).
|
||||
|
||||
## Collaborate with your team
|
||||
## Production build
|
||||
|
||||
* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
|
||||
* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
|
||||
* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
|
||||
* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
|
||||
* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
||||
```sh
|
||||
npm run build # builds the SPA into client/dist
|
||||
npm start # runs server.js, serves API + SPA on the same port
|
||||
```
|
||||
|
||||
## Test and Deploy
|
||||
For Hostinger / managed Node hosts:
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
```sh
|
||||
npm run package # builds caelum-deploy.zip (~0.5 MB)
|
||||
```
|
||||
|
||||
* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
|
||||
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
|
||||
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
|
||||
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
|
||||
* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
|
||||
Upload the zip, extract, set `.env`, run `npm install && node server.js`.
|
||||
|
||||
***
|
||||
## Nox
|
||||
|
||||
# Editing this README
|
||||
Caelum ships its own programming language for observation scripts. Nox is statically typed, with units (`60s`, `30arcsec`) and coordinate frames (`Coord<ICRS>`) as first-class types, structured concurrency with automatic rollback, and edge-triggered policies for unattended operation.
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
```nox
|
||||
session "spring-galaxies" {
|
||||
requires telescope("Astra-1"), weather(clouds < 20%)
|
||||
|
||||
## Suggestions for a good README
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
safety on cloud { rollback() }
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
parallel {
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
}
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
for target in [M31, M42, M51] {
|
||||
T.slew(target)
|
||||
repeat 5 { T.expose(60s, filter: "L") }
|
||||
}
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
Run it from the shell:
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
```sh
|
||||
node nox/runtime/bin/nox.js check program.nox
|
||||
node nox/runtime/bin/nox.js run program.nox
|
||||
```
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
Or from the browser at `/nox` after signing in.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
Full documentation: `/nox/docs` route, or browse [nox/docs/](nox/docs/) directly.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
## MySQL setup
|
||||
|
||||
The server uses MySQL 8 for both the app DB and the SpaceDB catalog.
|
||||
|
||||
### Create the databases
|
||||
|
||||
```sql
|
||||
CREATE DATABASE caelum_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
CREATE DATABASE caelum_spacedb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
CREATE USER 'caelum'@'%' IDENTIFIED BY 'change-me';
|
||||
GRANT ALL PRIVILEGES ON caelum_app.* TO 'caelum'@'%';
|
||||
GRANT ALL PRIVILEGES ON caelum_spacedb.* TO 'caelum'@'%';
|
||||
FLUSH PRIVILEGES;
|
||||
```
|
||||
|
||||
### Configure connection
|
||||
|
||||
Edit `server/.env`:
|
||||
|
||||
```
|
||||
MYSQL_HOST=localhost
|
||||
MYSQL_PORT=3306
|
||||
MYSQL_USER=caelum
|
||||
MYSQL_PASSWORD=change-me
|
||||
MYSQL_DATABASE=caelum_app
|
||||
|
||||
MYSQL_SPACEDB_HOST=localhost
|
||||
MYSQL_SPACEDB_PORT=3306
|
||||
MYSQL_SPACEDB_USER=caelum
|
||||
MYSQL_SPACEDB_PASSWORD=change-me
|
||||
MYSQL_SPACEDB_DATABASE=caelum_spacedb
|
||||
|
||||
JWT_SECRET=change-me-to-a-random-string
|
||||
```
|
||||
|
||||
Set `MYSQL_SPACEDB_DATABASE=` (empty) to disable SpaceDB routes.
|
||||
|
||||
### Populate the databases
|
||||
|
||||
Start the server cold — it auto-creates the schema via `initDb()` in [server/src/config/database.js](server/src/config/database.js). Then run the seed script to load sample sites, telescopes, proposals, and frames:
|
||||
|
||||
```sh
|
||||
cd server && npm run seed
|
||||
```
|
||||
|
||||
The seed creates two accounts:
|
||||
|
||||
- `admin@observatory.local` / `admin123` (admin)
|
||||
- `observer@observatory.local` / `observer123` (observer)
|
||||
|
||||
SpaceDB routes return 503 until the JPL catalog is imported. The catalog import is not bundled with the repo because the dump is 1.2 GB. To populate it, either import your own JPL/NEAS dumps into `caelum_spacedb`, or run the legacy migrator if you already have a SQLite SpaceDB locally:
|
||||
|
||||
```sh
|
||||
cd server && npm run migrate -- --target spacedb
|
||||
```
|
||||
|
||||
If you already have a Caelum dev environment, you can regenerate fresh SQL dumps for your own use with:
|
||||
|
||||
```sh
|
||||
cd server && npm run migrate -- --dump ../sql
|
||||
```
|
||||
|
||||
These dumps live locally only (gitignored) so they never end up in the public repo.
|
||||
|
||||
## Repo layout
|
||||
|
||||
```
|
||||
caelum/
|
||||
├── client/ Vue 3 + Vite SPA
|
||||
├── server/ Express API + telescope drivers
|
||||
├── nox/ The Nox language (parser, runtime, docs, examples)
|
||||
├── sql/ Database dumps and migration helpers
|
||||
├── scripts/ Deploy bundler and other dev tools
|
||||
├── server.js Hostinger-style top-level entry point
|
||||
└── package.json Root workspace
|
||||
```
|
||||
|
||||
The Nox language is a self-contained sub-project. See [nox/docs/](nox/docs/) for its tutorial and reference.
|
||||
|
||||
## Testing
|
||||
|
||||
```sh
|
||||
cd nox/parser && npm test # parser, type checker (10/10 negative cases)
|
||||
cd nox/runtime && npm test # interpreter, CLI, rollback semantics
|
||||
```
|
||||
|
||||
CI runs both on every push.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
Pull requests welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow, code style, and how the project is structured.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
## Security
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
To report a security vulnerability, please follow the process in [SECURITY.md](SECURITY.md).
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
MIT. See [LICENSE](LICENSE).
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Core Rules
|
||||
|
||||
Short sentences only (8-10 words max).
|
||||
No filler, no preamble, no pleasantries.
|
||||
Tool first. Result first. No explain unless asked.
|
||||
Code stays normal. English gets compressed.
|
||||
|
||||
---
|
||||
|
||||
## Formatting
|
||||
|
||||
Output sounds human. Never AI-generated.
|
||||
Never use em-dashes or replacement hyphens.
|
||||
Avoid parenthetical clauses entirely.
|
||||
Hyphens map to standard grammar only.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
Paste at session start or drop as CLAUDE.md in project root.
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported versions
|
||||
|
||||
Caelum is pre-1.0. Only the `main` branch receives security fixes.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
**Do not** open a public issue for a security vulnerability.
|
||||
|
||||
Email the project maintainers at the address on the GitLab project page. Include:
|
||||
|
||||
- A description of the issue.
|
||||
- Steps to reproduce, or a proof-of-concept if you have one.
|
||||
- The commit SHA or release version where you observed the behaviour.
|
||||
- Whether you'd like to be credited in the fix announcement.
|
||||
|
||||
You will receive an acknowledgement within 72 hours. We aim to release a fix within 30 days for high-severity issues and 90 days for everything else. We will coordinate disclosure with you so the fix lands before the issue is published.
|
||||
|
||||
## Scope
|
||||
|
||||
The following are in scope:
|
||||
|
||||
- Authentication and authorisation in the API server.
|
||||
- Server-side request validation, SQL injection, command injection, path traversal.
|
||||
- Cross-site scripting in the SPA.
|
||||
- Improper secret handling in code or in the deploy bundle.
|
||||
- Vulnerabilities in the Nox runtime that could break out of the interpreter's sandbox.
|
||||
|
||||
The following are typically out of scope:
|
||||
|
||||
- Issues that require physical access to a user's machine.
|
||||
- Issues in a third-party dependency without a clear path to exploit Caelum.
|
||||
- Denial-of-service via volumetric attacks against your own deployment.
|
||||
- Social engineering of project maintainers.
|
||||
|
||||
## Hardening notes for self-hosters
|
||||
|
||||
- Set `JWT_SECRET` to a long random string. The seed value in the deploy template is intentionally invalid.
|
||||
- Use TLS in front of the Node process. The server binds plain HTTP.
|
||||
- Restrict the MySQL user's grants to only the two databases the application uses.
|
||||
- Keep your Node, npm, and OS packages up to date.
|
||||
- The Nox runtime in `real` mode connects to telescope and dome hardware. Treat the `/api/nox/run` endpoint as authenticated and rate-limited at your reverse proxy.
|
||||
|
||||
## Credits
|
||||
|
||||
Security researchers who report valid issues are credited in the fix's commit and release notes unless they prefer to remain anonymous.
|
||||
Generated
+138
-2
@@ -1,13 +1,20 @@
|
||||
{
|
||||
"name": "observatory-hub-client",
|
||||
"name": "caelum-client",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "observatory-hub-client",
|
||||
"name": "caelum-client",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.2",
|
||||
"@codemirror/commands": "^6.10.3",
|
||||
"@codemirror/language": "^6.12.3",
|
||||
"@codemirror/lint": "^6.9.6",
|
||||
"@codemirror/search": "^6.7.0",
|
||||
"@codemirror/state": "^6.6.0",
|
||||
"@codemirror/view": "^6.42.1",
|
||||
"pinia": "^2.3.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"vue": "^3.5.13",
|
||||
@@ -64,6 +71,87 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/autocomplete": {
|
||||
"version": "6.20.2",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.2.tgz",
|
||||
"integrity": "sha512-G5FPkgIiLjOgZMjqVjvuKQ1rGPtHogLldJr33eFJdVLtmwY+giGrlv/ewljLz6b9BSQLkjxuwBc6g6omDM+YxQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/commands": {
|
||||
"version": "6.10.3",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.3.tgz",
|
||||
"integrity": "sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.6.0",
|
||||
"@codemirror/view": "^6.27.0",
|
||||
"@lezer/common": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/language": {
|
||||
"version": "6.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz",
|
||||
"integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.23.0",
|
||||
"@lezer/common": "^1.5.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"@lezer/lr": "^1.0.0",
|
||||
"style-mod": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/lint": {
|
||||
"version": "6.9.6",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.6.tgz",
|
||||
"integrity": "sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.42.0",
|
||||
"crelt": "^1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/search": {
|
||||
"version": "6.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.0.tgz",
|
||||
"integrity": "sha512-ZvGm99wc/s2cITtMT15LFdn8aH/aS+V+DqyGq/N5ZlV5vWtH+nILvC2nw0zX7ByNoHHDZ2IxxdW38O0tc5nVHg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.37.0",
|
||||
"crelt": "^1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/state": {
|
||||
"version": "6.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz",
|
||||
"integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@marijn/find-cluster-break": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/view": {
|
||||
"version": "6.42.1",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.42.1.tgz",
|
||||
"integrity": "sha512-ToN3oFc0nsxNUYVF5P0ztLgbC4UPPjPtA9aKYhkOKQaZASpOUo6ISXyQLP66ctVwlDc+j6Jv0uK5IFALkiXztg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/state": "^6.6.0",
|
||||
"crelt": "^1.0.6",
|
||||
"style-mod": "^4.1.0",
|
||||
"w3c-keyname": "^2.2.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
@@ -512,6 +600,36 @@
|
||||
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@lezer/common": {
|
||||
"version": "1.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
|
||||
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@lezer/highlight": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
|
||||
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@lezer/lr": {
|
||||
"version": "1.4.10",
|
||||
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
|
||||
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/common": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@marijn/find-cluster-break": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",
|
||||
"integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@rollup/rollup-android-arm-eabi": {
|
||||
"version": "4.60.3",
|
||||
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.3.tgz",
|
||||
@@ -1034,6 +1152,12 @@
|
||||
"integrity": "sha512-24uqU4OIiX29ryC3MeWid/Xf2fa2EFRUVLb77nRhk+UrTVrh/XiGtFAFmJBAtBRbjwNdsPRP+jj/OL27Eg1NDA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/crelt": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
|
||||
"integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
@@ -1356,6 +1480,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/style-mod": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
|
||||
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.16",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",
|
||||
@@ -1510,6 +1640,12 @@
|
||||
"vue": "^3.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-keyname": {
|
||||
"version": "2.2.8",
|
||||
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.18.3",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
{
|
||||
"name": "caelum-client",
|
||||
"version": "0.1.0",
|
||||
"description": "Caelum web client: Vue 3 SPA with dashboards, scheduling, archive, and the Nox console.",
|
||||
"license": "MIT",
|
||||
"author": "Paul Hitt",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -9,6 +12,13 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.2",
|
||||
"@codemirror/commands": "^6.10.3",
|
||||
"@codemirror/language": "^6.12.3",
|
||||
"@codemirror/lint": "^6.9.6",
|
||||
"@codemirror/search": "^6.7.0",
|
||||
"@codemirror/state": "^6.6.0",
|
||||
"@codemirror/view": "^6.42.1",
|
||||
"pinia": "^2.3.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"vue": "^3.5.13",
|
||||
|
||||
+8
-4
@@ -10,18 +10,21 @@ const auth = useAuthStore();
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
const isAuth = computed(() => route.name === 'login' || route.name === 'register');
|
||||
// `isAuth` is a misnomer: it means "use the full-screen, no-sidebar layout".
|
||||
// Auth screens, the public landing, and the public Nox pages all need this.
|
||||
const FULLSCREEN_ROUTES = new Set(['login', 'register', 'landing', 'nox-docs', 'nox-examples']);
|
||||
const isAuth = computed(() => FULLSCREEN_ROUTES.has(route.name));
|
||||
|
||||
function logout() {
|
||||
auth.logout();
|
||||
router.push('/login');
|
||||
router.push('/');
|
||||
}
|
||||
|
||||
const navGroups = [
|
||||
{
|
||||
label: 'Operations',
|
||||
items: [
|
||||
{ to: '/', name: 'dashboard', icon: '○', label: 'Dashboard', keywords: 'home overview' },
|
||||
{ to: '/dashboard', name: 'dashboard', icon: '○', label: 'Dashboard', keywords: 'home overview' },
|
||||
{ to: '/inbox', name: 'inbox', icon: '\u{1F4E5}', label: 'Inbox', keywords: 'notifications requests invites mentions activity' },
|
||||
{ to: '/messages', names: ['messages','message-thread'], icon: '\u{2709}', label: 'Messages', keywords: 'direct chat dm private' },
|
||||
{ to: '/schedule', name: 'schedule', icon: '\u{1F4C5}', label: 'Schedule', keywords: 'calendar bookings sessions' },
|
||||
@@ -40,6 +43,7 @@ const navGroups = [
|
||||
{ to: '/feed', name: 'feed', icon: '\u{1F4E1}', label: 'Activity Feed', keywords: 'recent network events sessions frames' },
|
||||
{ to: '/discover', names: ['discover', 'observatory'], icon: '\u{1F30D}', label: 'Discover', keywords: 'browse public observatories share network community' },
|
||||
{ to: '/plans', name: 'plans', icon: '\u{1F4CB}', label: 'Plans', keywords: 'observing target lists reusable catalog' },
|
||||
{ to: '/nox', name: 'nox', icon: '\u{1F319}', label: 'Nox Console', keywords: 'language dsl scripting program code' },
|
||||
{ to: '/community', name: 'community', icon: '\u{1F3C6}', label: 'Community', keywords: 'leaderboard top contributors observers stats' },
|
||||
],
|
||||
},
|
||||
@@ -234,7 +238,7 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main-content">
|
||||
<main class="main-content" :class="{ 'main-content-wide': route.name === 'nox' }">
|
||||
<RouterView />
|
||||
</main>
|
||||
|
||||
|
||||
@@ -103,6 +103,13 @@ a:hover { color: var(--accent-hover); }
|
||||
max-width: 1200px;
|
||||
}
|
||||
|
||||
/* Pages that want the full available width (e.g. the Nox IDE, which packs
|
||||
a sidebar / editor / output panel and benefits from every pixel) opt in
|
||||
to this variant. */
|
||||
.main-content.main-content-wide {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
@@ -30,14 +30,14 @@ function bookingsForCell(telescopeId, day) {
|
||||
return props.bookings
|
||||
.filter(b => b.telescope_id === telescopeId)
|
||||
.filter(b => {
|
||||
const bs = new Date(b.start_time.includes('T') ? b.start_time : b.start_time.replace(' ', 'T') + 'Z');
|
||||
const be = new Date(b.end_time.includes('T') ? b.end_time : b.end_time.replace(' ', 'T') + 'Z');
|
||||
const bs = new Date(b.start_time.includes('T') ? b.start_time : b.start_time);
|
||||
const be = new Date(b.end_time.includes('T') ? b.end_time : b.end_time);
|
||||
return be > dayStart && bs < dayEnd;
|
||||
});
|
||||
}
|
||||
|
||||
function fmtTime(ts) {
|
||||
return new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z').toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
return new Date(ts.includes('T') ? ts : ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function pickSlot(t, day) {
|
||||
|
||||
@@ -120,7 +120,7 @@ const shutterBadge = s => ({ open: 'badge-online', closed: 'badge-idle', opening
|
||||
<span v-if="s.driver_host">{{ s.driver_host }}<span v-if="s.driver_port">:{{ s.driver_port }}</span></span>
|
||||
<span v-if="s.endpoint_url" style="font-family:monospace">{{ s.endpoint_url }}</span>
|
||||
· every {{ s.poll_interval_s }}s
|
||||
<span v-if="s.last_polled_at"> · last {{ new Date(s.last_polled_at.replace(' ','T')+'Z').toLocaleTimeString() }}</span>
|
||||
<span v-if="s.last_polled_at"> · last {{ new Date(s.last_polled_at).toLocaleTimeString() }}</span>
|
||||
<span v-if="s.last_error" style="color:var(--danger)"> · error: {{ s.last_error }}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -188,7 +188,7 @@ const shutterBadge = s => ({ open: 'badge-online', closed: 'badge-idle', opening
|
||||
<strong>{{ it.name }}</strong>
|
||||
<span class="badge badge-slewing" style="margin-left:0.4rem">{{ it.kind }}</span>
|
||||
<div class="device-meta">
|
||||
<span v-if="it.last_event_at">last event: {{ new Date(it.last_event_at.replace(' ','T')+'Z').toLocaleString() }}</span>
|
||||
<span v-if="it.last_event_at">last event: {{ new Date(it.last_event_at).toLocaleString() }}</span>
|
||||
<span v-else>no events yet</span>
|
||||
</div>
|
||||
<code class="webhook-url">POST {{ origin }}/api/hardware/webhook/{{ it.webhook_token.slice(0, 12) }}…</code>
|
||||
|
||||
@@ -67,7 +67,7 @@ onUnmounted(() => {
|
||||
});
|
||||
|
||||
const fmt = ts => {
|
||||
const d = new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z');
|
||||
const d = new Date(ts.includes('T') ? ts : ts);
|
||||
const diff = Date.now() - d.getTime();
|
||||
if (diff < 60000) return 'just now';
|
||||
if (diff < 3600000) return Math.floor(diff/60000) + 'm ago';
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
|
||||
import { buildEditor } from '../views/nox/editor.js';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: { type: String, default: '' },
|
||||
});
|
||||
const emit = defineEmits(['update:modelValue', 'run']);
|
||||
|
||||
const host = ref(null);
|
||||
let editor = null;
|
||||
let internalUpdate = false;
|
||||
|
||||
onMounted(() => {
|
||||
editor = buildEditor({
|
||||
parent: host.value,
|
||||
initialDoc: props.modelValue,
|
||||
onChange: text => {
|
||||
internalUpdate = true;
|
||||
emit('update:modelValue', text);
|
||||
internalUpdate = false;
|
||||
},
|
||||
onRunRequest: () => emit('run'),
|
||||
});
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (editor) editor.destroy();
|
||||
editor = null;
|
||||
});
|
||||
|
||||
watch(() => props.modelValue, v => {
|
||||
if (!editor || internalUpdate) return;
|
||||
if (editor.getValue() !== v) editor.setValue(v);
|
||||
});
|
||||
|
||||
defineExpose({ focus: () => editor && editor.focus() });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="host" class="nox-editor"></div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.nox-editor { height: 100%; overflow: hidden; }
|
||||
.nox-editor :deep(.cm-editor) { height: 100%; }
|
||||
.nox-editor :deep(.cm-scroller) { overflow: auto; }
|
||||
</style>
|
||||
@@ -11,7 +11,7 @@ const props = defineProps({
|
||||
|
||||
function parseTs(s) {
|
||||
if (!s) return null;
|
||||
return new Date(s.includes('T') ? s : s.replace(' ', 'T') + 'Z').getTime();
|
||||
return new Date(s.includes('T') ? s : s).getTime();
|
||||
}
|
||||
|
||||
const startMs = computed(() => parseTs(props.startTime));
|
||||
|
||||
+11
-2
@@ -2,9 +2,10 @@ import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { useAuthStore } from './stores/auth.js';
|
||||
|
||||
const routes = [
|
||||
{ path: '/', name: 'landing', component: () => import('./views/Landing.vue'), meta: { guest: true } },
|
||||
{ path: '/login', name: 'login', component: () => import('./views/Login.vue'), meta: { guest: true } },
|
||||
{ path: '/register', name: 'register', component: () => import('./views/Register.vue'), meta: { guest: true } },
|
||||
{ path: '/', name: 'dashboard', component: () => import('./views/Dashboard.vue') },
|
||||
{ path: '/dashboard', name: 'dashboard', component: () => import('./views/Dashboard.vue') },
|
||||
{ path: '/sites', name: 'sites', component: () => import('./views/Sites.vue') },
|
||||
{ path: '/site/:id', name: 'site', component: () => import('./views/Site.vue'), props: true },
|
||||
{ path: '/telescope/:id', name: 'telescope', component: () => import('./views/Telescope.vue'), props: true },
|
||||
@@ -24,13 +25,21 @@ const routes = [
|
||||
{ path: '/settings', name: 'settings', component: () => import('./views/Settings.vue') },
|
||||
{ path: '/plans', name: 'plans', component: () => import('./views/Plans.vue') },
|
||||
{ path: '/session/:bookingId', name: 'session', component: () => import('./views/Session.vue'), props: true },
|
||||
{ path: '/nox', name: 'nox', component: () => import('./views/Nox.vue') },
|
||||
{ path: '/nox/docs', name: 'nox-docs', component: () => import('./views/NoxDocs.vue'), meta: { guest: true } },
|
||||
{ path: '/nox/examples', name: 'nox-examples', component: () => import('./views/NoxExamples.vue'), meta: { guest: true } },
|
||||
];
|
||||
|
||||
const router = createRouter({ history: createWebHistory(), routes });
|
||||
|
||||
// Routes that are publicly viewable regardless of auth state. We never
|
||||
// bounce away from these so signed-in users can browse them too.
|
||||
const ALWAYS_PUBLIC = new Set(['nox-docs', 'nox-examples']);
|
||||
|
||||
router.beforeEach((to) => {
|
||||
const auth = useAuthStore();
|
||||
if (!to.meta.guest && !auth.token) return { name: 'login' };
|
||||
if (ALWAYS_PUBLIC.has(to.name)) return;
|
||||
if (!to.meta.guest && !auth.token) return { name: 'landing' };
|
||||
if (to.meta.guest && auth.token) return { name: 'dashboard' };
|
||||
});
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ onUnmounted(() => { if (poll) clearInterval(poll); });
|
||||
|
||||
const fmt = ts => {
|
||||
if (!ts) return '';
|
||||
const d = new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z');
|
||||
const d = new Date(ts.includes('T') ? ts : ts);
|
||||
const diff = Date.now() - d.getTime();
|
||||
if (diff < 60000) return 'just now';
|
||||
if (diff < 3600000) return Math.floor(diff/60000) + 'm ago';
|
||||
|
||||
@@ -33,12 +33,12 @@ async function cancelMine(r) {
|
||||
|
||||
const fmt = ts => {
|
||||
if (!ts) return '';
|
||||
const d = new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z');
|
||||
const d = new Date(ts.includes('T') ? ts : ts);
|
||||
return d.toLocaleString();
|
||||
};
|
||||
const fmtRel = ts => {
|
||||
if (!ts) return '';
|
||||
const d = new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z');
|
||||
const d = new Date(ts.includes('T') ? ts : ts);
|
||||
const diff = Date.now() - d.getTime();
|
||||
if (diff < 60000) return 'just now';
|
||||
if (diff < 3600000) return Math.floor(diff/60000) + 'm ago';
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useRouter, RouterLink } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth.js';
|
||||
import { highlightNox } from './nox/highlight.js';
|
||||
|
||||
const auth = useAuthStore();
|
||||
const router = useRouter();
|
||||
|
||||
// If already signed in, skip the landing.
|
||||
onMounted(() => {
|
||||
if (auth.token) router.replace('/dashboard');
|
||||
});
|
||||
|
||||
const mode = ref('login'); // 'login' | 'signup'
|
||||
const email = ref('');
|
||||
const username = ref('');
|
||||
const password = ref('');
|
||||
const error = ref('');
|
||||
const loading = ref(false);
|
||||
|
||||
// Static Nox snippet shown on the landing page. The mini-highlighter below
|
||||
// turns this into colored HTML using the same palette as the IDE.
|
||||
const noxSample = `session "spring-galaxies" {
|
||||
requires
|
||||
telescope("Astra-1"),
|
||||
weather(clouds < 20%, wind < 30kph)
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
safety on cloud { rollback() }
|
||||
|
||||
parallel {
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
}
|
||||
|
||||
for target in [M31, M42, M51] {
|
||||
T.slew(target)
|
||||
T.focus(method: "v-curve")
|
||||
repeat 5 {
|
||||
T.expose(60s, filter: "L")
|
||||
T.dither(10arcsec)
|
||||
}
|
||||
}
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
}`;
|
||||
|
||||
const noxPreviewHtml = highlightNox(noxSample);
|
||||
|
||||
function goToNox() {
|
||||
if (auth.token) router.push('/nox');
|
||||
else { mode.value = 'signup'; error.value = ''; }
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
error.value = '';
|
||||
loading.value = true;
|
||||
try {
|
||||
if (mode.value === 'login') {
|
||||
await auth.login(email.value, password.value);
|
||||
} else {
|
||||
await auth.register(email.value, username.value, password.value);
|
||||
}
|
||||
router.push('/dashboard');
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="landing">
|
||||
<div class="landing-hero">
|
||||
<div class="landing-brand">
|
||||
<span class="brand-mark">✦</span>
|
||||
<span class="brand-name">Caelum</span>
|
||||
</div>
|
||||
<h1 class="landing-title">A network for the next generation of observatories.</h1>
|
||||
<p class="landing-tagline">
|
||||
Share telescope time, coordinate sessions, and publish your data — across observatories
|
||||
from backyard rooftops to mountain summits.
|
||||
</p>
|
||||
<ul class="landing-features">
|
||||
<li><span>🌐</span><div><strong>Open network.</strong> Discover and request time on telescopes shared by other observers.</div></li>
|
||||
<li><span>🛰️</span><div><strong>Live sessions.</strong> Run real observations with collaborators in the same room — or across continents.</div></li>
|
||||
<li><span>🗄️</span><div><strong>Science archive.</strong> Upload FITS, auto-parse headers, cross-match SDSS, and share frames publicly or with your network.</div></li>
|
||||
<li><span>☄️</span><div><strong>SpaceDB.</strong> 1.5M+ asteroids and comets from NASA/JPL, with close-approach and impact data.</div></li>
|
||||
<li><span>🌙</span><div><strong>Nox language.</strong> A typed DSL for telescope and dome control. Catches unit mistakes at edit time, unwinds on failure, runs unattended.</div></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="landing-auth">
|
||||
<div class="auth-tabs">
|
||||
<button :class="['tab', { active: mode === 'login' }]" @click="mode = 'login'; error = ''">Sign in</button>
|
||||
<button :class="['tab', { active: mode === 'signup' }]" @click="mode = 'signup'; error = ''">Create account</button>
|
||||
</div>
|
||||
<div class="auth-pane">
|
||||
<h2>{{ mode === 'login' ? 'Welcome back' : 'Join Caelum' }}</h2>
|
||||
<p class="auth-sub">{{ mode === 'login' ? 'Sign in to continue to your observatory network.' : 'Create your account — it takes ten seconds.' }}</p>
|
||||
<div v-if="error" class="error-msg">{{ error }}</div>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="form-group">
|
||||
<label>Email</label>
|
||||
<input v-model="email" type="email" class="form-control" placeholder="you@example.com" required autocomplete="email" />
|
||||
</div>
|
||||
<div v-if="mode === 'signup'" class="form-group">
|
||||
<label>Username</label>
|
||||
<input v-model="username" type="text" class="form-control" placeholder="Choose a username" required autocomplete="username" minlength="2" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Password</label>
|
||||
<input v-model="password" type="password" class="form-control"
|
||||
:placeholder="mode === 'signup' ? 'At least 6 characters' : 'Your password'"
|
||||
required :minlength="mode === 'signup' ? 6 : undefined"
|
||||
:autocomplete="mode === 'signup' ? 'new-password' : 'current-password'" />
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary submit-btn" :disabled="loading">
|
||||
{{ loading
|
||||
? (mode === 'login' ? 'Signing in…' : 'Creating account…')
|
||||
: (mode === 'login' ? 'Sign in' : 'Create account') }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Nox language showcase -->
|
||||
<section class="nox-showcase">
|
||||
<div class="nox-showcase-inner">
|
||||
<div class="nox-text">
|
||||
<div class="nox-eyebrow">
|
||||
<span class="nox-glyph">🌙</span>
|
||||
<span>Nox · a language for telescopes</span>
|
||||
</div>
|
||||
<h2>Script tonight's run. Not next month's outage.</h2>
|
||||
<p>
|
||||
Nox is a typed DSL built into Caelum. You write observation logic the way you think about it:
|
||||
slew, expose, dither, repeat. The type checker watches the units, the frames, and the resources.
|
||||
The runtime unwinds when something fails.
|
||||
</p>
|
||||
<ul class="nox-points">
|
||||
<li><strong>Units are types.</strong> <code>30arcsec</code> is not <code>30s</code>. The checker rejects the swap before you push.</li>
|
||||
<li><strong>Frames are types.</strong> <code>Coord<ICRS></code> and <code>Coord<AltAz></code> do not mix by accident.</li>
|
||||
<li><strong>Failures unwind.</strong> When a parallel task fails, every successful sibling's rollback fires.</li>
|
||||
<li><strong>Observable.</strong> Every operation streams to a trace. Replay, audit, or render live.</li>
|
||||
</ul>
|
||||
<div class="nox-actions">
|
||||
<button class="btn btn-primary" @click="goToNox">{{ auth.token ? 'Open Nox Console' : 'Sign in to try Nox' }}</button>
|
||||
<RouterLink class="nox-docs-link" to="/nox/docs">Read the docs</RouterLink>
|
||||
<RouterLink class="nox-docs-link" to="/nox/examples">Browse examples</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<pre class="nox-code"><code v-html="noxPreviewHtml"></code></pre>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.landing {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-columns: 1.2fr 1fr;
|
||||
gap: 4rem;
|
||||
padding: 4rem 5rem;
|
||||
background:
|
||||
radial-gradient(ellipse at top right, rgba(56, 189, 248, 0.15), transparent 50%),
|
||||
radial-gradient(ellipse at bottom left, rgba(125, 211, 252, 0.08), transparent 60%),
|
||||
var(--bg-primary);
|
||||
}
|
||||
|
||||
.landing-hero { max-width: 580px; }
|
||||
|
||||
.landing-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
.brand-mark {
|
||||
font-size: 1.4rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
.brand-name {
|
||||
font-size: 1.05rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.landing-title {
|
||||
font-size: 2.6rem;
|
||||
line-height: 1.15;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1.25rem;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.landing-tagline {
|
||||
font-size: 1.05rem;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 2.5rem;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.landing-features {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
.landing-features li {
|
||||
display: flex;
|
||||
gap: 0.85rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.landing-features li > span {
|
||||
font-size: 1.15rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.landing-features li > div {
|
||||
font-size: 0.92rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.landing-features strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.landing-auth {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.auth-tabs {
|
||||
display: flex;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius) var(--radius) 0 0;
|
||||
padding: 0.3rem;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.tab {
|
||||
flex: 1;
|
||||
background: transparent;
|
||||
border: none;
|
||||
padding: 0.55rem 0.75rem;
|
||||
border-radius: 6px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.88rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.tab:hover { color: var(--text-primary); }
|
||||
.tab.active {
|
||||
background: var(--bg-input);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.auth-pane {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-top: none;
|
||||
border-radius: 0 0 var(--radius) var(--radius);
|
||||
padding: 1.75rem;
|
||||
}
|
||||
.auth-pane h2 {
|
||||
font-size: 1.35rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.auth-sub {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.86rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.65rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.auth-tabs, .auth-pane { box-sizing: border-box; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.landing {
|
||||
grid-template-columns: 1fr;
|
||||
padding: 2.5rem 1.5rem;
|
||||
gap: 2.5rem;
|
||||
}
|
||||
.landing-title { font-size: 2rem; }
|
||||
.landing-features li > div { font-size: 0.88rem; }
|
||||
.auth-tabs, .auth-pane { max-width: 100%; }
|
||||
}
|
||||
|
||||
/* --- Nox showcase --- */
|
||||
.nox-showcase {
|
||||
grid-column: 1 / -1;
|
||||
margin: 4rem -5rem 0;
|
||||
padding: 4rem 5rem;
|
||||
background:
|
||||
radial-gradient(ellipse at top left, rgba(125, 211, 252, 0.10), transparent 55%),
|
||||
linear-gradient(180deg, transparent, rgba(0,0,0,0.20)),
|
||||
#0b1530;
|
||||
color: #e6ecff;
|
||||
}
|
||||
.nox-showcase-inner {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.2fr;
|
||||
gap: 3rem;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
align-items: center;
|
||||
}
|
||||
.nox-eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.82rem;
|
||||
letter-spacing: 0.06em;
|
||||
color: #9bb6ff;
|
||||
background: rgba(155, 182, 255, 0.10);
|
||||
padding: 0.3rem 0.7rem;
|
||||
border-radius: 999px;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.nox-glyph { font-size: 0.95rem; }
|
||||
.nox-text h2 {
|
||||
font-size: 2rem;
|
||||
line-height: 1.15;
|
||||
font-weight: 600;
|
||||
margin: 0 0 1rem;
|
||||
color: #fff;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
.nox-text p {
|
||||
font-size: 1rem;
|
||||
color: #cfd8ee;
|
||||
margin: 0 0 1.25rem;
|
||||
max-width: 520px;
|
||||
}
|
||||
.nox-points {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0 0 1.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
.nox-points li { color: #cfd8ee; font-size: 0.92rem; }
|
||||
.nox-points strong { color: #fff; }
|
||||
.nox-points code {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, monospace;
|
||||
font-size: 0.85em;
|
||||
background: rgba(255,255,255,0.08);
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
color: #ffd28b;
|
||||
}
|
||||
.nox-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
.nox-actions .btn-primary {
|
||||
padding: 0.65rem 1.1rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.nox-docs-link {
|
||||
color: #9bb6ff;
|
||||
font-size: 0.9rem;
|
||||
text-decoration: none;
|
||||
border-bottom: 1px dashed rgba(155, 182, 255, 0.5);
|
||||
}
|
||||
.nox-docs-link:hover { color: #fff; border-bottom-color: #fff; }
|
||||
|
||||
/* code preview */
|
||||
.nox-code {
|
||||
background: #1a2545;
|
||||
color: #e6ecff;
|
||||
border: 1px solid rgba(155, 182, 255, 0.22);
|
||||
border-radius: 10px;
|
||||
padding: 1.25rem 1.5rem;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Monaco, monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
box-shadow: 0 14px 40px rgba(0,0,0,0.35);
|
||||
max-height: 480px;
|
||||
}
|
||||
.nox-code code { font-family: inherit; }
|
||||
|
||||
/* highlight palette */
|
||||
.nox-code .t-comment { color: #7686a8; font-style: italic; }
|
||||
.nox-code .t-string { color: #a3e3b4; }
|
||||
.nox-code .t-number { color: #ffd28b; }
|
||||
.nox-code .t-unit { color: #ffae5c; font-weight: 600; }
|
||||
.nox-code .t-keyword { color: #8ab4ff; font-weight: 600; }
|
||||
.nox-code .t-type { color: #66d9d6; }
|
||||
.nox-code .t-const { color: #d3a4ff; }
|
||||
.nox-code .t-ident { color: #e6ecff; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.nox-showcase { margin: 2.5rem -1.5rem 0; padding: 2.5rem 1.5rem; }
|
||||
.nox-showcase-inner { grid-template-columns: 1fr; gap: 1.5rem; }
|
||||
.nox-text h2 { font-size: 1.6rem; }
|
||||
.nox-code { font-size: 11.5px; }
|
||||
}
|
||||
</style>
|
||||
@@ -131,11 +131,7 @@ function medal(i) { return medals[i] || ''; }
|
||||
<div v-if="drillBusy" style="padding:1rem;text-align:center;color:var(--text-muted)">Loading…</div>
|
||||
<div v-else-if="drillData?.error" class="error-msg">{{ drillData.error }}</div>
|
||||
<div v-else-if="drillData">
|
||||
<div style="font-size:0.78rem;color:var(--text-muted);margin-bottom:0.4rem">Live count: <strong style="color:var(--accent)">{{ drillData.count }}</strong>{{ drillData.rows.length === 200 ? ' (showing first 200)' : '' }}</div>
|
||||
<details style="margin-bottom:0.6rem">
|
||||
<summary style="font-size:0.72rem;color:var(--text-muted);cursor:pointer">show SQL</summary>
|
||||
<pre style="font-size:0.72rem;background:var(--bg-input);padding:0.5rem;border-radius:var(--radius);overflow-x:auto;white-space:pre-wrap;word-break:break-all">{{ drillData.sql }}</pre>
|
||||
</details>
|
||||
<div style="font-size:0.78rem;color:var(--text-muted);margin-bottom:0.6rem">Live count: <strong style="color:var(--accent)">{{ drillData.count }}</strong>{{ drillData.count > drillData.rows.length ? ` (showing first ${drillData.rows.length})` : '' }}</div>
|
||||
<div class="drill-list">
|
||||
<div v-for="r in drillData.rows" :key="r.id || JSON.stringify(r)" class="drill-row">
|
||||
<div><strong>{{ rowLabel(drillMetric, r).primary }}</strong></div>
|
||||
|
||||
@@ -15,7 +15,7 @@ async function submit() {
|
||||
loading.value = true;
|
||||
try {
|
||||
await auth.login(email.value, password.value);
|
||||
router.push('/');
|
||||
router.push('/dashboard');
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
} finally {
|
||||
|
||||
@@ -65,7 +65,7 @@ watch(() => route.params.username, async (u) => { if (u) await openConversation(
|
||||
|
||||
const fmt = ts => {
|
||||
if (!ts) return '';
|
||||
const d = new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z');
|
||||
const d = new Date(ts.includes('T') ? ts : ts);
|
||||
const today = new Date(); today.setHours(0,0,0,0);
|
||||
if (d.getTime() >= today.getTime()) return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
return d.toLocaleDateString();
|
||||
|
||||
@@ -0,0 +1,831 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { api } from '../services/api.js';
|
||||
import NoxEditor from '../components/NoxEditor.vue';
|
||||
import { renderMarkdown, makeDocLinkHandler, resolveDocPath } from './nox/markdown.js';
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// state
|
||||
// ------------------------------------------------------------------
|
||||
const STORAGE_KEY = 'nox.workspace.v1';
|
||||
|
||||
const tabs = ref([]);
|
||||
const activeTabId = ref(null);
|
||||
|
||||
const examples = ref([]);
|
||||
const savedFiles = ref([]);
|
||||
const sidebarSection = ref('examples');
|
||||
|
||||
const mode = ref('mock');
|
||||
const outputView = ref('ops');
|
||||
const opFilter = ref('');
|
||||
|
||||
const editorRef = ref(null);
|
||||
const opsScrollRef = ref(null);
|
||||
|
||||
const docOpen = ref(false);
|
||||
const docTitle = ref('');
|
||||
const docHtml = ref('');
|
||||
const docPath = ref('');
|
||||
|
||||
// Re-route in-modal `.md` link clicks back through openDoc so the user
|
||||
// can browse internal docs without leaving the IDE. App-link clicks (e.g.
|
||||
// /nox/examples) close the modal and navigate.
|
||||
const handleDocLinkClick = makeDocLinkHandler({
|
||||
getCurrentPath: () => docPath.value,
|
||||
onDocNavigate: (resolved) => openDoc(resolved, prettifyDocTitle(resolved)),
|
||||
onAppNavigate: (href) => { docOpen.value = false; window.location.assign(href); },
|
||||
});
|
||||
|
||||
function prettifyDocTitle(path) {
|
||||
// Best-effort: take the filename minus extension, replace dashes with spaces.
|
||||
const name = path.split('/').pop().replace(/\.md$/, '');
|
||||
return name.replace(/^[0-9]+-/, '').replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
||||
}
|
||||
|
||||
let runAbort = null;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// derived
|
||||
// ------------------------------------------------------------------
|
||||
const activeTab = computed(() => tabs.value.find(t => t.id === activeTabId.value));
|
||||
const currentSource = computed({
|
||||
get: () => activeTab.value ? activeTab.value.source : '',
|
||||
set: v => {
|
||||
if (activeTab.value) {
|
||||
if (activeTab.value.source !== v) activeTab.value.dirty = true;
|
||||
activeTab.value.source = v;
|
||||
persist();
|
||||
}
|
||||
},
|
||||
});
|
||||
const filteredOps = computed(() => {
|
||||
if (!activeTab.value) return [];
|
||||
const q = opFilter.value.trim().toLowerCase();
|
||||
if (!q) return activeTab.value.ops;
|
||||
return activeTab.value.ops.filter(op =>
|
||||
(op.kind && op.kind.toLowerCase().includes(q)) ||
|
||||
(op.op && op.op.toLowerCase().includes(q))
|
||||
);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// lifecycle
|
||||
// ------------------------------------------------------------------
|
||||
onMounted(async () => {
|
||||
restore();
|
||||
try {
|
||||
examples.value = await api.get('/nox/examples');
|
||||
if (tabs.value.length === 0 && examples.value.length) {
|
||||
openExample(examples.value[0]);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('failed to load examples', e);
|
||||
}
|
||||
window.addEventListener('keydown', handleHotkey);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('keydown', handleHotkey);
|
||||
if (runAbort) runAbort.abort();
|
||||
});
|
||||
|
||||
watch([tabs, activeTabId], persist, { deep: true });
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// persistence
|
||||
// ------------------------------------------------------------------
|
||||
function persist() {
|
||||
const lite = tabs.value.map(t => ({
|
||||
id: t.id, name: t.name, source: t.source, dirty: t.dirty,
|
||||
}));
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
||||
tabs: lite, activeTabId: activeTabId.value, mode: mode.value,
|
||||
}));
|
||||
}
|
||||
|
||||
function restore() {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return;
|
||||
const data = JSON.parse(raw);
|
||||
if (Array.isArray(data.tabs)) {
|
||||
tabs.value = data.tabs.map(t => ({
|
||||
...t, ops: [], diagnostics: [], error: '', running: false,
|
||||
}));
|
||||
activeTabId.value = data.activeTabId || (tabs.value[0] && tabs.value[0].id);
|
||||
}
|
||||
if (data.mode) mode.value = data.mode;
|
||||
} catch (e) {
|
||||
console.warn('failed to restore workspace', e);
|
||||
}
|
||||
refreshSavedFiles();
|
||||
}
|
||||
|
||||
function refreshSavedFiles() {
|
||||
// Find any saved files outside the tab set (history of closed tabs).
|
||||
// For v0.1, the only persistence path is the open-tabs snapshot above.
|
||||
savedFiles.value = [];
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tabs
|
||||
// ------------------------------------------------------------------
|
||||
function newTab(name = 'untitled.nox', source = '') {
|
||||
const id = String(Date.now()) + Math.random().toString(36).slice(2, 6);
|
||||
const tab = { id, name, source, dirty: false, ops: [], diagnostics: [], error: '', running: false };
|
||||
tabs.value.push(tab);
|
||||
activeTabId.value = id;
|
||||
nextTick(() => editorRef.value && editorRef.value.focus());
|
||||
}
|
||||
|
||||
function closeTab(id) {
|
||||
const idx = tabs.value.findIndex(t => t.id === id);
|
||||
if (idx === -1) return;
|
||||
if (tabs.value[idx].dirty) {
|
||||
if (!confirm(`"${tabs.value[idx].name}" has unsaved changes. Close anyway?`)) return;
|
||||
}
|
||||
tabs.value.splice(idx, 1);
|
||||
if (activeTabId.value === id) {
|
||||
activeTabId.value = tabs.value[Math.min(idx, tabs.value.length - 1)]?.id || null;
|
||||
}
|
||||
if (tabs.value.length === 0) {
|
||||
newTab();
|
||||
}
|
||||
}
|
||||
|
||||
function selectTab(id) {
|
||||
activeTabId.value = id;
|
||||
nextTick(() => editorRef.value && editorRef.value.focus());
|
||||
}
|
||||
|
||||
function openExample(ex) {
|
||||
const existing = tabs.value.find(t => t.name === ex.name);
|
||||
if (existing) { selectTab(existing.id); return; }
|
||||
newTab(ex.name, ex.source);
|
||||
if (activeTab.value) activeTab.value.dirty = false;
|
||||
}
|
||||
|
||||
function renameActiveTab() {
|
||||
if (!activeTab.value) return;
|
||||
const next = prompt('Rename file:', activeTab.value.name);
|
||||
if (next && next.trim()) {
|
||||
activeTab.value.name = next.trim();
|
||||
}
|
||||
}
|
||||
|
||||
function downloadActiveTab() {
|
||||
if (!activeTab.value) return;
|
||||
const blob = new Blob([activeTab.value.source], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = activeTab.value.name.endsWith('.nox') ? activeTab.value.name : activeTab.value.name + '.nox';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
activeTab.value.dirty = false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// run / stop
|
||||
// ------------------------------------------------------------------
|
||||
async function runProgram() {
|
||||
const tab = activeTab.value;
|
||||
if (!tab || tab.running) return;
|
||||
tab.running = true;
|
||||
tab.error = '';
|
||||
tab.ops = [];
|
||||
outputView.value = 'ops';
|
||||
|
||||
runAbort = new AbortController();
|
||||
try {
|
||||
const res = await fetch('/api/nox/run-stream', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${localStorage.getItem('token') || ''}`,
|
||||
},
|
||||
body: JSON.stringify({ source: tab.source, mode: mode.value }),
|
||||
signal: runAbort.signal,
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = '';
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
let idx;
|
||||
while ((idx = buf.indexOf('\n\n')) !== -1) {
|
||||
const raw = buf.slice(0, idx);
|
||||
buf = buf.slice(idx + 2);
|
||||
handleSseEvent(tab, raw);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.name !== 'AbortError') tab.error = String(e.message || e);
|
||||
} finally {
|
||||
tab.running = false;
|
||||
runAbort = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopRun() {
|
||||
if (runAbort) runAbort.abort();
|
||||
}
|
||||
|
||||
function handleSseEvent(tab, raw) {
|
||||
const lines = raw.split('\n');
|
||||
let event = 'message';
|
||||
let data = '';
|
||||
for (const ln of lines) {
|
||||
if (ln.startsWith('event:')) event = ln.slice(6).trim();
|
||||
else if (ln.startsWith('data:')) data += ln.slice(5).trim();
|
||||
}
|
||||
if (!data) return;
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(data); } catch { return; }
|
||||
|
||||
if (event === 'op') {
|
||||
tab.ops.push(parsed);
|
||||
nextTick(() => {
|
||||
if (opsScrollRef.value) opsScrollRef.value.scrollTop = opsScrollRef.value.scrollHeight;
|
||||
});
|
||||
} else if (event === 'error') {
|
||||
tab.error = parsed.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function typeCheck() {
|
||||
const tab = activeTab.value;
|
||||
if (!tab) return;
|
||||
try {
|
||||
const res = await api.post('/nox/check', { source: tab.source });
|
||||
tab.diagnostics = res.diagnostics || [];
|
||||
outputView.value = 'diagnostics';
|
||||
} catch (e) {
|
||||
tab.error = String(e);
|
||||
}
|
||||
}
|
||||
|
||||
function clearOutput() {
|
||||
if (!activeTab.value) return;
|
||||
activeTab.value.ops = [];
|
||||
activeTab.value.error = '';
|
||||
}
|
||||
|
||||
function copyOpsAsJson() {
|
||||
if (!activeTab.value) return;
|
||||
navigator.clipboard.writeText(JSON.stringify(activeTab.value.ops, null, 2));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// hotkeys
|
||||
// ------------------------------------------------------------------
|
||||
async function openDoc(path, title) {
|
||||
docTitle.value = title;
|
||||
docPath.value = path;
|
||||
docOpen.value = true;
|
||||
try {
|
||||
const res = await fetch('/api/nox/docs/' + path);
|
||||
const md = await res.text();
|
||||
docHtml.value = renderMarkdown(md);
|
||||
} catch (e) {
|
||||
docHtml.value = `<pre>failed to load: ${e}</pre>`;
|
||||
}
|
||||
}
|
||||
|
||||
function closeDoc() { docOpen.value = false; }
|
||||
|
||||
function handleHotkey(e) {
|
||||
if (docOpen.value && e.key === 'Escape') { docOpen.value = false; return; }
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (!mod) return;
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
runProgram();
|
||||
} else if (e.key === 's') {
|
||||
e.preventDefault();
|
||||
downloadActiveTab();
|
||||
} else if (e.key === 'w' && tabs.value.length > 0) {
|
||||
e.preventDefault();
|
||||
closeTab(activeTabId.value);
|
||||
} else if (e.key === 'n') {
|
||||
e.preventDefault();
|
||||
newTab();
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// formatting helpers
|
||||
// ------------------------------------------------------------------
|
||||
function fmtArgs(args) {
|
||||
if (!args) return '';
|
||||
return Object.entries(args).map(([k, v]) => `${k}=${fmtValue(v)}`).join(' ');
|
||||
}
|
||||
function fmtValue(v) {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (typeof v === 'object' && v._tag === 'Quantity') return `${v.value}${v.dim}`;
|
||||
if (typeof v === 'object' && v._tag === 'Coord') return `Coord<${v.frame}>(${v.ra.toFixed(3)}, ${v.dec.toFixed(3)})`;
|
||||
if (typeof v === 'object') return JSON.stringify(v);
|
||||
return JSON.stringify(v);
|
||||
}
|
||||
function relTime(ms) {
|
||||
if (!ms) return '';
|
||||
return new Date(ms).toISOString().slice(11, 23);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="nox-page">
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>Nox Console</h1>
|
||||
<p class="page-subtitle">
|
||||
Typed DSL for telescope and dome control.
|
||||
<RouterLink to="/nox/docs">Docs</RouterLink> ·
|
||||
<RouterLink to="/nox/examples">Examples</RouterLink>
|
||||
</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<select
|
||||
class="form-control header-select"
|
||||
:value="''"
|
||||
@change="(e) => { const ex = examples.find(x => x.name === e.target.value); if (ex) openExample(ex); e.target.value = ''; }"
|
||||
:disabled="!examples.length"
|
||||
title="Insert an example program"
|
||||
>
|
||||
<option value="" disabled selected>Insert example…</option>
|
||||
<option v-for="ex in examples" :key="ex.name" :value="ex.name">{{ ex.name }}</option>
|
||||
</select>
|
||||
<select v-model="mode" class="form-control header-select">
|
||||
<option value="mock">Mock mode</option>
|
||||
<option value="real">Real hardware</option>
|
||||
</select>
|
||||
<button class="btn btn-ghost" @click="typeCheck" :disabled="!activeTab">Check</button>
|
||||
<button v-if="!activeTab?.running" class="btn btn-primary" @click="runProgram" :disabled="!activeTab">Run <span class="kbd">⌘↵</span></button>
|
||||
<button v-else class="btn btn-danger" @click="stopRun">Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="ide">
|
||||
|
||||
<div class="body">
|
||||
<!-- editor pane -->
|
||||
<section class="editor-pane">
|
||||
<div class="tabstrip">
|
||||
<div
|
||||
v-for="tab in tabs"
|
||||
:key="tab.id"
|
||||
class="tab"
|
||||
:class="{ active: tab.id === activeTabId, dirty: tab.dirty }"
|
||||
@click="selectTab(tab.id)"
|
||||
@dblclick="renameActiveTab"
|
||||
>
|
||||
<span class="tab-name">{{ tab.name }}</span>
|
||||
<span v-if="tab.dirty" class="tab-dot">●</span>
|
||||
<button class="tab-close" @click.stop="closeTab(tab.id)" title="Close (⌘W)">×</button>
|
||||
</div>
|
||||
<button class="tab-add" @click="newTab()" title="New file (⌘N)">+</button>
|
||||
<div class="grow"></div>
|
||||
<button class="btn btn-ghost btn-sm tabstrip-btn" @click="renameActiveTab" :disabled="!activeTab">Rename</button>
|
||||
<button class="btn btn-ghost btn-sm tabstrip-btn" @click="downloadActiveTab" :disabled="!activeTab">Save <span class="kbd">⌘S</span></button>
|
||||
</div>
|
||||
|
||||
<div class="editor-wrap">
|
||||
<NoxEditor
|
||||
v-if="activeTab"
|
||||
ref="editorRef"
|
||||
v-model="currentSource"
|
||||
@run="runProgram"
|
||||
/>
|
||||
<div v-else class="empty-state">No file open. Click + to create one.</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- output pane -->
|
||||
<section class="output-pane">
|
||||
<div class="output-tabs">
|
||||
<button :class="{ active: outputView==='ops' }" @click="outputView='ops'">
|
||||
Operations <span class="badge">{{ activeTab ? activeTab.ops.length : 0 }}</span>
|
||||
</button>
|
||||
<button :class="{ active: outputView==='diagnostics' }" @click="outputView='diagnostics'">
|
||||
Diagnostics <span class="badge" v-if="activeTab && activeTab.diagnostics.length">{{ activeTab.diagnostics.length }}</span>
|
||||
</button>
|
||||
<div class="grow"></div>
|
||||
<input
|
||||
v-if="outputView==='ops'"
|
||||
v-model="opFilter"
|
||||
class="filter-input"
|
||||
placeholder="filter ops…"
|
||||
/>
|
||||
<button class="btn btn-ghost btn-sm" @click="copyOpsAsJson" :disabled="!activeTab || !activeTab.ops.length">Copy</button>
|
||||
<button class="btn btn-ghost btn-sm" @click="clearOutput" :disabled="!activeTab">Clear</button>
|
||||
</div>
|
||||
|
||||
<div class="output-body">
|
||||
<div v-if="activeTab && activeTab.error" class="error">{{ activeTab.error }}</div>
|
||||
|
||||
<template v-if="outputView==='ops'">
|
||||
<ul v-if="filteredOps.length" class="ops" ref="opsScrollRef">
|
||||
<li v-for="(op, i) in filteredOps" :key="i">
|
||||
<span class="op-time">{{ relTime(op.t) }}</span>
|
||||
<span class="op-kind">{{ op.kind }}</span>
|
||||
<span class="op-name">{{ op.op }}</span>
|
||||
<span class="op-args">{{ fmtArgs(op.args) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else-if="!activeTab" class="empty">Open or create a file.</p>
|
||||
<p v-else-if="activeTab.running" class="empty">Running…</p>
|
||||
<p v-else class="empty">No operations yet. Press Run.</p>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<ul v-if="activeTab && activeTab.diagnostics.length" class="diags">
|
||||
<li v-for="(d, i) in activeTab.diagnostics" :key="i">
|
||||
<span class="loc">{{ d.line || '?' }}:{{ d.column || '?' }}</span>
|
||||
<span class="msg">{{ d.message }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty">No diagnostics.</p>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- doc viewer modal -->
|
||||
<div v-if="docOpen" class="doc-modal-backdrop" @click="closeDoc">
|
||||
<div class="doc-modal" @click.stop>
|
||||
<div class="doc-header">
|
||||
<h2>{{ docTitle }}</h2>
|
||||
<button class="btn btn-ghost btn-sm" @click="closeDoc" title="Close (Esc)">×</button>
|
||||
</div>
|
||||
<div class="doc-body" v-html="docHtml" @click="handleDocLinkClick"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- status row -->
|
||||
<footer class="statusbar">
|
||||
<span v-if="activeTab" class="status-item">{{ activeTab.name }}</span>
|
||||
<span v-if="activeTab" class="status-item" :class="{ bad: activeTab.diagnostics.length, ok: !activeTab.diagnostics.length }">
|
||||
<span class="dot"></span>
|
||||
{{ activeTab.diagnostics.length }} issue<span v-if="activeTab.diagnostics.length !== 1">s</span>
|
||||
</span>
|
||||
<span v-if="activeTab" class="status-item muted">{{ activeTab.ops.length }} op<span v-if="activeTab.ops.length !== 1">s</span></span>
|
||||
<span v-if="activeTab && activeTab.running" class="status-item running">running…</span>
|
||||
<div class="grow"></div>
|
||||
<span class="status-item muted">⌘↵ run · ⌘S save · ⌘N new · ⌘W close</span>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Integrated tool styling: the IDE inherits the app's dark theme via design
|
||||
tokens (no light-mode chrome), and the chrome around the editor is kept
|
||||
subtle so the console reads as another Caelum surface, not a separate
|
||||
product. */
|
||||
.nox-page { display: flex; flex-direction: column; }
|
||||
.page-header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1.25rem; }
|
||||
.page-header h1 { margin: 0; }
|
||||
.page-subtitle {
|
||||
margin: 0.3rem 0 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
.page-subtitle a { color: var(--accent); }
|
||||
|
||||
.header-actions { display: flex; gap: 0.5rem; align-items: center; }
|
||||
.header-select {
|
||||
padding: 5px 10px;
|
||||
font-size: 0.85rem;
|
||||
width: auto;
|
||||
min-width: 140px;
|
||||
}
|
||||
.btn-danger {
|
||||
background: var(--danger);
|
||||
border-color: var(--danger);
|
||||
color: white;
|
||||
}
|
||||
.btn-danger:hover { background: #fb7185; }
|
||||
|
||||
.ide {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 9rem);
|
||||
min-height: 520px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
.grow { flex: 1; }
|
||||
.kbd {
|
||||
font-size: 0.75em;
|
||||
opacity: 0.75;
|
||||
margin-left: 0.3rem;
|
||||
font-family: ui-monospace, monospace;
|
||||
}
|
||||
|
||||
/* body: editor + output, no internal sidebar — discovery happens through
|
||||
the page header (example picker) and the dedicated /nox/examples and
|
||||
/nox/docs routes, so we don't double-up on left chrome with the Caelum
|
||||
global sidebar. */
|
||||
.body {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* editor pane */
|
||||
.editor-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.tabstrip {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
background: var(--bg-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
height: 32px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 8px 0 12px;
|
||||
gap: 6px;
|
||||
border-right: 1px solid var(--border);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.tab:hover { background: var(--bg-input); color: var(--text-primary); }
|
||||
.tab.active {
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
border-bottom: 2px solid var(--accent);
|
||||
padding-bottom: 0;
|
||||
}
|
||||
.tab-name { user-select: none; }
|
||||
.tab-dot { color: var(--accent); font-size: 0.6rem; }
|
||||
.tab-close {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: var(--text-muted);
|
||||
padding: 0;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
font-size: 0.95rem;
|
||||
line-height: 1;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tab-close:hover { background: var(--bg-input); color: var(--text-primary); }
|
||||
.tab-add {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
font-size: 1rem;
|
||||
color: var(--text-muted);
|
||||
padding: 0 12px;
|
||||
border-right: 1px solid var(--border);
|
||||
cursor: pointer;
|
||||
}
|
||||
.tab-add:hover { color: var(--text-primary); }
|
||||
/* tighten the tabstrip-resident btn-sm so it sits inside the 32px strip */
|
||||
.tabstrip .tabstrip-btn {
|
||||
margin: 4px 4px 4px 0;
|
||||
align-self: center;
|
||||
font-size: 0.78rem;
|
||||
padding: 2px 10px;
|
||||
}
|
||||
|
||||
.editor-wrap { flex: 1; min-height: 0; display: flex; background: var(--bg-card); }
|
||||
.editor-wrap > * { flex: 1; }
|
||||
.empty-state {
|
||||
padding: 2rem;
|
||||
color: var(--text-muted);
|
||||
font-style: italic;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* output pane */
|
||||
.output-pane { display: flex; flex-direction: column; min-width: 0; background: var(--bg-card); }
|
||||
.output-tabs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
background: var(--bg-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
height: 32px;
|
||||
padding: 0 0.6rem;
|
||||
}
|
||||
.output-tabs > button:not(.btn) {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
padding: 0 8px;
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
border-radius: 0;
|
||||
align-self: stretch;
|
||||
cursor: pointer;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.output-tabs > button:not(.btn):hover { color: var(--text-secondary); }
|
||||
.output-tabs > button:not(.btn).active { color: var(--accent); border-bottom-color: var(--accent); }
|
||||
.output-tabs .badge {
|
||||
background: var(--bg-input);
|
||||
color: var(--text-secondary);
|
||||
padding: 1px 6px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.7rem;
|
||||
margin-left: 4px;
|
||||
text-transform: none;
|
||||
}
|
||||
.output-tabs > button.active .badge { background: var(--accent); color: var(--bg-primary); }
|
||||
.filter-input {
|
||||
font: inherit;
|
||||
font-size: 0.8rem;
|
||||
padding: 3px 8px;
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
color: var(--text-primary);
|
||||
width: 140px;
|
||||
}
|
||||
.filter-input::placeholder { color: var(--text-muted); }
|
||||
|
||||
.output-body {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
.error {
|
||||
background: rgba(248, 113, 113, 0.12);
|
||||
color: var(--danger);
|
||||
padding: 0.5rem 0.7rem;
|
||||
border: 1px solid rgba(248, 113, 113, 0.35);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 0.6rem;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.empty { color: var(--text-muted); font-style: italic; padding: 0.5rem; }
|
||||
.ops {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ops li {
|
||||
display: grid;
|
||||
grid-template-columns: 90px 140px 130px 1fr;
|
||||
gap: 0.5rem;
|
||||
padding: 3px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.ops li:hover { background: var(--bg-input); }
|
||||
.op-time { color: var(--text-muted); }
|
||||
.op-kind { color: var(--text-muted); }
|
||||
.op-name { color: var(--accent); font-weight: 600; }
|
||||
.op-args { color: var(--text-primary); overflow-wrap: anywhere; }
|
||||
|
||||
.diags {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.diags li { padding: 3px 4px; color: var(--danger); }
|
||||
.diags .loc { color: var(--text-muted); margin-right: 0.6rem; }
|
||||
|
||||
/* status row — slim, no shouting */
|
||||
.statusbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 4px 12px;
|
||||
background: var(--bg-primary);
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
}
|
||||
.status-item { display: inline-flex; align-items: center; gap: 0.4rem; }
|
||||
.status-item .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--text-muted); display: inline-block; }
|
||||
.status-item.ok .dot { background: var(--success); }
|
||||
.status-item.bad .dot { background: var(--danger); }
|
||||
.status-item.bad { color: var(--danger); }
|
||||
.status-item.muted { color: var(--text-muted); }
|
||||
.status-item.running { color: var(--accent); }
|
||||
|
||||
/* doc modal */
|
||||
.doc-modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
.doc-modal {
|
||||
width: min(900px, 92vw);
|
||||
height: min(90vh, 800px);
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: 0 12px 40px rgba(0,0,0,0.5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.doc-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.5rem 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
.doc-header h2 { margin: 0; font-size: 1rem; color: var(--text-primary); }
|
||||
.doc-header button { font-size: 1.1rem; }
|
||||
.doc-body {
|
||||
overflow: auto;
|
||||
padding: 1.5rem 2rem;
|
||||
line-height: 1.55;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.doc-body :deep(h1) { margin-top: 0; }
|
||||
.doc-body :deep(h1), .doc-body :deep(h2), .doc-body :deep(h3) { color: var(--text-primary); }
|
||||
.doc-body :deep(h2) { margin-top: 1.4rem; }
|
||||
.doc-body :deep(h3) { margin-top: 1.2rem; }
|
||||
.doc-body :deep(p) { margin: 0.6rem 0; }
|
||||
.doc-body :deep(ul) { margin: 0.4rem 0 0.8rem 1.2rem; }
|
||||
.doc-body :deep(li) { margin: 0.15rem 0; }
|
||||
.doc-body :deep(code) {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.9em;
|
||||
background: var(--bg-input);
|
||||
color: var(--accent-hover);
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.doc-body :deep(pre.code) {
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
padding: 0.8rem 1rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
overflow: auto;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.doc-body :deep(pre.code code) { background: transparent; color: inherit; padding: 0; }
|
||||
.doc-body :deep(table) {
|
||||
border-collapse: collapse;
|
||||
margin: 0.8rem 0;
|
||||
width: 100%;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.doc-body :deep(th), .doc-body :deep(td) {
|
||||
border: 1px solid var(--border);
|
||||
padding: 4px 8px;
|
||||
text-align: left;
|
||||
}
|
||||
.doc-body :deep(th) { background: var(--bg-input); color: var(--text-primary); font-weight: 600; }
|
||||
.doc-body :deep(a) { color: var(--accent); }
|
||||
.doc-body :deep(a.doc-inert) {
|
||||
color: var(--text-secondary);
|
||||
text-decoration: none;
|
||||
cursor: default;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85em;
|
||||
background: var(--bg-input);
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
border-bottom: 1px dotted #999;
|
||||
}
|
||||
.statusbar .status-item.running { animation: pulse 1.2s infinite; }
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,413 @@
|
||||
<script setup>
|
||||
import { ref, computed, watchEffect } from 'vue';
|
||||
import { useRoute, useRouter, RouterLink } from 'vue-router';
|
||||
import { renderMarkdown, DOC_TOC, makeDocLinkHandler } from './nox/markdown.js';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const currentPath = ref('');
|
||||
const docHtml = ref('');
|
||||
const docTitle = ref('');
|
||||
const loading = ref(true); // default-true so the page never renders empty
|
||||
const error = ref('');
|
||||
const sidebarOpen = ref(true);
|
||||
|
||||
const flatToc = computed(() => DOC_TOC.flatMap(s => s.items));
|
||||
|
||||
// Drive both initial load and route changes from one place so there's no
|
||||
// race between onMounted and the watcher firing.
|
||||
watchEffect(() => {
|
||||
const path = route.query.path ? String(route.query.path) : 'README.md';
|
||||
if (path !== currentPath.value) loadDoc(path);
|
||||
});
|
||||
|
||||
async function loadDoc(path) {
|
||||
currentPath.value = path;
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
docHtml.value = '';
|
||||
const entry = flatToc.value.find(e => e.path === path);
|
||||
docTitle.value = entry ? entry.title : path;
|
||||
try {
|
||||
const res = await fetch('/api/nox/docs/' + encodeURI(path));
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText || ''}`.trim());
|
||||
const md = await res.text();
|
||||
if (!md.trim()) throw new Error('empty response');
|
||||
docHtml.value = renderMarkdown(md);
|
||||
requestAnimationFrame(() => {
|
||||
const el = document.querySelector('.doc-content');
|
||||
if (el) el.scrollTop = 0;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[nox-docs] loadDoc failed:', path, e);
|
||||
error.value = `Failed to load ${path}: ${e.message || e}`;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectDoc(path) {
|
||||
router.replace({ path: '/nox/docs', query: { path } });
|
||||
}
|
||||
|
||||
// Go back in history. If the docs page was opened directly (no prior entry,
|
||||
// or the prior entry is the same docs page), fall back to the Caelum home.
|
||||
function goBack() {
|
||||
if (window.history.length > 1) {
|
||||
router.back();
|
||||
} else {
|
||||
router.push('/');
|
||||
}
|
||||
}
|
||||
|
||||
// Intercepts in-content link clicks:
|
||||
// `.md` paths route within the docs viewer
|
||||
// absolute SPA paths route via vue-router (e.g. /nox/examples)
|
||||
// inert refs are swallowed
|
||||
const handleDocLinkClick = makeDocLinkHandler({
|
||||
getCurrentPath: () => currentPath.value,
|
||||
onDocNavigate: (path) => selectDoc(path),
|
||||
onAppNavigate: (href) => router.push(href),
|
||||
});
|
||||
|
||||
// Prev / Next within the flattened table of contents.
|
||||
const currentIdx = computed(() => flatToc.value.findIndex(e => e.path === currentPath.value));
|
||||
const prevDoc = computed(() => currentIdx.value > 0 ? flatToc.value[currentIdx.value - 1] : null);
|
||||
const nextDoc = computed(() => currentIdx.value >= 0 && currentIdx.value < flatToc.value.length - 1
|
||||
? flatToc.value[currentIdx.value + 1] : null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="docs-page">
|
||||
<header class="docs-topbar">
|
||||
<button class="back-link" @click="goBack" title="Back">
|
||||
<span class="back-arrow">←</span> Back
|
||||
</button>
|
||||
<div class="docs-title">Nox Documentation</div>
|
||||
<button class="sidebar-toggle" @click="sidebarOpen = !sidebarOpen" title="Toggle navigation">
|
||||
{{ sidebarOpen ? '⟨' : '⟩' }}
|
||||
</button>
|
||||
<div class="grow"></div>
|
||||
<RouterLink to="/nox/examples" class="ghost-link">Examples</RouterLink>
|
||||
<RouterLink to="/nox" class="cta">Open Console</RouterLink>
|
||||
</header>
|
||||
|
||||
<div class="docs-body">
|
||||
<aside class="docs-sidebar" v-if="sidebarOpen">
|
||||
<div v-for="section in DOC_TOC" :key="section.section" class="toc-section">
|
||||
<h3>{{ section.section }}</h3>
|
||||
<ul>
|
||||
<li v-for="item in section.items"
|
||||
:key="item.path"
|
||||
:class="{ active: item.path === currentPath }"
|
||||
@click="selectDoc(item.path)">
|
||||
{{ item.title }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="doc-content">
|
||||
<div v-if="loading" class="state">
|
||||
<div class="spinner"></div>
|
||||
Loading <code>{{ currentPath || 'README.md' }}</code>…
|
||||
</div>
|
||||
<div v-else-if="error" class="state error">
|
||||
<strong>Failed to load document.</strong>
|
||||
<div>{{ error }}</div>
|
||||
<button class="retry" @click="loadDoc(currentPath)">Retry</button>
|
||||
</div>
|
||||
<article v-else-if="docHtml" v-html="docHtml" @click="handleDocLinkClick"></article>
|
||||
<div v-else class="state">No content.</div>
|
||||
|
||||
<nav class="doc-pager" v-if="!loading && !error">
|
||||
<button v-if="prevDoc" class="pager-btn prev" @click="selectDoc(prevDoc.path)">
|
||||
<span class="pager-label">Previous</span>
|
||||
<span class="pager-title">{{ prevDoc.title }}</span>
|
||||
</button>
|
||||
<span v-else></span>
|
||||
<button v-if="nextDoc" class="pager-btn next" @click="selectDoc(nextDoc.path)">
|
||||
<span class="pager-label">Next</span>
|
||||
<span class="pager-title">{{ nextDoc.title }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.docs-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
background: #fafbff;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
color: #1a1a2a;
|
||||
}
|
||||
.grow { flex: 1; }
|
||||
|
||||
/* topbar */
|
||||
.docs-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.65rem 1.25rem;
|
||||
border-bottom: 1px solid #e0e3ee;
|
||||
background: white;
|
||||
}
|
||||
.back-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: #1a3a8a;
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 4px 8px;
|
||||
margin-left: -8px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
}
|
||||
.back-link:hover { background: #eef3ff; }
|
||||
.back-arrow { font-size: 1rem; }
|
||||
.docs-title { font-size: 0.95rem; font-weight: 500; color: #555; }
|
||||
.sidebar-toggle {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: #777;
|
||||
cursor: pointer;
|
||||
font-size: 1.1rem;
|
||||
padding: 2px 6px;
|
||||
}
|
||||
.cta {
|
||||
text-decoration: none;
|
||||
padding: 5px 12px;
|
||||
border-radius: 4px;
|
||||
background: #1a73e8;
|
||||
color: white;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.cta:hover { background: #1561c2; }
|
||||
.ghost-link {
|
||||
text-decoration: none;
|
||||
color: #1a73e8;
|
||||
font-size: 0.88rem;
|
||||
padding: 4px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.ghost-link:hover { background: #f0f4ff; }
|
||||
|
||||
/* body */
|
||||
.docs-body {
|
||||
display: grid;
|
||||
grid-template-columns: 260px 1fr;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.docs-body:has(.docs-sidebar:not([style*='display: none'])) {
|
||||
/* default 2-col */
|
||||
}
|
||||
.docs-page:has(.docs-topbar .sidebar-toggle):not(:has(.docs-sidebar)) .docs-body {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
/* sidebar */
|
||||
.docs-sidebar {
|
||||
border-right: 1px solid #e0e3ee;
|
||||
overflow-y: auto;
|
||||
background: white;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
.toc-section { margin-bottom: 1rem; }
|
||||
.toc-section h3 {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: #888;
|
||||
margin: 0 1.2rem 0.4rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.toc-section ul { list-style: none; padding: 0; margin: 0; }
|
||||
.toc-section li {
|
||||
padding: 5px 1.2rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.88rem;
|
||||
color: #333;
|
||||
border-left: 2px solid transparent;
|
||||
}
|
||||
.toc-section li:hover { background: #f3f5fb; }
|
||||
.toc-section li.active {
|
||||
background: #eef3ff;
|
||||
border-left-color: #1a73e8;
|
||||
color: #1a3a8a;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* content */
|
||||
.doc-content {
|
||||
padding: 2rem 3rem 3rem;
|
||||
overflow-y: auto;
|
||||
max-width: 900px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
line-height: 1.6;
|
||||
color: #222;
|
||||
}
|
||||
.state {
|
||||
color: #555;
|
||||
text-align: center;
|
||||
margin-top: 3rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
.state code { background: #eef2fa; padding: 2px 6px; border-radius: 3px; font-family: ui-monospace, monospace; font-size: 0.85rem; }
|
||||
.state.error {
|
||||
color: #c62828;
|
||||
background: #fef0f0;
|
||||
border: 1px solid #f5c2c2;
|
||||
padding: 1rem 1.25rem;
|
||||
border-radius: 6px;
|
||||
margin-top: 1.5rem;
|
||||
text-align: left;
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
word-break: break-word;
|
||||
}
|
||||
.state.error strong { display: block; margin-bottom: 0.4rem; font-family: inherit; font-size: 0.9rem; }
|
||||
.state.error .retry {
|
||||
margin-top: 0.75rem;
|
||||
background: #c62828;
|
||||
color: white;
|
||||
border: 0;
|
||||
padding: 5px 14px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.spinner {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 2px solid #d0d6e3;
|
||||
border-top-color: #1a73e8;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.doc-content :deep(h1) {
|
||||
font-size: 2rem;
|
||||
margin: 0 0 1.5rem;
|
||||
color: #1a3a8a;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
.doc-content :deep(h2) {
|
||||
font-size: 1.4rem;
|
||||
margin: 2rem 0 0.6rem;
|
||||
color: #1a3a8a;
|
||||
border-bottom: 1px solid #e0e3ee;
|
||||
padding-bottom: 0.3rem;
|
||||
}
|
||||
.doc-content :deep(h3) {
|
||||
font-size: 1.1rem;
|
||||
margin: 1.5rem 0 0.4rem;
|
||||
color: #333;
|
||||
}
|
||||
.doc-content :deep(p) { margin: 0.8rem 0; color: #333; }
|
||||
.doc-content :deep(ul) { margin: 0.6rem 0 1rem 1.4rem; }
|
||||
.doc-content :deep(li) { margin: 0.25rem 0; }
|
||||
.doc-content :deep(code) {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Monaco, monospace;
|
||||
font-size: 0.88em;
|
||||
background: #eef2fa;
|
||||
color: #1a3a8a;
|
||||
padding: 2px 5px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.doc-content :deep(pre.code) {
|
||||
background: #0b1530;
|
||||
color: #e6ecff;
|
||||
padding: 1rem 1.25rem;
|
||||
border-radius: 8px;
|
||||
overflow-x: auto;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
margin: 0.8rem 0;
|
||||
}
|
||||
.doc-content :deep(pre.code code) {
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
padding: 0;
|
||||
}
|
||||
.doc-content :deep(table) {
|
||||
border-collapse: collapse;
|
||||
margin: 1rem 0;
|
||||
width: 100%;
|
||||
font-size: 0.9em;
|
||||
background: white;
|
||||
}
|
||||
.doc-content :deep(th), .doc-content :deep(td) {
|
||||
border: 1px solid #e0e3ee;
|
||||
padding: 6px 10px;
|
||||
text-align: left;
|
||||
}
|
||||
.doc-content :deep(th) { background: #f1f4fb; font-weight: 600; color: #1a3a8a; }
|
||||
.doc-content :deep(a) { color: #1a73e8; }
|
||||
.doc-content :deep(a.doc-inert) {
|
||||
color: #444;
|
||||
text-decoration: none;
|
||||
cursor: default;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Monaco, monospace;
|
||||
font-size: 0.88em;
|
||||
background: #eef2fa;
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
border-bottom: 1px dotted #8aa4d6;
|
||||
}
|
||||
.doc-content :deep(a.doc-inert:hover) { background: #e2e9f5; }
|
||||
.doc-content :deep(strong) { color: #1a1a2a; }
|
||||
|
||||
/* pager */
|
||||
.doc-pager {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 3rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid #e0e3ee;
|
||||
gap: 1rem;
|
||||
}
|
||||
.pager-btn {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
background: white;
|
||||
border: 1px solid #e0e3ee;
|
||||
border-radius: 8px;
|
||||
padding: 0.7rem 1rem;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
font: inherit;
|
||||
color: #333;
|
||||
max-width: 280px;
|
||||
flex: 1;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
}
|
||||
.pager-btn:hover { border-color: #1a73e8; background: #f9fbff; }
|
||||
.pager-btn.next { align-items: flex-end; text-align: right; }
|
||||
.pager-label { font-size: 0.7rem; color: #888; text-transform: uppercase; letter-spacing: 0.06em; }
|
||||
.pager-title { font-size: 0.92rem; font-weight: 500; color: #1a3a8a; margin-top: 0.2rem; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.docs-body { grid-template-columns: 1fr; }
|
||||
.docs-sidebar { display: none; }
|
||||
.doc-content { padding: 1.5rem 1.2rem; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,254 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted } from 'vue';
|
||||
import { useRouter, RouterLink } from 'vue-router';
|
||||
import { highlightNox } from './nox/highlight.js';
|
||||
|
||||
const router = useRouter();
|
||||
const examples = ref([]);
|
||||
const selected = ref('');
|
||||
const loading = ref(true);
|
||||
const error = ref('');
|
||||
|
||||
onMounted(load);
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const res = await fetch('/api/nox/examples');
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
examples.value = await res.json();
|
||||
if (examples.value.length) selected.value = examples.value[0].name;
|
||||
} catch (e) {
|
||||
error.value = e.message || String(e);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const current = computed(() => examples.value.find(e => e.name === selected.value) || null);
|
||||
const highlightedSource = computed(() => current.value ? highlightNox(current.value.source) : '');
|
||||
const summary = computed(() => {
|
||||
if (!current.value) return '';
|
||||
// Pull the first comment line as a one-liner subtitle.
|
||||
const m = current.value.source.match(/^\/\/\s*(.+)$/m);
|
||||
return m ? m[1] : '';
|
||||
});
|
||||
|
||||
function copyToClipboard() {
|
||||
if (!current.value) return;
|
||||
navigator.clipboard.writeText(current.value.source);
|
||||
}
|
||||
|
||||
function openInConsole() {
|
||||
// The IDE persists tabs to localStorage with key `nox.workspace.v1`.
|
||||
// Seed it with the current example so the new tab appears on load.
|
||||
if (!current.value) return;
|
||||
try {
|
||||
const raw = localStorage.getItem('nox.workspace.v1');
|
||||
const data = raw ? JSON.parse(raw) : { tabs: [], activeTabId: null, mode: 'mock' };
|
||||
const id = String(Date.now()) + Math.random().toString(36).slice(2, 6);
|
||||
data.tabs = (data.tabs || []).filter(t => t.name !== current.value.name);
|
||||
data.tabs.push({ id, name: current.value.name, source: current.value.source, dirty: false });
|
||||
data.activeTabId = id;
|
||||
localStorage.setItem('nox.workspace.v1', JSON.stringify(data));
|
||||
} catch { /* ignore storage failures; user will just see the default tab */ }
|
||||
router.push('/nox');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ex-page">
|
||||
<header class="ex-topbar">
|
||||
<RouterLink to="/" class="back-link"><span class="back-arrow">←</span> Caelum</RouterLink>
|
||||
<div class="title">Nox Examples</div>
|
||||
<div class="grow"></div>
|
||||
<RouterLink to="/nox/docs" class="ghost-link">Docs</RouterLink>
|
||||
<RouterLink to="/nox" class="cta">Open Console</RouterLink>
|
||||
</header>
|
||||
|
||||
<div class="ex-body">
|
||||
<aside class="ex-sidebar">
|
||||
<h3>Programs</h3>
|
||||
<ul>
|
||||
<li v-if="loading" class="muted">Loading…</li>
|
||||
<li v-else-if="error" class="bad">{{ error }}</li>
|
||||
<li
|
||||
v-else
|
||||
v-for="ex in examples"
|
||||
:key="ex.name"
|
||||
:class="{ active: ex.name === selected }"
|
||||
@click="selected = ex.name"
|
||||
>{{ ex.name }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<main class="ex-main">
|
||||
<template v-if="current">
|
||||
<div class="ex-header">
|
||||
<h1>{{ current.name }}</h1>
|
||||
<p v-if="summary" class="ex-sub">{{ summary }}</p>
|
||||
<div class="ex-actions">
|
||||
<button class="primary" @click="openInConsole">Open in Console</button>
|
||||
<button class="ghost" @click="copyToClipboard">Copy source</button>
|
||||
</div>
|
||||
</div>
|
||||
<pre class="ex-code"><code v-html="highlightedSource"></code></pre>
|
||||
</template>
|
||||
<div v-else-if="loading" class="state">Loading examples…</div>
|
||||
<div v-else-if="error" class="state bad">{{ error }}</div>
|
||||
<div v-else class="state">No examples available.</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.ex-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
background: #fafbff;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
color: #1a1a2a;
|
||||
}
|
||||
.grow { flex: 1; }
|
||||
|
||||
.ex-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.65rem 1.25rem;
|
||||
border-bottom: 1px solid #e0e3ee;
|
||||
background: white;
|
||||
}
|
||||
.back-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
color: #1a3a8a;
|
||||
text-decoration: none;
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.back-arrow { font-size: 1rem; }
|
||||
.title { font-size: 0.95rem; font-weight: 500; color: #555; }
|
||||
.ghost-link {
|
||||
text-decoration: none;
|
||||
color: #1a73e8;
|
||||
font-size: 0.88rem;
|
||||
padding: 4px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.ghost-link:hover { background: #f0f4ff; }
|
||||
.cta {
|
||||
text-decoration: none;
|
||||
padding: 5px 12px;
|
||||
border-radius: 4px;
|
||||
background: #1a73e8;
|
||||
color: white;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.cta:hover { background: #1561c2; }
|
||||
|
||||
.ex-body {
|
||||
display: grid;
|
||||
grid-template-columns: 260px 1fr;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.ex-sidebar {
|
||||
border-right: 1px solid #e0e3ee;
|
||||
overflow-y: auto;
|
||||
background: white;
|
||||
padding: 1rem 0 1rem 0;
|
||||
}
|
||||
.ex-sidebar h3 {
|
||||
font-size: 0.7rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: #888;
|
||||
margin: 0 1.2rem 0.4rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.ex-sidebar ul { list-style: none; padding: 0; margin: 0; }
|
||||
.ex-sidebar li {
|
||||
padding: 5px 1.2rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
color: #333;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, monospace;
|
||||
border-left: 2px solid transparent;
|
||||
}
|
||||
.ex-sidebar li:hover { background: #f3f5fb; }
|
||||
.ex-sidebar li.active {
|
||||
background: #eef3ff;
|
||||
border-left-color: #1a73e8;
|
||||
color: #1a3a8a;
|
||||
font-weight: 500;
|
||||
}
|
||||
.ex-sidebar .muted { color: #999; font-style: italic; font-family: inherit; }
|
||||
.ex-sidebar .bad { color: #c62828; font-family: inherit; }
|
||||
|
||||
.ex-main {
|
||||
overflow-y: auto;
|
||||
padding: 2rem 3rem 3rem;
|
||||
max-width: 1100px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.ex-header h1 {
|
||||
margin: 0 0 0.3rem;
|
||||
font-size: 1.4rem;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, monospace;
|
||||
color: #1a3a8a;
|
||||
}
|
||||
.ex-sub { color: #555; margin: 0 0 1rem; font-size: 0.95rem; }
|
||||
.ex-actions { display: flex; gap: 0.6rem; margin-bottom: 1.2rem; }
|
||||
button {
|
||||
padding: 5px 12px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #ccc;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
button.primary { background: #1a73e8; color: white; border-color: #1a73e8; }
|
||||
button.primary:hover { background: #1561c2; }
|
||||
button.ghost { background: transparent; border-color: #ccc; color: #444; }
|
||||
button.ghost:hover { background: #f0f0f0; }
|
||||
|
||||
.ex-code {
|
||||
background: #0b1530;
|
||||
color: #e6ecff;
|
||||
border: 1px solid rgba(155, 182, 255, 0.22);
|
||||
border-radius: 10px;
|
||||
padding: 1.25rem 1.5rem;
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Monaco, monospace;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
margin: 0;
|
||||
}
|
||||
.ex-code :deep(.t-comment) { color: #7686a8; font-style: italic; }
|
||||
.ex-code :deep(.t-string) { color: #a3e3b4; }
|
||||
.ex-code :deep(.t-number) { color: #ffd28b; }
|
||||
.ex-code :deep(.t-unit) { color: #ffae5c; font-weight: 600; }
|
||||
.ex-code :deep(.t-keyword) { color: #8ab4ff; font-weight: 600; }
|
||||
.ex-code :deep(.t-type) { color: #66d9d6; }
|
||||
.ex-code :deep(.t-const) { color: #d3a4ff; }
|
||||
.ex-code :deep(.t-ident) { color: #e6ecff; }
|
||||
|
||||
.state { margin-top: 3rem; text-align: center; color: #888; }
|
||||
.state.bad { color: #c62828; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.ex-body { grid-template-columns: 1fr; }
|
||||
.ex-sidebar { display: none; }
|
||||
.ex-main { padding: 1.5rem 1.2rem; }
|
||||
}
|
||||
</style>
|
||||
@@ -245,7 +245,7 @@ const reqStatusBadge = s => ({ PENDING: 'badge-idle', APPROVED: 'badge-online',
|
||||
<div>
|
||||
<RouterLink :to="`/u/${r.username}`" style="color:var(--accent);text-decoration:none"><strong>@{{ r.username }}</strong></RouterLink>
|
||||
<span style="color:#fbbf24;margin-left:0.5rem">{{ '★'.repeat(r.rating) }}<span style="color:var(--text-muted);opacity:0.4">{{ '★'.repeat(5 - r.rating) }}</span></span>
|
||||
<span style="font-size:0.72rem;color:var(--text-muted);margin-left:0.5rem">{{ new Date(r.created_at.replace(' ','T')+'Z').toLocaleDateString() }}</span>
|
||||
<span style="font-size:0.72rem;color:var(--text-muted);margin-left:0.5rem">{{ new Date(r.created_at).toLocaleDateString() }}</span>
|
||||
</div>
|
||||
<button v-if="r.user_id === auth.user?.id" class="btn btn-ghost btn-sm" style="color:var(--danger);font-size:0.75rem;padding:0" @click="deleteMyReview">×</button>
|
||||
</div>
|
||||
@@ -265,7 +265,7 @@ const reqStatusBadge = s => ({ PENDING: 'badge-idle', APPROVED: 'badge-online',
|
||||
<div style="display:flex;justify-content:space-between;align-items:start;gap:0.5rem">
|
||||
<div>
|
||||
<RouterLink :to="`/u/${c.username}`" style="color:var(--accent);text-decoration:none"><strong>@{{ c.username }}</strong></RouterLink>
|
||||
<span style="font-size:0.72rem;color:var(--text-muted);margin-left:0.5rem">{{ new Date(c.created_at.replace(' ','T')+'Z').toLocaleString() }}</span>
|
||||
<span style="font-size:0.72rem;color:var(--text-muted);margin-left:0.5rem">{{ new Date(c.created_at).toLocaleString() }}</span>
|
||||
</div>
|
||||
<button v-if="c.user_id === auth.user?.id" class="btn btn-ghost btn-sm" style="color:var(--danger);font-size:0.75rem;padding:0" @click="deleteComment(c)">×</button>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ async function submit() {
|
||||
loading.value = true;
|
||||
try {
|
||||
await auth.register(email.value, username.value, password.value);
|
||||
router.push('/');
|
||||
router.push('/dashboard');
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
} finally {
|
||||
|
||||
@@ -314,13 +314,13 @@ const stacks = computed(() => {
|
||||
return [...map.values()].filter(s => s.frames > 1).sort((a, b) => b.totalSeconds - a.totalSeconds);
|
||||
});
|
||||
|
||||
const fmtTime = ts => new Date(ts.includes('T') ? ts : ts.replace(' ', 'T') + 'Z').toLocaleTimeString();
|
||||
const fmtTime = ts => new Date(ts.includes('T') ? ts : ts).toLocaleTimeString();
|
||||
const noteIcon = nt => ({ slew: '↗', system: '⚙', exposure: '◉', finding: '★', issue: '⚠', weather: '☁', note: '✎' }[nt] || '✎');
|
||||
const noteClass = nt => `note-${nt || 'note'}`;
|
||||
const tStatusBadge = s => ({ PENDING: 'badge-idle', OBSERVING: 'badge-slewing', DONE: 'badge-online', SKIPPED: 'badge-offline' }[s] || 'badge-idle');
|
||||
const exposureProgress = e => {
|
||||
if (e.status !== 'RUNNING') return 100;
|
||||
const start = new Date((e.started_at || '').replace(' ', 'T') + 'Z').getTime();
|
||||
const start = new Date((e.started_at || '')).getTime();
|
||||
const total = (e.exposure_time || 60) * (e.exposure_count || 1) * 200;
|
||||
const elapsed = Date.now() - start;
|
||||
return Math.min(99, Math.max(5, (elapsed / total) * 100));
|
||||
@@ -348,7 +348,7 @@ const exposureProgress = e => {
|
||||
<span>
|
||||
{{ session.telescope.name }} @ {{ session.site.name }} ·
|
||||
host <RouterLink :to="`/u/${session.host.username}`" style="color:inherit"><strong>{{ session.host.username }}</strong></RouterLink> ·
|
||||
ends {{ new Date(session.booking.end_time.replace(' ','T')+'Z').toLocaleString() }}
|
||||
ends {{ new Date(session.booking.end_time).toLocaleString() }}
|
||||
</span>
|
||||
<span v-if="livePresence.length" class="presence-row">
|
||||
<span style="font-size:0.72rem;color:var(--text-muted);margin-right:0.3rem">live:</span>
|
||||
|
||||
@@ -80,27 +80,27 @@ async function deleteSite(s, e) {
|
||||
</div>
|
||||
|
||||
<div class="grid grid-2">
|
||||
<RouterLink v-for="s in sites" :key="s.id" :to="`/site/${s.id}`" class="card" style="text-decoration:none;color:inherit">
|
||||
<div style="display:flex;align-items:start;justify-content:space-between">
|
||||
<div>
|
||||
<h3>{{ s.name }} <span style="font-size:0.8rem;color:var(--accent);font-weight:normal">{{ s.code }}</span></h3>
|
||||
<p style="font-size:0.85rem;color:var(--text-muted);margin-top:0.25rem">
|
||||
<RouterLink v-for="s in sites" :key="s.id" :to="`/site/${s.id}`" class="card site-card">
|
||||
<div class="site-head">
|
||||
<div class="site-head-text">
|
||||
<h3>{{ s.name }} <span class="site-code">{{ s.code }}</span></h3>
|
||||
<p class="site-meta">
|
||||
{{ s.latitude?.toFixed(4) }}, {{ s.longitude?.toFixed(4) }} · {{ s.timezone }}
|
||||
</p>
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;align-items:center">
|
||||
<div class="site-head-actions">
|
||||
<span v-if="s.is_safe === 0" class="badge badge-error">unsafe</span>
|
||||
<span class="badge" :class="`badge-${s.status}`">{{ s.status }}</span>
|
||||
<button class="btn btn-ghost btn-sm" @click="openEdit(s, $event)" title="Edit">✎</button>
|
||||
<button class="btn btn-ghost btn-sm" style="color:var(--danger)" @click="deleteSite(s, $event)" title="Delete">×</button>
|
||||
<button class="btn btn-ghost btn-sm site-delete" @click="deleteSite(s, $event)" title="Delete">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:1.5rem;margin-top:1rem;font-size:0.85rem;color:var(--text-secondary)">
|
||||
<p class="site-desc">{{ s.description || ' ' }}</p>
|
||||
<div class="site-stats">
|
||||
<span>{{ s.enclosure_count || 0 }} enclosures</span>
|
||||
<span>{{ s.telescope_count || 0 }} telescopes</span>
|
||||
<span>{{ s.member_count || 0 }} members</span>
|
||||
</div>
|
||||
<p v-if="s.description" style="font-size:0.85rem;color:var(--text-muted);margin-top:0.5rem">{{ s.description }}</p>
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
@@ -152,3 +152,60 @@ async function deleteSite(s, e) {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* Site cards use a flex column so the stats row aligns to the bottom of each
|
||||
card and the description occupies whatever space remains. The grid
|
||||
already equalises heights; this evens out the internal layout. */
|
||||
.site-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
min-height: 200px;
|
||||
}
|
||||
.site-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.site-head-text { min-width: 0; }
|
||||
.site-head-text h3 { margin: 0; }
|
||||
.site-code {
|
||||
font-size: 0.8rem;
|
||||
color: var(--accent);
|
||||
font-weight: normal;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
.site-meta {
|
||||
margin: 0.25rem 0 0;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.site-head-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.site-delete { color: var(--danger); }
|
||||
|
||||
.site-desc {
|
||||
margin: 0;
|
||||
font-size: 0.88rem;
|
||||
color: var(--text-muted);
|
||||
flex: 1;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.site-stats {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-secondary);
|
||||
padding-top: 0.5rem;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -44,7 +44,7 @@ const fmtIntegration = s => {
|
||||
<div style="flex:1">
|
||||
<h2 style="margin:0">{{ profile.username }}</h2>
|
||||
<div style="color:var(--text-muted);font-size:0.85rem">
|
||||
{{ profile.role }} · joined {{ new Date(profile.created_at.replace(' ','T')+'Z').toLocaleDateString() }}
|
||||
{{ profile.role }} · joined {{ new Date(profile.created_at).toLocaleDateString() }}
|
||||
</div>
|
||||
</div>
|
||||
<RouterLink v-if="auth.user && auth.user.username !== profile.username" :to="`/messages/${profile.username}`" class="btn btn-secondary btn-sm">✉ Message</RouterLink>
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// Autocomplete for Nox. Sources: hard keywords, type names, builtin globals,
|
||||
// catalog identifiers, and method names by resource (rough heuristic based on
|
||||
// the token immediately before the dot).
|
||||
|
||||
import { CompletionContext } from '@codemirror/autocomplete';
|
||||
|
||||
const KEYWORDS = [
|
||||
'import', 'from', 'use', 'let', 'var', 'fn', 'return',
|
||||
'if', 'else', 'for', 'in', 'repeat', 'while', 'do', 'step', 'reached',
|
||||
'parallel', 'task', 'on', 'rollback',
|
||||
'session', 'requires', 'safety', 'policy', 'when',
|
||||
'yield', 'continue', 'break', 'halt', 'assert',
|
||||
'not', 'and', 'or', 'true', 'false', 'now', 'after', 'before',
|
||||
];
|
||||
|
||||
const RESOURCE_KINDS = ['telescope', 'dome', 'camera', 'filter_wheel', 'focuser'];
|
||||
|
||||
const TYPES = [
|
||||
'Int', 'Float', 'String', 'Bool',
|
||||
'Duration', 'Angle', 'Temperature', 'Speed', 'Steps', 'Pixels',
|
||||
'Coord', 'Time', 'Image', 'Percent',
|
||||
'Telescope', 'Dome', 'Camera', 'FilterWheel', 'Focuser',
|
||||
'Target', 'Schedule', 'Weather', 'FlatPanel',
|
||||
'ICRS', 'Topo', 'AltAz', 'Galactic',
|
||||
];
|
||||
|
||||
const GLOBALS = [
|
||||
{ label: 'now', type: 'variable' },
|
||||
{ label: 'sunset', type: 'variable' },
|
||||
{ label: 'sunrise', type: 'variable' },
|
||||
{ label: 'weather', type: 'variable' },
|
||||
{ label: 'schedule', type: 'variable' },
|
||||
{ label: 'cos', type: 'function', detail: '(angle: Angle) -> Float' },
|
||||
{ label: 'sin', type: 'function', detail: '(angle: Angle) -> Float' },
|
||||
{ label: 'parabola_min', type: 'function', detail: '(samples: [(Steps, Pixels)]) -> Steps' },
|
||||
{ label: 'rollback', type: 'function', detail: '() -> Void' },
|
||||
{ label: 'halt', type: 'function', detail: '() -> Void' },
|
||||
];
|
||||
|
||||
const CATALOG = ['M31', 'M42', 'M51', 'M81', 'M101', 'NGC_7000'];
|
||||
|
||||
// Method tables. Each value is an array of { label, detail }.
|
||||
const METHODS = {
|
||||
telescope: [
|
||||
{ label: 'slew', detail: '(target: Pointable) -> Void' },
|
||||
{ label: 'park', detail: '() -> Void' },
|
||||
{ label: 'home', detail: '() -> Void' },
|
||||
{ label: 'wait_until_settled', detail: '() -> Void' },
|
||||
{ label: 'cooldown', detail: '(target: Temperature, timeout?: Duration) -> Void' },
|
||||
{ label: 'warm_up', detail: '() -> Void' },
|
||||
{ label: 'expose', detail: '(exp: Duration, filter: String) -> Image' },
|
||||
{ label: 'focus', detail: '(method: String) -> Void' },
|
||||
{ label: 'focus_if_needed', detail: '(max_age?: Duration, temp_delta?: Temperature) -> Void' },
|
||||
{ label: 'dither', detail: '(amount: Angle, pattern?: String) -> Void' },
|
||||
{ label: 'auto_flat_exposure', detail: '(filter: String) -> Duration' },
|
||||
{ label: 'is_idle', detail: ': Bool' },
|
||||
{ label: 'filter_wheel', detail: ': FilterWheel' },
|
||||
{ label: 'focuser', detail: ': Focuser' },
|
||||
{ label: 'camera', detail: ': Camera' },
|
||||
],
|
||||
dome: [
|
||||
{ label: 'open', detail: '() -> Void' },
|
||||
{ label: 'close', detail: '() -> Void' },
|
||||
{ label: 'is_closed', detail: '() -> Bool' },
|
||||
{ label: 'flat_panel', detail: ': FlatPanel' },
|
||||
],
|
||||
camera: [
|
||||
{ label: 'shutter', detail: '(state: String) -> Void' },
|
||||
],
|
||||
filter_wheel: [
|
||||
{ label: 'select', detail: '(filter: String) -> Void' },
|
||||
],
|
||||
focuser: [
|
||||
{ label: 'move_to', detail: '(pos: Steps) -> Void' },
|
||||
],
|
||||
weather: [
|
||||
{ label: 'clouds', detail: ': Percent' },
|
||||
{ label: 'humidity', detail: ': Percent' },
|
||||
{ label: 'wind', detail: ': Speed' },
|
||||
{ label: 'is_clear', detail: ': Bool' },
|
||||
{ label: 'is_safe', detail: '() -> Bool' },
|
||||
],
|
||||
schedule: [
|
||||
{ label: 'tonight', detail: '() -> [Target]' },
|
||||
{ label: 'best_target', detail: '(t: Time) -> Target?' },
|
||||
],
|
||||
flat_panel: [
|
||||
{ label: 'on', detail: '(brightness: Percent) -> Void' },
|
||||
{ label: 'off', detail: '() -> Void' },
|
||||
],
|
||||
};
|
||||
|
||||
const LIST_METHODS = [
|
||||
{ label: 'filter', detail: '(pred: (T) -> Bool) -> [T]' },
|
||||
{ label: 'map', detail: '(fn: (T) -> Any) -> [Any]' },
|
||||
{ label: 'sort_by', detail: '(key: (T) -> Any) -> [T]' },
|
||||
{ label: 'push', detail: '(item: T) -> Void' },
|
||||
{ label: 'length', detail: '() -> Int' },
|
||||
];
|
||||
|
||||
const TIME_METHODS = [
|
||||
{ label: 'has_passed', detail: ': Bool' },
|
||||
];
|
||||
|
||||
const IMAGE_METHODS = [
|
||||
{ label: 'hfr', detail: '() -> Pixels' },
|
||||
];
|
||||
|
||||
// Scan the document for `use <kind> <name> = ...` lines to learn what kind
|
||||
// each user-defined binding is, so member completion can show the right
|
||||
// method table.
|
||||
function scanResourceBindings(doc) {
|
||||
const bindings = {};
|
||||
const text = doc.toString();
|
||||
const re = /\buse\s+(telescope|dome|camera|filter_wheel|focuser)\s+([A-Za-z_]\w*)\b/g;
|
||||
let m;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
bindings[m[2]] = m[1];
|
||||
}
|
||||
return bindings;
|
||||
}
|
||||
|
||||
export function noxCompletions(context) {
|
||||
const word = context.matchBefore(/[A-Za-z_]\w*/);
|
||||
if (!word && !context.explicit) return null;
|
||||
|
||||
// Look at the token immediately before the prefix to detect a member access.
|
||||
const beforePos = (word ? word.from : context.pos) - 1;
|
||||
const beforeChar = beforePos >= 0 ? context.state.doc.sliceString(beforePos, beforePos + 1) : '';
|
||||
|
||||
if (beforeChar === '.') {
|
||||
// Find the receiver: walk left past identifier characters.
|
||||
let p = beforePos - 1;
|
||||
while (p >= 0) {
|
||||
const c = context.state.doc.sliceString(p, p + 1);
|
||||
if (!/[A-Za-z0-9_]/.test(c)) break;
|
||||
p--;
|
||||
}
|
||||
const receiver = context.state.doc.sliceString(p + 1, beforePos);
|
||||
return memberCompletions(context, word, receiver);
|
||||
}
|
||||
|
||||
// Top-level completion.
|
||||
const options = [
|
||||
...KEYWORDS.map(k => ({ label: k, type: 'keyword' })),
|
||||
...TYPES.map(t => ({ label: t, type: 'type' })),
|
||||
...GLOBALS,
|
||||
...CATALOG.map(c => ({ label: c, type: 'constant' })),
|
||||
...RESOURCE_KINDS.map(k => ({ label: k, type: 'keyword' })),
|
||||
];
|
||||
|
||||
return {
|
||||
from: word ? word.from : context.pos,
|
||||
options,
|
||||
validFor: /^[A-Za-z_]\w*$/,
|
||||
};
|
||||
}
|
||||
|
||||
function memberCompletions(context, word, receiver) {
|
||||
const bindings = scanResourceBindings(context.state.doc);
|
||||
const kind = bindings[receiver];
|
||||
|
||||
let methods = [];
|
||||
if (kind && METHODS[kind]) {
|
||||
methods = METHODS[kind];
|
||||
} else if (METHODS[receiver]) {
|
||||
// Direct receiver match (weather, schedule, flat_panel, etc.)
|
||||
methods = METHODS[receiver];
|
||||
} else if (receiver === 'filter_wheel' || receiver === 'focuser' || receiver === 'camera') {
|
||||
methods = METHODS[receiver];
|
||||
} else {
|
||||
// Unknown receiver. Offer a union of likely method names.
|
||||
methods = [
|
||||
...LIST_METHODS,
|
||||
...TIME_METHODS,
|
||||
...IMAGE_METHODS,
|
||||
];
|
||||
}
|
||||
|
||||
return {
|
||||
from: word ? word.from : context.pos,
|
||||
options: methods.map(m => ({
|
||||
label: m.label,
|
||||
detail: m.detail,
|
||||
type: m.detail && m.detail.startsWith('(') ? 'method' : 'property',
|
||||
})),
|
||||
validFor: /^[A-Za-z_]\w*$/,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// Build a fully-loaded CodeMirror EditorView for Nox.
|
||||
//
|
||||
// Exposes a small façade so the Vue component can drive the editor without
|
||||
// dealing with CodeMirror's State/Compartment plumbing directly.
|
||||
|
||||
import { EditorState, Compartment } from '@codemirror/state';
|
||||
import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter, drawSelection, rectangularSelection, crosshairCursor } from '@codemirror/view';
|
||||
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||
import { bracketMatching, indentOnInput, foldGutter, foldKeymap, indentUnit } from '@codemirror/language';
|
||||
import { closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap } from '@codemirror/autocomplete';
|
||||
import { lintKeymap, lintGutter } from '@codemirror/lint';
|
||||
import { highlightSelectionMatches, searchKeymap, search } from '@codemirror/search';
|
||||
|
||||
import { noxLanguage, noxHighlighter } from './language.js';
|
||||
import { noxLinter } from './lint.js';
|
||||
import { noxCompletions } from './complete.js';
|
||||
|
||||
// Dark theme matching Caelum's design tokens. Reads the live computed values
|
||||
// from the running document so it stays in sync if the tokens change.
|
||||
function tok(name, fallback) {
|
||||
if (typeof document === 'undefined') return fallback;
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
}
|
||||
|
||||
function buildTheme() {
|
||||
const bg = tok('--bg-card', '#1e293b');
|
||||
const bgPrim = tok('--bg-primary', '#0f172a');
|
||||
const bgInput = tok('--bg-input', '#334155');
|
||||
const border = tok('--border', '#334155');
|
||||
const text = tok('--text-primary', '#f1f5f9');
|
||||
const textMuted = tok('--text-muted', '#64748b');
|
||||
const accent = tok('--accent', '#38bdf8');
|
||||
const danger = tok('--danger', '#f87171');
|
||||
|
||||
return EditorView.theme({
|
||||
'&': {
|
||||
fontSize: '13px',
|
||||
height: '100%',
|
||||
backgroundColor: bg,
|
||||
color: text,
|
||||
},
|
||||
'.cm-content': {
|
||||
fontFamily: 'ui-monospace, "SF Mono", Menlo, Monaco, monospace',
|
||||
padding: '10px 0',
|
||||
caretColor: accent,
|
||||
},
|
||||
'.cm-cursor': { borderLeftColor: accent },
|
||||
'.cm-gutters': {
|
||||
backgroundColor: bgPrim,
|
||||
color: textMuted,
|
||||
border: 'none',
|
||||
borderRight: `1px solid ${border}`,
|
||||
},
|
||||
'.cm-activeLine': { backgroundColor: 'rgba(56, 189, 248, 0.05)' },
|
||||
'.cm-activeLineGutter': { backgroundColor: 'rgba(56, 189, 248, 0.10)', color: accent },
|
||||
'.cm-selectionBackground, ::selection': { backgroundColor: 'rgba(56, 189, 248, 0.25) !important' },
|
||||
'.cm-selectionMatch': { backgroundColor: 'rgba(251, 191, 36, 0.20)' },
|
||||
'.cm-matchingBracket': { backgroundColor: 'rgba(56, 189, 248, 0.20)', outline: `1px solid ${accent}` },
|
||||
'.cm-tooltip': {
|
||||
backgroundColor: bg,
|
||||
border: `1px solid ${border}`,
|
||||
borderRadius: '4px',
|
||||
color: text,
|
||||
boxShadow: '0 4px 16px rgba(0,0,0,0.4)',
|
||||
},
|
||||
'.cm-tooltip-autocomplete > ul > li': { padding: '3px 8px', color: text },
|
||||
'.cm-tooltip-autocomplete > ul > li[aria-selected]': { backgroundColor: accent, color: bgPrim },
|
||||
'.cm-completionDetail': { color: textMuted },
|
||||
'.cm-diagnostic-error': { borderLeft: `3px solid ${danger}` },
|
||||
'.cm-lintRange-error': {
|
||||
backgroundImage: 'none',
|
||||
textDecoration: `underline wavy ${danger}`,
|
||||
textDecorationSkipInk: 'none',
|
||||
},
|
||||
'.cm-panels': { backgroundColor: bgPrim, color: text },
|
||||
'.cm-panel.cm-search input': { backgroundColor: bgInput, color: text, border: `1px solid ${border}` },
|
||||
'.cm-foldGutter .cm-foldGutter-marker': { color: textMuted },
|
||||
});
|
||||
}
|
||||
|
||||
const editorTheme = buildTheme();
|
||||
|
||||
export function buildEditor({ parent, initialDoc = '', onChange = () => {}, onRunRequest = () => {} }) {
|
||||
const updateListener = EditorView.updateListener.of(update => {
|
||||
if (update.docChanged) onChange(update.state.doc.toString());
|
||||
});
|
||||
|
||||
const runKeymap = keymap.of([
|
||||
{
|
||||
key: 'Mod-Enter',
|
||||
preventDefault: true,
|
||||
run: () => { onRunRequest(); return true; },
|
||||
},
|
||||
]);
|
||||
|
||||
const state = EditorState.create({
|
||||
doc: initialDoc,
|
||||
extensions: [
|
||||
lineNumbers(),
|
||||
lintGutter(),
|
||||
foldGutter(),
|
||||
highlightActiveLine(),
|
||||
highlightActiveLineGutter(),
|
||||
drawSelection(),
|
||||
rectangularSelection(),
|
||||
crosshairCursor(),
|
||||
history(),
|
||||
bracketMatching(),
|
||||
closeBrackets(),
|
||||
indentOnInput(),
|
||||
indentUnit.of(' '),
|
||||
highlightSelectionMatches(),
|
||||
search({ top: true }),
|
||||
autocompletion({ override: [noxCompletions] }),
|
||||
noxLanguage,
|
||||
noxHighlighter,
|
||||
noxLinter(),
|
||||
editorTheme,
|
||||
updateListener,
|
||||
runKeymap,
|
||||
keymap.of([
|
||||
...defaultKeymap,
|
||||
...historyKeymap,
|
||||
...closeBracketsKeymap,
|
||||
...completionKeymap,
|
||||
...lintKeymap,
|
||||
...searchKeymap,
|
||||
...foldKeymap,
|
||||
indentWithTab,
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const view = new EditorView({ state, parent });
|
||||
|
||||
return {
|
||||
view,
|
||||
getValue() { return view.state.doc.toString(); },
|
||||
setValue(text) {
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
});
|
||||
},
|
||||
focus() { view.focus(); },
|
||||
destroy() { view.destroy(); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Lightweight Nox syntax highlighter for static code previews (landing
|
||||
// page, docs, examples page). Matches the palette used by the IDE.
|
||||
// Not suitable for interactive editing — for that use the CodeMirror mode
|
||||
// in ./language.js.
|
||||
|
||||
const HARD_KEYWORDS = new Set([
|
||||
'import','from','use','let','var','fn','return','if','else','for','in',
|
||||
'repeat','while','do','parallel','task','on','session','requires','safety',
|
||||
'policy','when','yield','continue','break','halt','assert','not','and',
|
||||
'or','true','false','now','after','before',
|
||||
]);
|
||||
const SOFT_KEYWORDS = new Set([
|
||||
'step','reached','rollback','telescope','dome','camera','filter_wheel','focuser',
|
||||
]);
|
||||
const TYPE_NAMES = new Set([
|
||||
'Int','Float','String','Bool','Duration','Angle','Temperature','Speed',
|
||||
'Steps','Pixels','Coord','Time','Image','Percent','Telescope','Dome',
|
||||
'Camera','FilterWheel','Focuser','Target','Schedule','Weather','FlatPanel',
|
||||
'ICRS','Topo','AltAz','Galactic','Void','Any',
|
||||
]);
|
||||
const UNIT_SUFFIX_RE = /^(?:ms|min|s|h|deg|arcmin|arcsec|degC|kph|mps|steps|px)\b/;
|
||||
|
||||
function escapeHtml(s) {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
export function highlightNox(src) {
|
||||
const out = [];
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
const ch = src[i];
|
||||
|
||||
// line comment
|
||||
if (ch === '/' && src[i + 1] === '/') {
|
||||
const nl = src.indexOf('\n', i);
|
||||
const end = nl === -1 ? src.length : nl;
|
||||
out.push(`<span class="t-comment">${escapeHtml(src.slice(i, end))}</span>`);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
// block comment
|
||||
if (ch === '/' && src[i + 1] === '*') {
|
||||
const end = src.indexOf('*/', i + 2);
|
||||
const stop = end === -1 ? src.length : end + 2;
|
||||
out.push(`<span class="t-comment">${escapeHtml(src.slice(i, stop))}</span>`);
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
// string (with interpolation segments highlighted as code)
|
||||
if (ch === '"') {
|
||||
let j = i + 1;
|
||||
while (j < src.length && src[j] !== '"') {
|
||||
if (src[j] === '\\') j++;
|
||||
j++;
|
||||
}
|
||||
j = Math.min(j + 1, src.length);
|
||||
out.push(`<span class="t-string">${escapeHtml(src.slice(i, j))}</span>`);
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
// numbers, optional unit/percent
|
||||
if (/[0-9]/.test(ch) || (ch === '-' && /[0-9]/.test(src[i + 1] || ''))) {
|
||||
let j = i;
|
||||
if (src[j] === '-') j++;
|
||||
while (j < src.length && /[0-9.]/.test(src[j])) j++;
|
||||
const numEnd = j;
|
||||
const rest = src.slice(numEnd);
|
||||
const m = rest.match(UNIT_SUFFIX_RE);
|
||||
if (m) {
|
||||
out.push(`<span class="t-number">${escapeHtml(src.slice(i, numEnd))}</span><span class="t-unit">${escapeHtml(m[0])}</span>`);
|
||||
i = numEnd + m[0].length;
|
||||
continue;
|
||||
}
|
||||
if (rest.startsWith('%')) {
|
||||
out.push(`<span class="t-unit">${escapeHtml(src.slice(i, numEnd + 1))}</span>`);
|
||||
i = numEnd + 1;
|
||||
continue;
|
||||
}
|
||||
out.push(`<span class="t-number">${escapeHtml(src.slice(i, numEnd))}</span>`);
|
||||
i = numEnd;
|
||||
continue;
|
||||
}
|
||||
// identifier / keyword / type
|
||||
if (/[A-Za-z_]/.test(ch)) {
|
||||
let j = i;
|
||||
while (j < src.length && /[A-Za-z0-9_]/.test(src[j])) j++;
|
||||
const word = src.slice(i, j);
|
||||
let cls = 't-ident';
|
||||
if (HARD_KEYWORDS.has(word) || SOFT_KEYWORDS.has(word)) cls = 't-keyword';
|
||||
else if (TYPE_NAMES.has(word)) cls = 't-type';
|
||||
else if (/^[A-Z]/.test(word)) cls = 't-const';
|
||||
out.push(`<span class="${cls}">${escapeHtml(word)}</span>`);
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
// anything else: literal char (escaped)
|
||||
out.push(escapeHtml(ch));
|
||||
i++;
|
||||
}
|
||||
return out.join('');
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Nox syntax-highlighting mode for CodeMirror 6.
|
||||
//
|
||||
// We use StreamLanguage rather than a full Lezer grammar because Nox is
|
||||
// simple enough to tokenize line-by-line, and the parser already runs on the
|
||||
// server. The highlight buckets map to CodeMirror's standard tag set.
|
||||
|
||||
import { StreamLanguage } from '@codemirror/language';
|
||||
import { tags as t } from '@lezer/highlight';
|
||||
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
|
||||
|
||||
const HARD_KEYWORDS = new Set([
|
||||
'import', 'from', 'use', 'let', 'var', 'fn', 'return',
|
||||
'if', 'else', 'for', 'in', 'repeat', 'while', 'do',
|
||||
'parallel', 'task', 'on', 'session', 'requires', 'safety',
|
||||
'policy', 'when',
|
||||
'yield', 'continue', 'break', 'halt', 'assert',
|
||||
'not', 'and', 'or', 'true', 'false', 'now', 'after', 'before',
|
||||
]);
|
||||
|
||||
const SOFT_KEYWORDS = new Set([
|
||||
'step', 'reached', 'rollback',
|
||||
'telescope', 'dome', 'camera', 'filter_wheel', 'focuser',
|
||||
]);
|
||||
|
||||
const TYPE_NAMES = new Set([
|
||||
'Int', 'Float', 'String', 'Bool',
|
||||
'Duration', 'Angle', 'Temperature', 'Speed', 'Steps', 'Pixels',
|
||||
'Coord', 'Time', 'Image', 'Percent',
|
||||
'Telescope', 'Dome', 'Camera', 'FilterWheel', 'Focuser',
|
||||
'Target', 'Schedule', 'Weather', 'FlatPanel',
|
||||
'ICRS', 'Topo', 'AltAz', 'Galactic',
|
||||
'Void', 'Any',
|
||||
]);
|
||||
|
||||
const UNIT_SUFFIX = /^(?:ms|min|s|h|deg|arcmin|arcsec|degC|kph|mps|steps|px)\b/;
|
||||
|
||||
export const noxLanguage = StreamLanguage.define({
|
||||
name: 'nox',
|
||||
|
||||
startState() {
|
||||
return { inBlockComment: false };
|
||||
},
|
||||
|
||||
token(stream, state) {
|
||||
// Block comment continuation.
|
||||
if (state.inBlockComment) {
|
||||
while (!stream.eol()) {
|
||||
if (stream.match('*/')) { state.inBlockComment = false; return 'comment'; }
|
||||
stream.next();
|
||||
}
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
if (stream.eatSpace()) return null;
|
||||
|
||||
// Line comment.
|
||||
if (stream.match('//')) { stream.skipToEnd(); return 'lineComment'; }
|
||||
|
||||
// Block comment open.
|
||||
if (stream.match('/*')) {
|
||||
state.inBlockComment = true;
|
||||
while (!stream.eol()) {
|
||||
if (stream.match('*/')) { state.inBlockComment = false; return 'comment'; }
|
||||
stream.next();
|
||||
}
|
||||
return 'comment';
|
||||
}
|
||||
|
||||
// Strings.
|
||||
if (stream.match(/^"(?:[^"\\]|\\.)*"/)) return 'string';
|
||||
|
||||
// Numbers with optional unit suffix or percent.
|
||||
if (stream.match(/^[0-9]+(?:\.[0-9]+)?/)) {
|
||||
// Try unit suffix.
|
||||
if (stream.match(UNIT_SUFFIX)) return 'unit';
|
||||
if (stream.match('%')) return 'unit';
|
||||
return 'number';
|
||||
}
|
||||
|
||||
// Decorator.
|
||||
if (stream.match(/^@[A-Za-z_][A-Za-z0-9_]*/)) return 'meta';
|
||||
|
||||
// Identifiers / keywords.
|
||||
const m = stream.match(/^[A-Za-z_][A-Za-z0-9_]*/);
|
||||
if (m) {
|
||||
const word = m[0];
|
||||
if (HARD_KEYWORDS.has(word)) {
|
||||
if (['true', 'false'].includes(word)) return 'bool';
|
||||
if (word === 'now') return 'atom';
|
||||
return 'keyword';
|
||||
}
|
||||
if (SOFT_KEYWORDS.has(word)) return 'keyword';
|
||||
if (TYPE_NAMES.has(word)) return 'typeName';
|
||||
// Catalog identifiers like M31, NGC_7000 — anything starting with uppercase
|
||||
// gets a soft "constant" highlight unless it's already a known type.
|
||||
if (/^[A-Z]/.test(word)) return 'variableConstant';
|
||||
return 'variableName';
|
||||
}
|
||||
|
||||
// Operators and punctuation.
|
||||
if (stream.match(/^(?:->|=>|\.\.|[<>=!]=|[+\-*/]=)/)) return 'operator';
|
||||
if (stream.match(/^[+\-*/%<>=!?]/)) return 'operator';
|
||||
if (stream.match(/^[{}()[\],;:.@]/)) return 'punctuation';
|
||||
|
||||
stream.next();
|
||||
return null;
|
||||
},
|
||||
|
||||
tokenTable: {
|
||||
lineComment: t.lineComment,
|
||||
comment: t.blockComment,
|
||||
string: t.string,
|
||||
number: t.number,
|
||||
unit: t.unit,
|
||||
meta: t.meta,
|
||||
keyword: t.keyword,
|
||||
bool: t.bool,
|
||||
atom: t.atom,
|
||||
typeName: t.typeName,
|
||||
variableConstant: t.constant(t.variableName),
|
||||
variableName: t.variableName,
|
||||
operator: t.operator,
|
||||
punctuation: t.punctuation,
|
||||
},
|
||||
});
|
||||
|
||||
// Palette tuned for the app's dark theme. Hue families mirror the static
|
||||
// highlighter on the landing/examples pages.
|
||||
export const noxHighlight = HighlightStyle.define([
|
||||
{ tag: [t.lineComment, t.blockComment], color: '#7686a8', fontStyle: 'italic' },
|
||||
{ tag: t.string, color: '#a3e3b4' },
|
||||
{ tag: t.number, color: '#ffd28b' },
|
||||
{ tag: t.unit, color: '#ffae5c', fontWeight: '600' },
|
||||
{ tag: t.meta, color: '#d3a4ff' },
|
||||
{ tag: t.keyword, color: '#8ab4ff', fontWeight: '600' },
|
||||
{ tag: t.bool, color: '#8ab4ff' },
|
||||
{ tag: t.atom, color: '#8ab4ff' },
|
||||
{ tag: t.typeName, color: '#66d9d6' },
|
||||
{ tag: t.constant(t.variableName), color: '#d3a4ff' },
|
||||
{ tag: t.variableName, color: '#e6ecff' },
|
||||
{ tag: t.operator, color: '#94a3b8' },
|
||||
{ tag: t.punctuation, color: '#94a3b8' },
|
||||
]);
|
||||
|
||||
export const noxHighlighter = syntaxHighlighting(noxHighlight);
|
||||
@@ -0,0 +1,44 @@
|
||||
// Lint extension: posts source to /api/nox/check on a debounce, converts the
|
||||
// returned diagnostics to CodeMirror Diagnostic objects with character offsets.
|
||||
|
||||
import { linter } from '@codemirror/lint';
|
||||
import { api } from '../../services/api.js';
|
||||
|
||||
// Map { line, column } -> character offset in the document.
|
||||
function offsetFor(doc, line, column) {
|
||||
if (!line || line < 1) return 0;
|
||||
if (line > doc.lines) return doc.length;
|
||||
const lineObj = doc.line(line);
|
||||
// CodeMirror columns are 0-based here; our checker reports 1-based.
|
||||
return Math.min(lineObj.from + Math.max(0, (column || 1) - 1), lineObj.to);
|
||||
}
|
||||
|
||||
let pending = null;
|
||||
|
||||
export function noxLinter() {
|
||||
return linter(async view => {
|
||||
if (pending) clearTimeout(pending);
|
||||
const source = view.state.doc.toString();
|
||||
if (!source.trim()) return [];
|
||||
try {
|
||||
const { diagnostics } = await api.post('/nox/check', { source });
|
||||
if (!Array.isArray(diagnostics)) return [];
|
||||
const doc = view.state.doc;
|
||||
return diagnostics.map(d => {
|
||||
const from = offsetFor(doc, d.line || 1, d.column || 1);
|
||||
// Cover the token: extend through the next whitespace or punctuation.
|
||||
const lineObj = doc.line(d.line || 1);
|
||||
const lineText = lineObj.text.slice((d.column || 1) - 1);
|
||||
const tokenLen = (lineText.match(/^[A-Za-z0-9_]+/) || [lineText[0] || ''])[0].length || 1;
|
||||
return {
|
||||
from,
|
||||
to: Math.min(from + tokenLen, doc.length),
|
||||
severity: 'error',
|
||||
message: d.message,
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}, { delay: 400 });
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Tiny markdown renderer used by the IDE doc modal and the standalone
|
||||
// /nox/docs page. Handles enough of the format to read our own docs:
|
||||
// headings, fenced code, inline code, bullet lists, paragraphs, bold,
|
||||
// links, and pipe tables. Not spec-conformant — never feed it untrusted
|
||||
// markdown.
|
||||
|
||||
function escape(s) {
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function inline(s) {
|
||||
let r = escape(s);
|
||||
r = r.replace(/`([^`]+)`/g, (_, c) => `<code>${c}</code>`);
|
||||
r = r.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, href) => {
|
||||
// Four link kinds:
|
||||
// external -> open in a new tab (http, mailto, tel)
|
||||
// internal .md -> route within the docs viewer
|
||||
// app route -> absolute SPA path (starts with `/`), routed via vue-router
|
||||
// inert -> filesystem paths and other refs with no in-app target;
|
||||
// the click handler swallows these so they don't bounce
|
||||
// the user to a broken route.
|
||||
if (/^(https?:|mailto:|tel:)/.test(href)) {
|
||||
return `<a href="${href}" target="_blank" rel="noopener">${label}</a>`;
|
||||
}
|
||||
if (/\.md(?:$|[#?])/.test(href)) {
|
||||
return `<a href="${href}" data-doc-link>${label}</a>`;
|
||||
}
|
||||
if (href.startsWith('/')) {
|
||||
return `<a href="${href}" data-app-link>${label}</a>`;
|
||||
}
|
||||
return `<a href="#" class="doc-inert" data-doc-inert title="${href}">${label}</a>`;
|
||||
});
|
||||
return r;
|
||||
}
|
||||
|
||||
// Resolve a relative href (from inside an .md file) against the current doc's
|
||||
// path. Returns a path rooted in docsDir, e.g. "book/03-values-and-types.md".
|
||||
export function resolveDocPath(currentPath, href) {
|
||||
// Strip fragments and query strings; we only resolve the path portion.
|
||||
const cleaned = href.split('#')[0].split('?')[0];
|
||||
if (!cleaned) return currentPath;
|
||||
if (cleaned.startsWith('/')) return cleaned.replace(/^\/+/, '');
|
||||
|
||||
const baseDir = currentPath.includes('/')
|
||||
? currentPath.slice(0, currentPath.lastIndexOf('/'))
|
||||
: '';
|
||||
const baseParts = baseDir ? baseDir.split('/') : [];
|
||||
const relParts = cleaned.split('/');
|
||||
const out = [...baseParts];
|
||||
for (const p of relParts) {
|
||||
if (p === '..') out.pop();
|
||||
else if (p !== '.' && p !== '') out.push(p);
|
||||
}
|
||||
return out.join('/');
|
||||
}
|
||||
|
||||
// Click handler factory for v-html content.
|
||||
//
|
||||
// <a data-doc-link> -> resolved and forwarded to onDocNavigate
|
||||
// <a data-app-link> -> absolute SPA path, forwarded to onAppNavigate
|
||||
// <a data-doc-inert> -> swallowed so filesystem refs don't navigate
|
||||
// anything else -> passes through (external, anchors, etc.)
|
||||
//
|
||||
// `onAppNavigate` is optional; when omitted, app links fall through to the
|
||||
// browser's default navigation (which still works, just without router state).
|
||||
export function makeDocLinkHandler({ getCurrentPath, onDocNavigate, onAppNavigate }) {
|
||||
return function (event) {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.button !== 0) return; // ignore middle/right click
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
let el = event.target;
|
||||
while (el && el !== event.currentTarget) {
|
||||
if (el.tagName === 'A' && el.dataset) {
|
||||
if (el.dataset.docInert !== undefined) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (el.dataset.appLink !== undefined && onAppNavigate) {
|
||||
const href = el.getAttribute('href');
|
||||
if (href) {
|
||||
event.preventDefault();
|
||||
onAppNavigate(href);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (el.dataset.docLink !== undefined && onDocNavigate) {
|
||||
const href = el.getAttribute('href');
|
||||
if (href) {
|
||||
event.preventDefault();
|
||||
onDocNavigate(resolveDocPath(getCurrentPath(), href));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
el = el.parentElement;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function renderMarkdown(md) {
|
||||
const lines = String(md || '').split('\n');
|
||||
const out = [];
|
||||
let inCode = false;
|
||||
let codeBuf = [];
|
||||
let listOpen = false;
|
||||
let paraBuf = [];
|
||||
let tableHeader = null;
|
||||
let tableRows = [];
|
||||
|
||||
const flushPara = () => {
|
||||
if (paraBuf.length) {
|
||||
out.push('<p>' + paraBuf.join(' ') + '</p>');
|
||||
paraBuf = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (listOpen) { out.push('</ul>'); listOpen = false; }
|
||||
};
|
||||
const flushTable = () => {
|
||||
if (tableHeader) {
|
||||
let html = '<table><thead><tr>';
|
||||
for (const c of tableHeader) html += `<th>${inline(c)}</th>`;
|
||||
html += '</tr></thead><tbody>';
|
||||
for (const r of tableRows) {
|
||||
html += '<tr>';
|
||||
for (const c of r) html += `<td>${inline(c)}</td>`;
|
||||
html += '</tr>';
|
||||
}
|
||||
html += '</tbody></table>';
|
||||
out.push(html);
|
||||
tableHeader = null;
|
||||
tableRows = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const raw of lines) {
|
||||
if (inCode) {
|
||||
if (raw.trim().startsWith('```')) {
|
||||
out.push(`<pre class="code"><code>${escape(codeBuf.join('\n'))}</code></pre>`);
|
||||
codeBuf = [];
|
||||
inCode = false;
|
||||
} else {
|
||||
codeBuf.push(raw);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (raw.trim().startsWith('```')) {
|
||||
flushPara(); flushList(); flushTable();
|
||||
inCode = true;
|
||||
continue;
|
||||
}
|
||||
if (raw.startsWith('#')) {
|
||||
flushPara(); flushList(); flushTable();
|
||||
const m = raw.match(/^(#{1,6})\s+(.*)$/);
|
||||
if (m) {
|
||||
const lvl = m[1].length;
|
||||
out.push(`<h${lvl}>${inline(m[2])}</h${lvl}>`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (/^\s*\|.*\|\s*$/.test(raw)) {
|
||||
const cells = raw.trim().slice(1, -1).split('|').map(c => c.trim());
|
||||
if (!tableHeader) {
|
||||
tableHeader = cells;
|
||||
} else if (/^[-:\s|]+$/.test(raw)) {
|
||||
// separator row
|
||||
} else {
|
||||
tableRows.push(cells);
|
||||
}
|
||||
continue;
|
||||
} else if (tableHeader) {
|
||||
flushTable();
|
||||
}
|
||||
if (raw.trim().startsWith('- ')) {
|
||||
flushPara(); flushTable();
|
||||
if (!listOpen) { out.push('<ul>'); listOpen = true; }
|
||||
out.push(`<li>${inline(raw.trim().slice(2))}</li>`);
|
||||
continue;
|
||||
}
|
||||
if (raw.trim() === '') {
|
||||
flushPara(); flushList(); flushTable();
|
||||
continue;
|
||||
}
|
||||
paraBuf.push(inline(raw));
|
||||
}
|
||||
flushPara(); flushList(); flushTable();
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
// Table of contents for the standalone docs page.
|
||||
export const DOC_TOC = [
|
||||
{ section: 'Overview', items: [
|
||||
{ path: 'README.md', title: 'Index' },
|
||||
]},
|
||||
{ section: 'Tutorial', items: [
|
||||
{ path: 'book/01-why-nox.md', title: '1. Why Nox' },
|
||||
{ path: 'book/02-hello-nox.md', title: '2. Hello Nox' },
|
||||
{ path: 'book/03-values-and-types.md', title: '3. Values and Types' },
|
||||
{ path: 'book/04-operators.md', title: '4. Operators' },
|
||||
{ path: 'book/05-statements.md', title: '5. Statements' },
|
||||
{ path: 'book/06-functions.md', title: '6. Functions' },
|
||||
{ path: 'book/07-resources-and-sessions.md', title: '7. Sessions' },
|
||||
{ path: 'book/08-parallel-and-rollback.md', title: '8. Parallel and Rollback' },
|
||||
{ path: 'book/09-policies.md', title: '9. Policies' },
|
||||
{ path: 'book/10-cookbook.md', title: '10. Cookbook' },
|
||||
{ path: 'book/11-troubleshooting.md', title: '11. Troubleshooting' },
|
||||
]},
|
||||
{ section: 'Reference', items: [
|
||||
{ path: 'reference/grammar.md', title: 'Grammar' },
|
||||
{ path: 'reference/types.md', title: 'Types' },
|
||||
{ path: 'reference/statements.md', title: 'Statements' },
|
||||
{ path: 'reference/expressions.md', title: 'Expressions' },
|
||||
{ path: 'reference/builtins.md', title: 'Builtins' },
|
||||
{ path: 'reference/runtime-api.md', title: 'Runtime API' },
|
||||
{ path: 'reference/http-api.md', title: 'HTTP API' },
|
||||
{ path: 'reference/cli.md', title: 'CLI' },
|
||||
]},
|
||||
];
|
||||
@@ -0,0 +1,44 @@
|
||||
# Nox Documentation
|
||||
|
||||
Two tracks: a tutorial book and an API reference.
|
||||
|
||||
## Nox for Dummies
|
||||
|
||||
A guided walk through the language. Read in order.
|
||||
|
||||
1. [Why Nox](book/01-why-nox.md)
|
||||
2. [Hello Nox](book/02-hello-nox.md)
|
||||
3. [Values and Types](book/03-values-and-types.md)
|
||||
4. [Operators](book/04-operators.md)
|
||||
5. [Statements and Control Flow](book/05-statements.md)
|
||||
6. [Functions and Lambdas](book/06-functions.md)
|
||||
7. [Resources and Sessions](book/07-resources-and-sessions.md)
|
||||
8. [Parallel and Rollback](book/08-parallel-and-rollback.md)
|
||||
9. [Policies](book/09-policies.md)
|
||||
10. [Cookbook](book/10-cookbook.md)
|
||||
11. [Troubleshooting](book/11-troubleshooting.md)
|
||||
|
||||
## API Reference
|
||||
|
||||
Look up specific forms, types, methods, and endpoints.
|
||||
|
||||
- [Grammar](reference/grammar.md)
|
||||
- [Type System](reference/types.md)
|
||||
- [Statements](reference/statements.md)
|
||||
- [Expressions](reference/expressions.md)
|
||||
- [Builtins](reference/builtins.md)
|
||||
- [Runtime API](reference/runtime-api.md)
|
||||
- [HTTP API](reference/http-api.md)
|
||||
- [CLI](reference/cli.md)
|
||||
|
||||
## Try it
|
||||
|
||||
- [Open the Nox Console](/nox) — full IDE with type-checking, autocomplete, and live op log.
|
||||
- [Browse the example gallery](/nox/examples) — every shipped `.nox` program with syntax highlighting and a one-click "Open in Console".
|
||||
- [Grammar reference](reference/grammar.md) — the EBNF, in plain markdown.
|
||||
- [HTTP API reference](reference/http-api.md) — endpoints for embedding Nox into other tools.
|
||||
- [CLI reference](reference/cli.md) — `nox check / run / ops / parse` for shell use.
|
||||
|
||||
## Version
|
||||
|
||||
This documentation describes Nox v0.4.
|
||||
@@ -0,0 +1,47 @@
|
||||
# 1. Why Nox
|
||||
|
||||
Nox is a small programming language for telescopes and domes. You write `.nox` files. Observatory runs them.
|
||||
|
||||
## What problem it solves
|
||||
|
||||
Telescope scripting traditionally uses one of two things. Config files like YAML, which run fast but cannot loop or react. Or general-purpose Python, which can do anything and also crash an observatory at 3 AM.
|
||||
|
||||
Nox sits in the middle. It is a real language with variables, functions, loops, and concurrency. It also catches whole classes of bug at edit time.
|
||||
|
||||
## What makes it different
|
||||
|
||||
**Units are types.** You cannot pass seconds where degrees are expected. `60s` and `60deg` are different types. The type checker rejects mistakes before the dome opens.
|
||||
|
||||
```
|
||||
T.dither(amount: 30s) // rejected: expected Angle, got Duration
|
||||
T.dither(amount: 30arcsec) // fine
|
||||
```
|
||||
|
||||
**Coordinate frames are types.** A pointing in ICRS is not interchangeable with one in AltAz. The checker tracks the frame.
|
||||
|
||||
**Resources have capabilities.** A telescope can slew and image. A dome can open and close. The checker knows what is callable on what.
|
||||
|
||||
**Failures unwind.** When tasks run in parallel and one fails, every successful sibling's rollback handler fires. No half-opened domes after a cooler failure.
|
||||
|
||||
**Programs are observable.** Every operation is recorded. You replay or stream the trace.
|
||||
|
||||
## What Nox is not
|
||||
|
||||
It is not a general-purpose language. There is no file IO, no network, no shelling out. It expresses observation logic. The runtime handles everything else.
|
||||
|
||||
It is not a hardware driver. Nox calls into Observatory's existing telescope and dome services. Those services talk to the metal.
|
||||
|
||||
It is not finished. Camera and focuser methods log without effect. Capability annotations are not yet a grammar feature. See the README for the current carry-forward list.
|
||||
|
||||
## Who should use it
|
||||
|
||||
You want to script observations and not write Python.
|
||||
You want a type checker to catch unit mistakes.
|
||||
You want safety policies that wake up on weather.
|
||||
You want your scripts to be readable a year later.
|
||||
|
||||
## What this book covers
|
||||
|
||||
The next chapter installs Nox and runs your first program. After that each chapter introduces one piece of the language. The cookbook chapter shows realistic recipes. Troubleshooting closes the book.
|
||||
|
||||
The companion reference documents every form, every type, and every endpoint.
|
||||
@@ -0,0 +1,72 @@
|
||||
# 2. Hello Nox
|
||||
|
||||
You write Nox in `.nox` files. You run them four ways. CLI for the shell. HTTP for automation. SSE for streaming. Browser console for interactive work.
|
||||
|
||||
## Your first program
|
||||
|
||||
Create `hello.nox`:
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
T.slew(M31)
|
||||
T.wait_until_settled()
|
||||
```
|
||||
|
||||
This binds a telescope named `Astra-1` to the local name `T`. Then it slews to M31 and waits.
|
||||
|
||||
`M31` is a builtin catalog name. It resolves to a `Coord<ICRS>` value.
|
||||
|
||||
## Running from the shell
|
||||
|
||||
Install the CLI globally or run it from the workspace.
|
||||
|
||||
```sh
|
||||
node /Users/paulhitt/Documents/workspace/observatory/nox/runtime/bin/nox.js check hello.nox
|
||||
node /Users/paulhitt/Documents/workspace/observatory/nox/runtime/bin/nox.js run hello.nox
|
||||
node /Users/paulhitt/Documents/workspace/observatory/nox/runtime/bin/nox.js ops hello.nox
|
||||
```
|
||||
|
||||
`check` reports type errors and exits 1 on any. `run` executes against the mock driver and prints the op count. `ops` prints each operation in order.
|
||||
|
||||
Output of `ops`:
|
||||
|
||||
```
|
||||
T:Astra-1 slew target=Coord<ICRS>(10.685, 41.269)
|
||||
T:Astra-1 wait_until_settled
|
||||
2 ops
|
||||
```
|
||||
|
||||
## Running from the browser
|
||||
|
||||
Open the Observatory app and navigate to `/nox`. Pick an example from the dropdown or paste your program. Click Run. Operations stream in as they execute. The gutter shows diagnostics live as you type.
|
||||
|
||||
The browser is the easiest place to learn. Errors update inline. The example list covers most language features.
|
||||
|
||||
## Running from HTTP
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:3000/api/nox/run \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"source": "use telescope T = \"Astra-1\"\nT.park()"}'
|
||||
```
|
||||
|
||||
The response is a JSON object with a `log` array. Each entry is an operation. Useful for automation and integration tests.
|
||||
|
||||
For long programs, use `/api/nox/run-stream`. It streams Server-Sent Events with each `op` and a final `done`.
|
||||
|
||||
## Picking a mode
|
||||
|
||||
The runtime has two modes. Mock and real.
|
||||
|
||||
Mock is the default. It does not talk to hardware. Every operation logs to the trace and resolves immediately. This is how you develop and test.
|
||||
|
||||
Real talks to Observatory's services. Slew actually moves the mount. Open actually opens the dome. Other operations still log without effect until corresponding services land.
|
||||
|
||||
In the browser, pick the mode in the toolbar. Over HTTP, pass `"mode": "real"` in the body.
|
||||
|
||||
## What just happened
|
||||
|
||||
The parser turned your text into an AST. The type checker validated it. The interpreter walked the AST and issued operations against a driver. The driver decided what to do with each.
|
||||
|
||||
You will use these four surfaces interchangeably. The next chapter introduces values and types.
|
||||
@@ -0,0 +1,133 @@
|
||||
# 3. Values and Types
|
||||
|
||||
Everything in Nox has a type. The type checker uses types to catch mistakes. The runtime uses tagged values so units and frames survive at runtime.
|
||||
|
||||
## Primitives
|
||||
|
||||
Four basic primitives.
|
||||
|
||||
```nox
|
||||
let count: Int = 5
|
||||
let ratio: Float = 1.5
|
||||
let label: String = "L"
|
||||
let active: Bool = true
|
||||
```
|
||||
|
||||
`Int` widens to `Float` implicitly. `Float` to `Int` does not.
|
||||
|
||||
## Quantities
|
||||
|
||||
A quantity is a number with a unit. Units belong to dimensions. Two quantities of the same dimension are commensurable. Two of different dimensions are not.
|
||||
|
||||
```nox
|
||||
let exp: Duration = 60s
|
||||
let dith: Angle = 10arcsec
|
||||
let cool: Temperature = -20degC
|
||||
let gust: Speed = 30kph
|
||||
let pos: Steps = 12000steps
|
||||
let hfr: Pixels = 2.5px
|
||||
```
|
||||
|
||||
Available unit suffixes:
|
||||
|
||||
| Dimension | Suffixes |
|
||||
| ----------- | ------------------------- |
|
||||
| Duration | `ms`, `s`, `min`, `h` |
|
||||
| Angle | `deg`, `arcmin`, `arcsec` |
|
||||
| Temperature | `degC` |
|
||||
| Speed | `mps`, `kph` |
|
||||
| Steps | `steps` |
|
||||
| Pixels | `px` |
|
||||
|
||||
Arithmetic rules:
|
||||
|
||||
```nox
|
||||
30s + 60s // 90 Duration
|
||||
30s + 2arcsec // error: mismatched dimensions
|
||||
2 * 30s // 60 Duration
|
||||
30s / 2 // 15 Duration
|
||||
```
|
||||
|
||||
Mixing units within a dimension is fine at the type level. Conversion happens at the I/O boundary.
|
||||
|
||||
## Percent
|
||||
|
||||
Percent is its own type. `20%` is `0.20` at runtime. Comparisons treat it as a fraction.
|
||||
|
||||
```nox
|
||||
let clouds_max: Percent = 20%
|
||||
```
|
||||
|
||||
## Coordinates
|
||||
|
||||
Coordinates carry a frame.
|
||||
|
||||
```nox
|
||||
let m31: Coord<ICRS> = M31
|
||||
let zenith: Coord<AltAz> = Coord<AltAz>(az: 0deg, alt: 90deg)
|
||||
```
|
||||
|
||||
Frames available: `ICRS`, `Topo`, `AltAz`, `Galactic`. A `Coord<ICRS>` is not assignable to a `Coord<AltAz>`. Conversions are explicit.
|
||||
|
||||
## Time
|
||||
|
||||
`Time` is a wall-clock instant. `now`, `sunset`, and `sunrise` are globals of type `Time`.
|
||||
|
||||
```nox
|
||||
let t = sunset + 30min
|
||||
if sunset.has_passed { halt }
|
||||
```
|
||||
|
||||
`Time + Duration -> Time` and `Time - Duration -> Time`.
|
||||
|
||||
## Containers
|
||||
|
||||
Lists, dicts, tuples. Homogeneous.
|
||||
|
||||
```nox
|
||||
let targets: [Coord<ICRS>] = [M31, M42]
|
||||
let plan: {String: (Duration, Int)} = { "L": (60s, 20), "R": (120s, 8) }
|
||||
let pair: (Steps, Pixels) = (12000steps, 2.5px)
|
||||
```
|
||||
|
||||
Empty list literals adopt the declared type:
|
||||
|
||||
```nox
|
||||
var samples: [(Steps, Pixels)] = []
|
||||
```
|
||||
|
||||
## Optional
|
||||
|
||||
`T?` means optional T. You cannot pass an `Optional<T>` where `T` is expected. Use a guard to narrow.
|
||||
|
||||
```nox
|
||||
let next = schedule.best_target(now) // Target?
|
||||
|
||||
if next? {
|
||||
T.slew(next) // here next is Target, not Target?
|
||||
}
|
||||
```
|
||||
|
||||
The `?` postfix is a presence test. Inside the guard, the checker narrows the binding to non-null. Without a guard, the call fails type checking.
|
||||
|
||||
## Resources
|
||||
|
||||
Resources are handles bound by `use`. Their type names are capitalized.
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1" // T: Telescope
|
||||
use dome D = "North" // D: Dome
|
||||
```
|
||||
|
||||
The string is a resource name resolved against your inventory at runtime.
|
||||
|
||||
## Pointable
|
||||
|
||||
Some methods accept either a `Coord` or a `Target` from the schedule. The union type is `Coord<ICRS> | Target`.
|
||||
|
||||
```nox
|
||||
T.slew(M31) // Coord
|
||||
T.slew(schedule.best_target(now)) // Target (after narrowing)
|
||||
```
|
||||
|
||||
The next chapter covers operators in depth.
|
||||
@@ -0,0 +1,124 @@
|
||||
# 4. Operators
|
||||
|
||||
Operators in Nox follow C-family precedence. The type checker watches dimensions on every operation.
|
||||
|
||||
## Arithmetic
|
||||
|
||||
`+`, `-`, `*`, `/`, `%` work on numbers and quantities.
|
||||
|
||||
```nox
|
||||
let a = 60s + 30s // 90 Duration
|
||||
let b = 2 * 30arcsec // 60 Angle
|
||||
let c = 100steps / 4 // 25 Steps
|
||||
let d = 10 % 3 // 1 Int
|
||||
```
|
||||
|
||||
Same-dimension addition and subtraction preserve the dimension. Scalar multiplication preserves the dimension. Division by a scalar preserves the dimension. Quantity-by-quantity multiplication is allowed but currently typed as `Any` since dimensional algebra is not yet modeled.
|
||||
|
||||
Time arithmetic special-cases Duration:
|
||||
|
||||
```nox
|
||||
sunset + 30min // Time
|
||||
sunset - 30min // Time
|
||||
```
|
||||
|
||||
## Comparison
|
||||
|
||||
`<`, `<=`, `>`, `>=`, `==`, `!=` produce `Bool`. Operands must be commensurable.
|
||||
|
||||
```nox
|
||||
weather.clouds < 20% // ok
|
||||
weather.wind > 30kph // ok
|
||||
weather.wind > 30s // error: cannot compare Speed and Duration
|
||||
```
|
||||
|
||||
## Logical
|
||||
|
||||
`and`, `or`, `not`. Short-circuiting.
|
||||
|
||||
```nox
|
||||
weather.is_clear and not sunset.has_passed
|
||||
```
|
||||
|
||||
`and` also drives narrowing. `if a? and b? { ... }` narrows both `a` and `b` inside the branch.
|
||||
|
||||
## Range
|
||||
|
||||
`..` builds a range value for `for`-loops. Step is optional. Step keyword goes after the range.
|
||||
|
||||
```nox
|
||||
for i in 0 .. 10 { ... }
|
||||
for ra in 150deg .. 210deg step 30arcmin { ... }
|
||||
```
|
||||
|
||||
Range endpoints must be commensurable. The interpreter guards against zero step and wrong-direction step.
|
||||
|
||||
## Member and call
|
||||
|
||||
`.` for member access. `(...)` for call. `[...]` for index. Postfix and chainable.
|
||||
|
||||
```nox
|
||||
T.filter_wheel.select("L")
|
||||
plan["L"][0]
|
||||
schedule.tonight().filter(t => t.altitude(now) > 30deg)
|
||||
```
|
||||
|
||||
Field names after `.` are not reserved words. You can access `T.camera` even though `camera` is contextually a resource kind elsewhere.
|
||||
|
||||
## Postfix `?`
|
||||
|
||||
A presence test on Optional. Returns `Bool`. Inside an `if` guard the checker narrows the operand to the non-null type.
|
||||
|
||||
```nox
|
||||
if next? { T.slew(next) }
|
||||
```
|
||||
|
||||
## Named arguments
|
||||
|
||||
Function calls accept named arguments. Mix freely with positional.
|
||||
|
||||
```nox
|
||||
T.expose(60s, filter: "L")
|
||||
T.dither(amount: 10arcsec, pattern: "spiral")
|
||||
```
|
||||
|
||||
Each parameter can be passed once. Missing required parameters are an error. Unknown parameter names are an error.
|
||||
|
||||
## Precedence summary
|
||||
|
||||
From tightest to loosest:
|
||||
|
||||
```
|
||||
postfix . [] () ?
|
||||
unary - + not
|
||||
multiplicative * / %
|
||||
additive + -
|
||||
range ..
|
||||
comparison < <= > >= == !=
|
||||
and
|
||||
or
|
||||
lambda =>
|
||||
after / before (time predicates)
|
||||
```
|
||||
|
||||
## Common mistakes
|
||||
|
||||
```nox
|
||||
T.expose(filter: "L", 60s)
|
||||
```
|
||||
|
||||
Named args can come before positional ones, but positional ones still fill slots in order. Be explicit.
|
||||
|
||||
```nox
|
||||
let step = 30arcmin / cos(0deg)
|
||||
```
|
||||
|
||||
`cos` returns `Float`. Quantity divided by `Float` stays a Quantity. Watch this when you expect the result to be a plain number.
|
||||
|
||||
```nox
|
||||
if maybe? and use_it { ... }
|
||||
```
|
||||
|
||||
This narrows `maybe` only when the whole condition is true. If `use_it` is false, the body does not run, so narrowing applies as expected.
|
||||
|
||||
The next chapter covers statements.
|
||||
@@ -0,0 +1,152 @@
|
||||
# 5. Statements and Control Flow
|
||||
|
||||
A Nox program is a sequence of statements. Statements have no value. Expressions do.
|
||||
|
||||
## Bindings
|
||||
|
||||
`let` is immutable. `var` is mutable. Both accept an optional type annotation.
|
||||
|
||||
```nox
|
||||
let exp = 60s
|
||||
let exp: Duration = 60s
|
||||
var count = 0
|
||||
```
|
||||
|
||||
You can reassign `var` with `=`, `+=`, `-=`, `*=`, `/=`.
|
||||
|
||||
```nox
|
||||
var n = 5
|
||||
n += 1
|
||||
```
|
||||
|
||||
## Blocks
|
||||
|
||||
Curly braces group statements. Blocks are required for control-flow bodies.
|
||||
|
||||
```nox
|
||||
if weather.is_clear {
|
||||
T.slew(M31)
|
||||
}
|
||||
```
|
||||
|
||||
The body is always a block. Single-statement-without-braces is not supported.
|
||||
|
||||
## If
|
||||
|
||||
```nox
|
||||
if cond { ... }
|
||||
if cond { ... } else { ... }
|
||||
if cond { ... } else if cond { ... } else { ... }
|
||||
```
|
||||
|
||||
The condition must be `Bool`. `if x?` narrows `x` to non-null in the then-branch.
|
||||
|
||||
## For
|
||||
|
||||
`for binding in iterable { body }`. The iterable is a list, range, or dict.
|
||||
|
||||
```nox
|
||||
for t in targets { T.slew(t) }
|
||||
for ra in 150deg .. 210deg step 1deg { ... }
|
||||
for (filter, count) in plan_entries { ... }
|
||||
```
|
||||
|
||||
For-bindings can destructure tuples. Use parentheses for nested patterns.
|
||||
|
||||
```nox
|
||||
for (filter, (exp, count)) in dict_of_tuples { ... }
|
||||
```
|
||||
|
||||
Bare multi-bindings work too.
|
||||
|
||||
```nox
|
||||
for filter, exp, count in target.requested_frames { ... }
|
||||
```
|
||||
|
||||
## Repeat
|
||||
|
||||
Run a body a fixed number of times.
|
||||
|
||||
```nox
|
||||
repeat 5 { T.expose(60s, filter: "L") }
|
||||
```
|
||||
|
||||
The count must be `Int`. Use `break` to exit and `continue` to skip.
|
||||
|
||||
## While
|
||||
|
||||
Loop as long as a condition holds.
|
||||
|
||||
```nox
|
||||
var i = 0
|
||||
while i < 10 {
|
||||
T.expose(60s, filter: "L")
|
||||
i += 1
|
||||
}
|
||||
```
|
||||
|
||||
The condition is re-tested before each iteration. `break` and `continue` work as expected. The runtime caps iterations at one million so an accidental forever-loop fails loudly rather than hanging.
|
||||
|
||||
## Assert
|
||||
|
||||
Aborts execution if the condition is false. The optional message becomes the error.
|
||||
|
||||
```nox
|
||||
assert D.is_closed(), "dome must be closed for panel flats"
|
||||
```
|
||||
|
||||
## Return / Yield / Halt
|
||||
|
||||
`return` exits a function with an optional value.
|
||||
|
||||
```nox
|
||||
fn f() -> Int { return 42 }
|
||||
```
|
||||
|
||||
`yield` is for cooperative scheduling. In the current runtime it evaluates the operand and continues.
|
||||
|
||||
`halt` stops the program gracefully. Use it inside policies or sessions for explicit termination.
|
||||
|
||||
## Break / Continue
|
||||
|
||||
Inside loops only.
|
||||
|
||||
```nox
|
||||
for t in targets {
|
||||
if not weather.is_safe() { break }
|
||||
T.slew(t)
|
||||
}
|
||||
```
|
||||
|
||||
## Expression statements
|
||||
|
||||
Any expression can stand as a statement. Most operations are this kind.
|
||||
|
||||
```nox
|
||||
T.slew(M31)
|
||||
T.expose(60s, filter: "L")
|
||||
some_pure_function(42)
|
||||
```
|
||||
|
||||
## Semicolons
|
||||
|
||||
Optional. You may use them to put two statements on one line.
|
||||
|
||||
```nox
|
||||
T.park(); D.close()
|
||||
```
|
||||
|
||||
## Scoping
|
||||
|
||||
Each block opens a new scope. Names defined inside a block are not visible outside it.
|
||||
|
||||
```nox
|
||||
{
|
||||
let temp = 5
|
||||
}
|
||||
// temp is unbound here
|
||||
```
|
||||
|
||||
Top-level `use`, `let`, `fn`, and `var` are visible across the whole module. Inside a `session`, `use` and `fn` are hoisted so safety handlers can refer to them regardless of textual order.
|
||||
|
||||
Next chapter: functions and lambdas.
|
||||
@@ -0,0 +1,125 @@
|
||||
# 6. Functions and Lambdas
|
||||
|
||||
Functions package logic. They take named typed parameters and return a value.
|
||||
|
||||
## Declarations
|
||||
|
||||
```nox
|
||||
fn measure_hfr(exp: Duration) -> Pixels {
|
||||
let img = T.expose(exp, filter: "L")
|
||||
return img.hfr()
|
||||
}
|
||||
```
|
||||
|
||||
The return type is optional. If omitted the function returns `Void`. Parameter types are mandatory. The body is always a block.
|
||||
|
||||
Functions are hoisted at the top level. You can call a function defined later in the file. Inside a session, functions hoist too.
|
||||
|
||||
## Default values
|
||||
|
||||
Optional parameters carry a default and can be omitted at call sites.
|
||||
|
||||
```nox
|
||||
fn cooldown(target: Temperature, timeout: Duration = 5min) { ... }
|
||||
|
||||
cooldown(-20degC)
|
||||
cooldown(-20degC, timeout: 10min)
|
||||
```
|
||||
|
||||
This syntax is in the grammar but not currently exposed on builtin methods. User-defined functions can use it.
|
||||
|
||||
## Named arguments
|
||||
|
||||
Callers may pass arguments by name. Position still works.
|
||||
|
||||
```nox
|
||||
fn focus(method: String, max_age: Duration) { ... }
|
||||
|
||||
focus("v-curve", 10min)
|
||||
focus(method: "v-curve", max_age: 10min)
|
||||
focus(max_age: 10min, method: "v-curve") // out of order is fine when named
|
||||
```
|
||||
|
||||
## Closures
|
||||
|
||||
Functions capture the enclosing scope. References resolve outward through the chain.
|
||||
|
||||
```nox
|
||||
let base_exp = 60s
|
||||
fn shoot() { T.expose(base_exp, filter: "L") }
|
||||
```
|
||||
|
||||
## Lambdas
|
||||
|
||||
Anonymous functions for inline use.
|
||||
|
||||
```nox
|
||||
let bright = targets.filter(t => t.altitude(now) > 30deg)
|
||||
```
|
||||
|
||||
The body of a lambda is one expression. To run multiple statements use a `do` block.
|
||||
|
||||
```nox
|
||||
let coords = targets.map(t => do {
|
||||
T.slew(t)
|
||||
return t.position
|
||||
})
|
||||
```
|
||||
|
||||
`do { ... }` lets a lambda hold a statement body. The block does not collide with dict literals because the leading `do` is explicit.
|
||||
|
||||
## Returning from lambdas
|
||||
|
||||
Inside a `do` block, `return` returns from the lambda.
|
||||
|
||||
```nox
|
||||
plan.map(t => do {
|
||||
if not weather.is_safe() { return null }
|
||||
return T.expose(60s, filter: "L")
|
||||
})
|
||||
```
|
||||
|
||||
## Currying and partial application
|
||||
|
||||
Not supported. Wrap a closure if you need it.
|
||||
|
||||
```nox
|
||||
fn fixed_filter(filter: String) -> Fn {
|
||||
return exp => T.expose(exp, filter: filter)
|
||||
}
|
||||
```
|
||||
|
||||
## Function values
|
||||
|
||||
You can store and pass functions around like any other value.
|
||||
|
||||
```nox
|
||||
let shooters: [Fn] = [shoot_l, shoot_r, shoot_g, shoot_b]
|
||||
for f in shooters { f() }
|
||||
```
|
||||
|
||||
Function types use the same arrow syntax as the return clause.
|
||||
|
||||
## Subtyping
|
||||
|
||||
Function types are contravariant in parameters and covariant in return. A function expecting `Target` accepts a function from `Any`. A function returning `Coord<ICRS>` accepts a function returning `Coord` of any narrower frame.
|
||||
|
||||
This rule lets lambdas with inferred `Any` parameters be passed to typed callers without a cast.
|
||||
|
||||
## A working example
|
||||
|
||||
```nox
|
||||
fn v_curve_focus(center: Steps, span: Steps, step_size: Steps) -> Steps {
|
||||
var samples: [(Steps, Pixels)] = []
|
||||
for pos in (center - span) .. (center + span) step step_size {
|
||||
T.focuser.move_to(pos)
|
||||
samples.push((pos, measure_hfr(5s)))
|
||||
}
|
||||
return parabola_min(samples)
|
||||
}
|
||||
|
||||
let best = v_curve_focus(center: 12000steps, span: 500steps, step_size: 50steps)
|
||||
T.focuser.move_to(best)
|
||||
```
|
||||
|
||||
Next chapter: resources and sessions.
|
||||
@@ -0,0 +1,106 @@
|
||||
# 7. Resources and Sessions
|
||||
|
||||
Resources are hardware handles. Sessions group related work with explicit requirements and safety handlers.
|
||||
|
||||
## Resource kinds
|
||||
|
||||
Five kinds. Telescope, dome, camera, filter_wheel, focuser. You declare a resource with `use`.
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
```
|
||||
|
||||
The right-hand side is a string. The runtime resolves the string against your inventory. Telescopes and domes are top-level entities. Cameras, filter wheels, and focusers live under a telescope and are accessed by member.
|
||||
|
||||
```nox
|
||||
T.camera.shutter("closed")
|
||||
T.filter_wheel.select("L")
|
||||
T.focuser.move_to(12000steps)
|
||||
```
|
||||
|
||||
## Method tables
|
||||
|
||||
Each resource exposes a fixed set of methods. See the API reference for the full list. Typed signatures mean wrong-unit arguments are caught at edit time.
|
||||
|
||||
```nox
|
||||
T.slew(M31) // Pointable
|
||||
T.expose(60s, filter: "L") // Duration + String
|
||||
T.dither(10arcsec) // Angle
|
||||
T.cooldown(target: -20degC, timeout: 5min)
|
||||
```
|
||||
|
||||
## Sessions
|
||||
|
||||
A `session` block scopes resources, requirements, and safety handlers under a single label.
|
||||
|
||||
```nox
|
||||
session "spring-galaxies" {
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
// body
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
T.slew(M31)
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
```
|
||||
|
||||
Sessions hoist their `use` and `fn` declarations. Safety handlers above the body can reference resources declared below.
|
||||
|
||||
## requires
|
||||
|
||||
Declare environmental and resource requirements up front. Each item is a context with predicates.
|
||||
|
||||
```nox
|
||||
session "x" {
|
||||
requires
|
||||
telescope("Astra-1"),
|
||||
dome("North"),
|
||||
weather(clouds < 20%, humidity < 80%, wind < 30kph),
|
||||
time(after sunset + 30min, before sunrise - 30min)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Each context provides an implicit scope. Inside `weather(...)` the names `clouds`, `humidity`, `wind`, and `is_clear` resolve against the weather struct. Inside `time(...)` you can use `after` and `before` as prefix operators on Time expressions.
|
||||
|
||||
The type checker validates the predicate types. The runtime registrar reads them when sessions start. The current runtime does not yet evaluate them on a loop.
|
||||
|
||||
## safety on
|
||||
|
||||
Register a handler that fires when an event or predicate triggers.
|
||||
|
||||
```nox
|
||||
safety on cloud { rollback() }
|
||||
safety on wind > 50kph { rollback() }
|
||||
safety on power_loss { T.park(); D.close() }
|
||||
```
|
||||
|
||||
The trigger is either a symbolic event name or a predicate expression. Event names are recognized as bare identifiers and resolved by the runtime. Predicate expressions are type-checked against the weather context plus the symbolic events.
|
||||
|
||||
`rollback()` is a builtin that parks the telescope, closes the dome, and marks the session aborted.
|
||||
|
||||
## Sessions over time
|
||||
|
||||
Sessions are the unit of work for a night. They reference your scheduling and proposal tables. The HTTP and SSE routes accept a session block as the program body.
|
||||
|
||||
Sessions can have local functions:
|
||||
|
||||
```nox
|
||||
session "deep-field" {
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
fn shoot(target: Coord<ICRS>, filter: String, n: Int) {
|
||||
T.slew(target)
|
||||
repeat n { T.expose(120s, filter: filter) }
|
||||
}
|
||||
|
||||
shoot(M31, "L", 20)
|
||||
shoot(M51, "R", 8)
|
||||
}
|
||||
```
|
||||
|
||||
Next chapter: parallel and rollback.
|
||||
@@ -0,0 +1,92 @@
|
||||
# 8. Parallel and Rollback
|
||||
|
||||
Some operations run independently. Some operations must undo on failure. Nox handles both with `parallel` and `on rollback`.
|
||||
|
||||
## Parallel
|
||||
|
||||
`parallel { ... }` runs its children concurrently. The block finishes when all children finish.
|
||||
|
||||
```nox
|
||||
parallel {
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
}
|
||||
```
|
||||
|
||||
Both operations start at once. Control resumes after the slowest finishes. Each child runs in its own scope. Failures in one do not silently leave the others mid-flight.
|
||||
|
||||
## Tasks
|
||||
|
||||
Inside a parallel block, you can label each unit with `task`. Tasks let you attach rollback handlers.
|
||||
|
||||
```nox
|
||||
parallel {
|
||||
task open_dome {
|
||||
D.open()
|
||||
on rollback { D.close() }
|
||||
}
|
||||
task cool_camera {
|
||||
T.cooldown(target: -20degC, timeout: 5min)
|
||||
on rollback { T.warm_up() }
|
||||
}
|
||||
task home_mount {
|
||||
T.home()
|
||||
on rollback { T.park() }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each task body runs sequentially. The `on rollback` statement registers a handler. The handler runs only if any sibling task fails.
|
||||
|
||||
## Rollback semantics
|
||||
|
||||
When any task in a parallel block rejects, every collected rollback handler fires. Handlers fire in reverse registration order. After all handlers complete, the original failure is re-raised.
|
||||
|
||||
A handler runs in the scope where it was registered. It can refer to local variables. Errors thrown inside a handler are swallowed so one bad handler does not block the rest.
|
||||
|
||||
## Failure propagation
|
||||
|
||||
A task can fail in three ways. An `assert` with a false condition. An explicit thrown error from a function. A type-checked runtime failure such as a missing required argument.
|
||||
|
||||
`halt` is different. It stops the program gracefully. It does not trigger rollback in the current runtime.
|
||||
|
||||
## When to use parallel
|
||||
|
||||
Use it when operations are independent and slow. Cooling a camera and opening a dome are classic. Both take time. Both can fail. Running them sequentially wastes minutes per session.
|
||||
|
||||
Use sequential code for ordered operations like slew then focus then expose. Parallel inside that would just add complexity.
|
||||
|
||||
## On-rollback outside parallel
|
||||
|
||||
If you put `on rollback { ... }` outside a parallel block, it is a no-op. The handler list it would register to does not exist. The grammar accepts it for forward compatibility with future session-level rollback.
|
||||
|
||||
## Worked example
|
||||
|
||||
```nox
|
||||
session "night" {
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
parallel {
|
||||
task open {
|
||||
D.open()
|
||||
on rollback { D.close() }
|
||||
}
|
||||
task cool {
|
||||
T.cooldown(target: -20degC)
|
||||
on rollback { T.warm_up() }
|
||||
}
|
||||
}
|
||||
|
||||
// If we got here, both succeeded. Continue.
|
||||
T.slew(M31)
|
||||
repeat 20 { T.expose(60s, filter: "L") }
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
```
|
||||
|
||||
If `cool` times out, the runtime closes the dome before propagating the failure. You never end the night with the dome open and the camera warm.
|
||||
|
||||
Next chapter: policies.
|
||||
@@ -0,0 +1,88 @@
|
||||
# 9. Policies
|
||||
|
||||
Sessions describe what to do. Policies describe how to react. A policy is a long-running set of rules that fire on conditions.
|
||||
|
||||
## Shape
|
||||
|
||||
```nox
|
||||
policy "opportunistic" {
|
||||
when sunset.has_passed and weather.is_clear {
|
||||
parallel { D.open(); T.cooldown(-20degC) }
|
||||
}
|
||||
|
||||
when weather.clouds > 30% or weather.wind > 40kph {
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
|
||||
when sunrise - 30min reached {
|
||||
T.park()
|
||||
D.close()
|
||||
halt
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each `when` rule has a condition and a body. The runtime evaluates each condition on every tick.
|
||||
|
||||
## Edge-triggered
|
||||
|
||||
Rules fire only when their condition transitions from false to true. A condition that stays true ticks past without re-firing. A condition that stays false also does nothing.
|
||||
|
||||
This matters. You do not want `weather.clouds > 30%` to call `park()` ten times a second. You want it to fire once when clouds appear.
|
||||
|
||||
The first tick treats every previous value as false. Any rule whose condition is true at startup fires once.
|
||||
|
||||
## Ticks
|
||||
|
||||
The runtime accepts `policy: { ticks, intervalMs }` options. Default `ticks=1, intervalMs=0`. Higher values run the policy as a daemon.
|
||||
|
||||
```sh
|
||||
curl -X POST http://localhost:3000/api/nox/run \
|
||||
-d '{"source": "...", "policy": {"ticks": 600, "intervalMs": 1000}}'
|
||||
```
|
||||
|
||||
This runs the policy for ten minutes at one-second resolution.
|
||||
|
||||
For real deployments, the daemon mode wraps a longer loop. The interpreter is async so each tick yields control.
|
||||
|
||||
## The `reached` keyword
|
||||
|
||||
A condition that names a Time value can use `reached` as a hint. The runtime treats it as a transition predicate against the wall clock.
|
||||
|
||||
```nox
|
||||
when sunrise - 30min reached { ... }
|
||||
```
|
||||
|
||||
Without `reached`, the condition is evaluated as a boolean each tick. `reached` makes the intent explicit and reads better.
|
||||
|
||||
## Halt
|
||||
|
||||
`halt` inside a policy body stops the daemon. Use it for sentinels like "after sunrise, we are done".
|
||||
|
||||
```nox
|
||||
when sunrise reached { T.park(); D.close(); halt }
|
||||
```
|
||||
|
||||
## Inside vs outside sessions
|
||||
|
||||
A policy is a top-level form, like a session. They can appear in the same file. The runtime currently processes top-level forms in order.
|
||||
|
||||
A typical real-world setup runs a session for the planned observations and a separate policy daemon for the safety reactions. The two share resource bindings.
|
||||
|
||||
## Worked example
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
policy "weather-watch" {
|
||||
when weather.clouds > 40% { T.park(); D.close() }
|
||||
when weather.wind > 50kph { T.park(); D.close() }
|
||||
when weather.clouds < 20% and not D.is_closed() { D.open() }
|
||||
}
|
||||
```
|
||||
|
||||
This daemon flips the dome and telescope based on weather. Run it alongside any session.
|
||||
|
||||
Next chapter: the cookbook.
|
||||
@@ -0,0 +1,206 @@
|
||||
# 10. Cookbook
|
||||
|
||||
Real recipes you can adapt. Each one builds on earlier chapters.
|
||||
|
||||
## Target list with dithering
|
||||
|
||||
```nox
|
||||
import { M31, M42, M51, M81, M101 } from "catalog/messier"
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
let targets = [M31, M42, M51, M81, M101]
|
||||
let exposure = 60s
|
||||
let frames = 5
|
||||
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
|
||||
for target in targets {
|
||||
T.slew(target)
|
||||
T.focus(method: "v-curve")
|
||||
repeat frames {
|
||||
T.expose(exposure, filter: "L")
|
||||
T.dither(10arcsec)
|
||||
}
|
||||
}
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
```
|
||||
|
||||
## V-curve autofocus
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
fn measure_hfr(exp: Duration) -> Pixels {
|
||||
let img = T.expose(exp, filter: "L")
|
||||
return img.hfr()
|
||||
}
|
||||
|
||||
fn v_curve_focus(center: Steps, span: Steps, step_size: Steps) -> Steps {
|
||||
var samples: [(Steps, Pixels)] = []
|
||||
for pos in (center - span) .. (center + span) step step_size {
|
||||
T.focuser.move_to(pos)
|
||||
samples.push((pos, measure_hfr(5s)))
|
||||
}
|
||||
return parabola_min(samples)
|
||||
}
|
||||
|
||||
let best = v_curve_focus(center: 12000steps, span: 500steps, step_size: 50steps)
|
||||
T.focuser.move_to(best)
|
||||
```
|
||||
|
||||
## LRGB sequence per filter
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
let plan: {String: (Duration, Int)} = {
|
||||
"L": (60s, 20),
|
||||
"R": (120s, 8),
|
||||
"G": (120s, 8),
|
||||
"B": (120s, 8),
|
||||
}
|
||||
|
||||
T.slew(NGC_7000)
|
||||
T.focus(method: "v-curve")
|
||||
|
||||
for (filter, (exp, count)) in plan {
|
||||
T.filter_wheel.select(filter)
|
||||
repeat count {
|
||||
T.expose(exp, filter: filter)
|
||||
T.dither(amount: 10arcsec, pattern: "spiral")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Bias, dark, flat calibration
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
@calibration(kind: "bias")
|
||||
fn bias_frames(n: Int) {
|
||||
T.camera.shutter("closed")
|
||||
repeat n { T.expose(0s, filter: "dark") }
|
||||
}
|
||||
|
||||
@calibration(kind: "dark")
|
||||
fn dark_frames(n: Int, exp: Duration) {
|
||||
T.camera.shutter("closed")
|
||||
repeat n { T.expose(exp, filter: "dark") }
|
||||
}
|
||||
|
||||
@calibration(kind: "flat")
|
||||
fn flat_frames(n: Int, filter: String) {
|
||||
assert D.is_closed(), "dome must be closed for panel flats"
|
||||
D.flat_panel.on(brightness: 50%)
|
||||
T.camera.shutter("open")
|
||||
repeat n { T.expose(T.auto_flat_exposure(filter), filter: filter) }
|
||||
D.flat_panel.off()
|
||||
}
|
||||
|
||||
bias_frames(50)
|
||||
dark_frames(20, 60s)
|
||||
dark_frames(20, 300s)
|
||||
for f in ["L", "R", "G", "B"] { flat_frames(20, filter: f) }
|
||||
```
|
||||
|
||||
## Survey a declination strip
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
let fov = 30arcmin
|
||||
let overlap = 10%
|
||||
|
||||
fn strip(dec: Angle, ra_start: Angle, ra_end: Angle) -> [Coord<ICRS>] {
|
||||
let step = fov * (1 - overlap)
|
||||
var tiles: [Coord<ICRS>] = []
|
||||
for ra in ra_start .. ra_end step step / cos(dec) {
|
||||
tiles.push(Coord<ICRS>(ra: ra, dec: dec))
|
||||
}
|
||||
return tiles
|
||||
}
|
||||
|
||||
let tiles = strip(dec: +30deg, ra_start: 150deg, ra_end: 210deg)
|
||||
|
||||
for tile in tiles {
|
||||
T.slew(tile)
|
||||
T.expose(120s, filter: "L")
|
||||
}
|
||||
```
|
||||
|
||||
## Unattended night with safety
|
||||
|
||||
```nox
|
||||
session "spring-galaxies" {
|
||||
requires
|
||||
telescope("Astra-1"),
|
||||
dome("North"),
|
||||
weather(clouds < 20%, humidity < 80%, wind < 30kph),
|
||||
time(after sunset + 30min, before sunrise - 30min)
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
safety on cloud { rollback() }
|
||||
safety on wind > 50kph { rollback() }
|
||||
safety on power_loss { T.park(); D.close() }
|
||||
|
||||
parallel {
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
}
|
||||
|
||||
let plan = schedule.tonight()
|
||||
.filter(t => t.altitude(now) > 30deg)
|
||||
.sort_by(t => -t.altitude(now))
|
||||
|
||||
for target in plan {
|
||||
if not weather.is_safe() { yield 5min; continue }
|
||||
|
||||
T.slew(target)
|
||||
T.focus_if_needed(max_age: 30min, temp_delta: 1degC)
|
||||
|
||||
for filter, exp, count in target.requested_frames {
|
||||
T.filter_wheel.select(filter)
|
||||
repeat count {
|
||||
T.expose(exp, filter: filter)
|
||||
T.dither(10arcsec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
```
|
||||
|
||||
## Weather-driven daemon
|
||||
|
||||
```nox
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
policy "weather-watch" {
|
||||
when sunset.has_passed and weather.is_clear {
|
||||
parallel { D.open(); T.cooldown(-20degC) }
|
||||
}
|
||||
when weather.clouds > 30% or weather.wind > 40kph {
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
when sunrise - 30min reached {
|
||||
T.park()
|
||||
D.close()
|
||||
halt
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Next chapter: troubleshooting.
|
||||
@@ -0,0 +1,164 @@
|
||||
# 11. Troubleshooting
|
||||
|
||||
Common errors with concrete fixes.
|
||||
|
||||
## Type mismatch on unit
|
||||
|
||||
```
|
||||
arg 1 (amount): expected Angle, got Duration
|
||||
```
|
||||
|
||||
You passed a Duration where an Angle was expected. Check the unit suffix.
|
||||
|
||||
```nox
|
||||
T.dither(amount: 30s) // wrong, 30s is Duration
|
||||
T.dither(amount: 30arcsec) // right
|
||||
```
|
||||
|
||||
## Cannot compare dimensions
|
||||
|
||||
```
|
||||
cannot compare Speed < Duration
|
||||
```
|
||||
|
||||
You compared two quantities of different dimensions. Match dimensions on both sides.
|
||||
|
||||
```nox
|
||||
weather.wind < 30s // wrong
|
||||
weather.wind < 30kph // right
|
||||
```
|
||||
|
||||
## Unknown identifier
|
||||
|
||||
```
|
||||
unknown identifier: clouds
|
||||
```
|
||||
|
||||
You referenced a name that is not in scope. Check spelling and check that the context provider is active.
|
||||
|
||||
```nox
|
||||
if clouds < 20% { ... } // wrong, clouds is not global
|
||||
if weather.clouds < 0.2 { ... } // right
|
||||
requires weather(clouds < 20%) // right, weather context provides clouds
|
||||
```
|
||||
|
||||
## Missing required argument
|
||||
|
||||
```
|
||||
missing argument: filter
|
||||
```
|
||||
|
||||
You omitted a required parameter. Pass it by name or position.
|
||||
|
||||
```nox
|
||||
T.expose(60s) // wrong
|
||||
T.expose(60s, filter: "L") // right
|
||||
```
|
||||
|
||||
## Unknown frame
|
||||
|
||||
```
|
||||
unknown frame: Lunar
|
||||
```
|
||||
|
||||
You used a coordinate frame that does not exist. Valid frames are `ICRS`, `Topo`, `AltAz`, `Galactic`.
|
||||
|
||||
## If condition not Bool
|
||||
|
||||
```
|
||||
if condition must be Bool, got Any
|
||||
```
|
||||
|
||||
The condition does not type-check as a boolean. Wrap it in a comparison or use a predicate.
|
||||
|
||||
```nox
|
||||
if T.expose(60s, filter: "L") { ... } // wrong, expose returns Image
|
||||
if T.is_idle { ... } // right
|
||||
```
|
||||
|
||||
## Repeat count not Int
|
||||
|
||||
```
|
||||
repeat count must be Int, got Duration
|
||||
```
|
||||
|
||||
`repeat` takes an integer. Use the right kind of value.
|
||||
|
||||
```nox
|
||||
repeat 60s { ... } // wrong
|
||||
repeat 5 { ... } // right
|
||||
```
|
||||
|
||||
## Unguarded Optional
|
||||
|
||||
```
|
||||
expected Coord<ICRS> | Target, got Target?
|
||||
```
|
||||
|
||||
You passed a possibly-null value where a non-null is required. Guard with `?`.
|
||||
|
||||
```nox
|
||||
T.slew(schedule.best_target(now)) // wrong, best_target returns Target?
|
||||
let next = schedule.best_target(now)
|
||||
if next? {
|
||||
T.slew(next) // right, next is narrowed to Target
|
||||
}
|
||||
```
|
||||
|
||||
## Range went the wrong way
|
||||
|
||||
```
|
||||
range 150..210 with negative step -31
|
||||
```
|
||||
|
||||
Your step is negative but the range increases. Check your math. Common cause: `1 - 10%` evaluates to `0.9`, not `-9`, but if you mistakenly write `10 - 1%` it becomes `9.99`. Use parentheses if unsure.
|
||||
|
||||
## List elements mismatched
|
||||
|
||||
```
|
||||
list elements have mismatched types: Int vs String
|
||||
```
|
||||
|
||||
A list literal mixed types. Lists are homogeneous. Use a tuple or split into multiple lists.
|
||||
|
||||
## Cannot iterate
|
||||
|
||||
```
|
||||
cannot iterate over Image
|
||||
```
|
||||
|
||||
You tried to iterate something that is not a list, range, or dict. Methods like `.filter` produce lists. `T.expose(...)` produces an `Image`. Apply iteration to the right value.
|
||||
|
||||
## Lambda parameter type unclear
|
||||
|
||||
When a lambda is passed to a function with a known parameter type, the lambda parameter inherits that type. If you see the lambda being inferred as `Fn<Any>` and the call rejecting it, check that the receiving method has a properly typed parameter.
|
||||
|
||||
## Runtime: not callable
|
||||
|
||||
```
|
||||
not callable: 60Duration
|
||||
```
|
||||
|
||||
You tried to call a value that is not a function. Check the spelling and the type.
|
||||
|
||||
## Runtime: cannot iterate
|
||||
|
||||
```
|
||||
cannot iterate: <Image filter="L">
|
||||
```
|
||||
|
||||
Same as the type-checker error but caught at runtime. Often means you called something that returned a non-iterable when you expected a list.
|
||||
|
||||
## Range step cannot be zero
|
||||
|
||||
```
|
||||
range step cannot be zero
|
||||
```
|
||||
|
||||
A step of zero would loop forever. Compute the step from the loop range before passing.
|
||||
|
||||
## Where to get help
|
||||
|
||||
The browser console at `/nox` shows live type checking. Diagnostics appear inline. Use the example dropdown to see working programs. The CLI `parse` command dumps the AST as JSON for debugging.
|
||||
|
||||
The reference documents every form. The cookbook shows realistic recipes. Read them together.
|
||||
@@ -0,0 +1,147 @@
|
||||
# Builtins Reference
|
||||
|
||||
Source: [builtins.js](../../parser/src/builtins.js).
|
||||
|
||||
## Global identifiers
|
||||
|
||||
| Name | Type | Notes |
|
||||
| ----------- | ----------- | -------------------------------------- |
|
||||
| `now` | `Time` | Wall-clock instant when read. |
|
||||
| `sunset` | `Time` | Today's sunset. |
|
||||
| `sunrise` | `Time` | Tomorrow's sunrise. |
|
||||
| `weather` | `Weather` | Weather struct (see below). |
|
||||
| `schedule` | `Schedule` | Scheduling struct. |
|
||||
| `cos(Angle)` | `Float` | Cosine. Angle argument required. |
|
||||
| `sin(Angle)` | `Float` | Sine. |
|
||||
| `parabola_min(samples)` | `Steps` | Parabolic fit minimum. Samples: `[(Steps, Pixels)]`. |
|
||||
| `rollback()` | `Void` | Triggers session rollback. |
|
||||
| `halt()` | `Void` | Halts the program. |
|
||||
|
||||
## Catalog identifiers
|
||||
|
||||
Built into module scope:
|
||||
|
||||
```
|
||||
M31 M42 M51 M81 M101 NGC_7000 // all Coord<ICRS>
|
||||
```
|
||||
|
||||
Imported via `import { ... } from "catalog/messier"` and `"catalog/ngc"`. Additional catalogs may be loaded by dropping JSON files into `nox/runtime/catalogs/<name>.json`.
|
||||
|
||||
## Weather struct
|
||||
|
||||
| Member | Type |
|
||||
| ------------ | ---------- |
|
||||
| `clouds` | `Percent` |
|
||||
| `humidity` | `Percent` |
|
||||
| `wind` | `Speed` |
|
||||
| `is_clear` | `Bool` |
|
||||
| `is_safe()` | `Bool` |
|
||||
|
||||
Inside a `requires weather(...)` or `safety on ...` predicate, these names are brought into scope as bare identifiers via the implicit-context resolver.
|
||||
|
||||
## Schedule struct
|
||||
|
||||
| Member | Type |
|
||||
| ---------------------------- | -------------- |
|
||||
| `tonight()` | `[Target]` |
|
||||
| `best_target(t: Time)` | `Target?` |
|
||||
|
||||
## Target struct
|
||||
|
||||
| Member | Type |
|
||||
| --------------------- | --------------------------------- |
|
||||
| `requested_frames` | `[(String, Duration, Int)]` |
|
||||
| `altitude(t: Time)` | `Angle` |
|
||||
|
||||
## Telescope methods
|
||||
|
||||
| Method | Returns | Notes |
|
||||
| ----------------------------------------------- | ------- | ------------------------------------ |
|
||||
| `slew(target: Coord<ICRS> \| Target)` | `Void` | Slews to a Pointable. |
|
||||
| `park()` | `Void` | |
|
||||
| `home()` | `Void` | |
|
||||
| `wait_until_settled()` | `Void` | Blocks until slew settles. |
|
||||
| `cooldown(target: Temperature, timeout?: Duration)` | `Void` | Cool the camera. |
|
||||
| `warm_up()` | `Void` | |
|
||||
| `expose(exp: Duration, filter: String)` | `Image` | Returns the captured frame. |
|
||||
| `focus(method: String)` | `Void` | |
|
||||
| `focus_if_needed(max_age?: Duration, temp_delta?: Temperature)` | `Void` | |
|
||||
| `dither(amount: Angle, pattern?: String)` | `Void` | |
|
||||
| `auto_flat_exposure(filter: String)` | `Duration` | Suggested flat-frame exposure. |
|
||||
| `is_idle` | `Bool` | Property, not a method. |
|
||||
| `filter_wheel` | `FilterWheel` | Nested resource. |
|
||||
| `focuser` | `Focuser` | |
|
||||
| `camera` | `Camera` | |
|
||||
|
||||
## Dome methods
|
||||
|
||||
| Method | Returns | Notes |
|
||||
| ---------------------------- | ------- | ----- |
|
||||
| `open()` | `Void` | |
|
||||
| `close()` | `Void` | |
|
||||
| `is_closed()` | `Bool` | |
|
||||
| `flat_panel` | `FlatPanel` | Nested resource. |
|
||||
|
||||
## Camera methods
|
||||
|
||||
| Method | Returns |
|
||||
| ---------------------------- | ------- |
|
||||
| `shutter(state: String)` | `Void` |
|
||||
|
||||
## FilterWheel methods
|
||||
|
||||
| Method | Returns |
|
||||
| ---------------------------- | ------- |
|
||||
| `select(filter: String)` | `Void` |
|
||||
|
||||
## Focuser methods
|
||||
|
||||
| Method | Returns |
|
||||
| ---------------------------- | ------- |
|
||||
| `move_to(pos: Steps)` | `Void` |
|
||||
|
||||
## FlatPanel methods
|
||||
|
||||
| Method | Returns |
|
||||
| ----------------------------------- | ------- |
|
||||
| `on(brightness: Percent)` | `Void` |
|
||||
| `off()` | `Void` |
|
||||
|
||||
## Image methods
|
||||
|
||||
| Method | Returns |
|
||||
| -------- | -------- |
|
||||
| `hfr()` | `Pixels` |
|
||||
|
||||
## List methods
|
||||
|
||||
These exist on every `List<T>`.
|
||||
|
||||
| Method | Returns |
|
||||
| --------------------------------------- | -------- |
|
||||
| `length()` | `Int` |
|
||||
| `push(item: T)` | `Void` |
|
||||
| `filter(pred: (T) -> Bool)` | `List<T>` |
|
||||
| `map(fn: (T) -> Any)` | `List<Any>` |
|
||||
| `sort_by(key: (T) -> Any)` | `List<T>` |
|
||||
|
||||
## Time fields
|
||||
|
||||
| Field | Type |
|
||||
| ------------ | ------ |
|
||||
| `has_passed` | `Bool` |
|
||||
|
||||
Arithmetic on Time:
|
||||
|
||||
```
|
||||
Time + Duration -> Time
|
||||
Time - Duration -> Time
|
||||
```
|
||||
|
||||
## Modules
|
||||
|
||||
| Module path | Names provided |
|
||||
| --------------------- | --------------------- |
|
||||
| `catalog/messier` | `M31`, `M42`, `M51`, `M81`, `M101` |
|
||||
| `catalog/ngc` | (fallback to JSON file) |
|
||||
| `catalog/<anything>` | Any imported name resolves as `Coord<ICRS>` at the type level. The runtime returns the corresponding entry from `catalogs/<name>.json` if present, or fails the import. |
|
||||
@@ -0,0 +1,97 @@
|
||||
# CLI Reference
|
||||
|
||||
The `nox` CLI ships as the `bin` of the `nox-runtime` package. Source: [bin/nox.js](../../runtime/bin/nox.js).
|
||||
|
||||
## Invocation
|
||||
|
||||
```sh
|
||||
node nox/runtime/bin/nox.js <command> <file>
|
||||
```
|
||||
|
||||
Or, once installed globally:
|
||||
|
||||
```sh
|
||||
nox <command> <file>
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
### `nox check <file>`
|
||||
|
||||
Type-check the file. Prints `clean` and exits 0 on success. Prints diagnostics and exits 1 if any are found.
|
||||
|
||||
```sh
|
||||
$ nox check program.nox
|
||||
clean
|
||||
|
||||
$ nox check broken.nox
|
||||
3:7 arg 1 (amount): expected Angle, got Duration
|
||||
```
|
||||
|
||||
### `nox run <file>`
|
||||
|
||||
Type-check, then execute against the mock driver. Prints a summary like `42 ops`. Exits 0 on success. Exits 1 if check fails, 3 if the program throws at runtime.
|
||||
|
||||
```sh
|
||||
$ nox run program.nox
|
||||
2 ops
|
||||
```
|
||||
|
||||
### `nox ops <file>`
|
||||
|
||||
Same as `run`, but prints each operation as it executes.
|
||||
|
||||
```sh
|
||||
$ nox ops program.nox
|
||||
T:Astra-1 slew target=Coord<ICRS>(10.685, 41.269)
|
||||
T:Astra-1 wait_until_settled
|
||||
2 ops
|
||||
```
|
||||
|
||||
### `nox parse <file>`
|
||||
|
||||
Parse the file and dump the AST as JSON. Useful for tooling and debugging.
|
||||
|
||||
```sh
|
||||
$ nox parse program.nox
|
||||
{
|
||||
"type": "Program",
|
||||
"body": [
|
||||
{"type": "Use", "kind": "telescope", "name": "T", "value": {...}, "loc": {...}},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Exits 4 on parse error.
|
||||
|
||||
### `nox help`
|
||||
|
||||
Print usage.
|
||||
|
||||
## Exit codes
|
||||
|
||||
| Code | Meaning |
|
||||
| ---- | ----------------------------------------------- |
|
||||
| 0 | Success |
|
||||
| 1 | Type check failed, or runtime failed under run/ops |
|
||||
| 2 | File not found |
|
||||
| 3 | Runtime error during execution |
|
||||
| 4 | Parse error |
|
||||
|
||||
## CI integration
|
||||
|
||||
```sh
|
||||
# fail the build on any type errors in observation scripts
|
||||
for f in scripts/*.nox; do
|
||||
nox check "$f" || exit 1
|
||||
done
|
||||
```
|
||||
|
||||
## Stdin
|
||||
|
||||
Not supported in v0.3. The CLI requires a file path. Pipe through a temp file if you need stdin:
|
||||
|
||||
```sh
|
||||
echo 'T.park()' > /tmp/p.nox && nox run /tmp/p.nox
|
||||
```
|
||||
@@ -0,0 +1,172 @@
|
||||
# Expression Reference
|
||||
|
||||
Expressions produce values. The type checker assigns each expression a type.
|
||||
|
||||
## Literals
|
||||
|
||||
```nox
|
||||
5 // Int
|
||||
1.5 // Float
|
||||
"text" // String
|
||||
"${expr} text" // Interpolated String
|
||||
true // Bool
|
||||
false // Bool
|
||||
20% // Percent (0.20 at runtime)
|
||||
60s 30arcsec ... // Quantity (see types.md for suffix list)
|
||||
now // Time
|
||||
```
|
||||
|
||||
## String interpolation
|
||||
|
||||
```nox
|
||||
let target = "M31"
|
||||
let filter = "L"
|
||||
let msg = "slewing to ${target} with filter ${filter}"
|
||||
```
|
||||
|
||||
Inside `"..."`, any `${expr}` segment is replaced with the value of the embedded expression. Embedded expressions are full Nox expressions: arithmetic, member access, function calls, etc. Brace nesting is respected so dict literals inside interpolation work. The embedded expression is type-checked at edit time. Quantity values render as their numeric magnitude (without a unit suffix).
|
||||
|
||||
## Identifiers
|
||||
|
||||
A bare identifier resolves against the current scope chain. Unknown identifiers are errors.
|
||||
|
||||
## Lists, dicts, tuples
|
||||
|
||||
```nox
|
||||
[1, 2, 3] // List<Int>
|
||||
[M31, M42] // List<Coord<ICRS>>
|
||||
{"L": 60s, "R": 120s} // Dict<String, Duration>
|
||||
(12000steps, 2.5px) // Tuple
|
||||
```
|
||||
|
||||
List elements must share a type. Dict keys share a type. Dict values share a type. Tuples are heterogeneous.
|
||||
|
||||
## Member access
|
||||
|
||||
```nox
|
||||
obj.name
|
||||
T.filter_wheel.select("L")
|
||||
```
|
||||
|
||||
Field names after `.` are not reserved. Keywords like `camera`, `for`, and `in` are valid member names.
|
||||
|
||||
## Index
|
||||
|
||||
```nox
|
||||
list[0]
|
||||
dict["L"]
|
||||
```
|
||||
|
||||
Index types: integer for lists, key-type for dicts.
|
||||
|
||||
## Call
|
||||
|
||||
```nox
|
||||
fn_or_method(arg1, arg2, name: value)
|
||||
```
|
||||
|
||||
Named arguments may appear in any order. Positional arguments fill remaining slots in order. Unknown names error. Duplicate names error.
|
||||
|
||||
## Typed constructor
|
||||
|
||||
```nox
|
||||
Coord<ICRS>(ra: 10.6847, dec: 41.2687)
|
||||
Coord<AltAz>(az: 0deg, alt: 90deg)
|
||||
```
|
||||
|
||||
The type arguments must reference a known type. Currently only `Coord` is constructible this way.
|
||||
|
||||
## Postfix `?`
|
||||
|
||||
```nox
|
||||
maybe?
|
||||
```
|
||||
|
||||
Presence test on an Optional value. Returns `Bool`. Inside an `if` guard the operand narrows to its inner type.
|
||||
|
||||
## Range
|
||||
|
||||
```nox
|
||||
start .. end
|
||||
start .. end step step_size // step is on the surrounding for-loop, not the range
|
||||
```
|
||||
|
||||
Range endpoints must be commensurable. Used in `for` loops.
|
||||
|
||||
## Unary
|
||||
|
||||
```nox
|
||||
-x // numeric or quantity negation
|
||||
+x // no-op
|
||||
not e // logical not
|
||||
```
|
||||
|
||||
## Arithmetic
|
||||
|
||||
```nox
|
||||
a + b a - b a * b a / b a % b
|
||||
```
|
||||
|
||||
Number+number stays Int if both are Int, else Float.
|
||||
Quantity+Quantity same dimension stays in that dimension.
|
||||
Quantity*Number scales the quantity.
|
||||
Time+Duration and Time-Duration produce Time.
|
||||
|
||||
## Comparison
|
||||
|
||||
```nox
|
||||
a < b a <= b a > b a >= b a == b a != b
|
||||
a in b
|
||||
```
|
||||
|
||||
Operands must be commensurable. Result is `Bool`.
|
||||
|
||||
`x in list`: true if any element equals x.
|
||||
`x in dict`: true if x is a key.
|
||||
`s in big_string`: true if s is a substring.
|
||||
|
||||
## Logical
|
||||
|
||||
```nox
|
||||
a and b
|
||||
a or b
|
||||
not a
|
||||
```
|
||||
|
||||
Short-circuiting. Result is `Bool`. `and` drives narrowing in if-conditions.
|
||||
|
||||
## After / Before
|
||||
|
||||
```nox
|
||||
after Expression
|
||||
before Expression
|
||||
```
|
||||
|
||||
Prefix operators that tag time predicates. Used inside `requires` and `time(...)` contexts. Type is `Time` for the operand.
|
||||
|
||||
## Lambda
|
||||
|
||||
```nox
|
||||
x => expr
|
||||
(x, y) => expr
|
||||
(x: Int, y: Duration) => expr
|
||||
x => do { statements }
|
||||
() => expr
|
||||
```
|
||||
|
||||
Lambda body is one expression, or `do { ... }` for a statement body. Parameter types are inferred from context when not annotated.
|
||||
|
||||
## Precedence
|
||||
|
||||
Tighter to looser:
|
||||
|
||||
1. Postfix: `.`, `[]`, `()`, `?`
|
||||
2. Unary: `-`, `+`, `not`
|
||||
3. Multiplicative: `*`, `/`, `%`
|
||||
4. Additive: `+`, `-`
|
||||
5. Range: `..`
|
||||
6. Comparison: `<`, `<=`, `>`, `>=`, `==`, `!=`
|
||||
7. `and`
|
||||
8. `or`
|
||||
9. Lambda: `=>`
|
||||
10. Time: `after`, `before`
|
||||
@@ -0,0 +1,160 @@
|
||||
# Grammar Reference
|
||||
|
||||
The canonical grammar lives in [grammar.ebnf](../../spec/grammar.ebnf). This page summarizes it for human reading.
|
||||
|
||||
## Tokens
|
||||
|
||||
### Keywords (hard-reserved)
|
||||
|
||||
```
|
||||
import from
|
||||
use let var fn return
|
||||
if else for in repeat while do
|
||||
parallel task on
|
||||
session requires safety
|
||||
policy when
|
||||
yield continue break halt assert
|
||||
not and or true false now after before
|
||||
```
|
||||
|
||||
### Soft keywords (image-checked, not reserved)
|
||||
|
||||
These are recognized as identifiers and only treated specially in specific syntactic positions.
|
||||
|
||||
```
|
||||
step reached rollback telescope dome camera filter_wheel focuser
|
||||
```
|
||||
|
||||
You can name a variable `step` or `rollback` freely. They only become keyword-like inside `for ... step EXPR`, `when EXPR reached`, `on rollback { ... }`, and `use <kind> <name>`.
|
||||
|
||||
### Literals
|
||||
|
||||
| Form | Example | Type |
|
||||
| ----------------- | --------------- | ------------------- |
|
||||
| Number | `5`, `1.5` | `Int` or `Float` |
|
||||
| Unit | `60s`, `30arcsec` | `Quantity` |
|
||||
| String | `"L"` | `String` |
|
||||
| Bool | `true`, `false` | `Bool` |
|
||||
| Percent | `20%` | `Percent` |
|
||||
| Now | `now` | `Time` |
|
||||
| Identifier | `M31`, `target` | resolved by scope |
|
||||
|
||||
### Unit suffixes
|
||||
|
||||
```
|
||||
ms s min h (Duration)
|
||||
deg arcmin arcsec (Angle)
|
||||
degC (Temperature)
|
||||
kph mps (Speed)
|
||||
steps (Steps)
|
||||
px (Pixels)
|
||||
```
|
||||
|
||||
### Operators
|
||||
|
||||
```
|
||||
multi-char: -> => .. <= >= == != += -= *= /=
|
||||
single-char: { } ( ) [ ] , ; : . @ ? = < > + - * / %
|
||||
```
|
||||
|
||||
## Top-level forms
|
||||
|
||||
```ebnf
|
||||
Program = { TopLevel } ;
|
||||
TopLevel = ImportDecl
|
||||
| UseDecl
|
||||
| DecoratedDecl
|
||||
| FnDecl
|
||||
| SessionDecl
|
||||
| PolicyDecl
|
||||
| Statement ;
|
||||
```
|
||||
|
||||
`Let` and `Var` are reachable via `Statement` and are valid at the top level.
|
||||
|
||||
## Declarations
|
||||
|
||||
```
|
||||
import { A, B, C } from "module/path"
|
||||
use <kind> <name> = <expr>
|
||||
let <name> [: <type>] = <expr>
|
||||
var <name> [: <type>] = <expr>
|
||||
fn <name>(<params>) [-> <type>] { <body> }
|
||||
@<decorator>[(<args>)] fn ...
|
||||
session "<label>" { <members> }
|
||||
policy "<label>" { <when-rules> }
|
||||
```
|
||||
|
||||
## Statements
|
||||
|
||||
```
|
||||
<assign-target> <op> <expr> // = += -= *= /=
|
||||
if <expr> { ... } [else { ... }]
|
||||
for <pattern> in <expr> [step <expr>] { ... }
|
||||
repeat <expr> { ... }
|
||||
parallel { <statements> }
|
||||
task <name> { <statements> }
|
||||
on rollback { <statements> }
|
||||
return [<expr>]
|
||||
yield [<expr>]
|
||||
continue
|
||||
break
|
||||
halt
|
||||
assert <expr> [, <expr>]
|
||||
<expr-statement>
|
||||
```
|
||||
|
||||
## Patterns (for-loop bindings)
|
||||
|
||||
```
|
||||
NamePat = identifier
|
||||
TuplePat = "(" Pattern ("," Pattern)+ ")"
|
||||
ForBinding = Pattern ("," Pattern)* // bare multi-binding allowed
|
||||
```
|
||||
|
||||
Bare multi-binding is shorthand for a tuple pattern when destructuring a tuple element.
|
||||
|
||||
## Expressions
|
||||
|
||||
Precedence climbs from low to high:
|
||||
|
||||
```
|
||||
LambdaExpr IDENT => EXPR | (PARAMS) => EXPR | ... => do { STMTS }
|
||||
TimeExpr after EXPR | before EXPR
|
||||
OrExpr l or r
|
||||
AndExpr l and r
|
||||
NotExpr not e
|
||||
CompareExpr l <op> r (< <= > >= == !=)
|
||||
RangeExpr l .. r
|
||||
AddExpr l + r | l - r
|
||||
MulExpr l * r | l / r | l % r
|
||||
UnaryExpr +e | -e
|
||||
PostfixExpr e.f e[i] e(args) e?
|
||||
PrimaryExpr literal | ident | (e) | [list] | {dict} | TypedCtor
|
||||
```
|
||||
|
||||
## Type expressions
|
||||
|
||||
```
|
||||
TypeExpr = NamedType | ListType | DictType | TupleType
|
||||
NamedType = Identifier ["<" TypeArgs ">"]
|
||||
ListType = "[" TypeExpr "]"
|
||||
DictType = "{" TypeExpr ":" TypeExpr "}"
|
||||
TupleType = "(" TypeExpr ("," TypeExpr)+ ")"
|
||||
```
|
||||
|
||||
## Comments
|
||||
|
||||
```
|
||||
// line comment
|
||||
/* block comment */
|
||||
```
|
||||
|
||||
## Decorators
|
||||
|
||||
```
|
||||
@calibration(kind: "flat")
|
||||
fn flat_frames(n: Int, filter: String) { ... }
|
||||
```
|
||||
|
||||
Decorators attach metadata to a function or let-binding. Multiple decorators may be stacked. They are visible in the AST.
|
||||
@@ -0,0 +1,135 @@
|
||||
# HTTP API Reference
|
||||
|
||||
Mounted at `/api/nox`. Source: [server/src/routes/nox.js](../../../server/src/routes/nox.js).
|
||||
|
||||
All endpoints accept and return JSON unless noted. Authentication piggybacks on the Observatory auth layer; the routes themselves do not require auth in the current build.
|
||||
|
||||
## `POST /api/nox/check`
|
||||
|
||||
Type-check a program. Does not execute.
|
||||
|
||||
**Body**
|
||||
|
||||
```json
|
||||
{ "source": "use telescope T = \"Astra-1\"\nT.slew(M31)" }
|
||||
```
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
{ "diagnostics": [] }
|
||||
```
|
||||
|
||||
**Response 400** when `source` is missing or not a string.
|
||||
|
||||
Each diagnostic:
|
||||
|
||||
```json
|
||||
{ "line": 3, "column": 7, "message": "..." }
|
||||
```
|
||||
|
||||
## `POST /api/nox/run`
|
||||
|
||||
Type-check, then execute. Buffers the full op log and returns it at the end.
|
||||
|
||||
**Body**
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "...",
|
||||
"mode": "mock", // or "real"
|
||||
"policy": { "ticks": 1, "intervalMs": 0 } // optional
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
{
|
||||
"log": [
|
||||
{ "kind": "T:Astra-1", "op": "slew", "args": {"target": {...}}, "t": 1737000000000 },
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Response 400** for type errors, runtime errors, or missing source. The body contains `{ "error": "<message>", "log": [...] }` with whatever ops ran before the failure.
|
||||
|
||||
## `POST /api/nox/run-stream`
|
||||
|
||||
Same as `/run` but streams Server-Sent Events. Use when the program is long-running or the client wants to render the op log live.
|
||||
|
||||
**Body** identical to `/run`.
|
||||
|
||||
**Response** `text/event-stream`.
|
||||
|
||||
**Events**
|
||||
|
||||
| Event | Data shape | Meaning |
|
||||
| ------- | ----------------------------------- | ----------------------------- |
|
||||
| `op` | `{ kind, op, args, t }` | One operation executed. |
|
||||
| `done` | `{ count }` | Program finished cleanly. |
|
||||
| `error` | `{ message }` | Program threw. |
|
||||
|
||||
**Example consumer (browser fetch)**
|
||||
|
||||
```js
|
||||
const res = await fetch('/api/nox/run-stream', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ source, mode: 'mock' }),
|
||||
});
|
||||
const reader = res.body.getReader();
|
||||
const dec = new TextDecoder();
|
||||
let buf = '';
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += dec.decode(value, { stream: true });
|
||||
let idx;
|
||||
while ((idx = buf.indexOf('\n\n')) !== -1) {
|
||||
const raw = buf.slice(0, idx);
|
||||
buf = buf.slice(idx + 2);
|
||||
// parse `event:` and `data:` lines
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## `GET /api/nox/examples`
|
||||
|
||||
Return the bundled example programs.
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
[
|
||||
{ "name": "01-hello-slew.nox", "source": "..." },
|
||||
{ "name": "02-messier-marathon.nox", "source": "..." },
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Useful for the Vue console's example picker. Files are read from `nox/examples/*.nox` on each request.
|
||||
|
||||
## Modes
|
||||
|
||||
`mode: "mock"` runs with the in-memory mock driver. Operations log but do not touch hardware. Use for development and dry runs.
|
||||
|
||||
`mode: "real"` builds a driver that resolves resource names against the `telescopes` and `enclosures` tables and forwards calls to `telescope-control.slewTo`, `external-drivers.domeAction`, and similar services. Operations that do not yet have a backing service log without effect.
|
||||
|
||||
## Policy options
|
||||
|
||||
When the program contains a `policy "..." { ... }` block, the runtime evaluates rules on a tick loop.
|
||||
|
||||
```json
|
||||
{ "policy": { "ticks": 600, "intervalMs": 1000 } }
|
||||
```
|
||||
|
||||
Default `ticks: 1, intervalMs: 0` runs each rule once on entry. Higher values run as a daemon. `halt` inside a rule aborts the loop.
|
||||
|
||||
## Errors
|
||||
|
||||
| HTTP | Cause |
|
||||
| ---- | --------------------------------------------------------- |
|
||||
| 400 | Missing source, source not a string, type errors, runtime errors |
|
||||
| 500 | Bug in the runtime; check server logs |
|
||||
@@ -0,0 +1,139 @@
|
||||
# Runtime API Reference
|
||||
|
||||
The `nox-runtime` package exposes the parser, checker, interpreter, and helpers as ES modules.
|
||||
|
||||
## Imports
|
||||
|
||||
```js
|
||||
import {
|
||||
run, // execute a program
|
||||
checkSource, // type-check source
|
||||
parseSource, // produce CST
|
||||
compile, // produce AST
|
||||
createMockDriver,
|
||||
mockGlobals,
|
||||
} from "nox-runtime";
|
||||
```
|
||||
|
||||
## `run(source, options) -> Promise<{ log }>`
|
||||
|
||||
Execute a Nox program against a driver.
|
||||
|
||||
```js
|
||||
const { log } = await run(source, {
|
||||
strict: true, // run checkSource first; throw on diagnostics
|
||||
driver: customDriver, // override the default mock driver
|
||||
onOp: entry => ..., // called synchronously for every op
|
||||
policy: { ticks: 60, intervalMs: 1000 }, // for policy daemons
|
||||
});
|
||||
```
|
||||
|
||||
Returns an object with `log: [opEntry]`. Each entry shape:
|
||||
|
||||
```js
|
||||
{ kind: "T:Astra-1", op: "slew", args: { target: ... }, t: 1737000000000 }
|
||||
```
|
||||
|
||||
If `strict` is true and the source has diagnostics, `run` throws before executing.
|
||||
|
||||
## `checkSource(source) -> { diagnostics }`
|
||||
|
||||
Run the parser and type checker. Returns diagnostics without executing.
|
||||
|
||||
```js
|
||||
const { diagnostics } = checkSource(src);
|
||||
for (const d of diagnostics) {
|
||||
console.log(`${d.line}:${d.column} ${d.message}`);
|
||||
}
|
||||
```
|
||||
|
||||
A diagnostic shape:
|
||||
|
||||
```js
|
||||
{ line: 3, column: 7, message: "..." }
|
||||
```
|
||||
|
||||
## `parseSource(source) -> Cst`
|
||||
|
||||
Returns the Chevrotain CST. Useful for tooling that walks the syntax tree.
|
||||
|
||||
## `compile(source) -> Ast`
|
||||
|
||||
Returns the AST. Each node carries a `type` discriminator and a `loc: {line, column}` field for diagnostics.
|
||||
|
||||
## `createMockDriver({ log, onOp }) -> Driver`
|
||||
|
||||
Build a driver that logs every operation. Defaults to the driver used inside `run`.
|
||||
|
||||
```js
|
||||
const log = [];
|
||||
const driver = createMockDriver({ log, onOp: e => console.log(e) });
|
||||
await run(src, { driver });
|
||||
```
|
||||
|
||||
## `mockGlobals() -> { now, sunset, weather, schedule, ... }`
|
||||
|
||||
The default values seeded into every program's top-level scope. Override by passing a custom driver that supplies its own globals.
|
||||
|
||||
## Driver protocol
|
||||
|
||||
A driver is an object with `telescope(name)` and `dome(name)` factories. Each factory returns a JS object exposing the methods declared in [builtins.md](builtins.md).
|
||||
|
||||
```js
|
||||
const driver = {
|
||||
telescope(name) {
|
||||
return {
|
||||
async slew(target) { /* ... */ },
|
||||
async park() { /* ... */ },
|
||||
async expose(exp, filter) { return { _tag: "Image", filter }; },
|
||||
// ... etc
|
||||
filter_wheel: { async select(filter) {} },
|
||||
focuser: { async move_to(pos) {} },
|
||||
camera: { async shutter(state) {} },
|
||||
};
|
||||
},
|
||||
dome(name) {
|
||||
return {
|
||||
async open() { /* ... */ },
|
||||
async close() { /* ... */ },
|
||||
is_closed() { return true; },
|
||||
flat_panel: { async on(b){}, async off(){} },
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
Methods are async and may return any value. Quantity arguments arrive as `{ _tag: "Quantity", value, dim }`. Coord arguments as `{ _tag: "Coord", frame, ra, dec }`.
|
||||
|
||||
## Runtime values
|
||||
|
||||
The runtime uses tagged objects for non-primitive values.
|
||||
|
||||
| Tag | Shape |
|
||||
| ---------- | -------------------------------------- |
|
||||
| `Quantity` | `{ value, dim }` |
|
||||
| `Coord` | `{ frame, ra, dec }` |
|
||||
| `Resource` | `{ kind, name, driver }` |
|
||||
| `Image` | additional driver fields |
|
||||
| `Time` | `{ date }` (JS Date) |
|
||||
| `Closure` | `{ params, body, env, name }` |
|
||||
| `Range` | `{ start, end, step }` |
|
||||
|
||||
Plain JS types for numbers, strings, bools, lists, dicts, tuples, null.
|
||||
|
||||
## Catalog files
|
||||
|
||||
Drop a JSON file at `nox/runtime/catalogs/<name>.json` to extend imports.
|
||||
|
||||
```json
|
||||
{
|
||||
"NGC_891": { "ra": 35.6394, "dec": 42.3492, "frame": "ICRS" },
|
||||
"NGC_2244": { "ra": 97.9667, "dec": 4.9522 }
|
||||
}
|
||||
```
|
||||
|
||||
Names from `import { NGC_891 } from "catalog/ngc"` then resolve to those coordinates.
|
||||
|
||||
## Capabilities
|
||||
|
||||
Each builtin function signature carries `caps: Set<String>` of capabilities. The checker accumulates these but does not yet enforce subset relations against `requires` clauses. See [types.md](types.md) for the canonical list.
|
||||
@@ -0,0 +1,121 @@
|
||||
# Statement Reference
|
||||
|
||||
## let / var
|
||||
|
||||
```nox
|
||||
let name [: TypeExpr] = Expression
|
||||
var name [: TypeExpr] = Expression
|
||||
```
|
||||
|
||||
`let` is immutable. `var` is mutable via assignment. Type annotation is optional. Empty list and dict literals adopt the declared type.
|
||||
|
||||
## Assignment
|
||||
|
||||
```nox
|
||||
target = Expression
|
||||
target += Expression
|
||||
target -= Expression
|
||||
target *= Expression
|
||||
target /= Expression
|
||||
```
|
||||
|
||||
Targets are identifiers, member accesses, or index expressions.
|
||||
|
||||
## If
|
||||
|
||||
```nox
|
||||
if Expression Block
|
||||
if Expression Block else Block
|
||||
if Expression Block else IfStatement
|
||||
```
|
||||
|
||||
Condition must type-check as `Bool`. `if x?` narrows `x` from `Optional<T>` to `T` in the then-branch. `and` chains compose narrowings.
|
||||
|
||||
## For
|
||||
|
||||
```nox
|
||||
for Pattern in Expression Block
|
||||
for Pattern in Expression step Expression Block
|
||||
```
|
||||
|
||||
Pattern is `Identifier`, `(Pattern, Pattern, ...)`, or bare `Identifier, Identifier, ...`. The iterable is a list, range, or dict.
|
||||
|
||||
`step` only applies to range iterables. Step must match the range element's dimension.
|
||||
|
||||
## Repeat
|
||||
|
||||
```nox
|
||||
repeat Expression Block
|
||||
```
|
||||
|
||||
The count must be `Int`. `break` exits early. `continue` skips to the next iteration.
|
||||
|
||||
## While
|
||||
|
||||
```nox
|
||||
while Expression Block
|
||||
```
|
||||
|
||||
Runs the body as long as the condition is true. Condition must be `Bool`. `break` exits. `continue` re-tests. The runtime caps iterations at 1,000,000 to prevent accidental runaways.
|
||||
|
||||
## Parallel
|
||||
|
||||
```nox
|
||||
parallel Block
|
||||
```
|
||||
|
||||
Each statement inside runs concurrently. `task name Block` labels a unit. `on rollback Block` registers a rollback handler that fires if any sibling task rejects.
|
||||
|
||||
## Task
|
||||
|
||||
```nox
|
||||
task identifier Block
|
||||
```
|
||||
|
||||
Valid only inside `parallel`. The body runs sequentially.
|
||||
|
||||
## on rollback
|
||||
|
||||
```nox
|
||||
on rollback Block
|
||||
```
|
||||
|
||||
Valid inside a `task`. Registers a handler to the enclosing parallel block's rollback chain. Handlers fire in reverse registration order on any task failure.
|
||||
|
||||
## Control flow
|
||||
|
||||
```nox
|
||||
return [Expression]
|
||||
yield [Expression]
|
||||
continue
|
||||
break
|
||||
halt
|
||||
```
|
||||
|
||||
`return` exits the enclosing function. `yield` is for cooperative scheduling; currently evaluates the operand and continues. `continue` and `break` are loop-local. `halt` stops the program gracefully.
|
||||
|
||||
## Assert
|
||||
|
||||
```nox
|
||||
assert Expression
|
||||
assert Expression, Expression
|
||||
```
|
||||
|
||||
Throws if the condition is falsy. The optional second argument becomes the error message.
|
||||
|
||||
## Expression statement
|
||||
|
||||
Any expression can be a statement. The result is discarded.
|
||||
|
||||
```nox
|
||||
T.slew(M31)
|
||||
some_pure_function()
|
||||
```
|
||||
|
||||
## Semicolons
|
||||
|
||||
Optional. Used to separate statements on the same line.
|
||||
|
||||
```nox
|
||||
T.park(); D.close()
|
||||
```
|
||||
@@ -0,0 +1,117 @@
|
||||
# Type System Reference
|
||||
|
||||
Source: [types.js](../../parser/src/types.js).
|
||||
|
||||
## Type kinds
|
||||
|
||||
Every type is one of the following discriminated objects.
|
||||
|
||||
| Kind | Shape | Example |
|
||||
| ----------- | -------------------------------------- | ---------------------- |
|
||||
| `Prim` | `{name}` | `Int`, `Float`, `String`, `Bool` |
|
||||
| `Quantity` | `{dim}` | `Duration`, `Angle` |
|
||||
| `Coord` | `{frame}` | `Coord<ICRS>` |
|
||||
| `Resource` | `{name}` | `Telescope` |
|
||||
| `Struct` | `{name, fields, methods}` | `Weather`, `Target` |
|
||||
| `Image` | `{bands}` | `Image` |
|
||||
| `Time` | atomic | `Time` |
|
||||
| `Optional` | `{element}` | `Target?` |
|
||||
| `Range` | `{element}` | range value |
|
||||
| `Percent` | atomic | `Percent` |
|
||||
| `List` | `{element}` | `[Coord<ICRS>]` |
|
||||
| `Dict` | `{key, value}` | `{String: Int}` |
|
||||
| `Tuple` | `{elements}` | `(Duration, Int)` |
|
||||
| `Fn` | `{params, returnType, paramNames, caps}` | functions |
|
||||
| `Union` | `{members}` | `Coord<ICRS> | Target` |
|
||||
| `Generic` | `{name}` | unresolved type param |
|
||||
| `Void` | atomic | no value |
|
||||
| `Any` | atomic | escape hatch |
|
||||
| `Error` | `{message}` | poisoned type |
|
||||
|
||||
## Dimensions
|
||||
|
||||
A Quantity belongs to one dimension. Adding two Quantities of the same dimension preserves it. Adding different dimensions is an error.
|
||||
|
||||
| Dimension | Base unit | Suffixes |
|
||||
| ------------- | --------- | ------------------------- |
|
||||
| `Duration` | s | `ms`, `s`, `min`, `h` |
|
||||
| `Angle` | deg | `deg`, `arcmin`, `arcsec` |
|
||||
| `Temperature` | degC | `degC` |
|
||||
| `Speed` | mps | `mps`, `kph` |
|
||||
| `Pixels` | px | `px` |
|
||||
| `Steps` | steps | `steps` |
|
||||
|
||||
## Frames
|
||||
|
||||
`Coord<F>` is parameterized by frame F.
|
||||
|
||||
| Frame | Meaning |
|
||||
| ---------- | ---------------------------------- |
|
||||
| `ICRS` | International Celestial Reference System |
|
||||
| `Topo` | Topocentric |
|
||||
| `AltAz` | Horizon coordinates |
|
||||
| `Galactic` | Galactic coordinates |
|
||||
|
||||
Frames are nominal. Conversion between frames is explicit at runtime.
|
||||
|
||||
## Resources
|
||||
|
||||
| Resource | Methods |
|
||||
| ------------- | ----------------------------------------------------------------- |
|
||||
| `Telescope` | slew, park, home, wait_until_settled, cooldown, warm_up, expose, focus, focus_if_needed, dither, auto_flat_exposure |
|
||||
| `Telescope` | members: filter_wheel, focuser, camera |
|
||||
| `Dome` | open, close, is_closed; member flat_panel |
|
||||
| `Camera` | shutter |
|
||||
| `FilterWheel` | select |
|
||||
| `Focuser` | move_to |
|
||||
| `FlatPanel` | on, off |
|
||||
|
||||
Method signatures are listed in [builtins.md](builtins.md).
|
||||
|
||||
## Assignability rules
|
||||
|
||||
`expected` accepts `actual` when:
|
||||
|
||||
- Either side is `Any`.
|
||||
- Either side is `Error` (suppresses cascades).
|
||||
- Both are equal under `typeEquals`.
|
||||
- `expected = Float` and `actual = Int` (Int widens).
|
||||
- `expected = Optional<T>` and `actual` is assignable to `T`.
|
||||
- `expected = Union<M...>` and any member accepts `actual`.
|
||||
- `actual = Union<M...>` and `expected` accepts every member.
|
||||
- `expected = Fn(P...)→R` and `actual = Fn(P'...)→R'` with P contravariant and R covariant.
|
||||
- `expected = List<T>` and `actual = List<T'>` with T' assignable to T.
|
||||
|
||||
Unguarded `Optional<T>` is NOT assignable to `T`. Use `if x?` to narrow.
|
||||
|
||||
## Type expressions in source
|
||||
|
||||
```nox
|
||||
let a: Duration = 60s
|
||||
let b: Coord<ICRS> = M31
|
||||
let c: [Coord<ICRS>] = [M31, M42]
|
||||
let d: {String: (Duration, Int)} = { "L": (60s, 20) }
|
||||
let e: (Steps, Pixels) = (12000steps, 2.5px)
|
||||
```
|
||||
|
||||
Implicit types: omit the annotation. The checker infers from the right-hand side.
|
||||
|
||||
## Capabilities
|
||||
|
||||
Each function signature carries a `caps: Set<String>` field listing the capabilities required by its body.
|
||||
|
||||
| Capability | Effect |
|
||||
| ------------------ | ---------------------------- |
|
||||
| `telescope.move` | slew, park, home |
|
||||
| `telescope.image` | expose, dither |
|
||||
| `telescope.focus` | focus, focuser.move_to |
|
||||
| `telescope.cool` | cooldown, warm_up |
|
||||
| `dome.move` | open, close |
|
||||
| `dome.flat_panel` | flat_panel.on, off |
|
||||
| `camera.shutter` | camera.shutter |
|
||||
| `filter_wheel.move`| filter_wheel.select |
|
||||
| `schedule.read` | schedule.tonight, best_target |
|
||||
| `weather.read` | weather.is_safe |
|
||||
| `io.network` | external driver calls |
|
||||
|
||||
Capabilities are collected but not yet validated against `requires(...)` clauses. Coming in v0.4.
|
||||
@@ -0,0 +1,7 @@
|
||||
// Minimal program: connect, slew to a named target, disconnect.
|
||||
// Demonstrates: resource binding, named catalog targets, implicit cleanup.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
T.slew(M31)
|
||||
T.wait_until_settled()
|
||||
@@ -0,0 +1,26 @@
|
||||
// Target list + exposure sequence.
|
||||
// Demonstrates: imports, lists, for-loops, typed durations, filter parameters.
|
||||
|
||||
import { M31, M42, M51, M81, M101 } from "catalog/messier"
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
let targets = [M31, M42, M51, M81, M101]
|
||||
let exposure: Duration = 60s
|
||||
let frames = 5
|
||||
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
|
||||
for target in targets {
|
||||
T.slew(target)
|
||||
T.focus(method: "v-curve")
|
||||
|
||||
repeat frames {
|
||||
T.expose(exposure, filter: "L")
|
||||
}
|
||||
}
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
@@ -0,0 +1,22 @@
|
||||
// V-curve autofocus: take exposures at stepped focus positions, fit parabola.
|
||||
// Demonstrates: functions, return types, unit arithmetic, named parameters,
|
||||
// numeric ranges with unit step.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
fn measure_hfr(exp: Duration) -> Pixels {
|
||||
let img = T.expose(exp, filter: "L")
|
||||
return img.hfr() // half-flux radius
|
||||
}
|
||||
|
||||
fn v_curve_focus(center: Steps, span: Steps, step: Steps) -> Steps {
|
||||
var samples: [(Steps, Pixels)] = []
|
||||
for pos in (center - span) .. (center + span) step step {
|
||||
T.focuser.move_to(pos)
|
||||
samples.push((pos, measure_hfr(5s)))
|
||||
}
|
||||
return parabola_min(samples)
|
||||
}
|
||||
|
||||
let best = v_curve_focus(center: 12000steps, span: 500steps, step: 50steps)
|
||||
T.focuser.move_to(best)
|
||||
@@ -0,0 +1,23 @@
|
||||
// LRGB sequence with random dither between frames.
|
||||
// Demonstrates: nested loops, angle units, dictionary literals,
|
||||
// per-filter exposure parameters.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
let plan: { String: (Duration, Int) } = {
|
||||
"L": (60s, 20),
|
||||
"R": (120s, 8),
|
||||
"G": (120s, 8),
|
||||
"B": (120s, 8),
|
||||
}
|
||||
|
||||
T.slew(NGC_7000)
|
||||
T.focus(method: "v-curve")
|
||||
|
||||
for (filter, (exp, count)) in plan {
|
||||
T.filter_wheel.select(filter)
|
||||
repeat count {
|
||||
T.expose(exp, filter: filter)
|
||||
T.dither(amount: 10arcsec, pattern: "spiral")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Full unattended automation: weather gating, scheduling, safety rollback.
|
||||
// Demonstrates: requires-clause, safety handlers, structured concurrency,
|
||||
// time predicates, declination/altitude filters.
|
||||
|
||||
session "spring-galaxies" {
|
||||
requires
|
||||
telescope("Astra-1"),
|
||||
dome("North"),
|
||||
weather(clouds < 20%, humidity < 80%, wind < 30kph),
|
||||
time(after sunset + 30min, before sunrise - 30min)
|
||||
|
||||
safety on cloud { rollback() }
|
||||
safety on wind > 50kph { rollback() }
|
||||
safety on power_loss { T.park(); D.close() }
|
||||
|
||||
// rollback() is a builtin: parks scope, closes dome, marks session aborted.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
// The safety handlers above reference T and D defined here. In Nox a
|
||||
// session's `use` bindings are visible to its `safety` clauses regardless
|
||||
// of textual order.
|
||||
|
||||
parallel {
|
||||
D.open()
|
||||
T.cooldown(target: -20degC)
|
||||
}
|
||||
// If either fails, both are rolled back atomically.
|
||||
|
||||
let plan = schedule.tonight()
|
||||
.filter(t => t.altitude(now) > 30deg)
|
||||
.sort_by(t => -t.altitude(now))
|
||||
|
||||
for target in plan {
|
||||
if not weather.is_safe() { yield 5min; continue }
|
||||
|
||||
T.slew(target)
|
||||
T.focus_if_needed(max_age: 30min, temp_delta: 1degC)
|
||||
|
||||
for filter, exp, count in target.requested_frames {
|
||||
T.filter_wheel.select(filter)
|
||||
repeat count {
|
||||
T.expose(exp, filter: filter)
|
||||
T.dither(10arcsec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
T.park()
|
||||
D.close()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// REPL session — each line is one statement, type at the prompt.
|
||||
// Demonstrates: implicit current-telescope, sugar for common ops,
|
||||
// inspection commands, unit-aware expressions.
|
||||
|
||||
> connect "Astra-1"
|
||||
> slew M31
|
||||
> expose 30s filter "L"
|
||||
> ?status // builtin introspection
|
||||
telescope: Astra-1
|
||||
ra: 00h42m44s dec: +41d16m09s
|
||||
tracking: sidereal
|
||||
filter: L
|
||||
cooler: -20.0 degC
|
||||
|
||||
> dither 15arcsec
|
||||
> expose 60s
|
||||
> park
|
||||
@@ -0,0 +1,25 @@
|
||||
// Structured concurrency with automatic rollback.
|
||||
// Demonstrates: parallel block, transactional semantics, custom on-fail.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
// All children must succeed, else every successful child is unwound
|
||||
// (in reverse order) via its registered `on rollback` handler.
|
||||
parallel {
|
||||
task open_dome {
|
||||
D.open()
|
||||
on rollback { D.close() }
|
||||
}
|
||||
task cool_camera {
|
||||
T.cooldown(target: -20degC, timeout: 5min)
|
||||
on rollback { T.warm_up() }
|
||||
}
|
||||
task home_mount {
|
||||
T.home()
|
||||
on rollback { T.park() }
|
||||
}
|
||||
}
|
||||
|
||||
// Past this point all three succeeded. Continue with the session.
|
||||
T.slew(M42)
|
||||
@@ -0,0 +1,24 @@
|
||||
// Declination strip survey: tile a region of sky with mosaic pointings.
|
||||
// Demonstrates: coordinate arithmetic, frame-typed values, generators.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
|
||||
let fov: Angle = 30arcmin // field of view (square)
|
||||
let overlap = 10%
|
||||
|
||||
fn strip(dec: Angle, ra_start: Angle, ra_end: Angle) -> [Coord<ICRS>] {
|
||||
let step = fov * (1 - overlap)
|
||||
var tiles: [Coord<ICRS>] = []
|
||||
for ra in ra_start .. ra_end step step / cos(dec) {
|
||||
tiles.push(Coord<ICRS>(ra: ra, dec: dec))
|
||||
}
|
||||
return tiles
|
||||
}
|
||||
|
||||
// RA in degrees (1h = 15deg). 10h..14h corresponds to 150deg..210deg.
|
||||
let tiles = strip(dec: +30deg, ra_start: 150deg, ra_end: 210deg)
|
||||
|
||||
for tile in tiles {
|
||||
T.slew(tile)
|
||||
T.expose(120s, filter: "L")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Bias / dark / flat calibration frames.
|
||||
// Demonstrates: enum-like literals, conditional context (dome state),
|
||||
// metadata annotations.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
@calibration(kind: "bias")
|
||||
fn bias_frames(n: Int) {
|
||||
T.camera.shutter("closed")
|
||||
repeat n { T.expose(0s, filter: "dark") }
|
||||
}
|
||||
|
||||
@calibration(kind: "dark")
|
||||
fn dark_frames(n: Int, exp: Duration) {
|
||||
T.camera.shutter("closed")
|
||||
repeat n { T.expose(exp, filter: "dark") }
|
||||
}
|
||||
|
||||
@calibration(kind: "flat")
|
||||
fn flat_frames(n: Int, filter: String) {
|
||||
assert D.is_closed(), "dome must be closed for panel flats"
|
||||
D.flat_panel.on(brightness: 50%)
|
||||
T.camera.shutter("open")
|
||||
repeat n { T.expose(T.auto_flat_exposure(filter), filter: filter) }
|
||||
D.flat_panel.off()
|
||||
}
|
||||
|
||||
bias_frames(50)
|
||||
dark_frames(20, 60s)
|
||||
dark_frames(20, 300s)
|
||||
for f in ["L", "R", "G", "B"] { flat_frames(20, filter: f) }
|
||||
@@ -0,0 +1,28 @@
|
||||
// Long-running policy: react to weather and time, no fixed plan.
|
||||
// Demonstrates: when-rules, predicates as first-class, daemon-style program.
|
||||
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
|
||||
policy "opportunistic" {
|
||||
// when-rules fire whenever their predicate transitions false -> true.
|
||||
when sunset.has_passed and weather.is_clear {
|
||||
parallel { D.open(); T.cooldown(-20degC) }
|
||||
}
|
||||
|
||||
when weather.clouds > 30% or weather.wind > 40kph {
|
||||
T.park(); D.close()
|
||||
}
|
||||
|
||||
when T.is_idle and weather.is_clear {
|
||||
let next = schedule.best_target(now)
|
||||
if next? {
|
||||
T.slew(next)
|
||||
T.expose(60s, filter: "L")
|
||||
}
|
||||
}
|
||||
|
||||
when sunrise - 30min reached {
|
||||
T.park(); D.close(); halt
|
||||
}
|
||||
}
|
||||
Generated
+68
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "nox-parser",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nox-parser",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"chevrotain": "^12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@chevrotain/cst-dts-gen": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-12.0.0.tgz",
|
||||
"integrity": "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@chevrotain/gast": "12.0.0",
|
||||
"@chevrotain/types": "12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@chevrotain/gast": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-12.0.0.tgz",
|
||||
"integrity": "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@chevrotain/types": "12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@chevrotain/regexp-to-ast": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-12.0.0.tgz",
|
||||
"integrity": "sha512-p+EW9MaJwgaHguhoqwOtx/FwuGr+DnNn857sXWOi/mClXIkPGl3rn7hGNWvo31HA3vyeQxjqe+H36yZJwYU8cA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@chevrotain/types": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-12.0.0.tgz",
|
||||
"integrity": "sha512-S+04vjFQKeuYw0/eW3U52LkAHQsB1ASxsPGsLPUyQgrZ2iNNibQrsidruDzjEX2JYfespXMG0eZmXlhA6z7nWA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@chevrotain/utils": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz",
|
||||
"integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/chevrotain": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-12.0.0.tgz",
|
||||
"integrity": "sha512-csJvb+6kEiQaqo1woTdSAuOWdN0WTLIydkKrBnS+V5gZz0oqBrp4kQ35519QgK6TpBThiG3V1vNSHlIkv4AglQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@chevrotain/cst-dts-gen": "12.0.0",
|
||||
"@chevrotain/gast": "12.0.0",
|
||||
"@chevrotain/regexp-to-ast": "12.0.0",
|
||||
"@chevrotain/types": "12.0.0",
|
||||
"@chevrotain/utils": "12.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "nox-parser",
|
||||
"version": "0.1.0",
|
||||
"description": "Parser, AST builder, and type checker for the Nox telescope and dome control language.",
|
||||
"license": "MIT",
|
||||
"author": "Paul Hitt",
|
||||
"type": "module",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
"test": "node test/parse-all.js && node test/build-ast.js && node test/types-smoke.js && node test/check.js && node test/check-negative.js",
|
||||
"test:parse": "node test/parse-all.js",
|
||||
"test:ast": "node test/build-ast.js",
|
||||
"test:types": "node test/types-smoke.js",
|
||||
"test:check": "node test/check.js",
|
||||
"test:check-neg": "node test/check-negative.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"chevrotain": "^12.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
import { parserInstance } from "./parser.js";
|
||||
import { tokenize } from "./lexer.js";
|
||||
import { loc, foldLeft } from "./ast.js";
|
||||
|
||||
const BaseVisitor = parserInstance.getBaseCstVisitorConstructor();
|
||||
|
||||
// Convenience: visit a single child (or null) and pluck first token for loc.
|
||||
function only(arr) { return arr && arr.length ? arr[0] : null; }
|
||||
function img(tok) { return tok ? tok.image : null; }
|
||||
|
||||
// Strip surrounding quotes from a StringLit token image.
|
||||
function unquote(image) {
|
||||
return image
|
||||
.slice(1, -1)
|
||||
.replace(/\\"/g, '"')
|
||||
.replace(/\\\\/g, "\\")
|
||||
.replace(/\\n/g, "\n")
|
||||
.replace(/\\t/g, "\t");
|
||||
}
|
||||
|
||||
// Split a UnitLit image like "30arcsec" into { value:30, unit:"arcsec" }.
|
||||
function splitUnit(image) {
|
||||
const m = image.match(/^([0-9]+(?:\.[0-9]+)?)([A-Za-z]+)$/);
|
||||
if (!m) throw new Error(`bad unit literal: ${image}`);
|
||||
return { value: parseFloat(m[1]), unit: m[2] };
|
||||
}
|
||||
|
||||
// Convert a string literal image (with quotes) to either a plain String AST
|
||||
// node or an InterpolatedString node if it contains `${...}` segments.
|
||||
// Embedded expressions are parsed by the same parser via a tiny wrapper.
|
||||
function splitInterpolation(image, locTok) {
|
||||
const body = image.slice(1, -1);
|
||||
const parts = [];
|
||||
let lit = '';
|
||||
let i = 0;
|
||||
while (i < body.length) {
|
||||
const ch = body[i];
|
||||
if (ch === '\\' && i + 1 < body.length) {
|
||||
lit += body[i] + body[i + 1];
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '$' && body[i + 1] === '{') {
|
||||
if (lit.length) {
|
||||
parts.push({ kind: 'lit', value: unescape(lit) });
|
||||
lit = '';
|
||||
}
|
||||
// Find the matching `}` with brace counting (so dict literals nest).
|
||||
let depth = 1;
|
||||
let j = i + 2;
|
||||
while (j < body.length) {
|
||||
const c = body[j];
|
||||
if (c === '{') depth++;
|
||||
else if (c === '}') { depth--; if (depth === 0) break; }
|
||||
j++;
|
||||
}
|
||||
if (depth !== 0) {
|
||||
throw new Error(`unterminated \${} at ${locTok.startLine}:${locTok.startColumn}`);
|
||||
}
|
||||
const innerSrc = body.slice(i + 2, j);
|
||||
const expr = parseEmbeddedExpr(innerSrc, locTok);
|
||||
parts.push({ kind: 'expr', value: expr });
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
lit += ch;
|
||||
i++;
|
||||
}
|
||||
if (lit.length) parts.push({ kind: 'lit', value: unescape(lit) });
|
||||
|
||||
// Plain string with no interpolations: keep the simpler AST shape.
|
||||
if (parts.length === 0) {
|
||||
return { type: 'String', value: '', loc: loc(locTok) };
|
||||
}
|
||||
if (parts.length === 1 && parts[0].kind === 'lit') {
|
||||
return { type: 'String', value: parts[0].value, loc: loc(locTok) };
|
||||
}
|
||||
return { type: 'InterpolatedString', parts, loc: loc(locTok) };
|
||||
}
|
||||
|
||||
function unescape(s) {
|
||||
return s
|
||||
.replace(/\\"/g, '"')
|
||||
.replace(/\\\\/g, '\\')
|
||||
.replace(/\\n/g, '\n')
|
||||
.replace(/\\t/g, '\t');
|
||||
}
|
||||
|
||||
// Recursive parse for an embedded expression. We wrap as `let __ = (EXPR)` so
|
||||
// the existing Program / LetDecl rules accept it, then peel back the value.
|
||||
function parseEmbeddedExpr(source, locTok) {
|
||||
const wrapped = `let __interp__ = (${source})`;
|
||||
const tokens = tokenize(wrapped);
|
||||
parserInstance.input = tokens;
|
||||
const cst = parserInstance.Program();
|
||||
if (parserInstance.errors.length) {
|
||||
const e = parserInstance.errors[0];
|
||||
throw new Error(`interpolation parse error at ${locTok.startLine}:${locTok.startColumn}: ${e.message}`);
|
||||
}
|
||||
const program = builderInstance.visit(cst);
|
||||
if (!program || program.type !== 'Program' || program.body.length !== 1) {
|
||||
throw new Error(`interpolation produced unexpected AST`);
|
||||
}
|
||||
return program.body[0].value;
|
||||
}
|
||||
|
||||
export class NoxAstBuilder extends BaseVisitor {
|
||||
constructor() {
|
||||
super();
|
||||
this.validateVisitor();
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// top level
|
||||
// ============================================================
|
||||
Program(ctx) {
|
||||
return {
|
||||
type: "Program",
|
||||
body: (ctx.TopLevel || []).map(c => this.visit(c)),
|
||||
};
|
||||
}
|
||||
|
||||
TopLevel(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return this.visit(ctx[key][0]);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// declarations
|
||||
// ============================================================
|
||||
ImportDecl(ctx) {
|
||||
return {
|
||||
type: "Import",
|
||||
names: ctx.Identifier.map(t => t.image),
|
||||
from: unquote(ctx.StringLit[0].image),
|
||||
loc: loc(ctx.Import[0]),
|
||||
};
|
||||
}
|
||||
|
||||
UseDecl(ctx) {
|
||||
return {
|
||||
type: "Use",
|
||||
kind: ctx.Identifier[0].image,
|
||||
name: ctx.Identifier[1].image,
|
||||
value: this.visit(ctx.Expression),
|
||||
loc: loc(ctx.Use[0]),
|
||||
};
|
||||
}
|
||||
|
||||
LetDecl(ctx) {
|
||||
return {
|
||||
type: "Let",
|
||||
name: ctx.Identifier[0].image,
|
||||
declaredType: ctx.TypeExpr ? this.visit(ctx.TypeExpr) : null,
|
||||
value: this.visit(ctx.Expression),
|
||||
loc: loc(ctx.Let[0]),
|
||||
};
|
||||
}
|
||||
|
||||
VarDecl(ctx) {
|
||||
return {
|
||||
type: "Var",
|
||||
name: ctx.Identifier[0].image,
|
||||
declaredType: ctx.TypeExpr ? this.visit(ctx.TypeExpr) : null,
|
||||
value: this.visit(ctx.Expression),
|
||||
loc: loc(ctx.Var[0]),
|
||||
};
|
||||
}
|
||||
|
||||
FnDecl(ctx) {
|
||||
return {
|
||||
type: "Fn",
|
||||
name: ctx.Identifier[0].image,
|
||||
params: ctx.ParamList ? this.visit(ctx.ParamList) : [],
|
||||
returnType: ctx.TypeExpr ? this.visit(ctx.TypeExpr) : null,
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.Fn[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ParamList(ctx) {
|
||||
return ctx.Param.map(c => this.visit(c));
|
||||
}
|
||||
|
||||
Param(ctx) {
|
||||
return {
|
||||
name: ctx.Identifier[0].image,
|
||||
paramType: this.visit(ctx.TypeExpr),
|
||||
default: ctx.Expression ? this.visit(ctx.Expression) : null,
|
||||
};
|
||||
}
|
||||
|
||||
DecoratedDecl(ctx) {
|
||||
const decl = ctx.FnDecl
|
||||
? this.visit(ctx.FnDecl)
|
||||
: this.visit(ctx.LetDecl);
|
||||
return {
|
||||
type: "Decorated",
|
||||
decorators: ctx.Decorator.map(c => this.visit(c)),
|
||||
decl,
|
||||
};
|
||||
}
|
||||
|
||||
Decorator(ctx) {
|
||||
return {
|
||||
name: ctx.Identifier[0].image,
|
||||
args: ctx.ArgList ? this.visit(ctx.ArgList) : [],
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// session / policy
|
||||
// ============================================================
|
||||
SessionDecl(ctx) {
|
||||
return {
|
||||
type: "Session",
|
||||
name: unquote(ctx.StringLit[0].image),
|
||||
members: (ctx.SessionMember || []).map(c => this.visit(c)),
|
||||
loc: loc(ctx.Session[0]),
|
||||
};
|
||||
}
|
||||
|
||||
SessionMember(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return this.visit(ctx[key][0]);
|
||||
}
|
||||
|
||||
RequiresClause(ctx) {
|
||||
return {
|
||||
type: "Requires",
|
||||
items: ctx.RequireItem.map(c => this.visit(c)),
|
||||
loc: loc(ctx.Requires[0]),
|
||||
};
|
||||
}
|
||||
|
||||
RequireItem(ctx) {
|
||||
return {
|
||||
name: ctx.Identifier[0].image,
|
||||
args: (ctx.Expression || []).map(c => this.visit(c)),
|
||||
};
|
||||
}
|
||||
|
||||
SafetyClause(ctx) {
|
||||
return {
|
||||
type: "Safety",
|
||||
trigger: this.visit(ctx.Expression),
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.Safety[0]),
|
||||
};
|
||||
}
|
||||
|
||||
PolicyDecl(ctx) {
|
||||
return {
|
||||
type: "Policy",
|
||||
name: unquote(ctx.StringLit[0].image),
|
||||
rules: (ctx.WhenRule || []).map(c => this.visit(c)),
|
||||
loc: loc(ctx.Policy[0]),
|
||||
};
|
||||
}
|
||||
|
||||
WhenRule(ctx) {
|
||||
return {
|
||||
type: "When",
|
||||
condition: this.visit(ctx.Expression),
|
||||
reached: !!ctx.Identifier,
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.When[0]),
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// statements
|
||||
// ============================================================
|
||||
Block(ctx) {
|
||||
return (ctx.Statement || []).map(c => this.visit(c));
|
||||
}
|
||||
|
||||
Statement(ctx) {
|
||||
const key = Object.keys(ctx).find(k => k !== "Semicolon");
|
||||
return this.visit(ctx[key][0]);
|
||||
}
|
||||
|
||||
IfStmt(ctx) {
|
||||
const result = {
|
||||
type: "If",
|
||||
cond: this.visit(ctx.Expression),
|
||||
then: this.visit(ctx.Block[0]),
|
||||
else: null,
|
||||
loc: loc(ctx.If[0]),
|
||||
};
|
||||
if (ctx.IfStmt) result.else = this.visit(ctx.IfStmt);
|
||||
else if (ctx.Block.length > 1) result.else = this.visit(ctx.Block[1]);
|
||||
return result;
|
||||
}
|
||||
|
||||
ForStmt(ctx) {
|
||||
return {
|
||||
type: "For",
|
||||
binding: this.visit(ctx.ForBinding),
|
||||
iter: this.visit(ctx.Expression[0]),
|
||||
step: ctx.Expression.length > 1 ? this.visit(ctx.Expression[1]) : null,
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.For[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ForBinding(ctx) {
|
||||
const pats = ctx.Pattern.map(c => this.visit(c));
|
||||
if (pats.length === 1) return pats[0];
|
||||
return { type: "TuplePat", items: pats };
|
||||
}
|
||||
|
||||
Pattern(ctx) {
|
||||
if (ctx.Identifier) {
|
||||
return { type: "NamePat", name: ctx.Identifier[0].image };
|
||||
}
|
||||
return { type: "TuplePat", items: ctx.Pattern.map(c => this.visit(c)) };
|
||||
}
|
||||
|
||||
RepeatStmt(ctx) {
|
||||
return {
|
||||
type: "Repeat",
|
||||
count: this.visit(ctx.Expression),
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.Repeat[0]),
|
||||
};
|
||||
}
|
||||
|
||||
WhileStmt(ctx) {
|
||||
return {
|
||||
type: "While",
|
||||
cond: this.visit(ctx.Expression),
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.While[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ParallelStmt(ctx) {
|
||||
return {
|
||||
type: "Parallel",
|
||||
children: (ctx.Statement || []).map(c => this.visit(c)),
|
||||
loc: loc(ctx.Parallel[0]),
|
||||
};
|
||||
}
|
||||
|
||||
TaskStmt(ctx) {
|
||||
return {
|
||||
type: "Task",
|
||||
name: ctx.Identifier[0].image,
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.Task[0]),
|
||||
};
|
||||
}
|
||||
|
||||
OnRollbackStmt(ctx) {
|
||||
const idImage = ctx.Identifier[0].image;
|
||||
if (idImage !== "rollback") {
|
||||
throw new Error(`expected 'rollback' after 'on', got '${idImage}' at ${ctx.On[0].startLine}:${ctx.On[0].startColumn}`);
|
||||
}
|
||||
return {
|
||||
type: "OnRollback",
|
||||
body: this.visit(ctx.Block),
|
||||
loc: loc(ctx.On[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ReturnStmt(ctx) {
|
||||
return {
|
||||
type: "Return",
|
||||
value: ctx.Expression ? this.visit(ctx.Expression) : null,
|
||||
loc: loc(ctx.Return[0]),
|
||||
};
|
||||
}
|
||||
|
||||
YieldStmt(ctx) {
|
||||
return {
|
||||
type: "Yield",
|
||||
value: ctx.Expression ? this.visit(ctx.Expression) : null,
|
||||
loc: loc(ctx.Yield[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ContinueStmt(ctx) { return { type: "Continue", loc: loc(ctx.Continue[0]) }; }
|
||||
BreakStmt(ctx) { return { type: "Break", loc: loc(ctx.Break[0]) }; }
|
||||
HaltStmt(ctx) { return { type: "Halt", loc: loc(ctx.Halt[0]) }; }
|
||||
|
||||
AssertStmt(ctx) {
|
||||
return {
|
||||
type: "Assert",
|
||||
cond: this.visit(ctx.Expression[0]),
|
||||
message: ctx.Expression.length > 1 ? this.visit(ctx.Expression[1]) : null,
|
||||
loc: loc(ctx.Assert[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ExprOrAssignStmt(ctx) {
|
||||
const lhs = this.visit(ctx.Expression[0]);
|
||||
if (ctx.AssignOp) {
|
||||
return {
|
||||
type: "Assign",
|
||||
op: this.visit(ctx.AssignOp),
|
||||
target: lhs,
|
||||
value: this.visit(ctx.Expression[1]),
|
||||
};
|
||||
}
|
||||
return { type: "ExprStmt", expr: lhs };
|
||||
}
|
||||
|
||||
AssignOp(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return ctx[key][0].image;
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// expressions
|
||||
// ============================================================
|
||||
Expression(ctx) {
|
||||
if (ctx.LambdaExpr) return this.visit(ctx.LambdaExpr);
|
||||
return this.visit(ctx.TimeOrOrExpr);
|
||||
}
|
||||
|
||||
TimeOrOrExpr(ctx) {
|
||||
if (ctx.After) {
|
||||
return { type: "Time", op: "after", expr: this.visit(ctx.AddExpr[0]), loc: loc(ctx.After[0]) };
|
||||
}
|
||||
if (ctx.Before) {
|
||||
return { type: "Time", op: "before", expr: this.visit(ctx.AddExpr[0]), loc: loc(ctx.Before[0]) };
|
||||
}
|
||||
return this.visit(ctx.OrExpr);
|
||||
}
|
||||
|
||||
LambdaExpr(ctx) {
|
||||
let params;
|
||||
if (ctx.Identifier) {
|
||||
params = [{ name: ctx.Identifier[0].image, paramType: null }];
|
||||
} else {
|
||||
params = ctx.LambdaParamList ? this.visit(ctx.LambdaParamList) : [];
|
||||
}
|
||||
const body = ctx.DoBlock ? this.visit(ctx.DoBlock) : this.visit(ctx.Expression);
|
||||
return { type: "Lambda", params, body };
|
||||
}
|
||||
|
||||
DoBlock(ctx) {
|
||||
// The body becomes a block of statements; interpreter and checker run
|
||||
// these and use the last expression-statement's value as the result.
|
||||
return { type: "DoBlock", body: this.visit(ctx.Block) };
|
||||
}
|
||||
|
||||
LambdaParamList(ctx) {
|
||||
return ctx.LambdaParam.map(c => this.visit(c));
|
||||
}
|
||||
|
||||
LambdaParam(ctx) {
|
||||
return {
|
||||
name: ctx.Identifier[0].image,
|
||||
paramType: ctx.TypeExpr ? this.visit(ctx.TypeExpr) : null,
|
||||
};
|
||||
}
|
||||
|
||||
OrExpr(ctx) {
|
||||
const operands = ctx.AndExpr.map(c => this.visit(c));
|
||||
let node = operands[0];
|
||||
for (let i = 1; i < operands.length; i++) {
|
||||
node = { type: "BinOp", op: "or", left: node, right: operands[i], loc: node.loc || null };
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
AndExpr(ctx) {
|
||||
const operands = ctx.NotExpr.map(c => this.visit(c));
|
||||
let node = operands[0];
|
||||
for (let i = 1; i < operands.length; i++) {
|
||||
node = { type: "BinOp", op: "and", left: node, right: operands[i], loc: node.loc || null };
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
NotExpr(ctx) {
|
||||
const inner = this.visit(ctx.CompareExpr);
|
||||
if (ctx.Not) return { type: "Not", expr: inner, loc: loc(ctx.Not[0]) };
|
||||
return inner;
|
||||
}
|
||||
|
||||
CompareExpr(ctx) {
|
||||
const left = this.visit(ctx.RangeExpr[0]);
|
||||
if (!ctx.CompOp) return left;
|
||||
return {
|
||||
type: "BinOp",
|
||||
op: this.visit(ctx.CompOp),
|
||||
left,
|
||||
right: this.visit(ctx.RangeExpr[1]),
|
||||
loc: left.loc || null,
|
||||
};
|
||||
}
|
||||
|
||||
CompOp(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return ctx[key][0].image;
|
||||
}
|
||||
|
||||
RangeExpr(ctx) {
|
||||
const start = this.visit(ctx.AddExpr[0]);
|
||||
if (ctx.AddExpr.length === 1) return start;
|
||||
return {
|
||||
type: "Range",
|
||||
start,
|
||||
end: this.visit(ctx.AddExpr[1]),
|
||||
loc: start.loc || null,
|
||||
};
|
||||
}
|
||||
|
||||
AddExpr(ctx) {
|
||||
const operands = ctx.MulExpr.map(c => this.visit(c));
|
||||
const ops = [];
|
||||
if (ctx.Plus) for (const t of ctx.Plus) ops.push({ idx: t.startOffset, op: "+" });
|
||||
if (ctx.Minus) for (const t of ctx.Minus) ops.push({ idx: t.startOffset, op: "-" });
|
||||
ops.sort((a, b) => a.idx - b.idx);
|
||||
const tail = ops.map((o, i) => ({ op: o.op, right: operands[i + 1] }));
|
||||
return foldLeft(operands[0], tail);
|
||||
}
|
||||
|
||||
MulExpr(ctx) {
|
||||
const operands = ctx.UnaryExpr.map(c => this.visit(c));
|
||||
const ops = [];
|
||||
if (ctx.Star) for (const t of ctx.Star) ops.push({ idx: t.startOffset, op: "*" });
|
||||
if (ctx.Slash) for (const t of ctx.Slash) ops.push({ idx: t.startOffset, op: "/" });
|
||||
if (ctx.Percent) for (const t of ctx.Percent) ops.push({ idx: t.startOffset, op: "%" });
|
||||
ops.sort((a, b) => a.idx - b.idx);
|
||||
const tail = ops.map((o, i) => ({ op: o.op, right: operands[i + 1] }));
|
||||
return foldLeft(operands[0], tail);
|
||||
}
|
||||
|
||||
UnaryExpr(ctx) {
|
||||
const inner = this.visit(ctx.PostfixExpr);
|
||||
if (ctx.Minus) return { type: "Unary", op: "-", expr: inner };
|
||||
if (ctx.Plus) return { type: "Unary", op: "+", expr: inner };
|
||||
return inner;
|
||||
}
|
||||
|
||||
PostfixExpr(ctx) {
|
||||
let node = this.visit(ctx.PrimaryExpr);
|
||||
for (const s of ctx.Suffix || []) {
|
||||
node = this.applySuffix(node, s);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
applySuffix(receiver, suffixCst) {
|
||||
const sx = suffixCst.children;
|
||||
const loc = receiver.loc || null;
|
||||
if (sx.Dot) {
|
||||
const member = this.visit(sx.MemberName);
|
||||
return { type: "Member", object: receiver, name: member, loc };
|
||||
}
|
||||
if (sx.LBracket) {
|
||||
return { type: "Index", object: receiver, index: this.visit(sx.Expression), loc };
|
||||
}
|
||||
if (sx.LParen) {
|
||||
const args = sx.ArgList ? this.visit(sx.ArgList) : [];
|
||||
return { type: "Call", callee: receiver, args, loc };
|
||||
}
|
||||
if (sx.Question) {
|
||||
return { type: "Optional", expr: receiver, loc };
|
||||
}
|
||||
throw new Error("unknown suffix");
|
||||
}
|
||||
|
||||
Suffix(_ctx) { /* handled inline by applySuffix */ }
|
||||
|
||||
MemberName(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return ctx[key][0].image;
|
||||
}
|
||||
|
||||
ArgList(ctx) {
|
||||
return ctx.Arg.map(c => this.visit(c));
|
||||
}
|
||||
|
||||
Arg(ctx) {
|
||||
// Named arg shape: ctx has Identifier + Colon + Expression.
|
||||
if (ctx.Identifier && ctx.Colon) {
|
||||
return { name: ctx.Identifier[0].image, value: this.visit(ctx.Expression) };
|
||||
}
|
||||
return { name: null, value: this.visit(ctx.Expression) };
|
||||
}
|
||||
|
||||
PrimaryExpr(ctx) {
|
||||
if (ctx.NumberLit) {
|
||||
return { type: "Number", value: parseFloat(ctx.NumberLit[0].image), loc: loc(ctx.NumberLit[0]) };
|
||||
}
|
||||
if (ctx.UnitLit) {
|
||||
const { value, unit } = splitUnit(ctx.UnitLit[0].image);
|
||||
return { type: "UnitLit", value, unit, loc: loc(ctx.UnitLit[0]) };
|
||||
}
|
||||
if (ctx.PercentLit) {
|
||||
const v = parseFloat(ctx.PercentLit[0].image);
|
||||
return { type: "Percent", value: v, loc: loc(ctx.PercentLit[0]) };
|
||||
}
|
||||
if (ctx.StringLit) {
|
||||
return splitInterpolation(ctx.StringLit[0].image, ctx.StringLit[0]);
|
||||
}
|
||||
if (ctx.True) return { type: "Bool", value: true, loc: loc(ctx.True[0]) };
|
||||
if (ctx.False) return { type: "Bool", value: false, loc: loc(ctx.False[0]) };
|
||||
if (ctx.Now) return { type: "Now", loc: loc(ctx.Now[0]) };
|
||||
if (ctx.TypedConstructor) return this.visit(ctx.TypedConstructor);
|
||||
if (ctx.Identifier) {
|
||||
return { type: "Ident", name: ctx.Identifier[0].image, loc: loc(ctx.Identifier[0]) };
|
||||
}
|
||||
if (ctx.ListLit) return this.visit(ctx.ListLit);
|
||||
if (ctx.DictLit) return this.visit(ctx.DictLit);
|
||||
if (ctx.ParenOrTupleExpr) return this.visit(ctx.ParenOrTupleExpr);
|
||||
throw new Error("unknown primary");
|
||||
}
|
||||
|
||||
TypedConstructor(ctx) {
|
||||
return {
|
||||
type: "TypedCtor",
|
||||
name: ctx.Identifier[0].image,
|
||||
typeArgs: ctx.TypeExpr.map(c => this.visit(c)),
|
||||
args: ctx.ArgList ? this.visit(ctx.ArgList) : [],
|
||||
loc: loc(ctx.Identifier[0]),
|
||||
};
|
||||
}
|
||||
|
||||
ListLit(ctx) {
|
||||
return {
|
||||
type: "List",
|
||||
elements: (ctx.Expression || []).map(c => this.visit(c)),
|
||||
loc: loc(ctx.LBracket[0]),
|
||||
};
|
||||
}
|
||||
|
||||
DictLit(ctx) {
|
||||
return {
|
||||
type: "Dict",
|
||||
entries: (ctx.DictEntry || []).map(c => this.visit(c)),
|
||||
loc: loc(ctx.LBrace[0]),
|
||||
};
|
||||
}
|
||||
|
||||
DictEntry(ctx) {
|
||||
return {
|
||||
key: this.visit(ctx.Expression[0]),
|
||||
value: this.visit(ctx.Expression[1]),
|
||||
};
|
||||
}
|
||||
|
||||
ParenOrTupleExpr(ctx) {
|
||||
const elems = ctx.Expression.map(c => this.visit(c));
|
||||
if (elems.length === 1) return elems[0];
|
||||
return { type: "Tuple", elements: elems, loc: loc(ctx.LParen[0]) };
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// types
|
||||
// ============================================================
|
||||
TypeExpr(ctx) {
|
||||
const key = Object.keys(ctx)[0];
|
||||
return this.visit(ctx[key][0]);
|
||||
}
|
||||
|
||||
NamedType(ctx) {
|
||||
return {
|
||||
kind: "Named",
|
||||
name: ctx.Identifier[0].image,
|
||||
args: ctx.TypeExpr ? ctx.TypeExpr.map(c => this.visit(c)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
ListType(ctx) {
|
||||
return { kind: "List", element: this.visit(ctx.TypeExpr) };
|
||||
}
|
||||
|
||||
DictType(ctx) {
|
||||
return {
|
||||
kind: "Dict",
|
||||
key: this.visit(ctx.TypeExpr[0]),
|
||||
value: this.visit(ctx.TypeExpr[1]),
|
||||
};
|
||||
}
|
||||
|
||||
TupleType(ctx) {
|
||||
return {
|
||||
kind: "Tuple",
|
||||
elements: ctx.TypeExpr.map(c => this.visit(c)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const builder = new NoxAstBuilder();
|
||||
// Re-exposed inside the module so parseEmbeddedExpr can visit recursively
|
||||
// without creating a fresh builder instance per interpolation.
|
||||
const builderInstance = builder;
|
||||
|
||||
export function buildAst(cst) {
|
||||
return builder.visit(cst);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// AST node shapes for Nox.
|
||||
//
|
||||
// All nodes are plain JS objects discriminated by a `type` (expressions /
|
||||
// statements / top-level) or `kind` (type-expression nodes) field. Nodes
|
||||
// carry an optional `loc` field with { line, column } from the first token.
|
||||
//
|
||||
// Tree:
|
||||
// Program { type:'Program', body:[TopLevel] }
|
||||
// Import { type:'Import', names:[string], from:string }
|
||||
// Use { type:'Use', kind:string, name:string, value:Expr }
|
||||
// Let | Var { type:'Let'|'Var', name:string, declaredType:TypeNode?, value:Expr }
|
||||
// Fn { type:'Fn', name:string, params:[Param], returnType:TypeNode?, body:[Stmt] }
|
||||
// Decorated { type:'Decorated', decorators:[Decorator], decl:Fn|Let }
|
||||
// Session { type:'Session', name:string, members:[SessionMember] }
|
||||
// Policy { type:'Policy', name:string, rules:[When] }
|
||||
// Requires { type:'Requires', items:[{ name:string, args:[Expr] }] }
|
||||
// Safety { type:'Safety', trigger:Expr, body:[Stmt] }
|
||||
// When { type:'When', condition:Expr, reached:bool, body:[Stmt] }
|
||||
//
|
||||
// Statements:
|
||||
// If { type:'If', cond:Expr, then:[Stmt], else:[Stmt]|If|null }
|
||||
// For { type:'For', binding:Pattern, iter:Expr, step:Expr|null, body:[Stmt] }
|
||||
// Repeat { type:'Repeat', count:Expr, body:[Stmt] }
|
||||
// Parallel { type:'Parallel', children:[Stmt] }
|
||||
// Task { type:'Task', name:string, body:[Stmt] }
|
||||
// OnRollback { type:'OnRollback', body:[Stmt] }
|
||||
// Return { type:'Return', value:Expr|null }
|
||||
// Yield { type:'Yield', value:Expr|null }
|
||||
// Continue { type:'Continue' }
|
||||
// Break { type:'Break' }
|
||||
// Halt { type:'Halt' }
|
||||
// Assert { type:'Assert', cond:Expr, message:Expr|null }
|
||||
// Assign { type:'Assign', op:string, target:Expr, value:Expr }
|
||||
// ExprStmt { type:'ExprStmt', expr:Expr }
|
||||
//
|
||||
// Patterns:
|
||||
// { type:'NamePat', name:string }
|
||||
// { type:'TuplePat', items:[Pattern] }
|
||||
//
|
||||
// Expressions:
|
||||
// Lambda { type:'Lambda', params:[LambdaParam], body:Expr }
|
||||
// Time { type:'Time', op:'after'|'before', expr:Expr }
|
||||
// BinOp { type:'BinOp', op:string, left:Expr, right:Expr }
|
||||
// Not { type:'Not', expr:Expr }
|
||||
// Range { type:'Range', start:Expr, end:Expr }
|
||||
// Unary { type:'Unary', op:'+'|'-', expr:Expr }
|
||||
// Member { type:'Member', object:Expr, name:string }
|
||||
// Index { type:'Index', object:Expr, index:Expr }
|
||||
// Call { type:'Call', callee:Expr, args:[Arg] }
|
||||
// Optional { type:'Optional', expr:Expr }
|
||||
// Arg { name:string|null, value:Expr }
|
||||
// Number { type:'Number', value:number }
|
||||
// UnitLit { type:'UnitLit', value:number, unit:string }
|
||||
// String { type:'String', value:string }
|
||||
// Bool { type:'Bool', value:bool }
|
||||
// Percent { type:'Percent', value:number } // value is the percent, e.g. 20 for 20%
|
||||
// Now { type:'Now' }
|
||||
// Ident { type:'Ident', name:string }
|
||||
// TypedCtor { type:'TypedCtor', name:string, typeArgs:[TypeNode], args:[Arg] }
|
||||
// List { type:'List', elements:[Expr] }
|
||||
// Tuple { type:'Tuple', elements:[Expr] }
|
||||
// Dict { type:'Dict', entries:[{ key:Expr, value:Expr }] }
|
||||
//
|
||||
// Type nodes:
|
||||
// { kind:'Named', name:string, args:[TypeNode] }
|
||||
// { kind:'List', element:TypeNode }
|
||||
// { kind:'Dict', key:TypeNode, value:TypeNode }
|
||||
// { kind:'Tuple', elements:[TypeNode] }
|
||||
|
||||
export function loc(tok) {
|
||||
if (!tok) return null;
|
||||
return { line: tok.startLine, column: tok.startColumn };
|
||||
}
|
||||
|
||||
// Fold a left-associative chain.
|
||||
// first: first operand; tail: [{op, right}]. Each BinOp inherits its `loc`
|
||||
// from the left operand so diagnostics anchor on the originating expression.
|
||||
export function foldLeft(first, tail) {
|
||||
let node = first;
|
||||
for (const { op, right } of tail) {
|
||||
node = { type: "BinOp", op, left: node, right, loc: node.loc || null };
|
||||
}
|
||||
return node;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// Builtin globals, resource method tables, and module imports for Nox.
|
||||
// Each Fn signature lists ordered params; named-arg calls are resolved by
|
||||
// matching against an optional `paramNames` array. Optional params get a
|
||||
// trailing `?` in the name string. Lower types here, not AST nodes.
|
||||
|
||||
import {
|
||||
Prim, Quantity, Coord, Resource, List, Dict, Tuple, Fn, Generic,
|
||||
ImageT, Time, Optional, Range, Struct, PercentT, Union, Void, Any,
|
||||
Duration, Angle, Temperature, Speed, Int, Float, StringT, Bool, Pixels, Steps,
|
||||
} from "./types.js";
|
||||
|
||||
// ---------- helper to build a function signature ----------
|
||||
// params: [{ name, type, optional?:bool }]
|
||||
function sig(params, returnType, caps = []) {
|
||||
return {
|
||||
kind: "Fn",
|
||||
params: params.map(p => p.type),
|
||||
paramNames: params.map(p => p.name),
|
||||
paramOptional: params.map(p => !!p.optional),
|
||||
returnType,
|
||||
caps: new Set(caps),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- struct definitions ----------
|
||||
const Weather = Struct("Weather");
|
||||
Weather.fields = new Map([
|
||||
["clouds", PercentT()],
|
||||
["humidity", PercentT()],
|
||||
["wind", Speed()],
|
||||
["is_clear", Bool()],
|
||||
]);
|
||||
Weather.methods = new Map([
|
||||
["is_safe", sig([], Bool(), ["weather.read"])],
|
||||
]);
|
||||
|
||||
const Target = Struct("Target");
|
||||
Target.fields = new Map([
|
||||
["requested_frames", List(Tuple([StringT(), Duration(), Int()]))],
|
||||
]);
|
||||
Target.methods = new Map([
|
||||
["altitude", sig([{ name: "t", type: Time() }], Angle(), ["schedule.read"])],
|
||||
]);
|
||||
|
||||
const Schedule = Struct("Schedule");
|
||||
Schedule.methods = new Map([
|
||||
["tonight", sig([], List(Target), ["schedule.read"])],
|
||||
["best_target", sig([{ name: "t", type: Time() }], Optional(Target), ["schedule.read"])],
|
||||
]);
|
||||
|
||||
const FlatPanel = Struct("FlatPanel");
|
||||
FlatPanel.methods = new Map([
|
||||
["on", sig([{ name: "brightness", type: PercentT() }], Void(), ["dome.flat_panel"])],
|
||||
["off", sig([], Void(), ["dome.flat_panel"])],
|
||||
]);
|
||||
|
||||
const Camera = Struct("Camera");
|
||||
Camera.methods = new Map([
|
||||
["shutter", sig([{ name: "state", type: StringT() }], Void(), ["camera.shutter"])],
|
||||
]);
|
||||
|
||||
const FilterWheel = Struct("FilterWheel");
|
||||
FilterWheel.methods = new Map([
|
||||
["select", sig([{ name: "filter", type: StringT() }], Void(), ["filter_wheel.move"])],
|
||||
]);
|
||||
|
||||
const Focuser = Struct("Focuser");
|
||||
Focuser.methods = new Map([
|
||||
["move_to", sig([{ name: "pos", type: Steps() }], Void(), ["telescope.focus"])],
|
||||
]);
|
||||
|
||||
// ---------- resource method tables ----------
|
||||
// `T.<method>` look-up: methods keyed by resource name.
|
||||
export const RESOURCE_METHODS = {
|
||||
Telescope: new Map([
|
||||
// Pointable: anything we can slew to. Coord<ICRS> for raw positions,
|
||||
// Target for schedule entries.
|
||||
["slew", sig([{ name: "target", type: Union([Coord("ICRS"), Target]) }], Void(), ["telescope.move"])],
|
||||
["park", sig([], Void(), ["telescope.move"])],
|
||||
["home", sig([], Void(), ["telescope.move"])],
|
||||
["wait_until_settled", sig([], Void(), ["telescope.move"])],
|
||||
["cooldown", sig(
|
||||
[{ name: "target", type: Temperature() }, { name: "timeout", type: Duration(), optional: true }],
|
||||
Void(), ["telescope.cool"])],
|
||||
["warm_up", sig([], Void(), ["telescope.cool"])],
|
||||
["expose", sig(
|
||||
[{ name: "exp", type: Duration() }, { name: "filter", type: StringT() }],
|
||||
ImageT(), ["telescope.image"])],
|
||||
["focus", sig([{ name: "method", type: StringT() }], Void(), ["telescope.focus"])],
|
||||
["focus_if_needed", sig(
|
||||
[{ name: "max_age", type: Duration(), optional: true },
|
||||
{ name: "temp_delta", type: Temperature(), optional: true }],
|
||||
Void(), ["telescope.focus"])],
|
||||
["dither", sig(
|
||||
[{ name: "amount", type: Angle() }, { name: "pattern", type: StringT(), optional: true }],
|
||||
Void(), ["telescope.image"])],
|
||||
["auto_flat_exposure",
|
||||
sig([{ name: "filter", type: StringT() }], Duration(), ["telescope.image"])],
|
||||
["is_idle", Bool()], // property
|
||||
["filter_wheel", FilterWheel],
|
||||
["focuser", Focuser],
|
||||
["camera", Camera],
|
||||
]),
|
||||
Dome: new Map([
|
||||
["open", sig([], Void(), ["dome.move"])],
|
||||
["close", sig([], Void(), ["dome.move"])],
|
||||
["is_closed", sig([], Bool(), [])],
|
||||
["flat_panel", FlatPanel],
|
||||
]),
|
||||
Camera: Camera.methods,
|
||||
FilterWheel: FilterWheel.methods,
|
||||
Focuser: Focuser.methods,
|
||||
};
|
||||
|
||||
// ---------- struct method look-up (for objects whose type is Struct) ----------
|
||||
export const STRUCT_DEFS = {
|
||||
Weather, Target, Schedule, FlatPanel, Camera, FilterWheel, Focuser,
|
||||
// Image is a Prim-like type but accessed via methods; model as struct.
|
||||
Image: (() => {
|
||||
const s = Struct("Image");
|
||||
s.methods = new Map([
|
||||
["hfr", sig([], Pixels(), [])],
|
||||
]);
|
||||
return s;
|
||||
})(),
|
||||
};
|
||||
|
||||
// ---------- global bindings ----------
|
||||
// Catalog identifiers. Real catalog imports happen via ImportDecl.
|
||||
const ICRS_TARGET = Coord("ICRS");
|
||||
|
||||
export const CATALOG_TARGETS = ["M31", "M42", "M51", "M81", "M101", "NGC_7000"];
|
||||
|
||||
// Default top-level globals always in scope.
|
||||
export const GLOBALS = {
|
||||
now: Time(),
|
||||
sunset: Time(),
|
||||
sunrise: Time(),
|
||||
weather: Weather,
|
||||
schedule: Schedule,
|
||||
// Built-in functions
|
||||
cos: sig([{ name: "angle", type: Angle() }], Float(), []),
|
||||
sin: sig([{ name: "angle", type: Angle() }], Float(), []),
|
||||
parabola_min: sig(
|
||||
[{ name: "samples", type: List(Tuple([Steps(), Pixels()])) }],
|
||||
Steps(), []),
|
||||
rollback: sig([], Void(), []),
|
||||
halt: sig([], Void(), []),
|
||||
};
|
||||
|
||||
// Time arithmetic: Time + Duration -> Time, Time - Duration -> Time.
|
||||
// Plus there is Time.has_passed: Bool. Modeled inline by checker.
|
||||
export const TIME_FIELDS = new Map([
|
||||
["has_passed", Bool()],
|
||||
]);
|
||||
|
||||
// Modules importable via `import { ... } from "catalog/<name>"`.
|
||||
// All return Coord<ICRS> identifiers. The static map below names ones we
|
||||
// guarantee at the parser level; lookupImport() also accepts any path that
|
||||
// starts with `catalog/` and treats unknown names as Coord<ICRS> so user-
|
||||
// provided JSON catalogs don't trigger checker errors.
|
||||
const STATIC_MODULES = {
|
||||
"catalog/messier": Object.fromEntries(["M31","M42","M51","M81","M101"].map(n => [n, ICRS_TARGET])),
|
||||
};
|
||||
|
||||
export const MODULES = new Proxy(STATIC_MODULES, {
|
||||
has(target, prop) {
|
||||
return prop in target || (typeof prop === "string" && prop.startsWith("catalog/"));
|
||||
},
|
||||
get(target, prop) {
|
||||
if (prop in target) return target[prop];
|
||||
if (typeof prop === "string" && prop.startsWith("catalog/")) {
|
||||
// Any name imported from a catalog/* path is assumed Coord<ICRS>.
|
||||
return new Proxy({}, { has: () => true, get: () => ICRS_TARGET });
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
// ---------- Implicit context providers ----------
|
||||
// Each provider exposes a Map<name, Type> of field bindings that are
|
||||
// brought into scope when their head identifier appears in a requires or
|
||||
// safety predicate. `time` and resource kinds don't add bindings — their
|
||||
// args reference globals or named resources directly.
|
||||
export const CONTEXT_PROVIDERS = {
|
||||
weather: () => Weather.fields,
|
||||
time: () => new Map(),
|
||||
telescope: () => new Map(),
|
||||
dome: () => new Map(),
|
||||
camera: () => new Map(),
|
||||
};
|
||||
|
||||
// Bare-identifier event names allowed inside `safety on <event>` clauses.
|
||||
// These have no type information; the runtime registrar resolves them.
|
||||
export const SAFETY_EVENTS = [
|
||||
"cloud", "rain", "snow", "wind_burst", "humidity_spike",
|
||||
"power_loss", "emergency_stop", "comms_lost", "earthquake",
|
||||
];
|
||||
|
||||
// ---------- List builtin methods ----------
|
||||
// Resolved by the checker when a member access targets a List<T>. Returns
|
||||
// a signature specialized to T (see lookupListMember).
|
||||
export function listMethod(name, elementT) {
|
||||
switch (name) {
|
||||
case "length": return sig([], Int(), []);
|
||||
case "push": return sig([{ name: "item", type: elementT }], Void(), []);
|
||||
case "filter": return sig([{ name: "pred",
|
||||
type: { kind: "Fn", params: [elementT], paramNames: ["item"],
|
||||
paramOptional: [false], returnType: Bool(), caps: new Set() } }],
|
||||
List(elementT), []);
|
||||
case "map": return sig([{ name: "fn",
|
||||
type: { kind: "Fn", params: [elementT], paramNames: ["item"],
|
||||
paramOptional: [false], returnType: Any(), caps: new Set() } }],
|
||||
List(Any()), []);
|
||||
case "sort_by": return sig([{ name: "key",
|
||||
type: { kind: "Fn", params: [elementT], paramNames: ["item"],
|
||||
paramOptional: [false], returnType: Any(), caps: new Set() } }],
|
||||
List(elementT), []);
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,716 @@
|
||||
// Type checker for Nox.
|
||||
//
|
||||
// Pass 1: collect top-level declarations into the module scope so functions
|
||||
// can refer to each other regardless of order.
|
||||
// Pass 2: walk every node, inferring types and recording diagnostics.
|
||||
//
|
||||
// The checker is permissive: unknown symbols downgrade to Any to avoid
|
||||
// cascading errors, but we still emit a diagnostic at the original site.
|
||||
|
||||
import {
|
||||
Prim, Quantity, Coord, Resource, List, Dict, Tuple, Fn, Generic,
|
||||
ImageT, Time, Optional, Range, Struct, PercentT, Void, Any, ErrType,
|
||||
Duration, Angle, Temperature, Speed, Int, Float, StringT, Bool, Pixels, Steps,
|
||||
UNIT_TABLE, RESOURCES, DIMENSIONS, FRAMES,
|
||||
typeEquals, assignable, typeToString, typeFromAst,
|
||||
} from "./types.js";
|
||||
import {
|
||||
RESOURCE_METHODS, STRUCT_DEFS, GLOBALS, MODULES, CATALOG_TARGETS, TIME_FIELDS,
|
||||
listMethod, CONTEXT_PROVIDERS, SAFETY_EVENTS,
|
||||
} from "./builtins.js";
|
||||
|
||||
// ---------- scope ----------
|
||||
class Scope {
|
||||
constructor(parent = null) {
|
||||
this.parent = parent;
|
||||
this.symbols = new Map();
|
||||
}
|
||||
define(name, type) { this.symbols.set(name, type); }
|
||||
lookup(name) {
|
||||
for (let s = this; s; s = s.parent) {
|
||||
if (s.symbols.has(name)) return s.symbols.get(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- entry point ----------
|
||||
export function check(program) {
|
||||
const diags = [];
|
||||
const global = new Scope();
|
||||
|
||||
// seed globals + catalog
|
||||
for (const [k, v] of Object.entries(GLOBALS)) global.define(k, v);
|
||||
for (const name of CATALOG_TARGETS) global.define(name, Coord("ICRS"));
|
||||
|
||||
// Pass 1: hoist top-level fn names and use/let/var bindings.
|
||||
const top = collectTopBindings(program, global, diags);
|
||||
|
||||
// Pass 2: type-check every node.
|
||||
const c = new Checker(diags);
|
||||
c.checkProgram(program, top);
|
||||
|
||||
return { diagnostics: diags, scope: top };
|
||||
}
|
||||
|
||||
function collectTopBindings(program, parent, diags) {
|
||||
const scope = new Scope(parent);
|
||||
for (const node of program.body) {
|
||||
hoist(node, scope, diags);
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
function hoist(node, scope, diags) {
|
||||
switch (node.type) {
|
||||
case "Import":
|
||||
for (const n of node.names) {
|
||||
const mod = MODULES[node.from];
|
||||
if (!mod) diags.push(diag(node, `unknown module: ${node.from}`));
|
||||
else if (!(n in mod)) diags.push(diag(node, `'${n}' not exported by ${node.from}`));
|
||||
else scope.define(n, mod[n]);
|
||||
}
|
||||
return;
|
||||
case "Use":
|
||||
scope.define(node.name, resourceTypeFromKind(node.kind, node, diags));
|
||||
return;
|
||||
case "Let":
|
||||
case "Var":
|
||||
// Type recorded after RHS check during pass 2; placeholder for forward ref.
|
||||
scope.define(node.name, node.declaredType ? typeFromAst(node.declaredType) : Any());
|
||||
return;
|
||||
case "Fn":
|
||||
scope.define(node.name, fnSignatureFromAst(node));
|
||||
return;
|
||||
case "Decorated":
|
||||
hoist(node.decl, scope, diags);
|
||||
return;
|
||||
case "Session":
|
||||
case "Policy":
|
||||
// sessions/policies don't introduce module-scope names
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function resourceTypeFromKind(kind, node, diags) {
|
||||
const name = {
|
||||
telescope: "Telescope",
|
||||
dome: "Dome",
|
||||
camera: "Camera",
|
||||
filter_wheel: "FilterWheel",
|
||||
focuser: "Focuser",
|
||||
}[kind];
|
||||
if (!name) {
|
||||
diags.push(diag(node, `unknown resource kind: ${kind}`));
|
||||
return Any();
|
||||
}
|
||||
return Resource(name);
|
||||
}
|
||||
|
||||
function fnSignatureFromAst(node) {
|
||||
const params = node.params.map(p => typeFromAst(p.paramType));
|
||||
const paramNames = node.params.map(p => p.name);
|
||||
const paramOptional = node.params.map(p => p.default !== null);
|
||||
const ret = node.returnType ? typeFromAst(node.returnType) : Void();
|
||||
return { kind: "Fn", params, paramNames, paramOptional, returnType: ret, caps: new Set() };
|
||||
}
|
||||
|
||||
// ---------- checker class ----------
|
||||
class Checker {
|
||||
constructor(diags) {
|
||||
this.diags = diags;
|
||||
}
|
||||
|
||||
// ---------- top level ----------
|
||||
checkProgram(program, top) {
|
||||
for (const node of program.body) this.checkTop(node, top);
|
||||
}
|
||||
|
||||
checkTop(node, scope) {
|
||||
switch (node.type) {
|
||||
case "Import": return;
|
||||
case "Use": return this.checkExpr(node.value, scope);
|
||||
case "Let":
|
||||
case "Var": return this.checkLet(node, scope);
|
||||
case "Fn": return this.checkFn(node, scope);
|
||||
case "Decorated": return this.checkTop(node.decl, scope);
|
||||
case "Session": return this.checkSession(node, scope);
|
||||
case "Policy": return this.checkPolicy(node, scope);
|
||||
default: return this.checkStmt(node, scope);
|
||||
}
|
||||
}
|
||||
|
||||
checkLet(node, scope) {
|
||||
const decl = node.declaredType ? typeFromAst(node.declaredType) : null;
|
||||
if (decl) emitTypeErrors(decl, node, this.diags);
|
||||
// Empty list / dict literals adopt the declared type when present.
|
||||
let valueT;
|
||||
if (decl && isEmptyContainerLiteral(node.value)) {
|
||||
valueT = decl;
|
||||
this.checkExpr(node.value, scope);
|
||||
} else {
|
||||
valueT = this.checkExpr(node.value, scope);
|
||||
}
|
||||
if (decl && !assignable(decl, valueT)) {
|
||||
this.diags.push(diag(node, `type mismatch: ${typeToString(decl)} cannot accept ${typeToString(valueT)}`));
|
||||
}
|
||||
scope.define(node.name, decl || valueT);
|
||||
}
|
||||
|
||||
checkFn(node, parent) {
|
||||
const local = new Scope(parent);
|
||||
for (const p of node.params) local.define(p.name, typeFromAst(p.paramType));
|
||||
for (const s of node.body) this.checkStmt(s, local);
|
||||
}
|
||||
|
||||
checkSession(node, scope) {
|
||||
const local = new Scope(scope);
|
||||
// Pre-pass: hoist Use / Let / Var / Fn so safety handlers and other
|
||||
// clauses can refer to session-scoped names regardless of textual order.
|
||||
for (const m of node.members) {
|
||||
if (m.type === "Use") local.define(m.name, resourceTypeFromKind(m.kind, m, this.diags));
|
||||
else if (m.type === "Let" || m.type === "Var") {
|
||||
local.define(m.name, m.declaredType ? typeFromAst(m.declaredType) : Any());
|
||||
} else if (m.type === "Fn") {
|
||||
local.define(m.name, fnSignatureFromAst(m));
|
||||
}
|
||||
}
|
||||
for (const m of node.members) {
|
||||
switch (m.type) {
|
||||
case "Requires":
|
||||
// Type-check each predicate inside an implicit scope that exposes
|
||||
// the named context's fields (e.g. `weather(clouds < 20%)` brings
|
||||
// weather.clouds into scope as `clouds`).
|
||||
for (const item of m.items) {
|
||||
const ctxScope = pushContextScope(local, item.name);
|
||||
for (const arg of item.args) this.checkExpr(arg, ctxScope);
|
||||
}
|
||||
break;
|
||||
case "Safety": {
|
||||
// Safety triggers can be a symbolic event name (cloud, power_loss),
|
||||
// a weather-field predicate (wind > 50kph), or any other expression.
|
||||
// Provide both context bindings.
|
||||
const safetyCtx = pushSafetyScope(local);
|
||||
this.checkExpr(m.trigger, safetyCtx);
|
||||
for (const s of m.body) this.checkStmt(s, local);
|
||||
break;
|
||||
}
|
||||
case "Use":
|
||||
// already hoisted; just check the RHS
|
||||
this.checkExpr(m.value, local);
|
||||
break;
|
||||
case "Let":
|
||||
case "Var":
|
||||
this.checkLet(m, local);
|
||||
break;
|
||||
case "Fn":
|
||||
// already hoisted; just check the body
|
||||
this.checkFn(m, local);
|
||||
break;
|
||||
default:
|
||||
this.checkStmt(m, local);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkPolicy(node, scope) {
|
||||
const local = new Scope(scope);
|
||||
for (const rule of node.rules) {
|
||||
this.checkExpr(rule.condition, local);
|
||||
for (const s of rule.body) this.checkStmt(s, local);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- statements ----------
|
||||
checkStmt(node, scope) {
|
||||
switch (node.type) {
|
||||
case "Let":
|
||||
case "Var": return this.checkLet(node, scope);
|
||||
case "If": return this.checkIf(node, scope);
|
||||
case "For": return this.checkFor(node, scope);
|
||||
case "Repeat": return this.checkRepeat(node, scope);
|
||||
case "While": return this.checkWhile(node, scope);
|
||||
case "Parallel": for (const c of node.children) this.checkStmt(c, scope); return;
|
||||
case "Task": for (const s of node.body) this.checkStmt(s, scope); return;
|
||||
case "OnRollback": for (const s of node.body) this.checkStmt(s, scope); return;
|
||||
case "Return":
|
||||
case "Yield": if (node.value) this.checkExpr(node.value, scope); return;
|
||||
case "Continue":
|
||||
case "Break":
|
||||
case "Halt": return;
|
||||
case "Assert":
|
||||
this.checkExpr(node.cond, scope);
|
||||
if (node.message) this.checkExpr(node.message, scope);
|
||||
return;
|
||||
case "Assign":
|
||||
this.checkExpr(node.target, scope);
|
||||
this.checkExpr(node.value, scope);
|
||||
return;
|
||||
case "ExprStmt":
|
||||
this.checkExpr(node.expr, scope);
|
||||
return;
|
||||
default:
|
||||
this.diags.push(diag(node, `unhandled statement type: ${node.type}`));
|
||||
}
|
||||
}
|
||||
|
||||
checkIf(node, scope) {
|
||||
const cT = this.checkExpr(node.cond, scope);
|
||||
if (cT.kind !== "Bool" && cT.kind !== "Any" && !(cT.kind === "Prim" && cT.name === "Bool")) {
|
||||
this.diags.push(diag(node, `if condition must be Bool, got ${typeToString(cT)}`));
|
||||
}
|
||||
// Flow-sensitive narrowing: in the then-branch, `if x?` makes x non-null.
|
||||
const thenScope = narrowOnTrue(node.cond, scope);
|
||||
for (const s of node.then) this.checkStmt(s, thenScope);
|
||||
if (Array.isArray(node.else)) for (const s of node.else) this.checkStmt(s, scope);
|
||||
else if (node.else) this.checkStmt(node.else, scope);
|
||||
}
|
||||
|
||||
checkFor(node, scope) {
|
||||
const iterT = this.checkExpr(node.iter, scope);
|
||||
const elementT = iterableElement(iterT);
|
||||
if (!elementT) {
|
||||
this.diags.push(diag(node, `cannot iterate over ${typeToString(iterT)}`));
|
||||
}
|
||||
if (node.step) this.checkExpr(node.step, scope);
|
||||
const local = new Scope(scope);
|
||||
bindPattern(local, node.binding, elementT || Any());
|
||||
for (const s of node.body) this.checkStmt(s, local);
|
||||
}
|
||||
|
||||
checkRepeat(node, scope) {
|
||||
const n = this.checkExpr(node.count, scope);
|
||||
if (!isInt(n)) {
|
||||
this.diags.push(diag(node, `repeat count must be Int, got ${typeToString(n)}`));
|
||||
}
|
||||
for (const s of node.body) this.checkStmt(s, scope);
|
||||
}
|
||||
|
||||
checkWhile(node, scope) {
|
||||
const c = this.checkExpr(node.cond, scope);
|
||||
if (!(c.kind === "Prim" && c.name === "Bool") && c.kind !== "Any") {
|
||||
this.diags.push(diag(node, `while condition must be Bool, got ${typeToString(c)}`));
|
||||
}
|
||||
for (const s of node.body) this.checkStmt(s, scope);
|
||||
}
|
||||
|
||||
// ---------- expressions ----------
|
||||
checkExpr(node, scope) {
|
||||
if (!node) return Any();
|
||||
switch (node.type) {
|
||||
case "Number": return Int();
|
||||
case "Bool": return Bool();
|
||||
case "String": return StringT();
|
||||
case "InterpolatedString":
|
||||
for (const p of node.parts) if (p.kind === "expr") this.checkExpr(p.value, scope);
|
||||
return StringT();
|
||||
case "Percent": return PercentT();
|
||||
case "Now": return Time();
|
||||
case "UnitLit": return this.checkUnitLit(node);
|
||||
case "Ident": return this.checkIdent(node, scope);
|
||||
case "TypedCtor": return this.checkTypedCtor(node, scope);
|
||||
case "List": return this.checkList(node, scope);
|
||||
case "Tuple": return Tuple(node.elements.map(e => this.checkExpr(e, scope)));
|
||||
case "Dict": return this.checkDict(node, scope);
|
||||
case "Member": return this.checkMember(node, scope);
|
||||
case "Index": return this.checkIndex(node, scope);
|
||||
case "Call": return this.checkCall(node, scope);
|
||||
case "Optional": {
|
||||
// Postfix `?` is a presence test: `x?` evaluates to Bool.
|
||||
this.checkExpr(node.expr, scope);
|
||||
return Bool();
|
||||
}
|
||||
case "Unary": return this.checkUnary(node, scope);
|
||||
case "Not": this.checkExpr(node.expr, scope); return Bool();
|
||||
case "Range": return this.checkRange(node, scope);
|
||||
case "BinOp": return this.checkBinOp(node, scope);
|
||||
case "Time": this.checkExpr(node.expr, scope); return Time();
|
||||
case "Lambda": return this.checkLambda(node, scope);
|
||||
default:
|
||||
this.diags.push(diag(node, `unhandled expression: ${node.type}`));
|
||||
return Any();
|
||||
}
|
||||
}
|
||||
|
||||
checkUnitLit(node) {
|
||||
const u = UNIT_TABLE[node.unit];
|
||||
if (!u) {
|
||||
this.diags.push(diag(node, `unknown unit: ${node.unit}`));
|
||||
return Any();
|
||||
}
|
||||
return Quantity(u.dimension);
|
||||
}
|
||||
|
||||
checkIdent(node, scope) {
|
||||
const t = scope.lookup(node.name);
|
||||
if (!t) {
|
||||
this.diags.push(diag(node, `unknown identifier: ${node.name}`));
|
||||
return Any();
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
checkTypedCtor(node, scope) {
|
||||
if (node.name === "Coord") {
|
||||
const arg = node.typeArgs[0];
|
||||
const frame = arg && arg.kind === "Named" ? arg.name : null;
|
||||
if (!FRAMES.includes(frame)) {
|
||||
this.diags.push(diag(node, `unknown coordinate frame: ${frame}`));
|
||||
return Coord("ICRS");
|
||||
}
|
||||
for (const a of node.args) this.checkExpr(a.value, scope);
|
||||
return Coord(frame);
|
||||
}
|
||||
for (const a of node.args) this.checkExpr(a.value, scope);
|
||||
return Any();
|
||||
}
|
||||
|
||||
checkList(node, scope) {
|
||||
if (node.elements.length === 0) return List(Any());
|
||||
const ts = node.elements.map(e => this.checkExpr(e, scope));
|
||||
const first = ts[0];
|
||||
for (const t of ts.slice(1)) {
|
||||
if (!assignable(first, t) && !assignable(t, first)) {
|
||||
this.diags.push(diag(node, `list elements have mismatched types: ${typeToString(first)} vs ${typeToString(t)}`));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return List(first);
|
||||
}
|
||||
|
||||
checkDict(node, scope) {
|
||||
if (node.entries.length === 0) return Dict(Any(), Any());
|
||||
const keyTs = node.entries.map(e => this.checkExpr(e.key, scope));
|
||||
const valTs = node.entries.map(e => this.checkExpr(e.value, scope));
|
||||
return Dict(keyTs[0], valTs[0]);
|
||||
}
|
||||
|
||||
checkMember(node, scope) {
|
||||
const objT = this.checkExpr(node.object, scope);
|
||||
return this.lookupMember(objT, node.name, node);
|
||||
}
|
||||
|
||||
lookupMember(objT, name, locNode) {
|
||||
if (objT.kind === "Any") return Any();
|
||||
if (objT.kind === "Resource") {
|
||||
const tbl = RESOURCE_METHODS[objT.name];
|
||||
if (tbl && tbl.has(name)) return tbl.get(name);
|
||||
this.diags.push(diag(locNode, `${objT.name} has no member '${name}'`));
|
||||
return Any();
|
||||
}
|
||||
if (objT.kind === "Struct") {
|
||||
if (objT.fields && objT.fields.has(name)) return objT.fields.get(name);
|
||||
if (objT.methods && objT.methods.has(name)) return objT.methods.get(name);
|
||||
this.diags.push(diag(locNode, `${objT.name} has no member '${name}'`));
|
||||
return Any();
|
||||
}
|
||||
if (objT.kind === "Time") {
|
||||
if (TIME_FIELDS.has(name)) return TIME_FIELDS.get(name);
|
||||
this.diags.push(diag(locNode, `Time has no member '${name}'`));
|
||||
return Any();
|
||||
}
|
||||
if (objT.kind === "Image") {
|
||||
const s = STRUCT_DEFS.Image;
|
||||
if (s.methods.has(name)) return s.methods.get(name);
|
||||
this.diags.push(diag(locNode, `Image has no member '${name}'`));
|
||||
return Any();
|
||||
}
|
||||
if (objT.kind === "Optional") {
|
||||
// Drilling into an Optional. The runtime will need a guard; for now,
|
||||
// peel and continue.
|
||||
return this.lookupMember(objT.element, name, locNode);
|
||||
}
|
||||
if (objT.kind === "List") {
|
||||
const m = listMethod(name, objT.element);
|
||||
if (m) return m;
|
||||
this.diags.push(diag(locNode, `List has no member '${name}'`));
|
||||
return Any();
|
||||
}
|
||||
this.diags.push(diag(locNode, `cannot access member '${name}' on ${typeToString(objT)}`));
|
||||
return Any();
|
||||
}
|
||||
|
||||
checkIndex(node, scope) {
|
||||
const objT = this.checkExpr(node.object, scope);
|
||||
this.checkExpr(node.index, scope);
|
||||
if (objT.kind === "List") return objT.element;
|
||||
if (objT.kind === "Dict") return objT.value;
|
||||
if (objT.kind === "Tuple") return Any(); // could be statically known if index is literal
|
||||
if (objT.kind === "Any") return Any();
|
||||
this.diags.push(diag(node, `cannot index ${typeToString(objT)}`));
|
||||
return Any();
|
||||
}
|
||||
|
||||
checkCall(node, scope) {
|
||||
const calleeT = this.checkExpr(node.callee, scope);
|
||||
const argTs = node.args.map(a => ({ name: a.name, type: this.checkExpr(a.value, scope) }));
|
||||
|
||||
if (calleeT.kind === "Any") return Any();
|
||||
if (calleeT.kind !== "Fn") {
|
||||
this.diags.push(diag(node, `cannot call ${typeToString(calleeT)}`));
|
||||
return Any();
|
||||
}
|
||||
|
||||
// Resolve named args against the param list.
|
||||
const resolved = resolveArgs(calleeT, argTs, this.diags, node);
|
||||
for (let i = 0; i < resolved.length; i++) {
|
||||
const expected = calleeT.params[i];
|
||||
const provided = resolved[i];
|
||||
if (provided === null) continue; // optional and omitted
|
||||
if (!assignable(expected, provided)) {
|
||||
this.diags.push(diag(node,
|
||||
`arg ${i + 1} (${calleeT.paramNames ? calleeT.paramNames[i] : i}): expected ${typeToString(expected)}, got ${typeToString(provided)}`));
|
||||
}
|
||||
}
|
||||
return calleeT.returnType;
|
||||
}
|
||||
|
||||
checkUnary(node, scope) {
|
||||
const t = this.checkExpr(node.expr, scope);
|
||||
return t; // unary +/- preserves type
|
||||
}
|
||||
|
||||
checkRange(node, scope) {
|
||||
const a = this.checkExpr(node.start, scope);
|
||||
const b = this.checkExpr(node.end, scope);
|
||||
if (!commensurable(a, b)) {
|
||||
this.diags.push(diag(node, `range endpoints incompatible: ${typeToString(a)} .. ${typeToString(b)}`));
|
||||
}
|
||||
return Range(a);
|
||||
}
|
||||
|
||||
checkBinOp(node, scope) {
|
||||
const op = node.op;
|
||||
const l = this.checkExpr(node.left, scope);
|
||||
const r = this.checkExpr(node.right, scope);
|
||||
|
||||
if (op === "and" || op === "or") return Bool();
|
||||
if (["<", "<=", ">", ">=", "==", "!="].includes(op)) {
|
||||
if (!commensurable(l, r)) {
|
||||
this.diags.push(diag(node, `cannot compare ${typeToString(l)} ${op} ${typeToString(r)}`));
|
||||
}
|
||||
return Bool();
|
||||
}
|
||||
if (op === "in") {
|
||||
// Right side must be iterable. Left must match the element / key type.
|
||||
if (r.kind === "Any") return Bool();
|
||||
if (r.kind === "List") {
|
||||
if (!assignable(r.element, l)) {
|
||||
this.diags.push(diag(node, `cannot test '${typeToString(l)} in ${typeToString(r)}': element type is ${typeToString(r.element)}`));
|
||||
}
|
||||
} else if (r.kind === "Dict") {
|
||||
if (!assignable(r.key, l)) {
|
||||
this.diags.push(diag(node, `cannot test '${typeToString(l)} in ${typeToString(r)}': key type is ${typeToString(r.key)}`));
|
||||
}
|
||||
} else if (r.kind === "Prim" && r.name === "String") {
|
||||
if (!(l.kind === "Prim" && l.name === "String")) {
|
||||
this.diags.push(diag(node, `cannot test '${typeToString(l)} in String': left must be String`));
|
||||
}
|
||||
} else {
|
||||
this.diags.push(diag(node, `right side of 'in' must be List, Dict, or String, got ${typeToString(r)}`));
|
||||
}
|
||||
return Bool();
|
||||
}
|
||||
if (op === "+" || op === "-") {
|
||||
// Time + Duration -> Time, Time - Duration -> Time
|
||||
if (l.kind === "Time" && isDuration(r)) return Time();
|
||||
if (r.kind === "Time" && isDuration(l) && op === "+") return Time();
|
||||
if (sameQuantity(l, r)) return l;
|
||||
if (isNumber(l) && isNumber(r)) return numericResult(l, r);
|
||||
if (l.kind === "Any" || r.kind === "Any") return Any();
|
||||
this.diags.push(diag(node, `cannot ${op}: ${typeToString(l)} and ${typeToString(r)}`));
|
||||
return Any();
|
||||
}
|
||||
if (op === "*") {
|
||||
if (isNumber(l) && isQuantity(r)) return r;
|
||||
if (isQuantity(l) && isNumber(r)) return l;
|
||||
if (isNumber(l) && isNumber(r)) return numericResult(l, r);
|
||||
if (isQuantity(l) && isQuantity(r)) {
|
||||
// quantity * quantity is dimensionally complex; allow but type as Any.
|
||||
return Any();
|
||||
}
|
||||
if (l.kind === "Any" || r.kind === "Any") return Any();
|
||||
this.diags.push(diag(node, `cannot *: ${typeToString(l)} and ${typeToString(r)}`));
|
||||
return Any();
|
||||
}
|
||||
if (op === "/") {
|
||||
if (isQuantity(l) && isNumber(r)) return l;
|
||||
if (isNumber(l) && isNumber(r)) return numericResult(l, r);
|
||||
if (l.kind === "Any" || r.kind === "Any") return Any();
|
||||
this.diags.push(diag(node, `cannot /: ${typeToString(l)} and ${typeToString(r)}`));
|
||||
return Any();
|
||||
}
|
||||
if (op === "%") {
|
||||
if (isNumber(l) && isNumber(r)) return numericResult(l, r);
|
||||
return Any();
|
||||
}
|
||||
this.diags.push(diag(node, `unknown operator: ${op}`));
|
||||
return Any();
|
||||
}
|
||||
|
||||
checkLambda(node, parent) {
|
||||
const local = new Scope(parent);
|
||||
for (const p of node.params) {
|
||||
local.define(p.name, p.paramType ? typeFromAst(p.paramType) : Any());
|
||||
}
|
||||
let ret;
|
||||
if (node.body && node.body.type === "DoBlock") {
|
||||
for (const s of node.body.body) this.checkStmt(s, local);
|
||||
ret = Void();
|
||||
} else {
|
||||
ret = this.checkExpr(node.body, local);
|
||||
}
|
||||
return { kind: "Fn", params: node.params.map(p => p.paramType ? typeFromAst(p.paramType) : Any()),
|
||||
paramNames: node.params.map(p => p.name),
|
||||
paramOptional: node.params.map(() => false),
|
||||
returnType: ret, caps: new Set() };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
function diag(node, message) {
|
||||
const loc = node.loc || null;
|
||||
return { message, line: loc ? loc.line : null, column: loc ? loc.column : null };
|
||||
}
|
||||
|
||||
function bindPattern(scope, pat, t) {
|
||||
if (pat.type === "NamePat") {
|
||||
scope.define(pat.name, t);
|
||||
return;
|
||||
}
|
||||
if (pat.type === "TuplePat") {
|
||||
if (t.kind === "Tuple" && t.elements.length === pat.items.length) {
|
||||
for (let i = 0; i < pat.items.length; i++) bindPattern(scope, pat.items[i], t.elements[i]);
|
||||
} else {
|
||||
for (const item of pat.items) bindPattern(scope, item, Any());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function iterableElement(t) {
|
||||
if (t.kind === "List") return t.element;
|
||||
if (t.kind === "Range") return t.element;
|
||||
if (t.kind === "Dict") return Tuple([t.key, t.value]);
|
||||
if (t.kind === "Any") return Any();
|
||||
return null;
|
||||
}
|
||||
|
||||
// Narrow types in a scope based on a condition known to be true.
|
||||
// Currently handles `x?` (presence test on identifier) — narrows Optional<T> to T.
|
||||
function narrowOnTrue(cond, scope) {
|
||||
if (!cond) return scope;
|
||||
if (cond.type === "Optional" && cond.expr && cond.expr.type === "Ident") {
|
||||
const t = scope.lookup(cond.expr.name);
|
||||
if (t && t.kind === "Optional") {
|
||||
const child = new Scope(scope);
|
||||
child.define(cond.expr.name, t.element);
|
||||
return child;
|
||||
}
|
||||
}
|
||||
// `cond1 and cond2` narrows by both, in order.
|
||||
if (cond.type === "BinOp" && cond.op === "and") {
|
||||
return narrowOnTrue(cond.right, narrowOnTrue(cond.left, scope));
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
// Push a child scope with the named context provider's field bindings.
|
||||
// Falls through (returns parent unchanged) when the provider is unknown
|
||||
// or adds no bindings.
|
||||
function pushContextScope(parent, providerName) {
|
||||
const provider = CONTEXT_PROVIDERS[providerName];
|
||||
if (!provider) return parent;
|
||||
const fields = provider();
|
||||
if (!fields || fields.size === 0) return parent;
|
||||
const s = new Scope(parent);
|
||||
for (const [k, t] of fields) s.define(k, t);
|
||||
return s;
|
||||
}
|
||||
|
||||
// Scope used for the trigger expression of a `safety on ...` clause.
|
||||
// Adds weather fields plus the named-event identifiers as Any.
|
||||
function pushSafetyScope(parent) {
|
||||
const withWeather = pushContextScope(parent, "weather");
|
||||
const s = new Scope(withWeather);
|
||||
for (const ev of SAFETY_EVENTS) s.define(ev, Any());
|
||||
return s;
|
||||
}
|
||||
|
||||
// Walks a Type tree and emits a diagnostic for each Error node found.
|
||||
function emitTypeErrors(t, locNode, diags) {
|
||||
if (!t) return;
|
||||
if (t.kind === "Error") {
|
||||
diags.push(diag(locNode, t.message));
|
||||
return;
|
||||
}
|
||||
if (t.element) emitTypeErrors(t.element, locNode, diags);
|
||||
if (t.elements) for (const e of t.elements) emitTypeErrors(e, locNode, diags);
|
||||
if (t.params) for (const p of t.params) emitTypeErrors(p, locNode, diags);
|
||||
if (t.returnType) emitTypeErrors(t.returnType, locNode, diags);
|
||||
if (t.key) emitTypeErrors(t.key, locNode, diags);
|
||||
if (t.value && t.kind !== "Optional") emitTypeErrors(t.value, locNode, diags);
|
||||
}
|
||||
|
||||
function isEmptyContainerLiteral(node) {
|
||||
if (!node) return false;
|
||||
if (node.type === "List" && node.elements.length === 0) return true;
|
||||
if (node.type === "Dict" && node.entries.length === 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function isInt(t) { return t.kind === "Prim" && t.name === "Int"; }
|
||||
function isFloat(t) { return t.kind === "Prim" && (t.name === "Float" || t.name === "Int"); }
|
||||
function isNumber(t) { return isInt(t) || isFloat(t) || t.kind === "Percent"; }
|
||||
function isQuantity(t) { return t.kind === "Quantity"; }
|
||||
function isDuration(t) { return t.kind === "Quantity" && t.dim === "Duration"; }
|
||||
function sameQuantity(a, b) { return a.kind === "Quantity" && b.kind === "Quantity" && a.dim === b.dim; }
|
||||
function numericResult(a, b) {
|
||||
if (isInt(a) && isInt(b)) return Int();
|
||||
return Float();
|
||||
}
|
||||
|
||||
// Commensurable: comparable / addable / range-endpoints.
|
||||
function commensurable(a, b) {
|
||||
if (a.kind === "Any" || b.kind === "Any") return true;
|
||||
if (typeEquals(a, b)) return true;
|
||||
if (isNumber(a) && isNumber(b)) return true;
|
||||
if (sameQuantity(a, b)) return true;
|
||||
if (a.kind === "Time" && b.kind === "Time") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Resolve a call's args against the fn signature.
|
||||
// Returns an array of types per param (null for omitted optionals).
|
||||
function resolveArgs(fnT, argTs, diags, node) {
|
||||
const arity = fnT.params.length;
|
||||
const result = new Array(arity).fill(null);
|
||||
let positional = 0;
|
||||
for (const a of argTs) {
|
||||
if (a.name) {
|
||||
const idx = fnT.paramNames ? fnT.paramNames.indexOf(a.name) : -1;
|
||||
if (idx < 0) {
|
||||
diags.push(diag(node, `unknown parameter: ${a.name}`));
|
||||
continue;
|
||||
}
|
||||
if (result[idx] !== null) {
|
||||
diags.push(diag(node, `duplicate argument for parameter: ${a.name}`));
|
||||
continue;
|
||||
}
|
||||
result[idx] = a.type;
|
||||
} else {
|
||||
if (positional >= arity) {
|
||||
diags.push(diag(node, `too many positional arguments`));
|
||||
break;
|
||||
}
|
||||
result[positional++] = a.type;
|
||||
}
|
||||
}
|
||||
// Missing-arg check.
|
||||
for (let i = 0; i < arity; i++) {
|
||||
if (result[i] === null && !(fnT.paramOptional && fnT.paramOptional[i])) {
|
||||
const pname = fnT.paramNames ? fnT.paramNames[i] : `#${i + 1}`;
|
||||
diags.push(diag(node, `missing argument: ${pname}`));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { tokenize } from "./lexer.js";
|
||||
import { parse } from "./parser.js";
|
||||
import { buildAst } from "./ast-builder.js";
|
||||
import { check } from "./checker.js";
|
||||
|
||||
export { tokenize, parse, buildAst, check };
|
||||
|
||||
export function parseSource(source) {
|
||||
return parse(tokenize(source));
|
||||
}
|
||||
|
||||
export function compile(source) {
|
||||
return buildAst(parseSource(source));
|
||||
}
|
||||
|
||||
export function checkSource(source) {
|
||||
return check(compile(source));
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { createToken, Lexer } from "chevrotain";
|
||||
|
||||
// ---------- whitespace + comments ----------
|
||||
export const Whitespace = createToken({
|
||||
name: "Whitespace",
|
||||
pattern: /\s+/,
|
||||
group: Lexer.SKIPPED,
|
||||
});
|
||||
export const LineComment = createToken({
|
||||
name: "LineComment",
|
||||
pattern: /\/\/[^\n]*/,
|
||||
group: Lexer.SKIPPED,
|
||||
});
|
||||
export const BlockComment = createToken({
|
||||
name: "BlockComment",
|
||||
pattern: /\/\*[\s\S]*?\*\//,
|
||||
group: Lexer.SKIPPED,
|
||||
});
|
||||
|
||||
// ---------- identifier (declared early so keywords can use longer_alt) ----------
|
||||
export const Identifier = createToken({
|
||||
name: "Identifier",
|
||||
pattern: /[A-Za-z_][A-Za-z0-9_]*/,
|
||||
});
|
||||
|
||||
function kw(name, text) {
|
||||
return createToken({
|
||||
name,
|
||||
pattern: new RegExp(`${text}\\b`),
|
||||
longer_alt: Identifier,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- keywords ----------
|
||||
export const Import = kw("Import", "import");
|
||||
export const From = kw("From", "from");
|
||||
export const Use = kw("Use", "use");
|
||||
export const Let = kw("Let", "let");
|
||||
export const Var = kw("Var", "var");
|
||||
export const Fn = kw("Fn", "fn");
|
||||
export const Return = kw("Return", "return");
|
||||
export const If = kw("If", "if");
|
||||
export const Else = kw("Else", "else");
|
||||
export const For = kw("For", "for");
|
||||
export const In = kw("In", "in");
|
||||
export const Repeat = kw("Repeat", "repeat");
|
||||
export const While = kw("While", "while");
|
||||
export const Do = kw("Do", "do");
|
||||
export const Parallel = kw("Parallel", "parallel");
|
||||
export const Task = kw("Task", "task");
|
||||
export const On = kw("On", "on");
|
||||
export const Session = kw("Session", "session");
|
||||
export const Requires = kw("Requires", "requires");
|
||||
export const Safety = kw("Safety", "safety");
|
||||
export const Policy = kw("Policy", "policy");
|
||||
export const When = kw("When", "when");
|
||||
export const Yield = kw("Yield", "yield");
|
||||
export const Continue = kw("Continue", "continue");
|
||||
export const Break = kw("Break", "break");
|
||||
export const Halt = kw("Halt", "halt");
|
||||
export const Assert = kw("Assert", "assert");
|
||||
export const Not = kw("Not", "not");
|
||||
export const And = kw("And", "and");
|
||||
export const Or = kw("Or", "or");
|
||||
export const True = kw("True", "true");
|
||||
export const False = kw("False", "false");
|
||||
export const Now = kw("Now", "now");
|
||||
export const After = kw("After", "after");
|
||||
export const Before = kw("Before", "before");
|
||||
|
||||
// Soft keywords (matched as Identifier by the lexer; parser uses image checks):
|
||||
// step — in for-loop step clause
|
||||
// reached — in when-rule trailing word
|
||||
// rollback — in `on rollback { ... }` (also valid as a callable, e.g. `rollback()`)
|
||||
// telescope / dome / camera / filter_wheel / focuser — resource kinds in `use ...`
|
||||
|
||||
// ---------- literals ----------
|
||||
// Unit-suffixed numbers must come BEFORE NumberLit so the lexer doesn't
|
||||
// greedily consume the digits and leave the suffix as a stray identifier.
|
||||
// Supported suffixes mirror the EBNF UnitSuffix production.
|
||||
// ms s min h | deg arcmin arcsec | degC | kph mps | steps px
|
||||
// Order in the regex matters: longer alternatives first.
|
||||
export const UnitLit = createToken({
|
||||
name: "UnitLit",
|
||||
pattern: /[0-9]+(?:\.[0-9]+)?(?:arcsec|arcmin|degC|steps|min|deg|kph|mps|ms|px|s|h)\b/,
|
||||
});
|
||||
|
||||
export const PercentLit = createToken({
|
||||
name: "PercentLit",
|
||||
pattern: /[0-9]+(?:\.[0-9]+)?%/,
|
||||
});
|
||||
|
||||
export const NumberLit = createToken({
|
||||
name: "NumberLit",
|
||||
pattern: /[0-9]+(?:\.[0-9]+)?/,
|
||||
});
|
||||
|
||||
export const StringLit = createToken({
|
||||
name: "StringLit",
|
||||
pattern: /"(?:[^"\\]|\\.)*"/,
|
||||
});
|
||||
|
||||
// ---------- punctuation & operators ----------
|
||||
// Multi-char operators before single-char.
|
||||
export const Arrow = createToken({ name: "Arrow", pattern: /->/ });
|
||||
export const FatArrow = createToken({ name: "FatArrow", pattern: /=>/ });
|
||||
export const DotDot = createToken({ name: "DotDot", pattern: /\.\./ });
|
||||
export const LE = createToken({ name: "LE", pattern: /<=/ });
|
||||
export const GE = createToken({ name: "GE", pattern: />=/ });
|
||||
export const EQ = createToken({ name: "EQ", pattern: /==/ });
|
||||
export const NE = createToken({ name: "NE", pattern: /!=/ });
|
||||
export const PlusAssign = createToken({ name: "PlusAssign", pattern: /\+=/ });
|
||||
export const MinusAssign = createToken({ name: "MinusAssign", pattern: /-=/ });
|
||||
export const StarAssign = createToken({ name: "StarAssign", pattern: /\*=/ });
|
||||
export const SlashAssign = createToken({ name: "SlashAssign", pattern: /\/=/ });
|
||||
|
||||
export const LBrace = createToken({ name: "LBrace", pattern: /\{/ });
|
||||
export const RBrace = createToken({ name: "RBrace", pattern: /\}/ });
|
||||
export const LParen = createToken({ name: "LParen", pattern: /\(/ });
|
||||
export const RParen = createToken({ name: "RParen", pattern: /\)/ });
|
||||
export const LBracket = createToken({ name: "LBracket", pattern: /\[/ });
|
||||
export const RBracket = createToken({ name: "RBracket", pattern: /\]/ });
|
||||
export const Comma = createToken({ name: "Comma", pattern: /,/ });
|
||||
export const Semicolon = createToken({ name: "Semicolon", pattern: /;/ });
|
||||
export const Colon = createToken({ name: "Colon", pattern: /:/ });
|
||||
export const Dot = createToken({ name: "Dot", pattern: /\./ });
|
||||
export const At = createToken({ name: "At", pattern: /@/ });
|
||||
export const Question = createToken({ name: "Question", pattern: /\?/ });
|
||||
export const Assign = createToken({ name: "Assign", pattern: /=/ });
|
||||
export const LT = createToken({ name: "LT", pattern: /</ });
|
||||
export const GT = createToken({ name: "GT", pattern: />/ });
|
||||
export const Plus = createToken({ name: "Plus", pattern: /\+/ });
|
||||
export const Minus = createToken({ name: "Minus", pattern: /-/ });
|
||||
export const Star = createToken({ name: "Star", pattern: /\*/ });
|
||||
export const Slash = createToken({ name: "Slash", pattern: /\// });
|
||||
export const Percent = createToken({ name: "Percent", pattern: /%/ });
|
||||
|
||||
// Order matters: longer/specific tokens first; Identifier last.
|
||||
export const allTokens = [
|
||||
Whitespace, LineComment, BlockComment,
|
||||
|
||||
// keywords
|
||||
Import, From,
|
||||
Use,
|
||||
Let, Var, Fn, Return,
|
||||
If, Else, For, In, Repeat, While, Do,
|
||||
Parallel, Task, On,
|
||||
Session, Requires, Safety,
|
||||
Policy, When,
|
||||
Yield, Continue, Break, Halt, Assert,
|
||||
Not, And, Or, True, False, Now, After, Before,
|
||||
|
||||
// literals (UnitLit before NumberLit, PercentLit also before NumberLit)
|
||||
UnitLit, PercentLit, NumberLit, StringLit,
|
||||
|
||||
// multi-char operators
|
||||
Arrow, FatArrow, DotDot, LE, GE, EQ, NE,
|
||||
PlusAssign, MinusAssign, StarAssign, SlashAssign,
|
||||
|
||||
// single-char
|
||||
LBrace, RBrace, LParen, RParen, LBracket, RBracket,
|
||||
Comma, Semicolon, Colon, Dot, At, Question,
|
||||
Assign, LT, GT, Plus, Minus, Star, Slash, Percent,
|
||||
|
||||
// catch-all (must be last)
|
||||
Identifier,
|
||||
];
|
||||
|
||||
export const NoxLexer = new Lexer(allTokens, {
|
||||
positionTracking: "full",
|
||||
ensureOptimizations: false,
|
||||
});
|
||||
|
||||
export function tokenize(source) {
|
||||
const result = NoxLexer.tokenize(source);
|
||||
if (result.errors.length > 0) {
|
||||
const e = result.errors[0];
|
||||
throw new Error(`Lex error at ${e.line}:${e.column} — ${e.message}`);
|
||||
}
|
||||
return result.tokens;
|
||||
}
|
||||
@@ -0,0 +1,710 @@
|
||||
import { CstParser } from "chevrotain";
|
||||
import * as T from "./lexer.js";
|
||||
|
||||
export class NoxParser extends CstParser {
|
||||
constructor() {
|
||||
super(T.allTokens, { recoveryEnabled: false });
|
||||
const $ = this;
|
||||
|
||||
// ============================================================
|
||||
// top level
|
||||
// ============================================================
|
||||
$.RULE("Program", () => {
|
||||
$.MANY(() => $.SUBRULE($.TopLevel));
|
||||
});
|
||||
|
||||
// LetDecl / VarDecl are reachable via Statement, so they're omitted here
|
||||
// to avoid OR-ambiguity.
|
||||
$.RULE("TopLevel", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE($.ImportDecl) },
|
||||
{ ALT: () => $.SUBRULE($.UseDecl) },
|
||||
{ ALT: () => $.SUBRULE($.DecoratedDecl) },
|
||||
{ ALT: () => $.SUBRULE($.FnDecl) },
|
||||
{ ALT: () => $.SUBRULE($.SessionDecl) },
|
||||
{ ALT: () => $.SUBRULE($.PolicyDecl) },
|
||||
{ ALT: () => $.SUBRULE($.Statement) },
|
||||
]);
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// declarations
|
||||
// ============================================================
|
||||
$.RULE("ImportDecl", () => {
|
||||
$.CONSUME(T.Import);
|
||||
$.CONSUME(T.LBrace);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.CONSUME2(T.Identifier); });
|
||||
$.CONSUME(T.RBrace);
|
||||
$.CONSUME(T.From);
|
||||
$.CONSUME(T.StringLit);
|
||||
});
|
||||
|
||||
// Resource kind is a soft keyword (telescope|dome|camera|filter_wheel|focuser).
|
||||
// Parsed as Identifier; semantic check validates the image later.
|
||||
$.RULE("UseDecl", () => {
|
||||
$.CONSUME(T.Use);
|
||||
$.CONSUME(T.Identifier); // resource kind
|
||||
$.CONSUME2(T.Identifier); // binding name
|
||||
$.CONSUME(T.Assign);
|
||||
$.SUBRULE($.Expression);
|
||||
});
|
||||
|
||||
$.RULE("LetDecl", () => {
|
||||
$.CONSUME(T.Let);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.OPTION(() => { $.CONSUME(T.Colon); $.SUBRULE($.TypeExpr); });
|
||||
$.CONSUME(T.Assign);
|
||||
$.SUBRULE($.Expression);
|
||||
});
|
||||
|
||||
$.RULE("VarDecl", () => {
|
||||
$.CONSUME(T.Var);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.OPTION(() => { $.CONSUME(T.Colon); $.SUBRULE($.TypeExpr); });
|
||||
$.CONSUME(T.Assign);
|
||||
$.SUBRULE($.Expression);
|
||||
});
|
||||
|
||||
$.RULE("FnDecl", () => {
|
||||
$.CONSUME(T.Fn);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.CONSUME(T.LParen);
|
||||
$.OPTION(() => $.SUBRULE($.ParamList));
|
||||
$.CONSUME(T.RParen);
|
||||
$.OPTION2(() => { $.CONSUME(T.Arrow); $.SUBRULE($.TypeExpr); });
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("ParamList", () => {
|
||||
$.SUBRULE($.Param);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Param); });
|
||||
});
|
||||
|
||||
$.RULE("Param", () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.CONSUME(T.Colon);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.OPTION(() => { $.CONSUME(T.Assign); $.SUBRULE($.Expression); });
|
||||
});
|
||||
|
||||
$.RULE("DecoratedDecl", () => {
|
||||
$.AT_LEAST_ONE(() => $.SUBRULE($.Decorator));
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE($.FnDecl) },
|
||||
{ ALT: () => $.SUBRULE($.LetDecl) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("Decorator", () => {
|
||||
$.CONSUME(T.At);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.OPTION(() => {
|
||||
$.CONSUME(T.LParen);
|
||||
$.OPTION2(() => $.SUBRULE($.ArgList));
|
||||
$.CONSUME(T.RParen);
|
||||
});
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// session / policy
|
||||
// ============================================================
|
||||
$.RULE("SessionDecl", () => {
|
||||
$.CONSUME(T.Session);
|
||||
$.CONSUME(T.StringLit);
|
||||
$.CONSUME(T.LBrace);
|
||||
$.MANY(() => $.SUBRULE($.SessionMember));
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
$.RULE("SessionMember", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE($.RequiresClause) },
|
||||
{ ALT: () => $.SUBRULE($.SafetyClause) },
|
||||
{ ALT: () => $.SUBRULE($.UseDecl) },
|
||||
{ ALT: () => $.SUBRULE($.FnDecl) },
|
||||
{ ALT: () => $.SUBRULE($.Statement) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("RequiresClause", () => {
|
||||
$.CONSUME(T.Requires);
|
||||
$.SUBRULE($.RequireItem);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.RequireItem); });
|
||||
});
|
||||
|
||||
// `telescope("Astra-1")`, `weather(clouds < 20%, ...)`, etc.
|
||||
$.RULE("RequireItem", () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.CONSUME(T.LParen);
|
||||
$.OPTION(() => {
|
||||
$.SUBRULE($.Expression);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Expression); });
|
||||
});
|
||||
$.CONSUME(T.RParen);
|
||||
});
|
||||
|
||||
$.RULE("SafetyClause", () => {
|
||||
$.CONSUME(T.Safety);
|
||||
$.CONSUME(T.On);
|
||||
$.SUBRULE($.Expression);
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("PolicyDecl", () => {
|
||||
$.CONSUME(T.Policy);
|
||||
$.CONSUME(T.StringLit);
|
||||
$.CONSUME(T.LBrace);
|
||||
$.MANY(() => $.SUBRULE($.WhenRule));
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
$.RULE("WhenRule", () => {
|
||||
$.CONSUME(T.When);
|
||||
$.SUBRULE($.Expression);
|
||||
// soft-keyword `reached`
|
||||
$.OPTION({
|
||||
GATE: () => $.LA(1).tokenType === T.Identifier && $.LA(1).image === "reached",
|
||||
DEF: () => $.CONSUME(T.Identifier),
|
||||
});
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// statements
|
||||
// ============================================================
|
||||
$.RULE("Block", () => {
|
||||
$.CONSUME(T.LBrace);
|
||||
$.MANY(() => $.SUBRULE($.Statement));
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
$.RULE("Statement", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE($.LetDecl) },
|
||||
{ ALT: () => $.SUBRULE($.VarDecl) },
|
||||
{ ALT: () => $.SUBRULE($.IfStmt) },
|
||||
{ ALT: () => $.SUBRULE($.ForStmt) },
|
||||
{ ALT: () => $.SUBRULE($.RepeatStmt) },
|
||||
{ ALT: () => $.SUBRULE($.WhileStmt) },
|
||||
{ ALT: () => $.SUBRULE($.ParallelStmt) },
|
||||
{ ALT: () => $.SUBRULE($.TaskStmt) },
|
||||
{ ALT: () => $.SUBRULE($.OnRollbackStmt) },
|
||||
{ ALT: () => $.SUBRULE($.ReturnStmt) },
|
||||
{ ALT: () => $.SUBRULE($.YieldStmt) },
|
||||
{ ALT: () => $.SUBRULE($.ContinueStmt) },
|
||||
{ ALT: () => $.SUBRULE($.BreakStmt) },
|
||||
{ ALT: () => $.SUBRULE($.HaltStmt) },
|
||||
{ ALT: () => $.SUBRULE($.AssertStmt) },
|
||||
{ ALT: () => $.SUBRULE($.ExprOrAssignStmt) },
|
||||
]);
|
||||
// Optional trailing semicolon between statements.
|
||||
$.OPTION(() => $.CONSUME(T.Semicolon));
|
||||
});
|
||||
|
||||
$.RULE("IfStmt", () => {
|
||||
$.CONSUME(T.If);
|
||||
$.SUBRULE($.Expression);
|
||||
$.SUBRULE($.Block);
|
||||
$.OPTION(() => {
|
||||
$.CONSUME(T.Else);
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE2($.IfStmt) },
|
||||
{ ALT: () => $.SUBRULE2($.Block) },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("ForStmt", () => {
|
||||
$.CONSUME(T.For);
|
||||
$.SUBRULE($.ForBinding);
|
||||
$.CONSUME(T.In);
|
||||
$.SUBRULE($.Expression);
|
||||
// soft-keyword `step` for range stepping
|
||||
$.OPTION({
|
||||
GATE: () => $.LA(1).tokenType === T.Identifier && $.LA(1).image === "step",
|
||||
DEF: () => { $.CONSUME(T.Identifier); $.SUBRULE2($.Expression); },
|
||||
});
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
// For-binding allows: `x`, `x, y, z` (bare multi), `(x, y)`, or arbitrarily
|
||||
// nested tuple patterns like `(filter, (exp, count))`.
|
||||
$.RULE("ForBinding", () => {
|
||||
$.SUBRULE($.Pattern);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Pattern); });
|
||||
});
|
||||
|
||||
$.RULE("Pattern", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Identifier) },
|
||||
{
|
||||
ALT: () => {
|
||||
$.CONSUME(T.LParen);
|
||||
$.SUBRULE($.Pattern);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Pattern); });
|
||||
$.CONSUME(T.RParen);
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("RepeatStmt", () => {
|
||||
$.CONSUME(T.Repeat);
|
||||
$.SUBRULE($.Expression);
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("WhileStmt", () => {
|
||||
$.CONSUME(T.While);
|
||||
$.SUBRULE($.Expression);
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("ParallelStmt", () => {
|
||||
$.CONSUME(T.Parallel);
|
||||
$.CONSUME(T.LBrace);
|
||||
$.MANY(() => $.SUBRULE($.Statement));
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
$.RULE("TaskStmt", () => {
|
||||
$.CONSUME(T.Task);
|
||||
$.CONSUME(T.Identifier);
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
// `on rollback { ... }` — `rollback` is a soft keyword (Identifier with that image).
|
||||
$.RULE("OnRollbackStmt", () => {
|
||||
$.CONSUME(T.On);
|
||||
$.CONSUME(T.Identifier); // semantic: image must be "rollback"
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("ReturnStmt", () => {
|
||||
$.CONSUME(T.Return);
|
||||
$.OPTION({
|
||||
GATE: () => !startsBlockEnd($),
|
||||
DEF: () => $.SUBRULE($.Expression),
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("YieldStmt", () => {
|
||||
$.CONSUME(T.Yield);
|
||||
$.OPTION({
|
||||
GATE: () => !startsBlockEnd($),
|
||||
DEF: () => $.SUBRULE($.Expression),
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("ContinueStmt", () => $.CONSUME(T.Continue));
|
||||
$.RULE("BreakStmt", () => $.CONSUME(T.Break));
|
||||
$.RULE("HaltStmt", () => $.CONSUME(T.Halt));
|
||||
|
||||
$.RULE("AssertStmt", () => {
|
||||
$.CONSUME(T.Assert);
|
||||
$.SUBRULE($.Expression);
|
||||
$.OPTION(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Expression); });
|
||||
});
|
||||
|
||||
// Expression-or-assignment: parse an expression; if an assign op follows,
|
||||
// it's an assignment (LHS becomes target). Otherwise it's an expression statement.
|
||||
$.RULE("ExprOrAssignStmt", () => {
|
||||
$.SUBRULE($.Expression);
|
||||
$.OPTION(() => {
|
||||
$.SUBRULE($.AssignOp);
|
||||
$.SUBRULE2($.Expression);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("AssignOp", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Assign) },
|
||||
{ ALT: () => $.CONSUME(T.PlusAssign) },
|
||||
{ ALT: () => $.CONSUME(T.MinusAssign) },
|
||||
{ ALT: () => $.CONSUME(T.StarAssign) },
|
||||
{ ALT: () => $.CONSUME(T.SlashAssign) },
|
||||
]);
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// expressions (precedence climbing)
|
||||
// ============================================================
|
||||
$.RULE("Expression", () => {
|
||||
$.OR([
|
||||
{
|
||||
GATE: () => isLambdaAhead($),
|
||||
ALT: () => $.SUBRULE($.LambdaExpr),
|
||||
},
|
||||
{ ALT: () => $.SUBRULE($.TimeOrOrExpr) },
|
||||
]);
|
||||
});
|
||||
|
||||
// After / before are prefix unary at the expression level.
|
||||
$.RULE("TimeOrOrExpr", () => {
|
||||
$.OR([
|
||||
{ ALT: () => { $.CONSUME(T.After); $.SUBRULE($.AddExpr); } },
|
||||
{ ALT: () => { $.CONSUME(T.Before); $.SUBRULE2($.AddExpr); } },
|
||||
{ ALT: () => $.SUBRULE($.OrExpr) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("LambdaExpr", () => {
|
||||
$.OR([
|
||||
{
|
||||
ALT: () => {
|
||||
$.CONSUME(T.LParen);
|
||||
$.OPTION(() => $.SUBRULE($.LambdaParamList));
|
||||
$.CONSUME(T.RParen);
|
||||
},
|
||||
},
|
||||
{ ALT: () => $.CONSUME(T.Identifier) },
|
||||
]);
|
||||
$.CONSUME(T.FatArrow);
|
||||
// Lambda body: bare expression, or `do { stmts }` for multi-statement
|
||||
// bodies (we can't use a bare block because `{` already begins a DictLit).
|
||||
$.OR2([
|
||||
{ ALT: () => $.SUBRULE($.DoBlock) },
|
||||
{ ALT: () => $.SUBRULE($.Expression) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("DoBlock", () => {
|
||||
$.CONSUME(T.Do);
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
$.RULE("LambdaParamList", () => {
|
||||
$.SUBRULE($.LambdaParam);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.LambdaParam); });
|
||||
});
|
||||
|
||||
// Untyped or typed lambda params.
|
||||
$.RULE("LambdaParam", () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.OPTION(() => { $.CONSUME(T.Colon); $.SUBRULE($.TypeExpr); });
|
||||
});
|
||||
|
||||
$.RULE("OrExpr", () => {
|
||||
$.SUBRULE($.AndExpr);
|
||||
$.MANY(() => { $.CONSUME(T.Or); $.SUBRULE2($.AndExpr); });
|
||||
});
|
||||
|
||||
$.RULE("AndExpr", () => {
|
||||
$.SUBRULE($.NotExpr);
|
||||
$.MANY(() => { $.CONSUME(T.And); $.SUBRULE2($.NotExpr); });
|
||||
});
|
||||
|
||||
$.RULE("NotExpr", () => {
|
||||
$.OPTION(() => $.CONSUME(T.Not));
|
||||
$.SUBRULE($.CompareExpr);
|
||||
});
|
||||
|
||||
$.RULE("CompareExpr", () => {
|
||||
$.SUBRULE($.RangeExpr);
|
||||
$.OPTION(() => {
|
||||
$.SUBRULE($.CompOp);
|
||||
$.SUBRULE2($.RangeExpr);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("CompOp", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.LT) },
|
||||
{ ALT: () => $.CONSUME(T.LE) },
|
||||
{ ALT: () => $.CONSUME(T.GT) },
|
||||
{ ALT: () => $.CONSUME(T.GE) },
|
||||
{ ALT: () => $.CONSUME(T.EQ) },
|
||||
{ ALT: () => $.CONSUME(T.NE) },
|
||||
{ ALT: () => $.CONSUME(T.In) }, // containment: x in list/dict/string
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("RangeExpr", () => {
|
||||
$.SUBRULE($.AddExpr);
|
||||
$.OPTION(() => { $.CONSUME(T.DotDot); $.SUBRULE2($.AddExpr); });
|
||||
});
|
||||
|
||||
$.RULE("AddExpr", () => {
|
||||
$.SUBRULE($.MulExpr);
|
||||
$.MANY(() => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Plus) },
|
||||
{ ALT: () => $.CONSUME(T.Minus) },
|
||||
]);
|
||||
$.SUBRULE2($.MulExpr);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("MulExpr", () => {
|
||||
$.SUBRULE($.UnaryExpr);
|
||||
$.MANY(() => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Star) },
|
||||
{ ALT: () => $.CONSUME(T.Slash) },
|
||||
{ ALT: () => $.CONSUME(T.Percent) },
|
||||
]);
|
||||
$.SUBRULE2($.UnaryExpr);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("UnaryExpr", () => {
|
||||
$.OPTION(() => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Plus) },
|
||||
{ ALT: () => $.CONSUME(T.Minus) },
|
||||
]);
|
||||
});
|
||||
$.SUBRULE($.PostfixExpr);
|
||||
});
|
||||
|
||||
$.RULE("PostfixExpr", () => {
|
||||
$.SUBRULE($.PrimaryExpr);
|
||||
$.MANY(() => $.SUBRULE($.Suffix));
|
||||
});
|
||||
|
||||
$.RULE("Suffix", () => {
|
||||
$.OR([
|
||||
{ ALT: () => { $.CONSUME(T.Dot); $.SUBRULE($.MemberName); } },
|
||||
{ ALT: () => { $.CONSUME(T.LBracket); $.SUBRULE($.Expression); $.CONSUME(T.RBracket); } },
|
||||
{ ALT: () => { $.CONSUME(T.LParen); $.OPTION(() => $.SUBRULE($.ArgList)); $.CONSUME(T.RParen); } },
|
||||
{ ALT: () => $.CONSUME(T.Question) },
|
||||
]);
|
||||
});
|
||||
|
||||
// After `.`, accept an identifier OR any keyword (field/method names should
|
||||
// never be reserved). Allows `T.camera`, `T.return_to_park`, etc.
|
||||
$.RULE("MemberName", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.Identifier) },
|
||||
// Common keywords that read naturally as method/field names. Add more here as needed.
|
||||
{ ALT: () => $.CONSUME(T.On) },
|
||||
{ ALT: () => $.CONSUME(T.In) },
|
||||
{ ALT: () => $.CONSUME(T.For) },
|
||||
{ ALT: () => $.CONSUME(T.If) },
|
||||
{ ALT: () => $.CONSUME(T.Return) },
|
||||
{ ALT: () => $.CONSUME(T.Now) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("ArgList", () => {
|
||||
$.SUBRULE($.Arg);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Arg); });
|
||||
});
|
||||
|
||||
// Named arg: `identifier : expr`. Positional: bare `expr`.
|
||||
// We need to distinguish without true backtracking. An `Identifier`
|
||||
// followed by `:` (but NOT `::` or `:=` — neither exists here) is a name.
|
||||
$.RULE("Arg", () => {
|
||||
$.OR([
|
||||
{
|
||||
GATE: () => $.LA(1).tokenType === T.Identifier && $.LA(2).tokenType === T.Colon,
|
||||
ALT: () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.CONSUME(T.Colon);
|
||||
$.SUBRULE($.Expression);
|
||||
},
|
||||
},
|
||||
{ ALT: () => $.SUBRULE2($.Expression) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("PrimaryExpr", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.CONSUME(T.UnitLit) },
|
||||
{ ALT: () => $.CONSUME(T.PercentLit) },
|
||||
{ ALT: () => $.CONSUME(T.NumberLit) },
|
||||
{ ALT: () => $.CONSUME(T.StringLit) },
|
||||
{ ALT: () => $.CONSUME(T.True) },
|
||||
{ ALT: () => $.CONSUME(T.False) },
|
||||
{ ALT: () => $.CONSUME(T.Now) },
|
||||
{
|
||||
// Typed constructor: `Identifier < TypeArgs > ( ... )`.
|
||||
// We must distinguish from `a < b > c` comparisons, so we scan
|
||||
// ahead for a balanced `>` followed immediately by `(`.
|
||||
GATE: () => isTypedConstructorAhead($),
|
||||
ALT: () => $.SUBRULE($.TypedConstructor),
|
||||
},
|
||||
{ ALT: () => $.CONSUME(T.Identifier) },
|
||||
{ ALT: () => $.SUBRULE($.ListLit) },
|
||||
{ ALT: () => $.SUBRULE($.DictLit) },
|
||||
{ ALT: () => $.SUBRULE($.ParenOrTupleExpr) },
|
||||
]);
|
||||
});
|
||||
|
||||
$.RULE("TypedConstructor", () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.CONSUME(T.LT);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.TypeExpr); });
|
||||
$.CONSUME(T.GT);
|
||||
$.CONSUME(T.LParen);
|
||||
$.OPTION(() => $.SUBRULE($.ArgList));
|
||||
$.CONSUME(T.RParen);
|
||||
});
|
||||
|
||||
$.RULE("ListLit", () => {
|
||||
$.CONSUME(T.LBracket);
|
||||
$.OPTION(() => {
|
||||
$.SUBRULE($.Expression);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Expression); });
|
||||
$.OPTION2(() => $.CONSUME2(T.Comma));
|
||||
});
|
||||
$.CONSUME(T.RBracket);
|
||||
});
|
||||
|
||||
$.RULE("DictLit", () => {
|
||||
$.CONSUME(T.LBrace);
|
||||
$.OPTION(() => {
|
||||
$.SUBRULE($.DictEntry);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.DictEntry); });
|
||||
$.OPTION2(() => $.CONSUME2(T.Comma));
|
||||
});
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
$.RULE("DictEntry", () => {
|
||||
$.SUBRULE($.Expression);
|
||||
$.CONSUME(T.Colon);
|
||||
$.SUBRULE2($.Expression);
|
||||
});
|
||||
|
||||
// `(expr)` or `(a, b, ...)`. Lambda has already been peeled off at Expression level.
|
||||
$.RULE("ParenOrTupleExpr", () => {
|
||||
$.CONSUME(T.LParen);
|
||||
$.SUBRULE($.Expression);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.Expression); });
|
||||
$.CONSUME(T.RParen);
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// types
|
||||
// ============================================================
|
||||
$.RULE("TypeExpr", () => {
|
||||
$.OR([
|
||||
{ ALT: () => $.SUBRULE($.ListType) },
|
||||
{ ALT: () => $.SUBRULE($.DictType) },
|
||||
{ ALT: () => $.SUBRULE($.TupleType) },
|
||||
{ ALT: () => $.SUBRULE($.NamedType) },
|
||||
]);
|
||||
});
|
||||
|
||||
// `(T1, T2[, ...])` — at least two elements so it doesn't collide with a
|
||||
// parenthesized type expression (we don't currently support those).
|
||||
$.RULE("TupleType", () => {
|
||||
$.CONSUME(T.LParen);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.AT_LEAST_ONE(() => { $.CONSUME(T.Comma); $.SUBRULE2($.TypeExpr); });
|
||||
$.CONSUME(T.RParen);
|
||||
});
|
||||
|
||||
$.RULE("NamedType", () => {
|
||||
$.CONSUME(T.Identifier);
|
||||
$.OPTION(() => {
|
||||
$.CONSUME(T.LT);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.MANY(() => { $.CONSUME(T.Comma); $.SUBRULE2($.TypeExpr); });
|
||||
$.CONSUME(T.GT);
|
||||
});
|
||||
});
|
||||
|
||||
$.RULE("ListType", () => {
|
||||
$.CONSUME(T.LBracket);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.CONSUME(T.RBracket);
|
||||
});
|
||||
|
||||
$.RULE("DictType", () => {
|
||||
$.CONSUME(T.LBrace);
|
||||
$.SUBRULE($.TypeExpr);
|
||||
$.CONSUME(T.Colon);
|
||||
$.SUBRULE2($.TypeExpr);
|
||||
$.CONSUME(T.RBrace);
|
||||
});
|
||||
|
||||
this.performSelfAnalysis();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- lookahead helpers ----------
|
||||
|
||||
// True when the next-up tokens look like a lambda header:
|
||||
// `Identifier =>` single-param sugar
|
||||
// `( ) =>` empty params
|
||||
// `( Identifier ... ) =>` typed/untyped param list
|
||||
// We scan ahead for a `=>` before any token that couldn't appear in a
|
||||
// param list. This avoids true backtracking.
|
||||
function isLambdaAhead($) {
|
||||
const t1 = $.LA(1);
|
||||
// single-identifier lambda
|
||||
if (t1.tokenType === T.Identifier && $.LA(2).tokenType === T.FatArrow) return true;
|
||||
if (t1.tokenType !== T.LParen) return false;
|
||||
|
||||
// Scan inside the parens for a matching RParen followed by =>.
|
||||
let depth = 1;
|
||||
let i = 2;
|
||||
// Cap scan to avoid pathological inputs.
|
||||
while (i < 256) {
|
||||
const tok = $.LA(i);
|
||||
if (!tok || tok.tokenType === undefined) return false;
|
||||
if (tok.tokenType === T.LParen) depth++;
|
||||
else if (tok.tokenType === T.RParen) {
|
||||
depth--;
|
||||
if (depth === 0) {
|
||||
return $.LA(i + 1).tokenType === T.FatArrow;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// True at the start of a statement boundary — used to know when `return`
|
||||
// or `yield` has no expression operand.
|
||||
function startsBlockEnd($) {
|
||||
const t = $.LA(1).tokenType;
|
||||
return t === T.RBrace || t === T.Semicolon;
|
||||
}
|
||||
|
||||
// True iff the upcoming tokens are `Identifier < ... > (` with a balanced `>`.
|
||||
// Used to disambiguate `Coord<ICRS>(...)` from `a < b > c`.
|
||||
function isTypedConstructorAhead($) {
|
||||
if ($.LA(1).tokenType !== T.Identifier) return false;
|
||||
if ($.LA(2).tokenType !== T.LT) return false;
|
||||
let depth = 1;
|
||||
let i = 3;
|
||||
while (i < 64) {
|
||||
const tok = $.LA(i);
|
||||
if (!tok || tok.tokenType === undefined) return false;
|
||||
if (tok.tokenType === T.LT) depth++;
|
||||
else if (tok.tokenType === T.GT) {
|
||||
depth--;
|
||||
if (depth === 0) return $.LA(i + 1).tokenType === T.LParen;
|
||||
} else if (
|
||||
// tokens that can't appear inside a type-arg list — fail fast
|
||||
tok.tokenType === T.Semicolon ||
|
||||
tok.tokenType === T.LBrace ||
|
||||
tok.tokenType === T.RBrace
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Singleton parser instance (Chevrotain pattern: reuse instance, call reset per parse).
|
||||
const parserInstance = new NoxParser();
|
||||
|
||||
export function parse(tokens) {
|
||||
parserInstance.input = tokens;
|
||||
const cst = parserInstance.Program();
|
||||
if (parserInstance.errors.length > 0) {
|
||||
const e = parserInstance.errors[0];
|
||||
const loc = e.token ? `${e.token.startLine}:${e.token.startColumn}` : "?";
|
||||
throw new Error(`Parse error at ${loc} — ${e.message}`);
|
||||
}
|
||||
return cst;
|
||||
}
|
||||
|
||||
export { parserInstance };
|
||||
@@ -0,0 +1,227 @@
|
||||
// Nox type system primitives.
|
||||
//
|
||||
// A Type is a tagged object discriminated by `kind`:
|
||||
//
|
||||
// { kind:'Prim', name:'Int'|'Float'|'String'|'Bool'|'Pixels'|'Steps' }
|
||||
// { kind:'Quantity', dim:DimensionName }
|
||||
// { kind:'Coord', frame:FrameName }
|
||||
// { kind:'Resource', name:ResourceName }
|
||||
// { kind:'List', element:Type }
|
||||
// { kind:'Dict', key:Type, value:Type }
|
||||
// { kind:'Tuple', elements:[Type] }
|
||||
// { kind:'Fn', params:[Type], returnType:Type, caps:CapabilitySet }
|
||||
// { kind:'Generic', name:string } // unresolved param like T
|
||||
// { kind:'Image', bands:[string] } // exposure result
|
||||
// { kind:'Time' } // wall-clock instant
|
||||
// { kind:'Optional', element:Type } // T? (nullable)
|
||||
// { kind:'Range', element:Type } // produced by `a..b`
|
||||
// { kind:'Struct', name:string, fields:Map, methods:Map }
|
||||
// { kind:'Percent' } // 20%, 80%, etc.
|
||||
// { kind:'Union', members:[Type] } // sum type, e.g. Coord<ICRS> | Target
|
||||
// { kind:'Void' } // statement / no value
|
||||
// { kind:'Any' } // escape hatch (type checker rejects)
|
||||
// { kind:'Error', message:string } // poisoned node; suppresses cascades
|
||||
//
|
||||
// Dimensions group commensurable units. Two quantities can be compared,
|
||||
// added, subtracted iff dimensions match. Scalar * Quantity gives the
|
||||
// same dimension. Division of two quantities is not yet modeled; we'll
|
||||
// add a richer algebra when the type checker needs it.
|
||||
|
||||
export const DIMENSIONS = {
|
||||
Duration: { base: "s", units: { ms: 1e-3, s: 1, min: 60, h: 3600 } },
|
||||
Angle: { base: "deg", units: { deg: 1, arcmin: 1 / 60, arcsec: 1 / 3600 } },
|
||||
Temperature: { base: "degC", units: { degC: 1 } },
|
||||
Speed: { base: "mps", units: { mps: 1, kph: 1000 / 3600 } },
|
||||
Pixels: { base: "px", units: { px: 1 } },
|
||||
Steps: { base: "steps", units: { steps: 1 } },
|
||||
};
|
||||
|
||||
// Reverse map: unit suffix -> dimension name + conversion factor to base.
|
||||
export const UNIT_TABLE = (() => {
|
||||
const t = {};
|
||||
for (const [dim, info] of Object.entries(DIMENSIONS)) {
|
||||
for (const [u, factor] of Object.entries(info.units)) {
|
||||
t[u] = { dimension: dim, toBase: factor, base: info.base };
|
||||
}
|
||||
}
|
||||
return t;
|
||||
})();
|
||||
|
||||
export const FRAMES = ["ICRS", "Topo", "AltAz", "Galactic"];
|
||||
|
||||
export const RESOURCES = ["Telescope", "Dome", "Camera", "FilterWheel", "Focuser"];
|
||||
|
||||
export const PRIMITIVES = ["Int", "Float", "String", "Bool"];
|
||||
|
||||
// ---------- constructors ----------
|
||||
export const Prim = name => ({ kind: "Prim", name });
|
||||
export const Quantity = dim => ({ kind: "Quantity", dim });
|
||||
export const Coord = frame => ({ kind: "Coord", frame });
|
||||
export const Resource = name => ({ kind: "Resource", name });
|
||||
export const List = el => ({ kind: "List", element: el });
|
||||
export const Dict = (k, v) => ({ kind: "Dict", key: k, value: v });
|
||||
export const Tuple = els => ({ kind: "Tuple", elements: els });
|
||||
export const Fn = (params, returnType, caps = new Set()) =>
|
||||
({ kind: "Fn", params, returnType, caps });
|
||||
export const Generic = name => ({ kind: "Generic", name });
|
||||
export const ImageT = (bands = []) => ({ kind: "Image", bands });
|
||||
export const Time = () => ({ kind: "Time" });
|
||||
export const Optional = el => ({ kind: "Optional", element: el });
|
||||
export const Range = el => ({ kind: "Range", element: el });
|
||||
export const Struct = (name, fields = new Map(), methods = new Map()) =>
|
||||
({ kind: "Struct", name, fields, methods });
|
||||
export const PercentT = () => ({ kind: "Percent" });
|
||||
export const Union = members => ({ kind: "Union", members });
|
||||
export const Void = () => ({ kind: "Void" });
|
||||
export const Any = () => ({ kind: "Any" });
|
||||
export const ErrType = msg => ({ kind: "Error", message: msg });
|
||||
|
||||
// Common shortcuts.
|
||||
export const Duration = () => Quantity("Duration");
|
||||
export const Angle = () => Quantity("Angle");
|
||||
export const Temperature = () => Quantity("Temperature");
|
||||
export const Speed = () => Quantity("Speed");
|
||||
export const Int = () => Prim("Int");
|
||||
export const Float = () => Prim("Float");
|
||||
export const StringT = () => Prim("String");
|
||||
export const Bool = () => Prim("Bool");
|
||||
export const Pixels = () => Quantity("Pixels");
|
||||
export const Steps = () => Quantity("Steps");
|
||||
|
||||
// ---------- capabilities ----------
|
||||
// A capability tags what side effects a fn/scope may perform. The type
|
||||
// checker accumulates these from callees. Runtime enforces preconditions.
|
||||
export const CAPABILITIES = [
|
||||
"telescope.move", // slew, park, home
|
||||
"telescope.image", // expose, dither
|
||||
"telescope.focus",
|
||||
"telescope.cool",
|
||||
"dome.move",
|
||||
"dome.flat_panel",
|
||||
"camera.shutter",
|
||||
"filter_wheel.move",
|
||||
"schedule.read",
|
||||
"weather.read",
|
||||
"io.network", // external driver calls
|
||||
];
|
||||
|
||||
// ---------- equality + assignability ----------
|
||||
export function typeEquals(a, b) {
|
||||
if (a === b) return true;
|
||||
if (a.kind !== b.kind) return false;
|
||||
switch (a.kind) {
|
||||
case "Prim": return a.name === b.name;
|
||||
case "Quantity": return a.dim === b.dim;
|
||||
case "Coord": return a.frame === b.frame;
|
||||
case "Resource": return a.name === b.name;
|
||||
case "Generic": return a.name === b.name;
|
||||
case "Time":
|
||||
case "Percent":
|
||||
case "Void":
|
||||
case "Any": return true;
|
||||
case "List": return typeEquals(a.element, b.element);
|
||||
case "Dict": return typeEquals(a.key, b.key) && typeEquals(a.value, b.value);
|
||||
case "Optional": return typeEquals(a.element, b.element);
|
||||
case "Range": return typeEquals(a.element, b.element);
|
||||
case "Tuple": return a.elements.length === b.elements.length
|
||||
&& a.elements.every((t, i) => typeEquals(t, b.elements[i]));
|
||||
case "Image": return setEquals(a.bands, b.bands);
|
||||
case "Struct": return a.name === b.name;
|
||||
case "Fn": return a.params.length === b.params.length
|
||||
&& a.params.every((p, i) => typeEquals(p, b.params[i]))
|
||||
&& typeEquals(a.returnType, b.returnType);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
// `expected` accepts `actual` if assignable. Any conforms in both directions
|
||||
// to keep error reporting localized. Coord frames must match unless one is Any.
|
||||
// Int auto-widens to Float. Optional<T> accepts T. Functions are contravariant
|
||||
// in params and covariant in return type.
|
||||
export function assignable(expected, actual) {
|
||||
if (expected.kind === "Any" || actual.kind === "Any") return true;
|
||||
if (expected.kind === "Error" || actual.kind === "Error") return true;
|
||||
if (expected.kind === "Prim" && expected.name === "Float"
|
||||
&& actual.kind === "Prim" && actual.name === "Int") return true;
|
||||
if (expected.kind === "Optional" && assignable(expected.element, actual)) return true;
|
||||
// Optional<T> is NOT implicitly assignable to T — callers must guard with
|
||||
// `if x? { ... }` so flow-sensitive narrowing peels the Optional.
|
||||
if (expected.kind === "Union") {
|
||||
return expected.members.some(m => assignable(m, actual));
|
||||
}
|
||||
if (actual.kind === "Union") {
|
||||
// An actual Union value is assignable only if every member fits.
|
||||
return actual.members.every(m => assignable(expected, m));
|
||||
}
|
||||
if (expected.kind === "Fn" && actual.kind === "Fn") {
|
||||
if (expected.params.length !== actual.params.length) return false;
|
||||
for (let i = 0; i < expected.params.length; i++) {
|
||||
if (!assignable(actual.params[i], expected.params[i])) return false;
|
||||
}
|
||||
return assignable(expected.returnType, actual.returnType);
|
||||
}
|
||||
if (expected.kind === "List" && actual.kind === "List") {
|
||||
return assignable(expected.element, actual.element);
|
||||
}
|
||||
return typeEquals(expected, actual);
|
||||
}
|
||||
|
||||
function setEquals(a, b) {
|
||||
if (a.length !== b.length) return false;
|
||||
const sa = new Set(a), sb = new Set(b);
|
||||
for (const x of sa) if (!sb.has(x)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------- pretty printing ----------
|
||||
export function typeToString(t) {
|
||||
switch (t.kind) {
|
||||
case "Prim": return t.name;
|
||||
case "Quantity": return t.dim;
|
||||
case "Coord": return `Coord<${t.frame}>`;
|
||||
case "Resource": return t.name;
|
||||
case "Generic": return t.name;
|
||||
case "Time": return "Time";
|
||||
case "Percent": return "Percent";
|
||||
case "Void": return "Void";
|
||||
case "Any": return "Any";
|
||||
case "Image": return t.bands.length ? `Image<${t.bands.join("+")}>` : "Image";
|
||||
case "List": return `[${typeToString(t.element)}]`;
|
||||
case "Dict": return `{${typeToString(t.key)}: ${typeToString(t.value)}}`;
|
||||
case "Optional": return `${typeToString(t.element)}?`;
|
||||
case "Range": return `Range<${typeToString(t.element)}>`;
|
||||
case "Tuple": return `(${t.elements.map(typeToString).join(", ")})`;
|
||||
case "Struct": return t.name;
|
||||
case "Union": return t.members.map(typeToString).join(" | ");
|
||||
case "Fn": return `(${t.params.map(typeToString).join(", ")}) -> ${typeToString(t.returnType)}`;
|
||||
case "Error": return `<error: ${t.message}>`;
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- mapping AST type nodes (kind:'Named'|'List'|'Dict'|'Tuple') to Type ----------
|
||||
export function typeFromAst(node) {
|
||||
if (!node) return Any();
|
||||
switch (node.kind) {
|
||||
case "Named": return namedType(node.name, node.args || []);
|
||||
case "List": return List(typeFromAst(node.element));
|
||||
case "Dict": return Dict(typeFromAst(node.key), typeFromAst(node.value));
|
||||
case "Tuple": return Tuple(node.elements.map(typeFromAst));
|
||||
default: return ErrType(`unknown type node: ${node.kind}`);
|
||||
}
|
||||
}
|
||||
|
||||
function namedType(name, args) {
|
||||
if (PRIMITIVES.includes(name)) return Prim(name);
|
||||
if (Object.hasOwn(DIMENSIONS, name)) return Quantity(name);
|
||||
if (RESOURCES.includes(name)) return Resource(name);
|
||||
if (name === "Coord") {
|
||||
const frame = args[0] && args[0].kind === "Named" ? args[0].name : "ICRS";
|
||||
if (!FRAMES.includes(frame)) return ErrType(`unknown frame: ${frame}`);
|
||||
return Coord(frame);
|
||||
}
|
||||
if (name === "Image") return ImageT();
|
||||
if (name === "Time") return Time();
|
||||
// Unknown named types become generics for now. Type checker will resolve.
|
||||
return Generic(name);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { compile } from "../src/index.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
|
||||
const files = fs.readdirSync(examplesDir).filter(f => f.endsWith(".nox")).sort();
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
const results = {};
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(examplesDir, f), "utf8");
|
||||
try {
|
||||
const ast = compile(src);
|
||||
if (ast.type !== "Program") throw new Error(`root is not Program: ${ast.type}`);
|
||||
const summary = summarize(ast);
|
||||
results[f] = summary;
|
||||
console.log(` PASS ${f} ${JSON.stringify(summary)}`);
|
||||
pass++;
|
||||
} catch (e) {
|
||||
console.log(` FAIL ${f} ${e.message}`);
|
||||
if (process.env.STACK) console.log(e.stack);
|
||||
fail++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n${pass}/${pass + fail} AST builds succeeded.`);
|
||||
|
||||
// Dump full AST for example 05 (largest exercise) on demand.
|
||||
if (process.argv.includes("--dump")) {
|
||||
const src = fs.readFileSync(path.join(examplesDir, "05-automated-night.nox"), "utf8");
|
||||
console.log("\n--- AST for 05-automated-night.nox ---");
|
||||
console.log(JSON.stringify(compile(src), null, 2));
|
||||
}
|
||||
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
|
||||
function summarize(ast) {
|
||||
const counts = {};
|
||||
walk(ast, n => {
|
||||
if (n && typeof n === "object" && n.type) {
|
||||
counts[n.type] = (counts[n.type] || 0) + 1;
|
||||
}
|
||||
});
|
||||
return counts;
|
||||
}
|
||||
|
||||
function walk(node, fn) {
|
||||
if (!node || typeof node !== "object") return;
|
||||
fn(node);
|
||||
for (const k of Object.keys(node)) {
|
||||
const v = node[k];
|
||||
if (Array.isArray(v)) v.forEach(c => walk(c, fn));
|
||||
else if (v && typeof v === "object") walk(v, fn);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Confirm the checker reports errors on intentionally broken programs.
|
||||
import { checkSource } from "../src/index.js";
|
||||
|
||||
const cases = [
|
||||
{
|
||||
name: "wrong unit dimension",
|
||||
src: `use telescope T = "x"\nT.dither(amount: 30s)`,
|
||||
expect: /expected Angle, got Duration/,
|
||||
},
|
||||
{
|
||||
name: "unknown frame",
|
||||
src: `let p: Coord<Lunar> = M31`,
|
||||
expect: /unknown frame: Lunar/,
|
||||
},
|
||||
{
|
||||
name: "unknown identifier",
|
||||
src: `let x = NotARealCatalog`,
|
||||
expect: /unknown identifier: NotARealCatalog/,
|
||||
},
|
||||
{
|
||||
name: "missing required arg",
|
||||
src: `use telescope T = "x"\nT.expose(60s)`,
|
||||
expect: /missing argument: filter/,
|
||||
},
|
||||
{
|
||||
name: "wrong arg type",
|
||||
src: `use telescope T = "x"\nT.cooldown(target: 5deg)`,
|
||||
expect: /expected Temperature, got Angle/,
|
||||
},
|
||||
{
|
||||
name: "non-Bool if condition",
|
||||
src: `if 5 { halt }`,
|
||||
expect: /if condition must be Bool/,
|
||||
},
|
||||
{
|
||||
name: "non-Int repeat count",
|
||||
src: `repeat 5s { halt }`,
|
||||
expect: /repeat count must be Int/,
|
||||
},
|
||||
{
|
||||
name: "wrong unit in requires(weather(...))",
|
||||
src: `session "x" { requires weather(wind < 30s) }`,
|
||||
expect: /cannot compare Speed/,
|
||||
},
|
||||
{
|
||||
name: "wrong unit in safety on weather predicate",
|
||||
src: `session "x" {
|
||||
use telescope T = "y"
|
||||
safety on wind > 30s { T.park() }
|
||||
}`,
|
||||
expect: /cannot compare Speed/,
|
||||
},
|
||||
{
|
||||
name: "unguarded Optional passed to non-Optional param",
|
||||
src: `use telescope T = "x"
|
||||
let next = schedule.best_target(now)
|
||||
T.slew(next)`,
|
||||
expect: /expected.*got Target\?/,
|
||||
},
|
||||
];
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
for (const c of cases) {
|
||||
const { diagnostics } = checkSource(c.src);
|
||||
const matched = diagnostics.some(d => c.expect.test(d.message));
|
||||
if (matched) {
|
||||
console.log(` PASS ${c.name}`);
|
||||
pass++;
|
||||
} else {
|
||||
console.log(` FAIL ${c.name}`);
|
||||
console.log(` expected match: ${c.expect}`);
|
||||
console.log(` got: ${diagnostics.map(d => d.message).join(" | ") || "(no diagnostics)"}`);
|
||||
fail++;
|
||||
}
|
||||
}
|
||||
console.log(`\n${pass}/${pass + fail} negative cases caught.`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
@@ -0,0 +1,25 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { checkSource } from "../src/index.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
const files = fs.readdirSync(examplesDir).filter(f => f.endsWith(".nox")).sort();
|
||||
|
||||
let totalDiags = 0;
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(examplesDir, f), "utf8");
|
||||
const { diagnostics } = checkSource(src);
|
||||
totalDiags += diagnostics.length;
|
||||
if (diagnostics.length === 0) {
|
||||
console.log(` CLEAN ${f}`);
|
||||
} else {
|
||||
console.log(` ${diagnostics.length.toString().padStart(3)} ${f}`);
|
||||
for (const d of diagnostics) {
|
||||
const where = d.line ? `${d.line}:${d.column}` : "?";
|
||||
console.log(` ${where} ${d.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log(`\nTotal diagnostics: ${totalDiags}`);
|
||||
@@ -0,0 +1,39 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseSource } from "../src/index.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
|
||||
const files = fs.readdirSync(examplesDir).filter(f => f.endsWith(".nox")).sort();
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
for (const f of files) {
|
||||
const full = path.join(examplesDir, f);
|
||||
const src = fs.readFileSync(full, "utf8");
|
||||
try {
|
||||
const cst = parseSource(src);
|
||||
const nodeCount = countCstNodes(cst);
|
||||
console.log(` PASS ${f} (${nodeCount} CST nodes)`);
|
||||
pass++;
|
||||
} catch (e) {
|
||||
console.log(` FAIL ${f}`);
|
||||
console.log(` ${e.message}`);
|
||||
fail++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n${pass}/${pass + fail} examples parsed.`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
|
||||
function countCstNodes(cst) {
|
||||
if (!cst || typeof cst !== "object") return 0;
|
||||
let n = 1;
|
||||
if (cst.children) {
|
||||
for (const k of Object.keys(cst.children)) {
|
||||
for (const c of cst.children[k]) n += countCstNodes(c);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { compile } from "../src/index.js";
|
||||
import { typeFromAst, typeToString, UNIT_TABLE } from "../src/types.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
|
||||
// Walk an AST collecting every declared TypeNode (the ones with `kind` instead of `type`).
|
||||
function collectTypeNodes(ast, out = []) {
|
||||
if (!ast || typeof ast !== "object") return out;
|
||||
if (ast.kind && !ast.type) out.push(ast);
|
||||
for (const k of Object.keys(ast)) {
|
||||
const v = ast[k];
|
||||
if (Array.isArray(v)) v.forEach(c => collectTypeNodes(c, out));
|
||||
else if (v && typeof v === "object") collectTypeNodes(v, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Walk an AST collecting every UnitLit so we can sanity-check the unit table.
|
||||
function collectUnits(ast, out = []) {
|
||||
if (!ast || typeof ast !== "object") return out;
|
||||
if (ast.type === "UnitLit") out.push(ast.unit);
|
||||
for (const k of Object.keys(ast)) {
|
||||
const v = ast[k];
|
||||
if (Array.isArray(v)) v.forEach(c => collectUnits(c, out));
|
||||
else if (v && typeof v === "object") collectUnits(v, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const files = fs.readdirSync(examplesDir).filter(f => f.endsWith(".nox")).sort();
|
||||
|
||||
let unknownUnits = new Set();
|
||||
let unknownTypeReprs = new Set();
|
||||
let typeReprSamples = new Set();
|
||||
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(examplesDir, f), "utf8");
|
||||
const ast = compile(src);
|
||||
for (const u of collectUnits(ast)) {
|
||||
if (!UNIT_TABLE[u]) unknownUnits.add(u);
|
||||
}
|
||||
for (const tn of collectTypeNodes(ast)) {
|
||||
const t = typeFromAst(tn);
|
||||
const repr = typeToString(t);
|
||||
typeReprSamples.add(repr);
|
||||
if (t.kind === "Error") unknownTypeReprs.add(repr);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("Type annotations seen across examples:");
|
||||
for (const r of [...typeReprSamples].sort()) console.log(" " + r);
|
||||
|
||||
if (unknownUnits.size) {
|
||||
console.log("\nUNKNOWN UNITS:", [...unknownUnits]);
|
||||
process.exit(1);
|
||||
}
|
||||
if (unknownTypeReprs.size) {
|
||||
console.log("\nUNKNOWN TYPE REPRS:", [...unknownTypeReprs]);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("\nAll units recognized. All type annotations parsed.");
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env node
|
||||
// Nox CLI: check or run .nox files from the shell.
|
||||
//
|
||||
// nox check <file> type-check; exit 1 if any diagnostics
|
||||
// nox run <file> execute on mock driver
|
||||
// nox ops <file> execute and print the operation log
|
||||
// nox parse <file> parse and dump the AST as JSON
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { run, checkSource, compile } from "../src/index.js";
|
||||
import { show } from "../src/values.js";
|
||||
|
||||
const [, , cmd, file, ...rest] = process.argv;
|
||||
|
||||
if (!cmd || !file || cmd === "help" || cmd === "--help" || cmd === "-h") {
|
||||
usage();
|
||||
process.exit(cmd === "help" || cmd === "--help" || cmd === "-h" ? 0 : 1);
|
||||
}
|
||||
|
||||
const src = readSource(file);
|
||||
|
||||
switch (cmd) {
|
||||
case "check": await doCheck(src); break;
|
||||
case "run": await doRun(src, false); break;
|
||||
case "ops": await doRun(src, true); break;
|
||||
case "parse": doParse(src); break;
|
||||
default:
|
||||
console.error(`unknown command: ${cmd}`);
|
||||
usage();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function usage() {
|
||||
console.log(`usage: nox <check|run|ops|parse> <file.nox>
|
||||
|
||||
check type-check; exit 1 on any diagnostic
|
||||
run execute on mock driver; print op count
|
||||
ops execute and print each op
|
||||
parse parse and dump the AST as JSON`);
|
||||
}
|
||||
|
||||
function readSource(file) {
|
||||
const full = path.resolve(file);
|
||||
if (!fs.existsSync(full)) {
|
||||
console.error(`file not found: ${full}`);
|
||||
process.exit(2);
|
||||
}
|
||||
return fs.readFileSync(full, "utf8");
|
||||
}
|
||||
|
||||
async function doCheck(src) {
|
||||
const { diagnostics } = checkSource(src);
|
||||
if (diagnostics.length === 0) {
|
||||
console.log("clean");
|
||||
return;
|
||||
}
|
||||
for (const d of diagnostics) {
|
||||
const where = d.line ? `${d.line}:${d.column}` : "?";
|
||||
console.error(`${where} ${d.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
async function doRun(src, printOps) {
|
||||
const { diagnostics } = checkSource(src);
|
||||
if (diagnostics.length > 0) {
|
||||
for (const d of diagnostics) {
|
||||
const where = d.line ? `${d.line}:${d.column}` : "?";
|
||||
console.error(`${where} ${d.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const { log } = await run(src);
|
||||
if (printOps) {
|
||||
for (const op of log) {
|
||||
const args = Object.entries(op.args || {}).map(([k, v]) => `${k}=${show(v)}`).join(" ");
|
||||
console.log(`${op.kind} ${op.op}${args ? " " + args : ""}`);
|
||||
}
|
||||
}
|
||||
console.log(`${log.length} ops`);
|
||||
} catch (e) {
|
||||
console.error(`runtime error: ${e.message}`);
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
function doParse(src) {
|
||||
try {
|
||||
const ast = compile(src);
|
||||
process.stdout.write(JSON.stringify(ast, null, 2));
|
||||
process.stdout.write("\n");
|
||||
} catch (e) {
|
||||
console.error(`parse error: ${e.message}`);
|
||||
process.exit(4);
|
||||
}
|
||||
}
|
||||
Generated
+26
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "nox-runtime",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nox-runtime",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"nox-parser": "file:../parser"
|
||||
}
|
||||
},
|
||||
"../parser": {
|
||||
"name": "nox-parser",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"chevrotain": "^12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nox-parser": {
|
||||
"resolved": "../parser",
|
||||
"link": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "nox-runtime",
|
||||
"version": "0.1.0",
|
||||
"description": "Async tree-walking interpreter and CLI for the Nox telescope control language.",
|
||||
"license": "MIT",
|
||||
"author": "Paul Hitt",
|
||||
"type": "module",
|
||||
"main": "src/index.js",
|
||||
"bin": {
|
||||
"nox": "bin/nox.js"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node test/run-mock.js && node test/rollback.js && node test/policy-edge.js && node test/cli.js && node test/v04-features.js",
|
||||
"test:mock": "node test/run-mock.js",
|
||||
"test:rollback": "node test/rollback.js",
|
||||
"test:policy": "node test/policy-edge.js",
|
||||
"test:cli": "node test/cli.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"nox-parser": "file:../parser"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Runtime catalog values and import resolution.
|
||||
//
|
||||
// v0.1 ships a small hand-verified subset. Real deployments should drop a
|
||||
// JSON catalog into nox/runtime/catalogs/<name>.json (loaded lazily via
|
||||
// loadCatalogFile) — that file overrides / extends the builtin map.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Coord } from "./values.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const catalogsDir = path.resolve(here, "../catalogs");
|
||||
|
||||
// Hand-verified coordinates (ICRS, degrees).
|
||||
const CATALOG = {
|
||||
M31: Coord("ICRS", 10.6847, 41.2687),
|
||||
M42: Coord("ICRS", 83.8221, -5.3911),
|
||||
M51: Coord("ICRS", 202.4696, 47.1952),
|
||||
M81: Coord("ICRS", 148.8882, 69.0653),
|
||||
M101: Coord("ICRS", 210.8023, 54.3486),
|
||||
NGC_7000: Coord("ICRS", 314.7500, 44.3333),
|
||||
};
|
||||
|
||||
// Cache of loaded JSON catalogs keyed by module path.
|
||||
const fileCache = new Map();
|
||||
|
||||
function loadCatalogFile(modulePath) {
|
||||
if (fileCache.has(modulePath)) return fileCache.get(modulePath);
|
||||
const file = path.join(catalogsDir, modulePath.replace(/^catalog\//, "") + ".json");
|
||||
let table = {};
|
||||
try {
|
||||
const raw = fs.readFileSync(file, "utf8");
|
||||
const data = JSON.parse(raw);
|
||||
for (const [name, entry] of Object.entries(data)) {
|
||||
// Entry shape: { ra, dec, frame? }. ra/dec in degrees.
|
||||
table[name] = Coord(entry.frame || "ICRS", entry.ra, entry.dec);
|
||||
}
|
||||
} catch {
|
||||
/* file absent or unreadable; ignore */
|
||||
}
|
||||
fileCache.set(modulePath, table);
|
||||
return table;
|
||||
}
|
||||
|
||||
export function defaultCatalogValues() {
|
||||
return { ...CATALOG };
|
||||
}
|
||||
|
||||
export function resolveImport(from, name) {
|
||||
// Builtin catalog covers a handful of canonical targets.
|
||||
if (from === "catalog/messier" || from === "catalog/ngc") {
|
||||
if (CATALOG[name]) return CATALOG[name];
|
||||
}
|
||||
// Fall back to a JSON catalog file if one is present.
|
||||
const fileTable = loadCatalogFile(from);
|
||||
return fileTable[name] || null;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Mock telescope/dome/camera drivers.
|
||||
// Each method logs an operation to a shared log and returns a resolved
|
||||
// Promise. Useful for dry-runs and tests.
|
||||
|
||||
import { Image } from "../values.js";
|
||||
|
||||
export function createMockDriver({ log, onOp = null }) {
|
||||
function record(kind, op, args = {}) {
|
||||
const entry = { kind, op, args, t: Date.now() };
|
||||
log.push(entry);
|
||||
if (onOp) onOp(entry);
|
||||
}
|
||||
|
||||
return {
|
||||
// ---------- Telescope ----------
|
||||
telescope(name) {
|
||||
return {
|
||||
async slew(target) { record("T:" + name, "slew", { target }); },
|
||||
async park() { record("T:" + name, "park"); },
|
||||
async home() { record("T:" + name, "home"); },
|
||||
async wait_until_settled() { record("T:" + name, "wait_until_settled"); },
|
||||
async cooldown(target, timeout){ record("T:" + name, "cooldown", { target, timeout }); },
|
||||
async warm_up() { record("T:" + name, "warm_up"); },
|
||||
async expose(exp, filter) { record("T:" + name, "expose", { exp, filter }); return Image({ filter }); },
|
||||
async focus(method) { record("T:" + name, "focus", { method }); },
|
||||
async focus_if_needed(args) { record("T:" + name, "focus_if_needed", args); },
|
||||
async dither(amount, pattern) { record("T:" + name, "dither", { amount, pattern }); },
|
||||
async auto_flat_exposure(filter){ record("T:" + name, "auto_flat_exposure", { filter }); return 5; /* placeholder */ },
|
||||
is_idle: true,
|
||||
filter_wheel: {
|
||||
async select(filter) { record("T:" + name + ":fw", "select", { filter }); },
|
||||
},
|
||||
focuser: {
|
||||
async move_to(pos) { record("T:" + name + ":focuser", "move_to", { pos }); },
|
||||
},
|
||||
camera: {
|
||||
async shutter(state) { record("T:" + name + ":camera", "shutter", { state }); },
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
// ---------- Dome ----------
|
||||
dome(name) {
|
||||
return {
|
||||
async open() { record("D:" + name, "open"); },
|
||||
async close() { record("D:" + name, "close"); },
|
||||
is_closed() { return true; }, // mock
|
||||
flat_panel: {
|
||||
async on(brightness) { record("D:" + name + ":panel", "on", { brightness }); },
|
||||
async off() { record("D:" + name + ":panel", "off"); },
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Builtin globals exposed by mock runtime. The driver-free side (catalogs,
|
||||
// schedule, weather) lives here so the same surface works with any backend.
|
||||
export function mockGlobals() {
|
||||
return {
|
||||
now: { _tag: "Time", date: new Date("2026-05-14T20:00:00Z") },
|
||||
sunset: { _tag: "Time", date: new Date("2026-05-14T20:30:00Z") },
|
||||
sunrise: { _tag: "Time", date: new Date("2026-05-15T05:30:00Z") },
|
||||
weather: {
|
||||
// Percent values stored as fractions (0.10 = 10%).
|
||||
clouds: 0.10,
|
||||
humidity: 0.60,
|
||||
wind: { _tag: "Quantity", value: 12, dim: "Speed" },
|
||||
is_clear: true,
|
||||
is_safe() { return true; },
|
||||
},
|
||||
schedule: {
|
||||
tonight() { return []; },
|
||||
best_target(_t) { return null; },
|
||||
},
|
||||
cos(angle) { return Math.cos(quantityToRadians(angle)); },
|
||||
sin(angle) { return Math.sin(quantityToRadians(angle)); },
|
||||
parabola_min(samples) {
|
||||
// samples: [[Steps, Pixels]] expressed as runtime quantities.
|
||||
// Return Steps quantity at the parabola minimum (placeholder: midpoint).
|
||||
if (!samples || samples.length === 0) return { _tag: "Quantity", value: 0, dim: "Steps" };
|
||||
const xs = samples.map(s => s[0].value ?? s[0]);
|
||||
const mid = xs[Math.floor(xs.length / 2)];
|
||||
return { _tag: "Quantity", value: mid, dim: "Steps" };
|
||||
},
|
||||
rollback() { /* no-op in mock */ },
|
||||
halt() { throw new HaltSignal(); },
|
||||
};
|
||||
}
|
||||
|
||||
export class HaltSignal extends Error {
|
||||
constructor() { super("halt"); this.name = "HaltSignal"; }
|
||||
}
|
||||
|
||||
function quantityToRadians(q) {
|
||||
if (!q || q._tag !== "Quantity") return q;
|
||||
// Dimension-aware: only Angle gets converted.
|
||||
if (q.dim !== "Angle") return q.value;
|
||||
return q.value * Math.PI / 180; // declared in deg by convention
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { run } from "./interpreter.js";
|
||||
export { createMockDriver, mockGlobals } from "./drivers/mock.js";
|
||||
export { checkSource, compile, parseSource } from "nox-parser";
|
||||
@@ -0,0 +1,688 @@
|
||||
// Tree-walking interpreter for Nox.
|
||||
//
|
||||
// All execution is async. Driver calls are awaited so a slew really blocks
|
||||
// the for-loop until the mount reports settled. Control flow uses thrown
|
||||
// signals to short-circuit returns, breaks, continues, and halts.
|
||||
|
||||
import { compile, checkSource } from "nox-parser";
|
||||
import { RESOURCE_METHODS, STRUCT_DEFS, GLOBALS, MODULES } from "nox-parser/src/builtins.js";
|
||||
import {
|
||||
Tag, Quantity, Coord, Resource, Closure, Image, Time, Range, isTag, isQuantity, show,
|
||||
} from "./values.js";
|
||||
import { resolveImport, defaultCatalogValues } from "./builtins-rt.js";
|
||||
import { createMockDriver, mockGlobals, HaltSignal } from "./drivers/mock.js";
|
||||
|
||||
// ---------- control-flow signals ----------
|
||||
class ReturnSignal { constructor(v) { this.v = v; } }
|
||||
class BreakSignal {}
|
||||
class ContinueSignal {}
|
||||
|
||||
// Magic env key used to thread rollback handlers from a Task body to its
|
||||
// enclosing Parallel block. Not a valid Nox identifier so it cannot clash.
|
||||
const ROLLBACK_KEY = "__rollback__";
|
||||
|
||||
// ---------- environment ----------
|
||||
class Env {
|
||||
constructor(parent = null) { this.parent = parent; this.vars = new Map(); }
|
||||
define(name, value) { this.vars.set(name, value); }
|
||||
get(name) {
|
||||
for (let e = this; e; e = e.parent) if (e.vars.has(name)) return e.vars.get(name);
|
||||
throw new Error(`unbound variable: ${name}`);
|
||||
}
|
||||
set(name, value) {
|
||||
for (let e = this; e; e = e.parent) {
|
||||
if (e.vars.has(name)) { e.vars.set(name, value); return; }
|
||||
}
|
||||
throw new Error(`cannot assign to undeclared: ${name}`);
|
||||
}
|
||||
child() { return new Env(this); }
|
||||
}
|
||||
|
||||
// ---------- entry point ----------
|
||||
export async function run(source, options = {}) {
|
||||
const { strict = true, driver = null, onOp = null, policy = {} } = options;
|
||||
const log = [];
|
||||
const drv = driver || createMockDriver({ log, onOp });
|
||||
|
||||
if (strict) {
|
||||
const { diagnostics } = checkSource(source);
|
||||
if (diagnostics.length) {
|
||||
const lines = diagnostics.map(d => ` ${d.line || "?"}:${d.column || "?"} ${d.message}`);
|
||||
throw new Error(`type errors:\n${lines.join("\n")}`);
|
||||
}
|
||||
}
|
||||
|
||||
const ast = compile(source);
|
||||
const env = new Env();
|
||||
|
||||
// Seed globals + catalog at module scope.
|
||||
for (const [k, v] of Object.entries(mockGlobals())) env.define(k, v);
|
||||
for (const [k, v] of Object.entries(defaultCatalogValues())) env.define(k, v);
|
||||
|
||||
try {
|
||||
for (const node of ast.body) await execTop(node, env, drv, log, { policy });
|
||||
} catch (e) {
|
||||
if (e instanceof HaltSignal) { /* graceful */ }
|
||||
else throw e;
|
||||
}
|
||||
return { log };
|
||||
}
|
||||
|
||||
// ---------- top-level ----------
|
||||
async function execTop(node, env, drv, log, opts = {}) {
|
||||
switch (node.type) {
|
||||
case "Import":
|
||||
for (const n of node.names) {
|
||||
const val = resolveImport(node.from, n);
|
||||
if (val === null) throw new Error(`import not resolvable: ${n} from "${node.from}"`);
|
||||
env.define(n, val);
|
||||
}
|
||||
return;
|
||||
case "Use": {
|
||||
const val = await execExpr(node.value, env, drv);
|
||||
const name = val; // resource name string
|
||||
const handle = createResourceHandle(node.kind, name, drv);
|
||||
env.define(node.name, Resource(node.kind, name, handle));
|
||||
return;
|
||||
}
|
||||
case "Let":
|
||||
case "Var": {
|
||||
const v = await execExpr(node.value, env, drv);
|
||||
env.define(node.name, v);
|
||||
return;
|
||||
}
|
||||
case "Fn": {
|
||||
env.define(node.name, Closure(node.params, node.body, env, node.name));
|
||||
return;
|
||||
}
|
||||
case "Decorated":
|
||||
return execTop(node.decl, env, drv, log, opts);
|
||||
case "Session": return runSession(node, env, drv, log);
|
||||
case "Policy": return runPolicy(node, env, drv, log, opts.policy || {});
|
||||
default:
|
||||
return execStmt(node, env, drv);
|
||||
}
|
||||
}
|
||||
|
||||
function createResourceHandle(kind, name, drv) {
|
||||
switch (kind) {
|
||||
case "telescope": return drv.telescope(name);
|
||||
case "dome": return drv.dome(name);
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- session / policy ----------
|
||||
async function runSession(node, env, drv, log) {
|
||||
const local = env.child();
|
||||
// Hoist Use / Let / Var / Fn so safety handlers see them.
|
||||
for (const m of node.members) {
|
||||
if (m.type === "Use") {
|
||||
const name = await execExpr(m.value, local, drv);
|
||||
local.define(m.name, Resource(m.kind, name, createResourceHandle(m.kind, name, drv)));
|
||||
} else if (m.type === "Fn") {
|
||||
local.define(m.name, Closure(m.params, m.body, local, m.name));
|
||||
}
|
||||
}
|
||||
// Body pass.
|
||||
for (const m of node.members) {
|
||||
if (m.type === "Use" || m.type === "Fn") continue;
|
||||
if (m.type === "Requires" || m.type === "Safety") continue; // declarative; runtime would register
|
||||
if (m.type === "Let" || m.type === "Var") {
|
||||
const v = await execExpr(m.value, local, drv);
|
||||
local.define(m.name, v);
|
||||
continue;
|
||||
}
|
||||
await execStmt(m, local, drv);
|
||||
}
|
||||
}
|
||||
|
||||
async function runPolicy(node, env, drv, log, opts = {}) {
|
||||
// Edge-triggered semantics: each rule fires only when its predicate
|
||||
// transitions false -> true. Previous values are seeded to false so
|
||||
// currently-true conditions fire once on the first tick.
|
||||
//
|
||||
// opts.ticks (default 1) and opts.intervalMs (default 0) let callers
|
||||
// run the policy as a daemon. `halt` aborts the loop.
|
||||
const { ticks = 1, intervalMs = 0 } = opts;
|
||||
const local = env.child();
|
||||
const prev = new Array(node.rules.length).fill(false);
|
||||
for (let tick = 0; tick < ticks; tick++) {
|
||||
if (tick > 0 && intervalMs > 0) await new Promise(r => setTimeout(r, intervalMs));
|
||||
for (let i = 0; i < node.rules.length; i++) {
|
||||
const rule = node.rules[i];
|
||||
const cur = truthy(await execExpr(rule.condition, local, drv));
|
||||
if (cur && !prev[i]) {
|
||||
try {
|
||||
for (const s of rule.body) await execStmt(s, local, drv);
|
||||
} catch (e) {
|
||||
if (e instanceof HaltSignal) return;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
prev[i] = cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- statements ----------
|
||||
async function execStmt(node, env, drv) {
|
||||
switch (node.type) {
|
||||
case "Let":
|
||||
case "Var":
|
||||
env.define(node.name, await execExpr(node.value, env, drv));
|
||||
return;
|
||||
case "Assign":
|
||||
return execAssign(node, env, drv);
|
||||
case "ExprStmt":
|
||||
await execExpr(node.expr, env, drv);
|
||||
return;
|
||||
case "If":
|
||||
if (truthy(await execExpr(node.cond, env, drv))) {
|
||||
for (const s of node.then) await execStmt(s, env, drv);
|
||||
} else if (Array.isArray(node.else)) {
|
||||
for (const s of node.else) await execStmt(s, env, drv);
|
||||
} else if (node.else) {
|
||||
await execStmt(node.else, env, drv);
|
||||
}
|
||||
return;
|
||||
case "For":
|
||||
return execFor(node, env, drv);
|
||||
case "Repeat":
|
||||
return execRepeat(node, env, drv);
|
||||
case "While":
|
||||
return execWhile(node, env, drv);
|
||||
case "Parallel": {
|
||||
// Each task runs concurrently in its own env chain with a private
|
||||
// handlers list. If any task rejects, every handler collected across
|
||||
// all tasks fires in reverse order; the first failure is re-thrown.
|
||||
const allHandlers = [];
|
||||
const promises = node.children.map(c => {
|
||||
const childEnv = env.child();
|
||||
childEnv.define(ROLLBACK_KEY, []);
|
||||
return Promise.resolve(execStmt(c, childEnv, drv))
|
||||
.finally(() => {
|
||||
const hs = childEnv.vars.get(ROLLBACK_KEY) || [];
|
||||
for (const h of hs) allHandlers.push(h);
|
||||
});
|
||||
});
|
||||
const results = await Promise.allSettled(promises);
|
||||
const failed = results.find(r => r.status === "rejected");
|
||||
if (failed) {
|
||||
for (let i = allHandlers.length - 1; i >= 0; i--) {
|
||||
try { await allHandlers[i](); } catch (e) { /* swallow rollback errors */ }
|
||||
}
|
||||
throw failed.reason;
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "Task":
|
||||
for (const s of node.body) await execStmt(s, env, drv);
|
||||
return;
|
||||
case "OnRollback": {
|
||||
// Register the body as a rollback handler on the nearest enclosing
|
||||
// parallel block. Outside parallel the statement is a no-op.
|
||||
for (let e = env; e; e = e.parent) {
|
||||
if (e.vars.has(ROLLBACK_KEY)) {
|
||||
e.vars.get(ROLLBACK_KEY).push(async () => {
|
||||
for (const s of node.body) await execStmt(s, env, drv);
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "Return": throw new ReturnSignal(node.value ? await execExpr(node.value, env, drv) : null);
|
||||
case "Yield": /* mock: a real runtime would suspend; here we just evaluate */
|
||||
if (node.value) await execExpr(node.value, env, drv);
|
||||
return;
|
||||
case "Break": throw new BreakSignal();
|
||||
case "Continue": throw new ContinueSignal();
|
||||
case "Halt": throw new HaltSignal();
|
||||
case "Assert": {
|
||||
const ok = truthy(await execExpr(node.cond, env, drv));
|
||||
if (!ok) {
|
||||
const msg = node.message ? await execExpr(node.message, env, drv) : "assertion failed";
|
||||
throw new Error(String(msg));
|
||||
}
|
||||
return;
|
||||
}
|
||||
default:
|
||||
throw new Error(`unhandled statement: ${node.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function execAssign(node, env, drv) {
|
||||
const v = await execExpr(node.value, env, drv);
|
||||
if (node.target.type === "Ident") {
|
||||
if (node.op === "=") env.set(node.target.name, v);
|
||||
else {
|
||||
const cur = env.get(node.target.name);
|
||||
env.set(node.target.name, binop(node.op[0], cur, v));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.target.type === "Member") {
|
||||
const obj = await execExpr(node.target.object, env, drv);
|
||||
obj[node.target.name] = v;
|
||||
return;
|
||||
}
|
||||
throw new Error(`unsupported assign target: ${node.target.type}`);
|
||||
}
|
||||
|
||||
async function execFor(node, env, drv) {
|
||||
const iter = await execExpr(node.iter, env, drv);
|
||||
const stepV = node.step ? await execExpr(node.step, env, drv) : null;
|
||||
const items = expandIter(iter, stepV);
|
||||
const local = env.child();
|
||||
for (const item of items) {
|
||||
bindPattern(local, node.binding, item);
|
||||
try {
|
||||
for (const s of node.body) await execStmt(s, local, drv);
|
||||
} catch (e) {
|
||||
if (e instanceof BreakSignal) return;
|
||||
if (e instanceof ContinueSignal) continue;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function execRepeat(node, env, drv) {
|
||||
const count = await execExpr(node.count, env, drv);
|
||||
const n = typeof count === "number" ? count : (count.value | 0);
|
||||
for (let i = 0; i < n; i++) {
|
||||
try {
|
||||
for (const s of node.body) await execStmt(s, env, drv);
|
||||
} catch (e) {
|
||||
if (e instanceof BreakSignal) return;
|
||||
if (e instanceof ContinueSignal) continue;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bounded by MAX_ITERATIONS to prevent accidental runaway loops in scripts.
|
||||
const MAX_ITERATIONS = 1_000_000;
|
||||
|
||||
async function execWhile(node, env, drv) {
|
||||
for (let i = 0; i < MAX_ITERATIONS; i++) {
|
||||
const c = await execExpr(node.cond, env, drv);
|
||||
if (!truthy(c)) return;
|
||||
try {
|
||||
for (const s of node.body) await execStmt(s, env, drv);
|
||||
} catch (e) {
|
||||
if (e instanceof BreakSignal) return;
|
||||
if (e instanceof ContinueSignal) continue;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
throw new Error(`while loop exceeded ${MAX_ITERATIONS} iterations`);
|
||||
}
|
||||
|
||||
function bindPattern(env, pat, value) {
|
||||
if (pat.type === "NamePat") {
|
||||
env.define(pat.name, value);
|
||||
return;
|
||||
}
|
||||
if (pat.type === "TuplePat") {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error(`expected tuple to destructure, got ${typeof value}`);
|
||||
}
|
||||
for (let i = 0; i < pat.items.length; i++) bindPattern(env, pat.items[i], value[i]);
|
||||
}
|
||||
}
|
||||
|
||||
function expandIter(v, stepV) {
|
||||
if (Array.isArray(v)) return v;
|
||||
if (isTag(v, Tag.Range)) {
|
||||
const step = stepV !== null ? numVal(stepV) : 1;
|
||||
const start = numVal(v.start);
|
||||
const end = numVal(v.end);
|
||||
if (step === 0) throw new Error("range step cannot be zero");
|
||||
// Guard against wrong-direction steps that would loop forever.
|
||||
if (end > start && step < 0) throw new Error(`range ${start}..${end} with negative step ${step}`);
|
||||
if (end < start && step > 0) throw new Error(`range ${start}..${end} with positive step ${step}`);
|
||||
const out = [];
|
||||
const dim = isQuantity(v.start) ? v.start.dim : null;
|
||||
const cmp = step > 0 ? (x => x <= end) : (x => x >= end);
|
||||
for (let x = start; cmp(x); x += step) {
|
||||
out.push(dim ? Quantity(x, dim) : x);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (v instanceof Map) {
|
||||
return [...v.entries()].map(([k, val]) => [k, val]);
|
||||
}
|
||||
throw new Error(`cannot iterate: ${show(v)}`);
|
||||
}
|
||||
|
||||
function numVal(v) { return isQuantity(v) ? v.value : v; }
|
||||
|
||||
// ---------- expressions ----------
|
||||
async function execExpr(node, env, drv) {
|
||||
switch (node.type) {
|
||||
case "Number": return node.value;
|
||||
case "Bool": return node.value;
|
||||
case "String": return node.value;
|
||||
case "InterpolatedString": {
|
||||
let out = '';
|
||||
for (const p of node.parts) {
|
||||
if (p.kind === 'lit') out += p.value;
|
||||
else out += stringify(await execExpr(p.value, env, drv));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
case "Percent": return node.value / 100; // 20% -> 0.20
|
||||
case "Now": return env.get("now");
|
||||
case "UnitLit": return Quantity(node.value, dimOfUnit(node.unit));
|
||||
case "Ident": return env.get(node.name);
|
||||
case "List": return await Promise.all(node.elements.map(e => execExpr(e, env, drv)));
|
||||
case "Tuple": {
|
||||
const items = await Promise.all(node.elements.map(e => execExpr(e, env, drv)));
|
||||
items._tuple = true;
|
||||
return items;
|
||||
}
|
||||
case "Dict": {
|
||||
const m = new Map();
|
||||
for (const ent of node.entries) {
|
||||
m.set(await execExpr(ent.key, env, drv), await execExpr(ent.value, env, drv));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
case "TypedCtor":
|
||||
return await execTypedCtor(node, env, drv);
|
||||
case "Member":
|
||||
return await execMember(node, env, drv);
|
||||
case "Index":
|
||||
return await execIndex(node, env, drv);
|
||||
case "Call":
|
||||
return await execCall(node, env, drv);
|
||||
case "Optional": {
|
||||
const v = await execExpr(node.expr, env, drv);
|
||||
return v !== null && v !== undefined;
|
||||
}
|
||||
case "Unary": {
|
||||
const v = await execExpr(node.expr, env, drv);
|
||||
if (node.op === "-") return negate(v);
|
||||
return v;
|
||||
}
|
||||
case "Not":
|
||||
return !truthy(await execExpr(node.expr, env, drv));
|
||||
case "Range": {
|
||||
const start = await execExpr(node.start, env, drv);
|
||||
const end = await execExpr(node.end, env, drv);
|
||||
return Range(start, end, null);
|
||||
}
|
||||
case "BinOp": return await execBinOp(node, env, drv);
|
||||
case "Time": {
|
||||
// after/before are treated as identity at runtime; they tag predicates
|
||||
// for the requires-clause runtime, which we don't execute here.
|
||||
return await execExpr(node.expr, env, drv);
|
||||
}
|
||||
case "Lambda":
|
||||
return Closure(node.params, node.body, env, "lambda");
|
||||
default:
|
||||
throw new Error(`unhandled expression: ${node.type}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function execTypedCtor(node, env, drv) {
|
||||
if (node.name === "Coord") {
|
||||
const frame = node.typeArgs[0]?.name || "ICRS";
|
||||
const args = {};
|
||||
for (const a of node.args) args[a.name || "_"] = await execExpr(a.value, env, drv);
|
||||
return Coord(frame, numVal(args.ra ?? 0), numVal(args.dec ?? 0));
|
||||
}
|
||||
throw new Error(`unknown typed constructor: ${node.name}`);
|
||||
}
|
||||
|
||||
async function execMember(node, env, drv) {
|
||||
const obj = await execExpr(node.object, env, drv);
|
||||
if (Array.isArray(obj)) {
|
||||
return listMethodImpl(obj, node.name, drv);
|
||||
}
|
||||
if (isTag(obj, Tag.Resource)) {
|
||||
const m = obj.driver[node.name];
|
||||
if (m === undefined) throw new Error(`${obj.kind} has no member '${node.name}'`);
|
||||
return bindMethod(obj, node.name, m);
|
||||
}
|
||||
if (isTag(obj, Tag.Image)) {
|
||||
if (node.name === "hfr") return async () => Quantity(2.5, "Pixels"); // mock
|
||||
throw new Error(`Image has no member '${node.name}'`);
|
||||
}
|
||||
if (isTag(obj, Tag.Time)) {
|
||||
if (node.name === "has_passed") return obj.date.getTime() <= Date.now();
|
||||
throw new Error(`Time has no member '${node.name}'`);
|
||||
}
|
||||
if (obj && typeof obj === "object") {
|
||||
const v = obj[node.name];
|
||||
if (typeof v === "function") return v.bind(obj);
|
||||
return v;
|
||||
}
|
||||
throw new Error(`cannot access ${node.name} on ${show(obj)}`);
|
||||
}
|
||||
|
||||
// Wrap a driver/host method so it knows its parameter names (for named-arg
|
||||
// resolution at the call site).
|
||||
function bindMethod(resource, name, fn) {
|
||||
const sig = RESOURCE_METHODS[capitalize(resource.kind)]?.get(name);
|
||||
const paramNames = sig?.paramNames || [];
|
||||
const bound = (...args) => fn.apply(resource.driver, args);
|
||||
bound._paramNames = paramNames;
|
||||
// Nested resource (e.g. T.filter_wheel): not a function, just an object.
|
||||
if (typeof fn !== "function") return fn;
|
||||
return bound;
|
||||
}
|
||||
|
||||
function capitalize(s) { return s[0].toUpperCase() + s.slice(1).replace(/_(.)/g, (_, c) => c.toUpperCase()); }
|
||||
|
||||
// List method dispatcher. Wraps Nox closures so JS-style iteration can call them.
|
||||
function listMethodImpl(arr, name, drv) {
|
||||
switch (name) {
|
||||
case "length":
|
||||
return async () => arr.length;
|
||||
case "push":
|
||||
return async (item) => { arr.push(item); };
|
||||
case "filter":
|
||||
return async (pred) => {
|
||||
const out = [];
|
||||
for (const item of arr) {
|
||||
const keep = await callAny(pred, [{ name: null, value: item }], drv);
|
||||
if (truthy(keep)) out.push(item);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
case "map":
|
||||
return async (fn) => {
|
||||
const out = [];
|
||||
for (const item of arr) {
|
||||
out.push(await callAny(fn, [{ name: null, value: item }], drv));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
case "sort_by":
|
||||
return async (key) => {
|
||||
const decorated = await Promise.all(arr.map(async item => ({
|
||||
item,
|
||||
k: await callAny(key, [{ name: null, value: item }], drv),
|
||||
})));
|
||||
decorated.sort((a, b) => cmp(a.k, b.k));
|
||||
return decorated.map(d => d.item);
|
||||
};
|
||||
default:
|
||||
throw new Error(`List has no method '${name}'`);
|
||||
}
|
||||
}
|
||||
|
||||
// Call either a Closure or a JS function with raw {name,value} args.
|
||||
async function callAny(fn, rawArgs, drv) {
|
||||
if (isTag(fn, Tag.Closure)) return callClosure(fn, rawArgs, drv);
|
||||
if (typeof fn === "function") {
|
||||
const positional = resolvePositional(rawArgs, fn._paramNames || []);
|
||||
return await fn(...positional);
|
||||
}
|
||||
throw new Error(`not callable: ${show(fn)}`);
|
||||
}
|
||||
|
||||
async function execIndex(node, env, drv) {
|
||||
const obj = await execExpr(node.object, env, drv);
|
||||
const idx = await execExpr(node.index, env, drv);
|
||||
if (Array.isArray(obj)) return obj[numVal(idx) | 0];
|
||||
if (obj instanceof Map) return obj.get(idx);
|
||||
throw new Error(`cannot index ${show(obj)}`);
|
||||
}
|
||||
|
||||
async function execCall(node, env, drv) {
|
||||
const callee = await execExpr(node.callee, env, drv);
|
||||
const rawArgs = [];
|
||||
for (const a of node.args) rawArgs.push({ name: a.name, value: await execExpr(a.value, env, drv) });
|
||||
|
||||
if (isTag(callee, Tag.Closure)) return callClosure(callee, rawArgs, drv);
|
||||
if (typeof callee === "function") {
|
||||
const positional = resolvePositional(rawArgs, callee._paramNames || []);
|
||||
return await callee(...positional);
|
||||
}
|
||||
if (callee && typeof callee.call === "function") {
|
||||
// host objects with bound methods
|
||||
return await callee.call(null, ...rawArgs.map(a => a.value));
|
||||
}
|
||||
throw new Error(`not callable: ${show(callee)}`);
|
||||
}
|
||||
|
||||
function resolvePositional(rawArgs, paramNames) {
|
||||
const out = new Array(Math.max(paramNames.length, rawArgs.length));
|
||||
let pos = 0;
|
||||
for (const a of rawArgs) {
|
||||
if (a.name) {
|
||||
const i = paramNames.indexOf(a.name);
|
||||
if (i < 0) out.push(a.value); // unknown named arg passes through positional
|
||||
else out[i] = a.value;
|
||||
} else {
|
||||
out[pos++] = a.value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function callClosure(fn, rawArgs, drv) {
|
||||
const env = fn.env.child();
|
||||
const params = fn.params;
|
||||
const positional = resolvePositional(rawArgs, params.map(p => p.name));
|
||||
for (let i = 0; i < params.length; i++) {
|
||||
env.define(params[i].name, positional[i]);
|
||||
}
|
||||
try {
|
||||
// Body shapes: array of statements (fn decls), DoBlock (lambdas with
|
||||
// statement body), or a single expression (lambdas with expression body).
|
||||
if (Array.isArray(fn.body)) {
|
||||
for (const s of fn.body) await execStmt(s, env, drv);
|
||||
return null;
|
||||
}
|
||||
if (fn.body && fn.body.type === "DoBlock") {
|
||||
for (const s of fn.body.body) await execStmt(s, env, drv);
|
||||
return null;
|
||||
}
|
||||
return await execExpr(fn.body, env, drv);
|
||||
} catch (e) {
|
||||
if (e instanceof ReturnSignal) return e.v;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function execBinOp(node, env, drv) {
|
||||
const op = node.op;
|
||||
if (op === "and") {
|
||||
const l = await execExpr(node.left, env, drv);
|
||||
return truthy(l) ? truthy(await execExpr(node.right, env, drv)) : false;
|
||||
}
|
||||
if (op === "or") {
|
||||
const l = await execExpr(node.left, env, drv);
|
||||
return truthy(l) ? true : truthy(await execExpr(node.right, env, drv));
|
||||
}
|
||||
const l = await execExpr(node.left, env, drv);
|
||||
const r = await execExpr(node.right, env, drv);
|
||||
return binop(op, l, r);
|
||||
}
|
||||
|
||||
function binop(op, l, r) {
|
||||
if (op === "<") return cmp(l, r) < 0;
|
||||
if (op === "<=") return cmp(l, r) <= 0;
|
||||
if (op === ">") return cmp(l, r) > 0;
|
||||
if (op === ">=") return cmp(l, r) >= 0;
|
||||
if (op === "==") return cmp(l, r) === 0;
|
||||
if (op === "!=") return cmp(l, r) !== 0;
|
||||
if (op === "in") {
|
||||
if (Array.isArray(r)) return r.some(x => valueEquals(x, l));
|
||||
if (r instanceof Map) return [...r.keys()].some(k => valueEquals(k, l));
|
||||
if (typeof r === "string") return typeof l === "string" && r.includes(l);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Quantity arithmetic
|
||||
if (isQuantity(l) || isQuantity(r)) {
|
||||
const lv = numVal(l), rv = numVal(r);
|
||||
const dim = isQuantity(l) ? l.dim : r.dim;
|
||||
if (op === "+") return Quantity(lv + rv, dim);
|
||||
if (op === "-") return Quantity(lv - rv, dim);
|
||||
if (op === "*") return Quantity(lv * rv, dim);
|
||||
if (op === "/") return Quantity(lv / rv, dim);
|
||||
}
|
||||
if (op === "+") return l + r;
|
||||
if (op === "-") return l - r;
|
||||
if (op === "*") return l * r;
|
||||
if (op === "/") return l / r;
|
||||
if (op === "%") return l % r;
|
||||
throw new Error(`unknown binop: ${op}`);
|
||||
}
|
||||
|
||||
function cmp(l, r) {
|
||||
// String comparison falls through to JS semantics.
|
||||
if (typeof l === "string" && typeof r === "string") {
|
||||
return l < r ? -1 : l > r ? 1 : 0;
|
||||
}
|
||||
const a = numVal(l), b = numVal(r);
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}
|
||||
|
||||
function valueEquals(a, b) {
|
||||
if (a === b) return true;
|
||||
if (isQuantity(a) && isQuantity(b)) return a.dim === b.dim && a.value === b.value;
|
||||
if (isTag(a, Tag.Coord) && isTag(b, Tag.Coord)) {
|
||||
return a.frame === b.frame && a.ra === b.ra && a.dec === b.dec;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function negate(v) {
|
||||
if (isQuantity(v)) return Quantity(-v.value, v.dim);
|
||||
return -v;
|
||||
}
|
||||
|
||||
// Used by string interpolation. Quantities render as `value` only; users
|
||||
// add their own unit text if they want one. Coord/Image/Resource use show().
|
||||
function stringify(v) {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (typeof v === 'string') return v;
|
||||
if (typeof v === 'number') return String(v);
|
||||
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
||||
if (isQuantity(v)) return String(v.value);
|
||||
return show(v);
|
||||
}
|
||||
|
||||
function truthy(v) {
|
||||
if (v === null || v === undefined || v === false) return false;
|
||||
if (v === 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function dimOfUnit(unit) {
|
||||
// Mirror the parser's unit table.
|
||||
const table = {
|
||||
ms: "Duration", s: "Duration", min: "Duration", h: "Duration",
|
||||
deg: "Angle", arcmin: "Angle", arcsec: "Angle",
|
||||
degC: "Temperature",
|
||||
kph: "Speed", mps: "Speed",
|
||||
px: "Pixels", steps: "Steps",
|
||||
};
|
||||
return table[unit] || "Unknown";
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Runtime value representation for Nox.
|
||||
//
|
||||
// Most values are plain JS:
|
||||
// numbers -> JS number
|
||||
// strings -> JS string
|
||||
// bool -> JS bool
|
||||
// list/dict -> JS Array / Map
|
||||
// tuple -> JS Array with a hidden `_tuple` flag
|
||||
// null -> JS null (for Optional empty)
|
||||
//
|
||||
// Tagged values use a small `_tag` discriminator so we can preserve unit
|
||||
// dimensions, coordinate frames, and resource handles through computations.
|
||||
|
||||
export const Tag = Object.freeze({
|
||||
Quantity: "Quantity",
|
||||
Coord: "Coord",
|
||||
Resource: "Resource",
|
||||
Image: "Image",
|
||||
Time: "Time",
|
||||
Closure: "Closure",
|
||||
Range: "Range",
|
||||
});
|
||||
|
||||
export const Quantity = (value, dim) => ({ _tag: Tag.Quantity, value, dim });
|
||||
export const Coord = (frame, ra, dec) => ({ _tag: Tag.Coord, frame, ra, dec });
|
||||
export const Resource = (kind, name, driver) => ({ _tag: Tag.Resource, kind, name, driver });
|
||||
export const Image = (meta = {}) => ({ _tag: Tag.Image, ...meta });
|
||||
export const Time = (date) => ({ _tag: Tag.Time, date });
|
||||
export const Closure = (params, body, env, name = null) =>
|
||||
({ _tag: Tag.Closure, params, body, env, name });
|
||||
export const Range = (start, end, step) => ({ _tag: Tag.Range, start, end, step });
|
||||
|
||||
export function isTag(v, tag) { return v && typeof v === "object" && v._tag === tag; }
|
||||
export function isQuantity(v) { return isTag(v, Tag.Quantity); }
|
||||
|
||||
// Convert a quantity to its base unit so arithmetic is uniform internally.
|
||||
// Caller can re-tag the result.
|
||||
export function toBase(q, table) {
|
||||
if (!isQuantity(q)) return q;
|
||||
return q; // we already store quantities in their declared unit; conversions
|
||||
// happen at I/O boundaries (driver calls / output) for now.
|
||||
}
|
||||
|
||||
// Pretty-print a runtime value.
|
||||
export function show(v) {
|
||||
if (v === null || v === undefined) return "null";
|
||||
if (typeof v === "number" || typeof v === "string" || typeof v === "boolean") return JSON.stringify(v);
|
||||
if (Array.isArray(v)) return `[${v.map(show).join(", ")}]`;
|
||||
if (v instanceof Map) {
|
||||
const entries = [...v.entries()].map(([k, x]) => `${show(k)}: ${show(x)}`);
|
||||
return `{${entries.join(", ")}}`;
|
||||
}
|
||||
if (isQuantity(v)) return `${v.value}${v.dim}`;
|
||||
if (isTag(v, Tag.Coord)) return `Coord<${v.frame}>(${v.ra}, ${v.dec})`;
|
||||
if (isTag(v, Tag.Resource)) return `<${v.kind} ${v.name}>`;
|
||||
if (isTag(v, Tag.Image)) return `<Image ${v.filter || ""}>`;
|
||||
if (isTag(v, Tag.Time)) return `<Time ${v.date.toISOString()}>`;
|
||||
if (isTag(v, Tag.Closure)) return `<fn ${v.name || "lambda"}>`;
|
||||
if (isTag(v, Tag.Range)) return `<Range>`;
|
||||
return String(v);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Smoke-test the CLI by spawning it on each example.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const cli = path.resolve(here, "../bin/nox.js");
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
const files = fs.readdirSync(examplesDir).filter(f => f.endsWith(".nox")).sort();
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
for (const f of files) {
|
||||
const full = path.join(examplesDir, f);
|
||||
try {
|
||||
const checkOut = execFileSync(process.execPath, [cli, "check", full], { encoding: "utf8" }).trim();
|
||||
if (checkOut !== "clean") throw new Error(`check returned: ${checkOut}`);
|
||||
|
||||
const runOut = execFileSync(process.execPath, [cli, "run", full], { encoding: "utf8" }).trim();
|
||||
if (!/^\d+ ops$/.test(runOut)) throw new Error(`run returned: ${runOut}`);
|
||||
|
||||
console.log(` PASS ${f} ${runOut}`);
|
||||
pass++;
|
||||
} catch (e) {
|
||||
console.log(` FAIL ${f} ${e.message}`);
|
||||
fail++;
|
||||
}
|
||||
}
|
||||
console.log(`\n${pass}/${pass + fail} CLI checks + runs succeeded.`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
@@ -0,0 +1,31 @@
|
||||
// Verify that policy when-rules fire only on rising edges, not every tick.
|
||||
|
||||
import { run } from "../src/index.js";
|
||||
|
||||
const src = `
|
||||
use telescope T = "Astra-1"
|
||||
policy "p" {
|
||||
when weather.is_clear { T.home() }
|
||||
}
|
||||
`;
|
||||
|
||||
// Static weather: is_clear is always true. With ticks=3, the rule should
|
||||
// fire exactly once (tick 0: false -> true; ticks 1-2: true -> true, no fire).
|
||||
let homes = 0;
|
||||
const drv = {
|
||||
telescope() {
|
||||
return {
|
||||
async home() { homes++; },
|
||||
async park() {},
|
||||
};
|
||||
},
|
||||
dome() { return { async open(){}, async close(){}, is_closed(){return true;} }; },
|
||||
};
|
||||
await run(src, { strict: false, driver: drv, policy: { ticks: 3, intervalMs: 0 } });
|
||||
|
||||
console.log("home calls:", homes);
|
||||
if (homes !== 1) {
|
||||
console.log("FAIL expected 1 fire across 3 ticks, got", homes);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("PASS policy fires once on rising edge across 3 ticks");
|
||||
@@ -0,0 +1,67 @@
|
||||
// Verify that on-rollback handlers fire (in reverse order) when any task
|
||||
// in a parallel block fails.
|
||||
|
||||
import { run } from "../src/index.js";
|
||||
|
||||
// Three tasks. Task B will throw via halt. Tasks A and C registered rollback
|
||||
// handlers before B failed. Both rollbacks must run.
|
||||
const src = `
|
||||
use telescope T = "Astra-1"
|
||||
use dome D = "North"
|
||||
parallel {
|
||||
task open_dome {
|
||||
D.open()
|
||||
on rollback { D.close() }
|
||||
}
|
||||
task fail_now {
|
||||
assert false, "intentional failure for rollback test"
|
||||
on rollback { D.close() }
|
||||
}
|
||||
task home_mount {
|
||||
T.home()
|
||||
on rollback { T.park() }
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const log = [];
|
||||
let threw = false;
|
||||
try {
|
||||
// Custom driver that records onto our log so we can inspect order.
|
||||
const drv = {
|
||||
telescope(name) {
|
||||
return {
|
||||
async home() { log.push("T:" + name + ":home"); },
|
||||
async park() { log.push("T:" + name + ":park"); },
|
||||
};
|
||||
},
|
||||
dome(name) {
|
||||
return {
|
||||
async open() { log.push("D:" + name + ":open"); },
|
||||
async close() { log.push("D:" + name + ":close"); },
|
||||
is_closed() { return true; },
|
||||
};
|
||||
},
|
||||
};
|
||||
await run(src, { strict: false, driver: drv });
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
|
||||
// Expected: D:North:open, T:Astra-1:home, both ran. Then rollback fired and
|
||||
// we should see at least T:Astra-1:park and D:North:close from the handlers.
|
||||
const ops = log.join(", ");
|
||||
const hasOpen = log.includes("D:North:open");
|
||||
const hasHome = log.includes("T:Astra-1:home");
|
||||
const hasClose = log.includes("D:North:close");
|
||||
const hasPark = log.includes("T:Astra-1:park");
|
||||
|
||||
console.log("ops:", ops);
|
||||
console.log("threw:", threw, "open:", hasOpen, "home:", hasHome, "close:", hasClose, "park:", hasPark);
|
||||
|
||||
const pass = threw && hasOpen && hasHome && hasClose && hasPark;
|
||||
if (!pass) {
|
||||
console.log("FAIL");
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("PASS rollback fired for surviving tasks after a task failed");
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { run } from "../src/index.js";
|
||||
import { show } from "../src/values.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const examplesDir = path.resolve(here, "../../examples");
|
||||
|
||||
// The runtime is partial. Pick examples that exercise the core surface.
|
||||
const programs = [
|
||||
"01-hello-slew.nox",
|
||||
"02-messier-marathon.nox",
|
||||
"03-focus-run.nox",
|
||||
"04-dithered-imaging.nox",
|
||||
"05-automated-night.nox",
|
||||
"07-safety-rollback.nox",
|
||||
"08-survey-grid.nox",
|
||||
"09-calibration.nox",
|
||||
"10-policy.nox",
|
||||
];
|
||||
|
||||
let pass = 0, fail = 0;
|
||||
for (const f of programs) {
|
||||
const src = fs.readFileSync(path.join(examplesDir, f), "utf8");
|
||||
try {
|
||||
const t0 = Date.now();
|
||||
const { log } = await run(src);
|
||||
const dt = Date.now() - t0;
|
||||
console.log(` PASS ${f} ${log.length} ops in ${dt}ms`);
|
||||
if (process.argv.includes("--ops")) {
|
||||
for (const op of log) {
|
||||
const args = Object.entries(op.args || {})
|
||||
.map(([k, v]) => `${k}=${show(v)}`)
|
||||
.join(" ");
|
||||
console.log(` ${op.kind} ${op.op}${args ? " " + args : ""}`);
|
||||
}
|
||||
}
|
||||
pass++;
|
||||
} catch (e) {
|
||||
console.log(` FAIL ${f}`);
|
||||
console.log(` ${e.message}`);
|
||||
if (process.env.STACK) console.log(e.stack);
|
||||
fail++;
|
||||
}
|
||||
}
|
||||
console.log(`\n${pass}/${pass + fail} programs ran on mock.`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user