Compare commits

..
14 Commits
Author SHA1 Message Date
Alexander Bentkamp bb8be70bcb error: Tried to spawn a new thread, but 2023-11-27 22:12:37 +01:00
Alexander Bentkamp 85fef9373d fix rootUri 2023-11-24 10:19:34 +01:00
Alexander Bentkamp be34fe9cda didOpen 2023-11-23 22:07:44 +01:00
Alexander Bentkamp 6d61bc1942 connect to all game watchdog methods 2023-11-22 20:02:19 +01:00
Alexander Bentkamp 2613c16bbb bump toolchain 2023-11-22 18:26:16 +01:00
Alexander Bentkamp 926a013b10 more 2023-11-22 17:58:40 +01:00
Alexander Bentkamp 4e45111dd8 game info 2023-11-16 20:54:05 +01:00
Alexander Bentkamp 32a2ff3e18 game module import (not quite) 2023-11-15 21:27:52 +01:00
Alexander Bentkamp 8d29761579 stdout 2023-11-15 17:49:41 +01:00
Alexander Bentkamp 3ff46aeb54 merge dirs 2023-11-15 14:41:55 +01:00
Alexander Bentkamp 3d79c4ea60 connect wasm to monaco 2023-11-10 20:25:25 +01:00
Alexander Bentkamp 11dde6aad9 more 2023-11-10 15:34:31 +01:00
Alexander Bentkamp 8a6486bdd5 reverse-ffi IO 2023-11-10 11:27:09 +01:00
Alexander Bentkamp f6063023b4 reverse-ffi test 2023-11-10 10:44:37 +01:00
78 changed files with 6082 additions and 4571 deletions
+1
View File
@@ -0,0 +1 @@
LEAN4GAME_SINGLE_GAME=false
+1 -11
View File
@@ -5,17 +5,7 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: install elan - uses: actions/checkout@v3
run: |
set -o pipefail
curl -sSfL https://github.com/leanprover/elan/releases/download/v3.0.0/elan-x86_64-unknown-linux-gnu.tar.gz | tar xz
./elan-init -y
echo "$HOME/.elan/bin" >> $GITHUB_PATH
- uses: actions/checkout@v4
- uses: actions/setup-node@v3 - uses: actions/setup-node@v3
- name: print lean and lake versions
run: |
lean --version
lake --version
- run: npm install - run: npm install
- run: npm run build - run: npm run build
+5 -2
View File
@@ -1,5 +1,8 @@
node_modules node_modules
client/dist client/dist
games/ server/build
server/.lake server/lakefile.olean
server32bit
**/lake-packages/
**/.DS_Store **/.DS_Store
client/public/server.*
-7
View File
@@ -1,7 +0,0 @@
GameSkeleton
HiddenTactic
subgoals
KaTex
gameserver
lakefile
Zulip
+14 -24
View File
@@ -1,6 +1,6 @@
# Lean 4 Game # Lean 4 Game
This is the source code for a Lean game platform hosted at [adam.math.hhu.de](https://adam.math.hhu.de). This is the source code for a Lean 4 game platform hosted at [adam.math.hhu.de](https://adam.math.hhu.de).
## Creating a Game ## Creating a Game
@@ -8,30 +8,21 @@ Please follow the tutorial [Creating a Game](doc/create_game.md). In particular,
* Step 5: [How to Run Games Locally](doc/running_locally.md) * Step 5: [How to Run Games Locally](doc/running_locally.md)
* Step 7: [How to Update an existing Game](doc/update_game.md) * Step 7: [How to Update an existing Game](doc/update_game.md)
* Step 8: [How to Publishing a Game](doc/publish_game.md)
* [Troubleshooting](doc/troubleshoot.md) ### Publishing a Game
We encourage anybody to have games hosted on our [Lean Game Server](https://adam.math.hhu.de) for anybody to play. For that you simply need to contact us with the link to your game repo. We are also happy to add work-in-progress games and games in any language.
For example, you can [contact Jon on Zulip](https://leanprover.zulipchat.com/#narrow/dm/385895-Jon-Eugster). Or [via Email](https://www.math.hhu.de/en/lehrstuehle-/-personen-/-ansprechpartner/innen/lehrstuehle-des-mathematischen-instituts/lehrstuhl-fuer-algebraische-geometrie/team/jon-eugster).
## Documentation ## Documentation
The documentation is very much work in progress but the linked documentation here The documentation for the game engine itself is still missing, but there is [Creating a Game](doc/create_game.md) explaining the API to create a game.
should be up-to-date:
### Game creation API Some documentation:
- [Creating a Game](doc/create_game.md): **the main document to consult**. - [NPM Scripts](doc/npm_scripts.md)
- [More about Hints](doc/hints.md): describes the `Hint` and `Branch` tactic. - [Old documentation](doc/DOCUMENTATION.md)
### Frontend API
* [How to Run Games Locally](doc/running_locally.md): play a game on your computer
* [How to Update an existing Game](doc/update_game.md): update to a new lean version
* [How to Publishing a Game](doc/publish_game.md): load your game to adam.math.hhu.de for others to play
### Backend
not fully written yet.
* [Server](doc/DOCUMENTATION.md): describes the server part (i.e. the content of `server/` und `relay/`).
## Contributing ## Contributing
@@ -43,8 +34,7 @@ Providing the use access to a Lean instance running on the server is a severe se
## Credits ## Credits
The project has pimarily been developed by Alexander Bentkamp and Jon Eugster. The project is based on ideas from the [Lean Game Maker](https://github.com/mpedramfar/Lean-game-maker) and the [Natural Number Game
It is based on ideas from the [Lean Game Maker](https://github.com/mpedramfar/Lean-game-maker) and the [Natural Number Game
(NNG)](https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/) (NNG)](https://www.ma.imperial.ac.uk/~buzzard/xena/natural_number_game/)
by Kevin Buzzard and Mohammad Pedramfar, and on Patrick Massot's prototype: [NNG4](https://github.com/PatrickMassot/NNG4). of Kevin Buzzard and Mohammad Pedramfar.
The project is based on Patrick Massot's prototype: [NNG4](https://github.com/PatrickMassot/NNG4).
+94
View File
@@ -0,0 +1,94 @@
var stderrBuffer = ""
var messageBuffer = []
var initialized = false;
var flushing = false;
var headerMode = true;
var header="";
var re = /Content-Length: (\d+)\r\n/i;
var contentLength = 0;
var content = []
var utf8decoder = new TextDecoder();
function flushMessageBuffer(){
if (initialized && !flushing) {
while(messageBuffer.length > 0) {
flushing = true;
var msg = messageBuffer.shift();
console.log(`Send message: ${msg}`);
Module.ccall('send_message', 'void', ['string'], [msg]);
console.log(`Message done: ${msg}`);
}
flushing = false;
}
}
var Module = {
"arguments": ["--worker"],
"preRun": [function() {
function stdin() {
return null;
}
function stdout(asciiCode) {
if (headerMode) {
header += String.fromCharCode(asciiCode)
if (header.endsWith('\r\n\r\n')) {
const found = header.match(re)
if (found == null) { console.error(`Invalid header: ${header}`) }
contentLength = parseInt(found[1])
content = []
headerMode = false
}
} else {
content.push(asciiCode)
if (content.length == contentLength) {
const message = utf8decoder.decode(new Uint8Array(content))
console.log(`Server: ${message}`)
postMessage(message);
headerMode = true
header = ''
}
}
}
function stderr(asciiCode) {
stderrBuffer += String.fromCharCode(asciiCode)
}
FS.init(stdin, stdout, stderr);
}],
"noInitialRun": true,
"onRuntimeInitialized": () => {
Module.ccall('main', 'void', [], []);
initialized = true;
if (stderrBuffer !== "") {
console.log(stderrBuffer);
stderrBuffer = ""
}
flushMessageBuffer();
}
};
importScripts("server.js")
onmessage = (ev) => {
console.log(`Client: ${ev.data}`)
messageBuffer.push(ev.data);
flushMessageBuffer();
}
setInterval(() => {
if (stderrBuffer !== "") {
console.log(stderrBuffer);
stderrBuffer = ""
}
}, 1000)
setTimeout(() =>{
},2000)
+7 -8
View File
@@ -8,24 +8,23 @@ import '@fontsource/roboto/700.css';
import './css/reset.css'; import './css/reset.css';
import './css/app.css'; import './css/app.css';
import { PreferencesContext} from './components/infoview/context'; import { MobileContext } from './components/infoview/context';
import UsePreferences from "./state/hooks/use_preferences" import { useWindowDimensions } from './window_width';
export const GameIdContext = React.createContext<string>(undefined); export const GameIdContext = React.createContext<string>(undefined);
function App() { function App() {
const params = useParams() const params = useParams()
const gameId = "g/" + params.owner + "/" + params.repo const gameId = "g/" + params.owner + "/" + params.repo
const {width, height} = useWindowDimensions()
const {mobile, layout, isSavePreferences, setLayout, setIsSavePreferences} = UsePreferences() const [mobile, setMobile] = React.useState(width < 800)
return ( return (
<div className="app"> <div className="app">
<GameIdContext.Provider value={gameId}> <GameIdContext.Provider value={gameId}>
<PreferencesContext.Provider value={{mobile, layout, isSavePreferences, setLayout, setIsSavePreferences}}> <MobileContext.Provider value={{mobile, setMobile}}>
<Outlet /> <Outlet />
</PreferencesContext.Provider> </MobileContext.Provider>
</GameIdContext.Provider> </GameIdContext.Provider>
</div> </div>
) )
Binary file not shown.

After

Width:  |  Height:  |  Size: 398 KiB

+8 -12
View File
@@ -5,9 +5,9 @@ import * as React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDownload, faUpload, faEraser, faBook, faBookOpen, faGlobe, faHome, import { faDownload, faUpload, faEraser, faBook, faBookOpen, faGlobe, faHome,
faArrowRight, faArrowLeft, faXmark, faBars, faCode, faArrowRight, faArrowLeft, faXmark, faBars, faCode,
faCircleInfo, faTerminal, faMobileScreenButton, faDesktop, faGear } from '@fortawesome/free-solid-svg-icons' faCircleInfo, faTerminal } from '@fortawesome/free-solid-svg-icons'
import { GameIdContext } from "../app" import { GameIdContext } from "../app"
import { InputModeContext, PreferencesContext, WorldLevelIdContext } from "./infoview/context" import { InputModeContext, MobileContext, WorldLevelIdContext } from "./infoview/context"
import { GameInfo, useGetGameInfoQuery } from '../state/api' import { GameInfo, useGetGameInfoQuery } from '../state/api'
import { changedOpenedIntro, selectCompleted, selectDifficulty, selectProgress } from '../state/progress' import { changedOpenedIntro, selectCompleted, selectDifficulty, selectProgress } from '../state/progress'
import { useAppDispatch, useAppSelector } from '../hooks' import { useAppDispatch, useAppSelector } from '../hooks'
@@ -150,23 +150,22 @@ function InventoryButton({pageNumber, setPageNumber}) {
} }
/** the navigation bar on the welcome page */ /** the navigation bar on the welcome page */
export function WelcomeAppBar({pageNumber, setPageNumber, gameInfo, toggleImpressum, toggleEraseMenu, toggleUploadMenu, toggleInfo, togglePreferencesPopup} : { export function WelcomeAppBar({pageNumber, setPageNumber, gameInfo, toggleImpressum, toggleEraseMenu, toggleUploadMenu, toggleInfo} : {
pageNumber: number, pageNumber: number,
setPageNumber: any, setPageNumber: any,
gameInfo: GameInfo, gameInfo: GameInfo,
toggleImpressum: any, toggleImpressum: any,
toggleEraseMenu: any, toggleEraseMenu: any,
toggleUploadMenu: any, toggleUploadMenu: any,
toggleInfo: any, toggleInfo: any
togglePreferencesPopup: () => void;
}) { }) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const gameProgress = useAppSelector(selectProgress(gameId)) const gameProgress = useAppSelector(selectProgress(gameId))
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const [navOpen, setNavOpen] = React.useState(false) const [navOpen, setNavOpen] = React.useState(false)
return <div className="app-bar"> return <div className="app-bar">
<div className='app-bar-left'> <div>
<Button inverted="false" title="back to games selection" to="/"> <Button inverted="false" title="back to games selection" to="/">
<FontAwesomeIcon icon={faArrowLeft} />&nbsp;<FontAwesomeIcon icon={faGlobe} /> <FontAwesomeIcon icon={faArrowLeft} />&nbsp;<FontAwesomeIcon icon={faGlobe} />
</Button> </Button>
@@ -195,9 +194,6 @@ export function WelcomeAppBar({pageNumber, setPageNumber, gameInfo, toggleImpres
<Button title="Impressum, privacy policy" inverted="true" to="" onClick={() => {toggleImpressum(); setNavOpen(false)}}> <Button title="Impressum, privacy policy" inverted="true" to="" onClick={() => {toggleImpressum(); setNavOpen(false)}}>
<FontAwesomeIcon icon={faCircleInfo} />&nbsp;Impressum <FontAwesomeIcon icon={faCircleInfo} />&nbsp;Impressum
</Button> </Button>
<Button title="Preferences" inverted="true" to="" onClick={() => {togglePreferencesPopup(); setNavOpen(false)}}>
<FontAwesomeIcon icon={faGear} />&nbsp;Preferences
</Button>
</div> </div>
</div> </div>
} }
@@ -212,7 +208,7 @@ export function LevelAppBar({isLoading, levelTitle, toggleImpressum, pageNumber=
}) { }) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {worldId, levelId} = React.useContext(WorldLevelIdContext) const {worldId, levelId} = React.useContext(WorldLevelIdContext)
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const [navOpen, setNavOpen] = React.useState(false) const [navOpen, setNavOpen] = React.useState(false)
const gameInfo = useGetGameInfoQuery({game: gameId}) const gameInfo = useGetGameInfoQuery({game: gameId})
const completed = useAppSelector(selectCompleted(gameId, worldId, levelId)) const completed = useAppSelector(selectCompleted(gameId, worldId, levelId))
@@ -241,7 +237,7 @@ export function LevelAppBar({isLoading, levelTitle, toggleImpressum, pageNumber=
</> : </> :
<> <>
{/* DESKTOP VERSION */} {/* DESKTOP VERSION */}
<div className='app-bar-left'> <div>
<HomeButton isDropdown={false} /> <HomeButton isDropdown={false} />
<span className="app-bar-title">{worldTitle && `World: ${worldTitle}`}</span> <span className="app-bar-title">{worldTitle && `World: ${worldTitle}`}</span>
</div> </div>
-22
View File
@@ -1,7 +1,6 @@
import { GameHint } from "./infoview/rpc_api"; import { GameHint } from "./infoview/rpc_api";
import * as React from 'react'; import * as React from 'react';
import Markdown from './markdown'; import Markdown from './markdown';
import { ProofStep } from "./infoview/context";
export function Hint({hint, step, selected, toggleSelection, lastLevel} : {hint: GameHint, step: number, selected: number, toggleSelection: any, lastLevel?: boolean}) { export function Hint({hint, step, selected, toggleSelection, lastLevel} : {hint: GameHint, step: number, selected: number, toggleSelection: any, lastLevel?: boolean}) {
return <div className={`message information step-${step}` + (step == selected ? ' selected' : '') + (lastLevel ? ' recent' : '')} onClick={toggleSelection}> return <div className={`message information step-${step}` + (step == selected ? ' selected' : '') + (lastLevel ? ' recent' : '')} onClick={toggleSelection}>
@@ -44,24 +43,3 @@ export function DeletedHints({hints} : {hints: GameHint[]}) {
{hiddenHints.map((hint, i) => <DeletedHint key={`deleted-hidden-hint-${i}`} hint={hint}/>)} {hiddenHints.map((hint, i) => <DeletedHint key={`deleted-hidden-hint-${i}`} hint={hint}/>)}
</> </>
} }
/** Filter hints to not show consequtive identical hints twice.
*
* This function takes a `ProofStep[]` and extracts the hints in form of an
* element of type `GameHint[][]` where it removes hints that are identical to hints
* appearing in the previous step. Hidden hints are not filtered.
*
* This effectively means we prevent consequtive identical hints from being shown.
*/
export function filterHints(proof: ProofStep[]): GameHint[][] {
return proof.map((step, i) => {
if (i == 0){
return step.hints
} else {
// TODO: Writing all fields explicitely is somewhat fragile to changes, is there a
// good way to shallow-compare objects?
return step.hints.filter((hint) => hint.hidden ||
(proof[i-1].hints.find((x) => (x.text == hint.text && x.hidden == hint.hidden)) === undefined))
}
})
}
+6 -13
View File
@@ -5,7 +5,6 @@ import * as React from 'react';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { InteractiveDiagnostic, InteractiveTermGoal } from '@leanprover/infoview-api'; import { InteractiveDiagnostic, InteractiveTermGoal } from '@leanprover/infoview-api';
import { GameHint, InteractiveGoal, InteractiveGoals } from './rpc_api'; import { GameHint, InteractiveGoal, InteractiveGoals } from './rpc_api';
import { PreferencesState } from '../../state/preferences';
export const MonacoEditorContext = React.createContext<monaco.editor.IStandaloneCodeEditor>( export const MonacoEditorContext = React.createContext<monaco.editor.IStandaloneCodeEditor>(
null as any) null as any)
@@ -63,18 +62,12 @@ export const ProofStateContext = React.createContext<{
setProofState: () => {}, setProofState: () => {},
}) })
export interface IPreferencesContext extends PreferencesState{ export const MobileContext = React.createContext<{
mobile: boolean, // The variables that actually control the page 'layout' can only be changed through layout. mobile : boolean,
setLayout: React.Dispatch<React.SetStateAction<PreferencesState["layout"]>>; setMobile: React.Dispatch<React.SetStateAction<Boolean>>,
setIsSavePreferences: React.Dispatch<React.SetStateAction<Boolean>>; }>({
} mobile : false,
setMobile: () => {},
export const PreferencesContext = React.createContext<IPreferencesContext>({
mobile: false,
layout: "auto",
isSavePreferences: false,
setLayout: () => {},
setIsSavePreferences: () => {}
}) })
export const WorldLevelIdContext = React.createContext<{ export const WorldLevelIdContext = React.createContext<{
+15 -29
View File
@@ -27,14 +27,14 @@ import Markdown from '../markdown';
import { Infos } from './infos'; import { Infos } from './infos';
import { AllMessages, Errors, WithLspDiagnosticsContext } from './messages'; import { AllMessages, Errors, WithLspDiagnosticsContext } from './messages';
import { Goal } from './goals'; import { Goal } from './goals';
import { DeletedChatContext, InputModeContext, PreferencesContext, MonacoEditorContext, ProofContext, ProofStep, SelectionContext, WorldLevelIdContext } from './context'; import { DeletedChatContext, InputModeContext, MobileContext, MonacoEditorContext, ProofContext, ProofStep, SelectionContext, WorldLevelIdContext } from './context';
import { Typewriter, hasErrors, hasInteractiveErrors } from './typewriter'; import { Typewriter, hasErrors, hasInteractiveErrors } from './typewriter';
import { InteractiveDiagnostic } from '@leanprover/infoview/*'; import { InteractiveDiagnostic } from '@leanprover/infoview/*';
import { Button } from '../button'; import { Button } from '../button';
import { CircularProgress } from '@mui/material'; import { CircularProgress } from '@mui/material';
import { GameHint } from './rpc_api'; import { GameHint } from './rpc_api';
import { store } from '../../state/store'; import { store } from '../../state/store';
import { Hints, filterHints } from '../hints'; import { Hints } from '../hints';
/** Wrapper for the two editors. It is important that the `div` with `codeViewRef` is /** Wrapper for the two editors. It is important that the `div` with `codeViewRef` is
* always present, or the monaco editor cannot start. * always present, or the monaco editor cannot start.
@@ -156,7 +156,7 @@ export function Main(props: { world: string, level: number, data: LevelInfo}) {
const completed = useAppSelector(selectCompleted(gameId, props.world, props.level)) const completed = useAppSelector(selectCompleted(gameId, props.world, props.level))
console.debug(`template: ${props.data?.template}`) console.debug(`template: ${props.data.template}`)
// React.useEffect (() => { // React.useEffect (() => {
// if (props.data.template) { // if (props.data.template) {
@@ -347,9 +347,8 @@ export function TypewriterInterface({props}) {
const uri = model.uri.toString() const uri = model.uri.toString()
const [disableInput, setDisableInput] = React.useState<boolean>(false) const [disableInput, setDisableInput] = React.useState<boolean>(false)
const [loadingProgress, setLoadingProgress] = React.useState<number>(0)
const { setDeletedChat, showHelp, setShowHelp } = React.useContext(DeletedChatContext) const { setDeletedChat, showHelp, setShowHelp } = React.useContext(DeletedChatContext)
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const { proof } = React.useContext(ProofContext) const { proof } = React.useContext(ProofContext)
const { setTypewriterInput } = React.useContext(InputModeContext) const { setTypewriterInput } = React.useContext(InputModeContext)
const { selectedStep, setSelectedStep } = React.useContext(SelectionContext) const { selectedStep, setSelectedStep } = React.useContext(SelectionContext)
@@ -367,9 +366,9 @@ export function TypewriterInterface({props}) {
function deleteProof(line: number) { function deleteProof(line: number) {
return (ev) => { return (ev) => {
let deletedChat: Array<GameHint> = [] let deletedChat: Array<GameHint> = []
filterHints(proof).slice(line).map((hintsAtStep, i) => { proof.slice(line).map((step, i) => {
// Only add these hidden hints to the deletion stack which were visible // Only add these hidden hints to the deletion stack which were visible
deletedChat = [...deletedChat, ...hintsAtStep.filter(hint => (!hint.hidden || showHelp.has(line + i)))] deletedChat = [...deletedChat, ...step.hints.filter(hint => (!hint.hidden || showHelp.has(line + i)))]
}) })
setDeletedChat(deletedChat) setDeletedChat(deletedChat)
@@ -456,17 +455,6 @@ export function TypewriterInterface({props}) {
let lastStepErrors = proof.length ? hasInteractiveErrors(proof[proof.length - 1].errors) : false let lastStepErrors = proof.length ? hasInteractiveErrors(proof[proof.length - 1].errors) : false
useServerNotificationEffect("$/game/loading", (params : any) => {
if (params.kind == "loadConstants") {
setLoadingProgress(params.counter/100*50)
} else if (params.kind == "finalizeExtensions") {
setLoadingProgress(50 + params.counter/150*50)
} else {
console.error(`Unknown loading kind: ${params.kind}`)
}
})
return <div className="typewriter-interface"> return <div className="typewriter-interface">
<RpcContext.Provider value={rpcSess}> <RpcContext.Provider value={rpcSess}>
<div className="content"> <div className="content">
@@ -493,20 +481,18 @@ export function TypewriterInterface({props}) {
<Markdown>{props.data?.introduction}</Markdown> <Markdown>{props.data?.introduction}</Markdown>
</div> </div>
} }
{mobile && {mobile && <>
<Hints key={`hints-${i}`} <Hints key={`hints-${i}`}
hints={step.hints} showHidden={showHelp.has(i)} step={i} hints={step.hints} showHidden={showHelp.has(i)} step={i}
selected={selectedStep} toggleSelection={toggleSelectStep(i)}/> selected={selectedStep} toggleSelection={toggleSelectStep(i)}/>
{i == proof.length - 1 && hasHiddenHints(proof.length - 1) && !showHelp.has(k - withErr) &&
<Button className="btn btn-help" to="" onClick={activateHiddenHints}>
Show more help!
</Button>
}
</>
} }
<GoalsTabs proofStep={step} last={i == proof.length - (lastStepErrors ? 2 : 1)} onClick={toggleSelectStep(i)} onGoalChange={i == proof.length - 1 - withErr ? (n) => setDisableInput(n > 0) : (n) => {}}/> <GoalsTabs proofStep={step} last={i == proof.length - (lastStepErrors ? 2 : 1)} onClick={toggleSelectStep(i)} onGoalChange={i == proof.length - 1 - withErr ? (n) => setDisableInput(n > 0) : (n) => {}}/>
{mobile && i == proof.length - 1 &&
hasHiddenHints(proof.length - 1) && !showHelp.has(k - withErr) &&
<Button className="btn btn-help" to="" onClick={activateHiddenHints}>
Show more help!
</Button>
}
{/* Show a message that there are no goals left */} {/* Show a message that there are no goals left */}
{!step.goals.length && ( {!step.goals.length && (
<div className="message information"> <div className="message information">
@@ -523,7 +509,7 @@ export function TypewriterInterface({props}) {
} }
})} })}
{mobile && completed && {mobile && completed &&
<div className="button-row mobile"> <div className="button-row">
{props.level >= props.worldSize ? {props.level >= props.worldSize ?
<Button to={`/${gameId}`}> <Button to={`/${gameId}`}>
<FontAwesomeIcon icon={faHome} />&nbsp;Leave World <FontAwesomeIcon icon={faHome} />&nbsp;Leave World
@@ -535,7 +521,7 @@ export function TypewriterInterface({props}) {
} }
</div> </div>
} }
</> : <CircularProgress variant="determinate" value={loadingProgress} /> </> : <CircularProgress />
} }
</div> </div>
</div> </div>
+22 -45
View File
@@ -2,8 +2,7 @@ import * as React from 'react';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import '../css/inventory.css' import '../css/inventory.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faLock, faBan, faCheck } from '@fortawesome/free-solid-svg-icons' import { faLock, faBan } from '@fortawesome/free-solid-svg-icons'
import { faClipboard } from '@fortawesome/free-regular-svg-icons'
import { GameIdContext } from '../app'; import { GameIdContext } from '../app';
import Markdown from './markdown'; import Markdown from './markdown';
import { useLoadDocQuery, InventoryTile, LevelInfo, InventoryOverview, useLoadInventoryOverviewQuery } from '../state/api'; import { useLoadDocQuery, InventoryTile, LevelInfo, InventoryOverview, useLoadInventoryOverviewQuery } from '../state/api';
@@ -11,12 +10,10 @@ import { selectDifficulty, selectInventory } from '../state/progress';
import { store } from '../state/store'; import { store } from '../state/store';
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
export function Inventory({levelInfo, openDoc, lemmaTab, setLemmaTab, enableAll=false} : export function Inventory({levelInfo, openDoc, enableAll=false} :
{ {
levelInfo: LevelInfo|InventoryOverview, levelInfo: LevelInfo|InventoryOverview,
openDoc: (props: {name: string, type: string}) => void, openDoc: (props: {name: string, type: string}) => void,
lemmaTab: any,
setLemmaTab: any,
enableAll?: boolean, enableAll?: boolean,
}) { }) {
@@ -34,20 +31,19 @@ export function Inventory({levelInfo, openDoc, lemmaTab, setLemmaTab, enableAll=
} }
<h2>Theorems</h2> <h2>Theorems</h2>
{levelInfo?.lemmas && {levelInfo?.lemmas &&
<InventoryList items={levelInfo?.lemmas} docType="Lemma" openDoc={openDoc} level={levelInfo} enableAll={enableAll} tab={lemmaTab} setTab={setLemmaTab}/> <InventoryList items={levelInfo?.lemmas} docType="Lemma" openDoc={openDoc} defaultTab={levelInfo?.lemmaTab} level={levelInfo} enableAll={enableAll}/>
} }
</div> </div>
) )
} }
function InventoryList({items, docType, openDoc, tab=null, setTab=undefined, level=undefined, enableAll=false} : function InventoryList({items, docType, openDoc, defaultTab=null, level=undefined, enableAll=false} :
{ {
items: InventoryTile[], items: InventoryTile[],
docType: string, docType: string,
openDoc(props: {name: string, type: string}): void, openDoc(props: {name: string, type: string}): void,
tab?: any, defaultTab? : string,
setTab?: any, level? : LevelInfo|InventoryOverview,
level?: LevelInfo|InventoryOverview,
enableAll?: boolean, enableAll?: boolean,
}) { }) {
// TODO: `level` is only used in the `useEffect` below to check if a new level has // TODO: `level` is only used in the `useEffect` below to check if a new level has
@@ -63,6 +59,8 @@ function InventoryList({items, docType, openDoc, tab=null, setTab=undefined, lev
} }
const categories = Array.from(categorySet).sort() const categories = Array.from(categorySet).sort()
const [tab, setTab] = useState(defaultTab)
// Add inventory items from local store as unlocked. // Add inventory items from local store as unlocked.
// Items are unlocked if they are in the local store, or if the server says they should be // Items are unlocked if they are in the local store, or if the server says they should be
// given the dependency graph. (OR-connection) (TODO: maybe add different logic for different // given the dependency graph. (OR-connection) (TODO: maybe add different logic for different
@@ -70,6 +68,13 @@ function InventoryList({items, docType, openDoc, tab=null, setTab=undefined, lev
let inv: string[] = selectInventory(gameId)(store.getState()) let inv: string[] = selectInventory(gameId)(store.getState())
let modifiedItems : InventoryTile[] = items.map(tile => inv.includes(tile.name) ? {...tile, locked: false} : tile) let modifiedItems : InventoryTile[] = items.map(tile => inv.includes(tile.name) ? {...tile, locked: false} : tile)
useEffect(() => {
// If the level specifies `LemmaTab "Nat"`, we switch to this tab on loading.
// `defaultTab` is `null` or `undefined` otherwise, in which case we don't want to switch.
if (defaultTab) {
setTab(defaultTab)
}}, [level])
return <> return <>
{categories.length > 1 && {categories.length > 1 &&
<div className="tab-bar"> <div className="tab-bar">
@@ -81,29 +86,24 @@ function InventoryList({items, docType, openDoc, tab=null, setTab=undefined, lev
{[...modifiedItems].sort( {[...modifiedItems].sort(
// For lemas, sort entries `available > disabled > locked` // For lemas, sort entries `available > disabled > locked`
// otherwise alphabetically // otherwise alphabetically
(x, y) => +(docType == "Lemma") * (+x.locked - +y.locked || +x.disabled - +y.disabled) || x.displayName.localeCompare(y.displayName) (x, y) => +(docType == "Lemma") * (+x.locked - +y.locked || +x.disabled - +y.disabled)
).filter(item => !item.hidden && ((tab ?? categories[0]) == item.category)).map((item, i) => { ).filter(item => !item.hidden && ((tab ?? categories[0]) == item.category)).map((item, i) => {
return <InventoryItem key={`${item.category}-${item.name}`} return <InventoryItem key={`${item.category}-${item.name}`}
item={item}
showDoc={() => {openDoc({name: item.name, type: docType})}} showDoc={() => {openDoc({name: item.name, type: docType})}}
name={item.name} displayName={item.displayName} locked={difficulty > 0 ? item.locked : false} name={item.name} displayName={item.displayName} locked={difficulty > 0 ? item.locked : false}
disabled={item.disabled} newly={item.new} enableAll={enableAll} /> disabled={item.disabled} newly={item.new} enableAll={enableAll}/>
}) })
} }
</div> </div>
</> </>
} }
function InventoryItem({item, name, displayName, locked, disabled, newly, showDoc, enableAll=false}) { function InventoryItem({name, displayName, locked, disabled, newly, showDoc, enableAll=false}) {
const icon = locked ? <FontAwesomeIcon icon={faLock} /> : const icon = locked ? <FontAwesomeIcon icon={faLock} /> :
disabled ? <FontAwesomeIcon icon={faBan} /> : item.st disabled ? <FontAwesomeIcon icon={faBan} /> : ""
const className = locked ? "locked" : disabled ? "disabled" : newly ? "new" : "" const className = locked ? "locked" : disabled ? "disabled" : newly ? "new" : ""
// Note: This is somewhat a hack as the statement of lemmas comes currently in the form
// `Namespace.statement_name (x y : Nat) : some type`
const title = locked ? "Not unlocked yet" : const title = locked ? "Not unlocked yet" :
disabled ? "Not available in this level" : (item.altTitle ? item.altTitle.substring(item.altTitle.indexOf(' ') + 1) : '') disabled ? "Not available in this level" : ""
const [copied, setCopied] = useState(false)
const handleClick = () => { const handleClick = () => {
if (enableAll || !locked) { if (enableAll || !locked) {
@@ -111,21 +111,7 @@ function InventoryItem({item, name, displayName, locked, disabled, newly, showDo
} }
} }
const copyItemName = (ev) => { return <div className={`item ${className}${enableAll ? ' enabled' : ''}`} onClick={handleClick} title={title}>{icon} {displayName}</div>
navigator.clipboard.writeText(displayName)
setCopied(true)
setInterval(() => {
setCopied(false)
}, 3000);
ev.stopPropagation()
}
return <div className={`item ${className}${enableAll ? ' enabled' : ''}`} onClick={handleClick} title={title}>
{icon} {displayName}
<div className="copy-button" onClick={copyItemName}>
{copied ? <FontAwesomeIcon icon={faCheck} /> : <FontAwesomeIcon icon={faClipboard} />}
</div>
</div>
} }
export function Documentation({name, type, handleClose}) { export function Documentation({name, type, handleClose}) {
@@ -145,25 +131,16 @@ export function Documentation({name, type, handleClose}) {
export function InventoryPanel({levelInfo, visible = true}) { export function InventoryPanel({levelInfo, visible = true}) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const [lemmaTab, setLemmaTab] = useState(levelInfo?.lemmaTab)
// The inventory is overlayed by the doc entry of a clicked item // The inventory is overlayed by the doc entry of a clicked item
const [inventoryDoc, setInventoryDoc] = useState<{name: string, type: string}>(null) const [inventoryDoc, setInventoryDoc] = useState<{name: string, type: string}>(null)
// Set `inventoryDoc` to `null` to close the doc // Set `inventoryDoc` to `null` to close the doc
function closeInventoryDoc() {setInventoryDoc(null)} function closeInventoryDoc() {setInventoryDoc(null)}
useEffect(() => {
// If the level specifies `LemmaTab "Nat"`, we switch to this tab on loading.
// `defaultTab` is `null` or `undefined` otherwise, in which case we don't want to switch.
if (levelInfo?.lemmaTab) {
setLemmaTab(levelInfo?.lemmaTab)
}}, [levelInfo])
return <div className={`column inventory-panel ${visible ? '' : 'hidden'}`}> return <div className={`column inventory-panel ${visible ? '' : 'hidden'}`}>
{inventoryDoc ? {inventoryDoc ?
<Documentation name={inventoryDoc.name} type={inventoryDoc.type} handleClose={closeInventoryDoc}/> <Documentation name={inventoryDoc.name} type={inventoryDoc.type} handleClose={closeInventoryDoc}/>
: :
<Inventory levelInfo={levelInfo} openDoc={setInventoryDoc} enableAll={true} lemmaTab={lemmaTab} setLemmaTab={setLemmaTab}/> <Inventory levelInfo={levelInfo} openDoc={setInventoryDoc} enableAll={true}/>
} }
</div> </div>
} }
+67 -92
View File
@@ -7,12 +7,11 @@ import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css'; import '@fontsource/roboto/700.css';
import '../css/landing_page.css' import '../css/landing_page.css'
import coverRobo from '../assets/covers/formaloversum.png'
import bgImage from '../assets/bg.jpg' import bgImage from '../assets/bg.jpg'
import Markdown from './markdown'; import Markdown from './markdown';
import {PrivacyPolicyPopup} from './popup/privacy_policy' import {PrivacyPolicyPopup} from './popup/privacy_policy'
import { GameTile, useGetGameInfoQuery } from '../state/api'
import path from 'path';
const flag = { const flag = {
'Dutch': '🇳🇱', 'Dutch': '🇳🇱',
@@ -20,7 +19,6 @@ const flag = {
'French': '🇫🇷', 'French': '🇫🇷',
'German': '🇩🇪', 'German': '🇩🇪',
'Italian': '🇮🇹', 'Italian': '🇮🇹',
'Spanish': '🇪🇸',
} }
function GithubIcon({url='https://github.com'}) { function GithubIcon({url='https://github.com'}) {
@@ -34,42 +32,47 @@ function GithubIcon({url='https://github.com'}) {
</div> </div>
} }
function Tile({gameId, data}: {gameId: string, data: GameTile|undefined}) { function GameTile({
title,
gameId,
intro, // Catchy intro phrase.
image=null,
worlds='?',
levels='?',
prereq='&ndash;', // Optional list of games that this game builds on. Use markdown.
description, // Longer description. Supports Markdown.
language}) {
let navigate = useNavigate(); let navigate = useNavigate();
const routeChange = () =>{ const routeChange = () =>{
navigate(gameId); navigate(gameId);
} }
if (typeof data === 'undefined') {
return <></>
}
return <div className="game" onClick={routeChange}> return <div className="game" onClick={routeChange}>
<div className="wrapper"> <div className="wrapper">
<div className="title">{data.title}</div> <div className="title">{title}</div>
<div className="short-description">{data.short} <div className="short-description">{intro}
</div> </div>
{ data.image ? <img className="image" src={path.join("data", gameId, data.image)} alt="" /> : <div className="image"/> } { image ? <img className="image" src={image} alt="" /> : <div className="image"/> }
<div className="long description"><Markdown>{data.long}</Markdown></div> <div className="long description"><Markdown>{description}</Markdown></div>
</div> </div>
<table className="info"> <table className="info">
<tbody> <tbody>
<tr> <tr>
<td title="consider playing these games first.">Prerequisites</td> <td title="consider playing these games first.">Prerequisites</td>
<td><Markdown>{data.prerequisites.join(', ')}</Markdown></td> <td><Markdown>{prereq}</Markdown></td>
</tr> </tr>
<tr> <tr>
<td>Worlds</td> <td>Worlds</td>
<td>{data.worlds}</td> <td>{worlds}</td>
</tr> </tr>
<tr> <tr>
<td>Levels</td> <td>Levels</td>
<td>{data.levels}</td> <td>{levels}</td>
</tr> </tr>
<tr> <tr>
<td>Language</td> <td>Language</td>
<td title={`in ${data.languages.join(', ')}`}>{data.languages.map((lan) => flag[lan]).join(', ')}</td> <td title={`in ${language}`}>{flag[language]}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -85,59 +88,6 @@ function LandingPage() {
const openImpressum = () => setImpressum(true); const openImpressum = () => setImpressum(true);
const closeImpressum = () => setImpressum(false); const closeImpressum = () => setImpressum(false);
// const [allGames, setAllGames] = React.useState([])
// const [allTiles, setAllTiles] = React.useState([])
// const getTiles=()=>{
// fetch('featured_games.json', {
// headers : {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json'
// }
// }
// ).then(function(response){
// return response.json()
// }).then(function(data) {
// setAllGames(data.featured_games)
// })
// }
// React.useEffect(()=>{
// getTiles()
// },[])
// React.useEffect(()=>{
// Promise.allSettled(
// allGames.map((gameId) => (
// fetch(`data/g/${gameId}/game.json`).catch(err => {return undefined})))
// ).then(responses =>
// responses.forEach((result) => console.log(result)))
// // Promise.all(responses.map(res => {
// // if (res.status == "fulfilled") {
// // console.log(res.value.json())
// // return res.value.json()
// // } else {
// // return undefined
// // }
// // }))
// // ).then(allData => {
// // setAllTiles(allData.map(data => data?.tile))
// // })
// },[allGames])
// TODO: I would like to read the supported games list form a JSON,
// Then load all these games in
//
let allGames = [
"leanprover-community/nng4",
"hhu-adam/robo",
"djvelleman/stg4",
"miguelmarco/stg4",
"trequetrum/lean4game-logic",
]
let allTiles = allGames.map((gameId) => (useGetGameInfoQuery({game: `g/${gameId}`}).data?.tile))
return <div className="landing-page"> return <div className="landing-page">
<header style={{backgroundImage: `url(${bgImage})`}}> <header style={{backgroundImage: `url(${bgImage})`}}>
@@ -154,26 +104,49 @@ function LandingPage() {
</div> </div>
</header> </header>
<div className="game-list"> <div className="game-list">
{allTiles.length == 0 ?
<p>No Games loaded. Use <a>http://localhost:3000/#/g/local/FOLDER</a> to open a <GameTile
game directly from a local folder. title="Natural Number Game"
</p> gameId="g/hhu-adam/NNG4"
: allGames.map((id, i) => ( intro="The classical introduction game for Lean."
<Tile description="In this game you recreate the natural numbers $\mathbb{N}$ from the Peano axioms,
key={id} learning the basics about theorem proving in Lean.
gameId={`g/${id}`}
data={allTiles[i]} This is a good first introduction to Lean!"
/> worlds="4"
)) levels="30"
} language="English"
/>
<GameTile
title="Formaloversum"
gameId="g/hhu-adam/Robo"
intro="Erkunde das Leansche Universum mit deinem Robo, welcher dir bei der Verständigung mit den Formalosophen zur Seite steht."
description="
Dieses Spiel führt die Grundlagen zur Beweisführung in Lean ein und schneidet danach verschiedene Bereiche des Bachelorstudiums an.
(Das Spiel befindet sich noch in der Entstehungsphase.)"
image={coverRobo}
language="German"
/>
<GameTile
title="NNG (OLD)"
gameId="g/hhu-adam/nng4-old"
intro="The old version of the NNG copied from lean3."
description="This version is not maintained and might break at any point. You should play the new version instead"
worlds="9"
levels="72"
language="English"
/>
</div> </div>
<section> <section>
<div className="wrapper"> <div className="wrapper">
<h2>Development notes</h2> <h2>Development notes</h2>
<p> <p>
As this server runs lean on our university machines, it has a limited capacity. As this server runs lean on our university machines, it has a limited capacity.
Our current estimate is about 70 simultaneous games. Our current estimate is about 55 copies of the NNG or 25 copies of games importing
We hope to address and test this limitation better in the future. mathlib. We hope to address this limitation in the future.
</p> </p>
<p> <p>
Most aspects of the games and the infrastructure are still in development. Feel free to Most aspects of the games and the infrastructure are still in development. Feel free to
@@ -187,19 +160,18 @@ function LandingPage() {
<h2>Adding new games</h2> <h2>Adding new games</h2>
<p> <p>
If you are considering writing your own game, you should use If you are considering writing your own game, you should use
the <a target="_blank" href="https://github.com/hhu-adam/GameSkeleton">GameSkeleton Github Repo</a> as the <a target="_blank" href="https://github.com/hhu-adam/NNG4">NNG Github Repo</a> as
a template and read <a target="_blank" href="https://github.com/leanprover-community/lean4game/">How to Create a Game</a>. a template.
</p> </p>
<p> <p>
You can directly load your games into the server and play it using There is an option to load and run your own games directly on the server,
the correct URL. The <a target="_blank" href="https://github.com/leanprover-community/lean4game/">instructions above</a> also instructions are in the NNG repo. Since this is still in development we'd like to
explain the details for how to load your game to the server. encourage you to contact us for support creating your own game. The documentation is
not polished yet.
We'd like to encourage you to contact us if you have any questions.
</p> </p>
<p> <p>
Featured games on this page are added manually. To add games to this main page, you should get in contact as
Please get in contact and we-ll happily add yours. games will need to be added manually.
</p> </p>
</div> </div>
</section> </section>
@@ -217,6 +189,9 @@ function LandingPage() {
<a className="link" onClick={openImpressum}>Impressum</a> <a className="link" onClick={openImpressum}>Impressum</a>
{impressum? <PrivacyPolicyPopup handleClose={closeImpressum} />: null} {impressum? <PrivacyPolicyPopup handleClose={closeImpressum} />: null}
</footer> </footer>
{/* <PrivacyPolicy/> */}
</div> </div>
} }
+98 -128
View File
@@ -18,22 +18,22 @@ import { EditorConnection, EditorEvents } from '../../../node_modules/lean4-info
import { EventEmitter } from '../../../node_modules/lean4-infoview/src/infoview/event' import { EventEmitter } from '../../../node_modules/lean4-infoview/src/infoview/event'
import { GameIdContext } from '../app' import { GameIdContext } from '../app'
import { ConnectionContext, connection, useLeanClient } from '../connection'
import { useAppDispatch, useAppSelector } from '../hooks' import { useAppDispatch, useAppSelector } from '../hooks'
import { useGetGameInfoQuery, useLoadInventoryOverviewQuery, useLoadLevelQuery } from '../state/api' import { useGetGameInfoQuery, useLoadInventoryOverviewQuery, useLoadLevelQuery } from '../state/api'
import { changedSelection, codeEdited, selectCode, selectSelections, selectCompleted, helpEdited, import { changedSelection, codeEdited, selectCode, selectSelections, selectCompleted, helpEdited,
selectHelp, selectDifficulty, selectInventory, selectTypewriterMode, changeTypewriterMode } from '../state/progress' selectHelp, selectDifficulty, selectInventory } from '../state/progress'
import { store } from '../state/store' import { store } from '../state/store'
import { Button } from './button' import { Button } from './button'
import Markdown from './markdown' import Markdown from './markdown'
import {InventoryPanel} from './inventory' import {InventoryPanel} from './inventory'
import { hasInteractiveErrors } from './infoview/typewriter' import { hasInteractiveErrors } from './infoview/typewriter'
import { DeletedChatContext, InputModeContext, PreferencesContext, MonacoEditorContext, import { DeletedChatContext, InputModeContext, MobileContext, MonacoEditorContext,
ProofContext, ProofStep, SelectionContext, WorldLevelIdContext } from './infoview/context' ProofContext, ProofStep, SelectionContext, WorldLevelIdContext } from './infoview/context'
import { DualEditor } from './infoview/main' import { DualEditor } from './infoview/main'
import { GameHint } from './infoview/rpc_api' import { GameHint } from './infoview/rpc_api'
import { DeletedHints, Hint, Hints, filterHints } from './hints' import { DeletedHints, Hint, Hints } from './hints'
import { PrivacyPolicyPopup } from './popup/privacy_policy' import { PrivacyPolicyPopup } from './popup/privacy_policy'
import path from 'path';
import '@fontsource/roboto/300.css' import '@fontsource/roboto/300.css'
import '@fontsource/roboto/400.css' import '@fontsource/roboto/400.css'
@@ -43,20 +43,12 @@ import 'lean4web/client/src/editor/infoview.css'
import 'lean4web/client/src/editor/vscode.css' import 'lean4web/client/src/editor/vscode.css'
import '../css/level.css' import '../css/level.css'
import { LevelAppBar } from './app_bar' import { LevelAppBar } from './app_bar'
import { LeanClient } from 'lean4web/client/src/editor/leanclient'
import { DisposingWebSocketMessageReader } from 'lean4web/client/src/reader'
import { WebSocketMessageWriter, toSocket } from 'vscode-ws-jsonrpc'
import { IConnectionProvider } from 'monaco-languageclient'
import { monacoSetup } from 'lean4web/client/src/monacoSetup'
import { onigasmH } from 'onigasm/lib/onigasmH'
monacoSetup()
function Level() { function Level() {
const params = useParams() const params = useParams()
const levelId = parseInt(params.levelId) const levelId = parseInt(params.levelId)
const worldId = params.worldId const worldId = params.worldId
// useLoadWorldFiles(worldId)
const [impressum, setImpressum] = React.useState(false) const [impressum, setImpressum] = React.useState(false)
@@ -74,7 +66,7 @@ function Level() {
function ChatPanel({lastLevel}) { function ChatPanel({lastLevel}) {
const chatRef = useRef<HTMLDivElement>(null) const chatRef = useRef<HTMLDivElement>(null)
const {mobile} = useContext(PreferencesContext) const {mobile} = useContext(MobileContext)
const gameId = useContext(GameIdContext) const gameId = useContext(GameIdContext)
const {worldId, levelId} = useContext(WorldLevelIdContext) const {worldId, levelId} = useContext(WorldLevelIdContext)
const level = useLoadLevelQuery({game: gameId, world: worldId, level: levelId}) const level = useLoadLevelQuery({game: gameId, world: worldId, level: levelId})
@@ -146,24 +138,19 @@ function ChatPanel({lastLevel}) {
let introText: Array<string> = level?.data?.introduction.split(/\n(\s*\n)+/) let introText: Array<string> = level?.data?.introduction.split(/\n(\s*\n)+/)
// experimental: Remove all hints that appeared identically in the previous step
// This effectively prevent consequtive hints being shown.
let modifiedHints : GameHint[][] = filterHints(proof)
return <div className="chat-panel"> return <div className="chat-panel">
<div ref={chatRef} className="chat"> <div ref={chatRef} className="chat">
{introText?.filter(t => t.trim()).map(((t, i) => {introText?.filter(t => t.trim()).map(((t, i) =>
// Show the level's intro text as hints, too
<Hint key={`intro-p-${i}`} <Hint key={`intro-p-${i}`}
hint={{text: t, hidden: false}} step={0} selected={selectedStep} toggleSelection={toggleSelection(0)} /> hint={{text: t, hidden: false}} step={0} selected={selectedStep} toggleSelection={toggleSelection(0)} />
))} ))}
{modifiedHints.map((step, i) => { {proof.map((step, i) => {
// It the last step has errors, it will have the same hints // It the last step has errors, it will have the same hints
// as the second-to-last step. Therefore we should not display them. // as the second-to-last step. Therefore we should not display them.
if (!(i == proof.length - 1 && withErr)) { if (!(i == proof.length - 1 && withErr)) {
// TODO: Should not use index as key. // TODO: Should not use index as key.
return <Hints key={`hints-${i}`} return <Hints key={`hints-${i}`}
hints={step} showHidden={showHelp.has(i)} step={i} hints={step.hints} showHidden={showHelp.has(i)} step={i}
selected={selectedStep} toggleSelection={toggleSelection(i)} lastLevel={i == proof.length - 1}/> selected={selectedStep} toggleSelection={toggleSelection(i)} lastLevel={i == proof.length - 1}/>
} }
})} })}
@@ -215,15 +202,12 @@ function PlayableLevel({impressum, setImpressum}) {
const codeviewRef = useRef<HTMLDivElement>(null) const codeviewRef = useRef<HTMLDivElement>(null)
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {worldId, levelId} = useContext(WorldLevelIdContext) const {worldId, levelId} = useContext(WorldLevelIdContext)
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const dispatch = useAppDispatch()
const difficulty = useSelector(selectDifficulty(gameId))
const initialCode = useAppSelector(selectCode(gameId, worldId, levelId)) const initialCode = useAppSelector(selectCode(gameId, worldId, levelId))
const initialSelections = useAppSelector(selectSelections(gameId, worldId, levelId)) const initialSelections = useAppSelector(selectSelections(gameId, worldId, levelId))
const inventory: Array<String> = useSelector(selectInventory(gameId))
const typewriterMode = useSelector(selectTypewriterMode(gameId))
const setTypewriterMode = (newTypewriterMode: boolean) => dispatch(changeTypewriterMode({game: gameId, typewriterMode: newTypewriterMode}))
const gameInfo = useGetGameInfoQuery({game: gameId}) const gameInfo = useGetGameInfoQuery({game: gameId})
const level = useLoadLevelQuery({game: gameId, world: worldId, level: levelId}) const level = useLoadLevelQuery({game: gameId, world: worldId, level: levelId})
@@ -237,11 +221,12 @@ function PlayableLevel({impressum, setImpressum}) {
const [showHelp, setShowHelp] = useState<Set<number>>(new Set()) const [showHelp, setShowHelp] = useState<Set<number>>(new Set())
// Only for mobile layout // Only for mobile layout
const [pageNumber, setPageNumber] = useState(0) const [pageNumber, setPageNumber] = useState(0)
const [typewriterMode, setTypewriterMode] = useState(true)
// set to true to prevent switching between typewriter and editor // set to true to prevent switching between typewriter and editor
const [lockInputMode, setLockInputMode] = useState(false) const [lockInputMode, setLockInputMode] = useState(false)
const [typewriterInput, setTypewriterInput] = useState("") const [typewriterInput, setTypewriterInput] = useState("")
const lastLevel = levelId >= gameInfo.data?.worldSize[worldId] const lastLevel = levelId >= gameInfo.data?.worldSize[worldId]
const dispatch = useAppDispatch()
// impressum pop-up // impressum pop-up
function toggleImpressum() {setImpressum(!impressum)} function toggleImpressum() {setImpressum(!impressum)}
@@ -299,6 +284,12 @@ function PlayableLevel({impressum, setImpressum}) {
// a hint at the beginning of the proof... // a hint at the beginning of the proof...
const [selectedStep, setSelectedStep] = useState<number>() const [selectedStep, setSelectedStep] = useState<number>()
// if the user inventory changes, notify the server
useEffect(() => {
let leanClient = connection.getLeanClient(gameId)
leanClient.sendNotification('$/game/setInventory', {inventory: inventory, difficulty: difficulty})
}, [inventory])
useEffect (() => { useEffect (() => {
// Lock editor mode // Lock editor mode
if (level?.data?.template) { if (level?.data?.template) {
@@ -329,6 +320,8 @@ function PlayableLevel({impressum, setImpressum}) {
console.debug(`not inserting template.`) console.debug(`not inserting template.`)
} }
} }
} else {
setTypewriterMode(true)
} }
}, [level, levelId, worldId, gameId, editor]) }, [level, levelId, worldId, gameId, editor])
@@ -343,7 +336,7 @@ function PlayableLevel({impressum, setImpressum}) {
}, [gameId, worldId, levelId]) }, [gameId, worldId, levelId])
useEffect(() => { useEffect(() => {
if (!typewriterMode && editor) { if (!typewriterMode) {
// Delete last input attempt from command line // Delete last input attempt from command line
editor.executeEdits("typewriter", [{ editor.executeEdits("typewriter", [{
range: editor.getSelection(), range: editor.getSelection(),
@@ -372,7 +365,7 @@ function PlayableLevel({impressum, setImpressum}) {
// Effect when command line mode gets enabled // Effect when command line mode gets enabled
useEffect(() => { useEffect(() => {
if (onigasmH && editor && typewriterMode) { if (editor && typewriterMode) {
let code = editor.getModel().getLinesContent().filter(line => line.trim()) let code = editor.getModel().getLinesContent().filter(line => line.trim())
editor.executeEdits("typewriter", [{ editor.executeEdits("typewriter", [{
range: editor.getModel().getFullModelRange(), range: editor.getModel().getFullModelRange(),
@@ -395,7 +388,7 @@ function PlayableLevel({impressum, setImpressum}) {
// editor.setSelection(monaco.Selection.fromPositions(endPos, endPos)) // editor.setSelection(monaco.Selection.fromPositions(endPos, endPos))
// } // }
} }
}, [editor, typewriterMode, onigasmH == null]) }, [editor, typewriterMode])
return <> return <>
<div style={level.isLoading ? null : {display: "none"}} className="app-content loading"><CircularProgress /></div> <div style={level.isLoading ? null : {display: "none"}} className="app-content loading"><CircularProgress /></div>
@@ -441,7 +434,6 @@ function PlayableLevel({impressum, setImpressum}) {
function IntroductionPanel({gameInfo}) { function IntroductionPanel({gameInfo}) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {worldId} = useContext(WorldLevelIdContext) const {worldId} = useContext(WorldLevelIdContext)
const {mobile} = React.useContext(PreferencesContext)
let text: Array<string> = gameInfo.data?.worlds.nodes[worldId].introduction.split(/\n(\s*\n)+/) let text: Array<string> = gameInfo.data?.worlds.nodes[worldId].introduction.split(/\n(\s*\n)+/)
@@ -452,7 +444,7 @@ function IntroductionPanel({gameInfo}) {
hint={{text: t, hidden: false}} step={0} selected={null} toggleSelection={undefined} /> hint={{text: t, hidden: false}} step={0} selected={null} toggleSelection={undefined} />
))} ))}
</div> </div>
<div className={`button-row${mobile ? ' mobile' : ''}`}> <div className="button-row">
{gameInfo.data?.worldSize[worldId] == 0 ? {gameInfo.data?.worldSize[worldId] == 0 ?
<Button to={`/${gameId}`}><FontAwesomeIcon icon={faHome} /></Button> : <Button to={`/${gameId}`}><FontAwesomeIcon icon={faHome} /></Button> :
<Button to={`/${gameId}/world/${worldId}/level/1`}> <Button to={`/${gameId}/world/${worldId}/level/1`}>
@@ -468,17 +460,12 @@ export default Level
/** The site with the introduction text of a world */ /** The site with the introduction text of a world */
function Introduction({impressum, setImpressum}) { function Introduction({impressum, setImpressum}) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {mobile} = useContext(PreferencesContext) const {mobile} = useContext(MobileContext)
const inventory = useLoadInventoryOverviewQuery({game: gameId}) const inventory = useLoadInventoryOverviewQuery({game: gameId})
const gameInfo = useGetGameInfoQuery({game: gameId}) const gameInfo = useGetGameInfoQuery({game: gameId})
const {worldId} = useContext(WorldLevelIdContext)
let image: string = gameInfo.data?.worlds.nodes[worldId].image
const toggleImpressum = () => { const toggleImpressum = () => {
setImpressum(!impressum) setImpressum(!impressum)
} }
@@ -492,13 +479,7 @@ function Introduction({impressum, setImpressum}) {
: :
<Split minSize={0} snapOffset={200} sizes={[25, 50, 25]} className={`app-content level`}> <Split minSize={0} snapOffset={200} sizes={[25, 50, 25]} className={`app-content level`}>
<IntroductionPanel gameInfo={gameInfo} /> <IntroductionPanel gameInfo={gameInfo} />
<div className="world-image-container empty"> <div className="world-image-container empty"></div>
{image &&
// TODO: Temporary for testing
<img className={worldId=="Proposition" ? "cover" : "contain"} src={path.join("data", gameId, image)} alt="" />
}
</div>
<InventoryPanel levelInfo={inventory?.data} /> <InventoryPanel levelInfo={inventory?.data} />
</Split> </Split>
} }
@@ -531,32 +512,21 @@ function Introduction({impressum, setImpressum}) {
function useLevelEditor(codeviewRef, initialCode, initialSelections, onDidChangeContent, onDidChangeSelection) { function useLevelEditor(codeviewRef, initialCode, initialSelections, onDidChangeContent, onDidChangeSelection) {
const connection = React.useContext(ConnectionContext)
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {worldId, levelId} = useContext(WorldLevelIdContext) const {worldId, levelId} = useContext(WorldLevelIdContext)
const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor|null>(null) const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor|null>(null)
const [infoProvider, setInfoProvider] = useState<null|InfoProvider>(null) const [infoProvider, setInfoProvider] = useState<null|InfoProvider>(null)
const [infoviewApi, setInfoviewApi] = useState<null|InfoviewApi>(null)
const [editorConnection, setEditorConnection] = useState<null|EditorConnection>(null) const [editorConnection, setEditorConnection] = useState<null|EditorConnection>(null)
const uriStr = `file:///${worldId}/${levelId}` // Create Editor
const uri = monaco.Uri.parse(uriStr)
const inventory: Array<String> = useSelector(selectInventory(gameId))
const difficulty: number = useSelector(selectDifficulty(gameId))
useEffect(() => { useEffect(() => {
const model = monaco.editor.createModel(initialCode ?? '', 'lean4', uri)
if (onDidChangeContent) {
model.onDidChangeContent(() => onDidChangeContent(model.getValue()))
}
const editor = monaco.editor.create(codeviewRef.current!, { const editor = monaco.editor.create(codeviewRef.current!, {
model,
glyphMargin: true, glyphMargin: true,
quickSuggestions: false, quickSuggestions: false,
lineDecorationsWidth: 5,
folding: false,
lineNumbers: 'on',
lightbulb: { lightbulb: {
enabled: true enabled: true
}, },
@@ -568,61 +538,11 @@ function useLevelEditor(codeviewRef, initialCode, initialSelections, onDidChange
enabled: false enabled: false
}, },
lineNumbersMinChars: 3, lineNumbersMinChars: 3,
tabSize: 2,
'semanticHighlighting.enabled': true, 'semanticHighlighting.enabled': true,
theme: 'vs-code-theme-converted' theme: 'vs-code-theme-converted'
}) })
if (onDidChangeSelection) {
editor.onDidChangeCursorSelection(() => onDidChangeSelection(editor.getSelections()))
}
if (initialSelections) {
console.debug("Initial Selection: ", initialSelections)
// BUG: Somehow I get an `invalid arguments` bug here
// editor.setSelections(initialSelections)
}
setEditor(editor)
const abbrevRewriter = new AbbreviationRewriter(new AbbreviationProvider(), model, editor)
const socketUrl = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + '/websocket/' + gameId const infoProvider = new InfoProvider(connection.getLeanClient(gameId))
const connectionProvider : IConnectionProvider = {
get: async () => {
return await new Promise((resolve, reject) => {
console.log(`connecting ${socketUrl}`)
const websocket = new WebSocket(socketUrl)
websocket.addEventListener('error', (ev) => {
reject(ev)
})
websocket.addEventListener('message', (msg) => {
// console.log(msg.data)
})
websocket.addEventListener('open', () => {
const socket = toSocket(websocket)
const reader = new DisposingWebSocketMessageReader(socket)
const writer = new WebSocketMessageWriter(socket)
resolve({
reader,
writer
})
})
})
}
}
// Following `vscode-lean4/webview/index.ts`
const client = new LeanClient(connectionProvider, showRestartMessage, {inventory, difficulty})
const infoProvider = new InfoProvider(client)
// const div: HTMLElement = infoviewRef.current!
const imports = {
'@leanprover/infoview': `${window.location.origin}/index.production.min.js`,
'react': `${window.location.origin}/react.production.min.js`,
'react/jsx-runtime': `${window.location.origin}/react-jsx-runtime.production.min.js`,
'react-dom': `${window.location.origin}/react-dom.production.min.js`,
'react-popper': `${window.location.origin}/react-popper.production.min.js`
}
// loadRenderInfoview(imports, [infoProvider.getApi(), div], setInfoviewApi)
setInfoProvider(infoProvider)
client.restart()
const editorApi = infoProvider.getApi() const editorApi = infoProvider.getApi()
@@ -667,27 +587,77 @@ function useLevelEditor(codeviewRef, initialCode, initialSelections, onDidChange
setEditor(editor) setEditor(editor)
setInfoProvider(infoProvider) setInfoProvider(infoProvider)
setInfoviewApi(infoviewApi)
infoProvider.openPreview(editor, infoviewApi) return () => { infoProvider.dispose(); editor.dispose() }
const taskgutter = new LeanTaskGutter(infoProvider.client, editor) }, [])
// TODO: const {leanClient, leanClientStarted} = useLeanClient(gameId)
// setRestart(() => restart) const uriStr = `file:///${worldId}/${levelId}`
const uri = monaco.Uri.parse(uriStr)
return () => { // Create model when level changes
editor.dispose(); useEffect(() => {
model.dispose(); if (editor && leanClientStarted) {
abbrevRewriter.dispose();
taskgutter.dispose(); let model = monaco.editor.getModel(uri)
infoProvider.dispose(); if (!model) {
client.dispose(); model = monaco.editor.createModel(initialCode, 'lean4', uri)
}
model.onDidChangeContent(() => onDidChangeContent(model.getValue()))
editor.onDidChangeCursorSelection(() => onDidChangeSelection(editor.getSelections()))
editor.setModel(model)
if (initialSelections) {
console.debug("Initial Selection: ", initialSelections)
// BUG: Somehow I get an `invalid arguments` bug here
// editor.setSelections(initialSelections)
}
return () => {
editorConnection.api.sendClientNotification(uriStr, "textDocument/didClose", {textDocument: {uri: uriStr}})
}
} }
}, [gameId, worldId, levelId]) }, [editor, levelId, connection, leanClientStarted])
const showRestartMessage = () => {
// setRestartMessage(true) useEffect(() => {
console.log("TODO: SHOW RESTART MESSAGE") if (editor && leanClientStarted) {
}
let model = monaco.editor.getModel(uri)
infoviewApi.serverRestarted(leanClient.initializeResult)
infoProvider.openPreview(editor, infoviewApi)
const taskGutter = new LeanTaskGutter(infoProvider.client, editor)
const abbrevRewriter = new AbbreviationRewriter(new AbbreviationProvider(), model, editor)
return () => { abbrevRewriter.dispose(); taskGutter.dispose(); }
}
}, [editor, connection, leanClientStarted])
return {editor, infoProvider, editorConnection} return {editor, infoProvider, editorConnection}
} }
/** Open all files in this world on the server so that they will load faster when accessed */
function useLoadWorldFiles(worldId) {
const gameId = React.useContext(GameIdContext)
const gameInfo = useGetGameInfoQuery({game: gameId})
const store = useStore()
useEffect(() => {
if (gameInfo.data) {
const models = []
for (let levelId = 1; levelId <= gameInfo.data.worldSize[worldId]; levelId++) {
const uri = monaco.Uri.parse(`file:///${worldId}/${levelId}`)
let model = monaco.editor.getModel(uri)
if (model) {
models.push(model)
} else {
const code = selectCode(gameId, worldId, levelId)(store.getState())
models.push(monaco.editor.createModel(code, 'lean4', uri))
}
}
return () => { for (let model of models) { model.dispose() } }
}
}, [gameInfo.data, worldId])
}
@@ -1,90 +0,0 @@
import * as React from 'react'
import { Input, Typography } from '@mui/material'
import Markdown from '../markdown'
import { Switch, Button, ButtonGroup } from '@mui/material';
import Box from '@mui/material/Box';
import Slider from '@mui/material/Slider';
import FormControlLabel from '@mui/material/FormControlLabel';
import { IPreferencesContext } from "../infoview/context"
interface PreferencesPopupProps extends Omit<IPreferencesContext, 'mobile'> {
handleClose: () => void
}
export function PreferencesPopup({ layout, setLayout, isSavePreferences, setIsSavePreferences, handleClose }: PreferencesPopupProps) {
const marks = [
{
value: 0,
label: 'Mobile',
key: "mobile"
},
{
value: 1,
label: 'Auto',
key: "auto"
},
{
value: 2,
label: 'Desktop',
key: "desktop"
},
];
const handlerChangeLayout = (_: Event, value: number) => {
setLayout(marks[value].key as IPreferencesContext["layout"])
}
return <div className="modal-wrapper">
<div className="modal-backdrop" onClick={handleClose} />
<div className="modal">
<div className="codicon codicon-close modal-close" onClick={handleClose}></div>
<Typography variant="body1" component="div" className="settings">
<div className='preferences-category'>
<div className='category-title'>
<h3>Layout</h3>
</div>
<div className='preferences-item first leave-left-gap'>
<FormControlLabel
control={
<Box sx={{ width: 300 }}>
<Slider
aria-label="Always visible"
value={marks.find(item => item.key === layout).value}
step={1}
marks={marks}
max={2}
sx={{
'& .MuiSlider-track': { display: 'none', },
}}
onChange={handlerChangeLayout}
/>
</Box>
}
label=""
/>
</div>
</div>
<div className='preferences-category tail-category'>
<div className='preferences-item'>
<FormControlLabel
control={
<Switch
checked={isSavePreferences}
onChange={() => setIsSavePreferences(!isSavePreferences)}
name="checked"
color="primary"
/>
}
label="Save my settings (in the browser store)"
labelPlacement="end"
/>
</div>
</div>
</Typography>
</div>
</div>
}
+4 -13
View File
@@ -10,14 +10,13 @@ import { useAppDispatch, useAppSelector } from '../hooks'
import { changedOpenedIntro, selectOpenedIntro } from '../state/progress' import { changedOpenedIntro, selectOpenedIntro } from '../state/progress'
import { useGetGameInfoQuery, useLoadInventoryOverviewQuery } from '../state/api' import { useGetGameInfoQuery, useLoadInventoryOverviewQuery } from '../state/api'
import { Button } from './button' import { Button } from './button'
import { PreferencesContext } from './infoview/context' import { MobileContext } from './infoview/context'
import { InventoryPanel } from './inventory' import { InventoryPanel } from './inventory'
import { ErasePopup } from './popup/erase' import { ErasePopup } from './popup/erase'
import { InfoPopup } from './popup/game_info' import { InfoPopup } from './popup/game_info'
import { PrivacyPolicyPopup } from './popup/privacy_policy' import { PrivacyPolicyPopup } from './popup/privacy_policy'
import { RulesHelpPopup } from './popup/rules_help' import { RulesHelpPopup } from './popup/rules_help'
import { UploadPopup } from './popup/upload' import { UploadPopup } from './popup/upload'
import { PreferencesPopup} from "./popup/preferences"
import { WorldTreePanel } from './world_tree' import { WorldTreePanel } from './world_tree'
import '../css/welcome.css' import '../css/welcome.css'
@@ -27,7 +26,7 @@ import { Hint } from './hints'
/** the panel showing the game's introduction text */ /** the panel showing the game's introduction text */
function IntroductionPanel({introduction, setPageNumber}: {introduction: string, setPageNumber}) { function IntroductionPanel({introduction, setPageNumber}: {introduction: string, setPageNumber}) {
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
@@ -64,9 +63,7 @@ function IntroductionPanel({introduction, setPageNumber}: {introduction: string,
/** main page of the game showing among others the tree of worlds/levels */ /** main page of the game showing among others the tree of worlds/levels */
function Welcome() { function Welcome() {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const {mobile} = React.useContext(PreferencesContext) const {mobile} = React.useContext(MobileContext)
const {layout, isSavePreferences, setLayout, setIsSavePreferences} = React.useContext(PreferencesContext)
const gameInfo = useGetGameInfoQuery({game: gameId}) const gameInfo = useGetGameInfoQuery({game: gameId})
const inventory = useLoadInventoryOverviewQuery({game: gameId}) const inventory = useLoadInventoryOverviewQuery({game: gameId})
@@ -80,20 +77,15 @@ function Welcome() {
const [info, setInfo] = React.useState(false) const [info, setInfo] = React.useState(false)
const [rulesHelp, setRulesHelp] = React.useState(false) const [rulesHelp, setRulesHelp] = React.useState(false)
const [uploadMenu, setUploadMenu] = React.useState(false) const [uploadMenu, setUploadMenu] = React.useState(false)
const [preferencesPopup, setPreferencesPopup] = React.useState(false)
function closeEraseMenu() {setEraseMenu(false)} function closeEraseMenu() {setEraseMenu(false)}
function closeImpressum() {setImpressum(false)} function closeImpressum() {setImpressum(false)}
function closeInfo() {setInfo(false)} function closeInfo() {setInfo(false)}
function closeRulesHelp() {setRulesHelp(false)} function closeRulesHelp() {setRulesHelp(false)}
function closeUploadMenu() {setUploadMenu(false)} function closeUploadMenu() {setUploadMenu(false)}
function closePreferencesPopup() {setPreferencesPopup(false)}
function toggleEraseMenu() {setEraseMenu(!eraseMenu)} function toggleEraseMenu() {setEraseMenu(!eraseMenu)}
function toggleImpressum() {setImpressum(!impressum)} function toggleImpressum() {setImpressum(!impressum)}
function toggleInfo() {setInfo(!info)} function toggleInfo() {setInfo(!info)}
function toggleUploadMenu() {setUploadMenu(!uploadMenu)} function toggleUploadMenu() {setUploadMenu(!uploadMenu)}
function togglePreferencesPopup() {setPreferencesPopup(!preferencesPopup)}
// set the window title // set the window title
useEffect(() => { useEffect(() => {
@@ -109,7 +101,7 @@ function Welcome() {
: <> : <>
<WelcomeAppBar pageNumber={pageNumber} setPageNumber={setPageNumber} gameInfo={gameInfo.data} toggleImpressum={toggleImpressum} <WelcomeAppBar pageNumber={pageNumber} setPageNumber={setPageNumber} gameInfo={gameInfo.data} toggleImpressum={toggleImpressum}
toggleEraseMenu={toggleEraseMenu} toggleUploadMenu={toggleUploadMenu} toggleEraseMenu={toggleEraseMenu} toggleUploadMenu={toggleUploadMenu}
toggleInfo={toggleInfo} togglePreferencesPopup={togglePreferencesPopup}/> toggleInfo={toggleInfo} />
<div className="app-content"> <div className="app-content">
{ mobile ? { mobile ?
<div className="welcome mobile"> <div className="welcome mobile">
@@ -136,7 +128,6 @@ function Welcome() {
{eraseMenu? <ErasePopup handleClose={closeEraseMenu}/> : null} {eraseMenu? <ErasePopup handleClose={closeEraseMenu}/> : null}
{uploadMenu? <UploadPopup handleClose={closeUploadMenu}/> : null} {uploadMenu? <UploadPopup handleClose={closeUploadMenu}/> : null}
{info ? <InfoPopup info={gameInfo.data?.info} handleClose={closeInfo}/> : null} {info ? <InfoPopup info={gameInfo.data?.info} handleClose={closeInfo}/> : null}
{preferencesPopup ? <PreferencesPopup layout={layout} isSavePreferences={isSavePreferences} setLayout={setLayout} setIsSavePreferences={setIsSavePreferences} handleClose={closePreferencesPopup}/> : null}
</> </>
} }
+2 -5
View File
@@ -16,7 +16,6 @@ import { selectDifficulty, changedDifficulty, selectCompleted } from '../state/p
import { store } from '../state/store' import { store } from '../state/store'
import '../css/world_tree.css' import '../css/world_tree.css'
import { PreferencesContext } from './infoview/context'
// Settings for the world tree // Settings for the world tree
cytoscape.use( klay ) cytoscape.use( klay )
@@ -198,15 +197,13 @@ export function WorldSelectionMenu({rulesHelp, setRulesHelp}) {
const gameId = React.useContext(GameIdContext) const gameId = React.useContext(GameIdContext)
const difficulty = useSelector(selectDifficulty(gameId)) const difficulty = useSelector(selectDifficulty(gameId))
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const { mobile } = React.useContext(PreferencesContext)
function label(x : number) { function label(x : number) {
return x == 0 ? 'none' : x == 1 ? 'relaxed' : 'regular' return x == 0 ? 'none' : x == 1 ? 'relaxed' : 'regular'
} }
return <nav className={`world-selection-menu${mobile ? '' : ' desktop'}`}> return <nav className="world-selection-menu">
<div className="slider-wrap"> <div className="slider-wrap">
<span className="difficulty-label">Rules <span className="difficulty-label">Rules
<FontAwesomeIcon icon={rulesHelp ? faXmark : faCircleQuestion} className='helpButton' onClick={() => (setRulesHelp(!rulesHelp))}/> <FontAwesomeIcon icon={rulesHelp ? faXmark : faCircleQuestion} className='helpButton' onClick={() => (setRulesHelp(!rulesHelp))}/>
@@ -216,7 +213,7 @@ export function WorldSelectionMenu({rulesHelp, setRulesHelp}) {
title="Game Rules" title="Game Rules"
min={0} max={2} min={0} max={2}
aria-label="Game Rules" aria-label="Game Rules"
value={difficulty} defaultValue={difficulty}
marks={[ marks={[
{value: 0, label: label(0)}, {value: 0, label: label(0)},
{value: 1, label: label(1)}, {value: 1, label: label(1)},
+68
View File
@@ -0,0 +1,68 @@
/**
* @fileOverview todo
*/
import * as React from 'react';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
import { LeanClient } from './leanclient';
export class Connection {
private game: string = undefined // We only keep a connection to a single game at a time
private leanClient: LeanClient = null
getLeanClient(game): LeanClient {
if (this.game !== game) {
if (this.leanClient) {
this.leanClient.stop() // Stop previous Lean client
}
this.game = game
// Start a new Lean client for the new `gameId`.
const socketUrl = ((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + '/websocket/' + game
const uri = monaco.Uri.parse('file:///')
this.leanClient = new LeanClient(socketUrl, undefined, uri, () => {})
}
return this.leanClient
}
/** If not already started, starts the Lean client. resolves the returned promise as soon as a
* Lean client is running.
*/
startLeanClient = (game) => {
return new Promise<LeanClient>((resolve) => {
const leanClient = this.getLeanClient(game)
if (leanClient.isRunning()) {
resolve(leanClient)
} else {
if (!leanClient.isStarted()) {
leanClient.start()
}
leanClient.restarted(() => {
// This keep alive message is not recognized by the server,
// but it makes sure that the websocket connection does not
// time out after 60 seconds.
setInterval(() => {leanClient.sendNotification('$/keepAlive', {}) }, 5000)
resolve(leanClient)
})
}
})
}
}
export const connection = new Connection()
export const ConnectionContext = React.createContext(null);
export const useLeanClient = (gameId) => {
const leanClient = connection.getLeanClient(gameId)
const [leanClientStarted, setLeanClientStarted] = React.useState(leanClient.isStarted())
React.useEffect(() => {
const t1 = leanClient.restarted(() => { console.log("START"); setLeanClientStarted(true) })
const t2 = leanClient.stopped(() => { console.log("STOP"); setLeanClientStarted(false) })
return () => {t1.dispose(); t2.dispose()}
}, [leanClient, setLeanClientStarted])
return {leanClientStarted, leanClient}
}
-7
View File
@@ -105,18 +105,11 @@ em {
position: relative; position: relative;
flex-direction: row; flex-direction: row;
justify-content: space-between; justify-content: space-between;
align-items: center;
padding: 1.1em; padding: 1.1em;
filter: drop-shadow(0 0 5px rgba(0,0,0,0.5)); filter: drop-shadow(0 0 5px rgba(0,0,0,0.5));
z-index: 2; z-index: 2;
} }
.app-bar > .app-bar-left{
display: flex;
align-items: center;
gap: .5em;
}
.app-bar-title, .app-bar-subtitle { .app-bar-title, .app-bar-subtitle {
color: white; color: white;
font-weight: 500; font-weight: 500;
+1 -23
View File
@@ -26,11 +26,7 @@
.inventory .item { .inventory .item {
background: #fff; background: #fff;
border: solid 1px #777; border: solid 1px #777;
padding-left: .5rem; padding: .1em .5em;
padding-right: 1.0rem;
padding-top: .1rem;
padding-bottom: .1rem;
position: relative;
} }
.inventory .item.locked { .inventory .item.locked {
@@ -76,21 +72,3 @@
color: black; color: black;
border-bottom: 0.3em solid #999; border-bottom: 0.3em solid #999;
} }
.inventory .item .copy-button {
min-width: 3px;
min-height: 3px;
display: inline-block;
color: #ccc;
font-size: 0.6em;
padding-right: .2rem;
vertical-align: top;
position: absolute;
top: 0;
right: 0;
height: 100%;
width: 1rem;
align-items: end;
text-align: end;
}
-1
View File
@@ -48,7 +48,6 @@ a {
border: 1px solid rgb(140, 140, 140); border: 1px solid rgb(140, 140, 140);
border-radius: 20px; border-radius: 20px;
box-shadow: 5px 5px 8px rgb(140, 140, 140); box-shadow: 5px 5px 8px rgb(140, 140, 140);
width: 100%;
max-width: 500px; max-width: 500px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
+5 -29
View File
@@ -232,20 +232,6 @@ td code {
height: 100%; height: 100%;
} */ } */
.button-row.mobile {
margin: .5rem;
padding-top: .2rem;
}
.button-row.mobile .btn {
padding: .5em;
border-radius: .2em;
width: 100%;
margin: 0;
text-align: center;
}
.typewriter-interface { .typewriter-interface {
display: flex; display: flex;
flex-flow: column; flex-flow: column;
@@ -331,6 +317,11 @@ td code {
margin-right: 0; margin-right: 0;
} }
#home-btn {
margin-right: .5em;
margin-left: 0;
}
.menu.dropdown .svg-inline--fa { .menu.dropdown .svg-inline--fa {
width: 1.8rem; width: 1.8rem;
} }
@@ -345,21 +336,6 @@ td code {
background-color: #eee; background-color: #eee;
} }
.world-image-container {
display: flex;
flex-direction: column;
justify-content: center;
}
.world-image-container img.contain {
object-fit: contain;
}
.world-image-container img.cover {
height: 100%;
object-fit: cover;
}
.typewriter-interface .proof { .typewriter-interface .proof {
background-color: #fff; background-color: #fff;
} }
-12
View File
@@ -187,15 +187,3 @@ h5, h6 {
margin-left: 0.3rem; margin-left: 0.3rem;
margin-right: 0.3rem; margin-right: 0.3rem;
} }
.preferences-category.tail-category{
margin-top: 2em;
}
.preferences-item.first{
margin-top: 1em;
}
.preferences-item.leave-left-gap{
margin-left: 3em;
}
+1 -4
View File
@@ -49,6 +49,7 @@ svg .disabled {
} }
.world-selection-menu { .world-selection-menu {
position: absolute;
right: 1em; right: 1em;
top: 1em; top: 1em;
/* margin: 1em; */ /* margin: 1em; */
@@ -59,10 +60,6 @@ svg .disabled {
filter: drop-shadow(4px 4px 5px rgba(0,0,0,0.5)); filter: drop-shadow(4px 4px 5px rgba(0,0,0,0.5));
} }
.world-selection-menu.desktop {
position: absolute;
}
.world-selection-menu .btn, .welcome .btn { .world-selection-menu .btn, .welcome .btn {
min-width: 5em; min-width: 5em;
text-align: center; text-align: center;
+16 -6
View File
@@ -1,6 +1,7 @@
import * as React from 'react' import * as React from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import App from './app' import App from './app'
import { ConnectionContext, connection } from './connection'
import { store } from './state/store' import { store } from './state/store'
import { Provider } from 'react-redux' import { Provider } from 'react-redux'
import type { RouteObject } from "react-router" import type { RouteObject } from "react-router"
@@ -9,8 +10,20 @@ import ErrorPage from './components/error_page'
import Welcome from './components/welcome' import Welcome from './components/welcome'
import LandingPage from './components/landing_page' import LandingPage from './components/landing_page'
import Level from './components/level' import Level from './components/level'
import { monacoSetup } from 'lean4web/client/src/monacoSetup'
monacoSetup()
// // Do not show the landing page in the dev-container context
// let root_path: RouteObject = (process.env.LEAN4GAME_SINGLE_GAME == "true") ? {
// path: "/",
// loader: () => redirect("/g/local/game")
// } : {
// path: "/",
// element: <LandingPage />,
// }
// If `VITE_LEAN4GAME_SINGLE` is set to true, then `/` should be redirected to // If `VITE_LEAN4GAME_SINGLE` is set to true, then `/` should be redirected to
// `/g/local/game`. This is used for the devcontainer setup // `/g/local/game`. This is used for the devcontainer setup
@@ -30,11 +43,6 @@ const router = createHashRouter([
path: "/game/nng", path: "/game/nng",
loader: () => redirect("/g/hhu-adam/NNG4") loader: () => redirect("/g/hhu-adam/NNG4")
}, },
{
// For backwards compatibility
path: "/g/hhu-adam/NNG4",
loader: () => redirect("/g/leanprover-community/NNG4")
},
{ {
path: "/g/:owner/:repo", path: "/g/:owner/:repo",
element: <App />, element: <App />,
@@ -57,7 +65,9 @@ const root = createRoot(container!);
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<Provider store={store}> <Provider store={store}>
<RouterProvider router={router} /> <ConnectionContext.Provider value={connection}>
<RouterProvider router={router} />
</ConnectionContext.Provider>
</Provider> </Provider>
</React.StrictMode> </React.StrictMode>
); );
+612
View File
@@ -0,0 +1,612 @@
/* This file is based on `vscode-lean4/src/leanclient.ts` */
import {
TextDocument, EventEmitter, Diagnostic,
DocumentHighlight, Range, DocumentHighlightKind, workspace,
Disposable, Uri, ConfigurationChangeEvent, OutputChannel, DiagnosticCollection,
WorkspaceFolder, window
} from 'vscode'
import {
DidChangeTextDocumentParams,
DidCloseTextDocumentParams,
DidOpenTextDocumentNotification,
DocumentFilter,
InitializeResult,
MonacoLanguageClient as LanguageClient,
LanguageClientOptions,
PublishDiagnosticsParams,
CloseAction, ErrorAction,
RevealOutputChannelOn,
} from 'monaco-languageclient'
import { State } from 'vscode-languageclient'
import * as ls from 'vscode-languageserver-protocol'
import { toSocket } from 'vscode-ws-jsonrpc'
import {
// toolchainPath, lakePath, addServerEnvPaths, serverArgs, serverLoggingEnabled, serverLoggingPath, shouldAutofocusOutput,
getElaborationDelay
// lakeEnabled
} from 'lean4web/client/src/editor/config'
// import { assert } from './utils/assert'
import { LeanFileProgressParams, LeanFileProgressProcessingInfo } from '@leanprover/infoview-api'
// import { LocalStorageService } from './utils/localStorage'
// import { batchExecute } from './utils/batch'
// import { readLeanVersion } from './utils/projectInfo'
import * as fs from 'fs'
import { URL } from 'url'
import { join } from 'path'
// import { logger } from './utils/logger'
import { SemVer } from 'semver'
// import { fileExists, isFileInFolder } from './utils/fsHelper'
import { c2pConverter, p2cConverter, patchConverters } from 'lean4web/client/src/editor/utils/converters'
import { WasmReader, WasmWriter, WebSocketMessageWriter, WebSocketMessageReader } from './wasm'
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
export type ServerProgress = Map<Uri, LeanFileProgressProcessingInfo[]>
export function getFullRange (diag: Diagnostic): Range {
return (diag as any)?.fullRange || diag.range
}
export class LeanClient implements Disposable {
running: boolean = false
private client: LanguageClient | undefined
// private toolchainPath: string
// private readonly outputChannel: OutputChannel
// private readonly storageManager: LocalStorageService
private readonly workspaceFolder: WorkspaceFolder | undefined
private readonly folderUri: Uri
private readonly subscriptions: Disposable[] = []
private noPrompt: boolean = false
private showingRestartMessage: boolean = false
// private readonly elanDefaultToolchain: string
private readonly didChangeEmitter = new EventEmitter<DidChangeTextDocumentParams>()
didChange = this.didChangeEmitter.event
private readonly diagnosticsEmitter = new EventEmitter<PublishDiagnosticsParams>()
diagnostics = this.diagnosticsEmitter.event
private readonly didSetLanguageEmitter = new EventEmitter<string>()
didSetLanguage = this.didSetLanguageEmitter.event
private readonly didCloseEmitter = new EventEmitter<DidCloseTextDocumentParams>()
didClose = this.didCloseEmitter.event
private readonly customNotificationEmitter = new EventEmitter<{ method: string, params: any }>()
/** Fires whenever a custom notification (i.e. one not defined in LSP) is received. */
customNotification = this.customNotificationEmitter.event
/** saved progress info in case infoview is opened, it needs to get all of it. */
progress: ServerProgress = new Map()
private readonly progressChangedEmitter = new EventEmitter<[string, LeanFileProgressProcessingInfo[]]>()
progressChanged = this.progressChangedEmitter.event
private readonly stoppedEmitter = new EventEmitter()
stopped = this.stoppedEmitter.event
private readonly restartedEmitter = new EventEmitter()
restarted = this.restartedEmitter.event
private readonly restartingEmitter = new EventEmitter()
restarting = this.restartingEmitter.event
private readonly restartedWorkerEmitter = new EventEmitter<string>()
restartedWorker = this.restartedWorkerEmitter.event
private readonly serverFailedEmitter = new EventEmitter<string>()
serverFailed = this.serverFailedEmitter.event
/** Files which are open. */
private readonly isOpen: Map<string, TextDocument> = new Map()
constructor (private readonly socketUrl: string, workspaceFolder: WorkspaceFolder | undefined, folderUri: Uri,
public readonly showRestartMessage: () => void) {
// this.storageManager = storageManager
// this.outputChannel WebSocketMessageWriter= outputChannel
this.workspaceFolder = workspaceFolder // can be null when opening adhoc files.
this.folderUri = folderUri
// this.elanDefaultToolchain = elanDefaultToolchain
// this.subscriptions.push(workspace.onDidChangeConfiguration((e) => this.configChanged(e)))
}
dispose (): void {
this.subscriptions.forEach((s) => s.dispose())
if (this.isStarted()) void this.stop()
}
// async showRestartMessage (restartFile: boolean = false): Promise<void> {
// // if (!this.showingRestartMessage) {
// // this.showingRestartMessage = true
// // let restartItem: string
// // let messageTitle: string
// // if (!restartFile) {
// // restartItem = 'Restart Lean Server'
// // messageTitle = 'Lean Server has stopped unexpectedly.'
// // } else {
// // restartItem = 'Restart Lean Server on this file'
// // messageTitle = 'The Lean Server has stopped processing this file.'
// // }
// // const item = await this.showErrorMessage(messageTitle, restartItem)
// // this.showingRestartMessage = false
// // if (item === restartItem) {
// // void this.start()
// // // if (restartFile && (window.activeTextEditor != null)) {
// // // await this.restartFile(window.activeTextEditor.document)
// // // } else {
// // // void this.start()
// // // }
// // }
// // }
// }
async restart (): Promise<void> {
const startTime = Date.now()
console.log('[LeanClient] Restarting Lean Server')
if (this.isStarted()) {
await this.stop()
}
this.restartingEmitter.fire(undefined)
// this.toolchainPath = this.storageManager.getLeanPath()
// if (!this.toolchainPath) this.toolchainPath = toolchainPath()
// let version = this.storageManager.getLeanVersion()
// const env = addServerEnvPaths(process.env)
// if (serverLoggingEnabled()) {
// env.LEAN_SERVER_LOG_DIR = serverLoggingPath()
// }
// let executable = lakePath() ||
// (this.toolchainPath ? join(this.toolchainPath, 'bin', 'lake') : 'lake')
// check if the lake process will start (skip it on scheme: 'untitled' files)
// let useLake = lakeEnabled() && this.folderUri && this.folderUri.scheme === 'file'
// if (useLake) {
// let knownDate = false
// const lakefile = Uri.joinPath(this.folderUri, 'lakefile.lean')
// if (!await fileExists(new URL(lakefile.toString()))) {
// useLake = false
// } else {
// // see if we can avoid the more expensive checkLakeVersion call.
// const date = await this.checkToolchainVersion(this.folderUri)
// if (date != null) {
// // Feb 16 2022 is when the 3.1.0.pre was released.
// useLake = date >= new Date(2022, 1, 16)
// knownDate = true
// }
// if (useLake && !knownDate) {
// useLake = await this.checkLakeVersion(executable, version)
// }
// }
// }
// if (!useLake) {
// executable = (this.toolchainPath) ? join(this.toolchainPath, 'bin', 'lean') : 'lean'
// }
// const cwd = this.folderUri?.fsPath
// if (!cwd && !version) {
// // Fixes issue #227, for adhoc files it would pick up the cwd from the open folder
// // which is not what we want. For adhoc files we want the (default) toolchain instead.
// version = this.elanDefaultToolchain
// }
// let options = version ? ['+' + version] : []
// if (useLake) {
// options = options.concat(['serve', '--'])
// } else {
// options = options.concat(['--server'])
// }
// Add folder name to command-line so that it shows up in `ps aux`.
// if (cwd) {
// options.push('' + cwd)
// } else {
// options.push('untitled')
// }
// const serverOptions: ServerOptions = {
// command: executable,
// args: options.concat(serverArgs()),
// options: {
// cwd,
// env
// }
// }
const clientOptions: LanguageClientOptions = {
// use a language id as a document selector
documentSelector: ['lean4'],
initializationOptions: {
editDelay: getElaborationDelay(), hasWidgets: true
},
connectionOptions: {
maxRestartCount: 0,
cancellationStrategy: undefined as any
},
// disable the default error handler
errorHandler: {
error: () => ({ action: ErrorAction.Continue }),
closed: () => ({ action: CloseAction.DoNotRestart })
},
middleware: {
handleDiagnostics: (uri, diagnostics, next) => {
next(uri, diagnostics)
if (this.client == null) return
const uri_ = c2pConverter.asUri(uri)
const diagnostics_ = []
for (const d of diagnostics) {
const d_: ls.Diagnostic = {
...c2pConverter.asDiagnostic(d)
}
diagnostics_.push(d_)
}
this.diagnosticsEmitter.fire({ uri: uri_, diagnostics: diagnostics_ })
},
// didOpen: async () => {
// // Note: as per the LSP spec: An open notification must not be sent more than once
// // without a corresponding close notification send before. This means open and close
// // notification must be balanced and the max open count for a particular textDocument
// // is one. So this even does nothing the notification is handled by the
// // openLean4Document method below after the 'lean4' languageId is established and
// // it has weeded out documents opened to invisible editors (like 'git:' schemes and
// // invisible editors created for Ctrl+Hover events. A side effect of unbalanced
// // open/close notification is leaking 'lean --worker' processes.
// // See https://github.com/microsoft/vscode/issues/78453).
// },
didChange: async (data, next) => {
await next(data)
if (!this.running || (this.client == null)) return // there was a problem starting lean server.
const params = c2pConverter.asChangeTextDocumentParams(data)
this.didChangeEmitter.fire(params)
},
didClose: async (doc, next) => {
if (!this.isOpen.delete(doc.uri.toString())) {
return
}
await next(doc)
if (!this.running || (this.client == null)) return // there was a problem starting lean server.
const params = c2pConverter.asCloseTextDocumentParams(doc)
this.didCloseEmitter.fire(params)
},
provideDocumentHighlights: async (doc, pos, ctok, next) => {
const leanHighlights = await next(doc, pos, ctok)
if (leanHighlights?.length) return leanHighlights
// vscode doesn't fall back to textual highlights,
// so we need to do that manually
await new Promise((res) => setTimeout(res, 250))
if (ctok.isCancellationRequested) return
const wordRange = doc.getWordRangeAtPosition(pos)
if (wordRange == null) return
const word = doc.getText(wordRange)
const highlights: DocumentHighlight[] = []
const text = doc.getText()
const nonWordPattern = '[`~@$%^&*()-=+\\[{\\]}⟨⟩⦃⦄⟦⟧⟮⟯‹›\\\\|;:\",./\\s]|^|$'
const regexp = new RegExp(`(?<=${nonWordPattern})${escapeRegExp(word)}(?=${nonWordPattern})`, 'g')
for (const match of text.matchAll(regexp)) {
const start = doc.positionAt(match.index ?? 0)
highlights.push({
range: new Range(start, start.translate(0, match[0].length)),
kind: DocumentHighlightKind.Text
})
}
return highlights
}
}
}
if (!this.client) {
this.client = new LanguageClient({
id: 'lean4',
name: 'Lean 4',
clientOptions,
connectionProvider: {
get: async () => {
return await new Promise((resolve, reject) => {
const worker = new Worker("worker.js")
const reader = new WasmReader(worker)
const writer = new WasmWriter(worker)
resolve({
reader,
writer
})
})
}
}
})
} else {
await this.client.start()
}
// HACK: Prevent monaco from panicking when the Lean server crashes
this.client.handleFailedRequest = (type, token: any, error: any, defaultValue, showNotification?: boolean) => {
return defaultValue
}
let insideRestart = true
patchConverters(this.client.protocol2CodeConverter, this.client.code2ProtocolConverter)
try {
this.client.onDidChangeState(async (s) => {
// see https://github.com/microsoft/vscode-languageserver-node/issues/825
if (s.newState === State.Starting) {
console.log('[LeanClient] starting')
} else if (s.newState === State.Running) {
const end = Date.now()
console.log(`[LeanClient] running, started in ${end - startTime} ms`)
this.running = true // may have been auto restarted after it failed.
if (!insideRestart) {
this.restartedEmitter.fire(undefined)
}
} else if (s.newState === State.Stopped) {
this.running = false
console.log('[LeanClient] has stopped or it failed to start')
if (!this.noPrompt) {
// only raise this event and show the message if we are not the ones
// who called the stop() method.
this.stoppedEmitter.fire({ message: 'Lean server has stopped.', reason: '' })
await this.showRestartMessage()
}
}
})
await this.client.start()
// tell the new client about the documents that are already open!
// for (const key of this.isOpen.keys()) {
// const doc = this.isOpen.get(key)
// if (doc != null) this.notifyDidOpen(doc)
// }
// if we got this far then the client is happy so we are running!
this.running = true
} catch (error) {
console.log(error)
this.serverFailedEmitter.fire('' + error)
insideRestart = false
return
}
// HACK(WN): Register a default notification handler to fire on custom notifications.
// A mechanism to do this is provided in vscode-jsonrpc. One can register a `StarNotificationHandler`
// here: https://github.com/microsoft/vscode-languageserver-node/blob/b2fc85d28a1a44c22896559ee5f4d3ba37a02ef5/jsonrpc/src/common/connection.ts#L497
// which fires on any LSP notifications not in the standard, for example the `$/lean/..` ones.
// However this mechanism is not exposed in vscode-languageclient, so we hack around its implementation.
const starHandler = (method: string, params_: any) => {
if (method === '$/lean/fileProgress' && (this.client != null)) {
const params = params_ as LeanFileProgressParams
const uri = p2cConverter.asUri(params.textDocument.uri)
this.progressChangedEmitter.fire([uri.toString(), params.processing])
// save the latest progress on this Uri in case infoview needs it later.
this.progress.set(uri, params.processing)
}
this.customNotificationEmitter.fire({ method, params: params_ })
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
this.client.onNotification(starHandler as any, () => {})
// Reveal the standard error output channel when the server prints something to stderr.
// The vscode-languageclient library already takes care of writing it to the output channel.
// let stderrMsgBoxVisible = false;
// (this.client)._serverProcess.stderr.on('data', async (chunk: Buffer) => {
// if (shouldAutofocusOutput()) {
// this.client?.outputChannel.show(true)
// } else if (!stderrMsgBoxVisible) {
// stderrMsgBoxVisible = true
// const outputItem = 'Show stderr output'
// const outPrompt = `Lean server printed an error:\n${chunk.toString()}`
// if (await window.showErrorMessage(outPrompt, outputItem) === outputItem) {
// this.outputChannel.show(false)
// }
// stderrMsgBoxVisible = false
// }
// })
this.restartedEmitter.fire(undefined)
insideRestart = false
}
async openLean4Document (doc: TextDocument) {
if (this.isOpen.has(doc.uri.toString())) return
if (!await this.isSameWorkspace(doc.uri)) {
// skip it, this file belongs to a different workspace...
return
}
this.isOpen.set(doc.uri.toString(), doc)
if (!this.running) return // there was a problem starting lean server.
// didOpenEditor may have also changed the language, so we fire the
// event here because the InfoView should be wired up to receive it now.
this.didSetLanguageEmitter.fire(doc.languageId)
this.notifyDidOpen(doc)
}
notifyDidOpen (doc: TextDocument) {
// BUG: was `DidOpenTextDocumentNotification.type` instead of the string, but that failed
void this.client?.sendNotification('textDocument/didOpen', {
textDocument: {
uri: doc.uri.toString(),
languageId: doc.languageId,
version: 1,
text: doc.getText()
}
})
}
async isSameWorkspace (uri: Uri): Promise<boolean> {
// if (this.folderUri) {
// if (this.folderUri.scheme !== uri.scheme) return false
// if (this.folderUri.scheme === 'file') {
// const realPath1 = await fs.promises.realpath(this.folderUri.fsPath)
// const realPath2 = await fs.promises.realpath(uri.fsPath)
// return isFileInFolder(realPath2, realPath1)
// } else {
// return uri.toString().startsWith(this.folderUri.toString())
// }
// } else {
// return uri.scheme === 'untitled'
// }
return false
}
getWorkspaceFolder (): string {
return this.folderUri?.toString()
}
async start (): Promise<void> {
return await this.restart()
}
isStarted (): boolean {
return this.client !== undefined
}
isRunning (): boolean {
if (this.client != null) {
return this.running
}
return false
}
async stop (): Promise<void> {
// assert(() => this.isStarted())
if ((this.client != null) && this.running) {
this.noPrompt = true
try {
// some timing conditions can happen while running unit tests that cause
// this to throw an exception which then causes those tests to fail.
await this.client.stop()
} catch (e) {
console.log(`[LeanClient] Error stopping language client: ${e}`)
}
}
this.noPrompt = false
this.progress = new Map()
this.client = undefined
this.running = false
}
configChanged (e: ConfigurationChangeEvent): void {
// let newToolchainPath = this.storageManager.getLeanPath()
// if (!newToolchainPath) newToolchainPath = toolchainPath()
// if (this.toolchainPath !== newToolchainPath) {
// void this.restart()
// }
}
async restartFile (doc: TextDocument): Promise<void> {
if (!this.running) return // there was a problem starting lean server.
// assert(() => this.isStarted())
if (!await this.isSameWorkspace(doc.uri)) {
// skip it, this file belongs to a different workspace...
return
}
const uri = doc.uri.toString()
console.log(`[LeanClient] Restarting File: ${uri}`)
// This causes a text document version number discontinuity. In
// (didChange (oldVersion) => restartFile => didChange (newVersion))
// the client emits newVersion = oldVersion + 1, despite the fact that the
// didOpen packet emitted below initializes the version number to be 1.
// This is not a problem though, since both client and server are fine
// as long as the version numbers are monotonous.
void this.client?.sendNotification('textDocument/didClose', {
textDocument: {
uri
}
})
void this.client?.sendNotification('textDocument/didOpen', {
textDocument: {
uri,
languageId: 'lean4',
version: 1,
text: doc.getText()
}
})
this.restartedWorkerEmitter.fire(uri)
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
async sendRequest (method: string, params: any): Promise<any> {
return this.running && (this.client != null)
? await this.client.sendRequest(method, params)
: await new Promise<any>((_, reject) => { reject('Client is not running') })
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
sendNotification (method: string, params: any): Promise<void> | undefined {
return this.running && (this.client != null) ? this.client.sendNotification(method, params) : undefined
}
async getDiagnosticParams (uri: Uri, diagnostics: readonly Diagnostic[]): Promise<PublishDiagnosticsParams> {
const params: PublishDiagnosticsParams = {
uri: c2pConverter.asUri(uri),
diagnostics: await c2pConverter.asDiagnostics(diagnostics as Diagnostic[])
}
return params
}
getDiagnostics (): DiagnosticCollection | undefined {
return this.running ? this.client?.diagnostics : undefined
}
get initializeResult (): InitializeResult | undefined {
return this.running ? this.client?.initializeResult : undefined
}
private async checkToolchainVersion (folderUri: Uri): Promise<Date | undefined> {
// see if we have a well known toolchain label that corresponds
// to a known date like 'leanprover/lean4:nightly-2022-02-01'
// const toolchainVersion = await readLeanVersion(folderUri)
// if (toolchainVersion) {
// const match = /^leanprover\/lean4:nightly-(\d+)-(\d+)-(\d+)$/.exec(toolchainVersion)
// if (match != null) {
// return new Date(parseInt(match[1]), parseInt(match[2]) - 1, parseInt(match[3]))
// }
// if (toolchainVersion === 'leanprover/lean4:stable') {
// return new Date(2022, 2, 1)
// }
// }
return undefined
}
// async checkLakeVersion (executable: string, version: string): Promise<boolean> {
// // Check that the Lake version is high enough to support "lake serve" option.
// const versionOptions = version ? ['+' + version, '--version'] : ['--version']
// const start = Date.now()
// const lakeVersion = await batchExecute(executable, versionOptions, this.folderUri?.fsPath, undefined)
// logger.log(`[LeanClient] Ran '${executable} ${versionOptions.join(' ')}' in ${Date.now() - start} ms`)
// const actual = this.extractVersion(lakeVersion)
// if (actual.compare('3.0.0') > 0) {
// return true
// }
// return false
// }
// private extractVersion (v: string | undefined): SemVer {
// if (!v) return new SemVer('0.0.0')
// const prefix = 'Lake version'
// if (v.startsWith(prefix)) v = v.slice(prefix.length).trim()
// const pos = v.indexOf('(')
// if (pos > 0) v = v.slice(0, pos).trim()
// try {
// return new SemVer(v)
// } catch {
// return new SemVer('0.0.0')
// }
// }
}
+26 -23
View File
@@ -2,29 +2,16 @@
* @fileOverview Define API of the server-client communication * @fileOverview Define API of the server-client communication
*/ */
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { Connection } from '../connection'
export interface GameTile {
title: string
short: string
long: string
languages: Array<string>
prerequisites: Array<string>
worlds: number
levels: number
image: string
}
export interface GameInfo { export interface GameInfo {
title: null|string, title: null|string,
introduction: null|string, introduction: null|string,
info: null|string, info: null|string,
worlds: null|{nodes: {[id:string]: {id: string, title: string, introduction: string, image: string}}, edges: string[][]}, worlds: null|{nodes: {[id:string]: {id: string, title: string, introduction: string}}, edges: string[][]},
worldSize: null|{[key: string]: number}, worldSize: null|{[key: string]: number},
authors: null|string[], authors: null|string[],
conclusion: null|string, conclusion: null|string,
tile: null|GameTile,
image: null|string
} }
export interface InventoryTile { export interface InventoryTile {
@@ -35,7 +22,6 @@ export interface InventoryTile {
locked: boolean, locked: boolean,
new: boolean, new: boolean,
hidden: boolean hidden: boolean
altTitle: string,
} }
export interface LevelInfo { export interface LevelInfo {
@@ -51,8 +37,7 @@ export interface LevelInfo {
lemmaTab: null|string, lemmaTab: null|string,
statementName: null|string, statementName: null|string,
displayName: null|string, displayName: null|string,
template: null|string, template: null|string
image: null|string
} }
/** Used to display the inventory on the welcome page */ /** Used to display the inventory on the welcome page */
@@ -72,22 +57,40 @@ interface Doc {
category: string, category: string,
} }
const customBaseQuery = async (
args : {game: string, method: string, params?: any},
{ signal, dispatch, getState, extra },
extraOptions
) => {
try {
const connection : Connection = extra.connection
let leanClient = await connection.startLeanClient(args.game)
console.log(`Sending request ${args.method}`)
let res = await leanClient.sendRequest(args.method, args.params)
console.log('Received response') //, res)
return {'data': res}
} catch (e) {
return {'error': e}
}
}
// Define a service using a base URL and expected endpoints // Define a service using a base URL and expected endpoints
export const apiSlice = createApi({ export const apiSlice = createApi({
reducerPath: 'gameApi', reducerPath: 'gameApi',
baseQuery: fetchBaseQuery({ baseUrl: window.location.origin + "/data" }), baseQuery: customBaseQuery,
endpoints: (builder) => ({ endpoints: (builder) => ({
getGameInfo: builder.query<GameInfo, {game: string}>({ getGameInfo: builder.query<GameInfo, {game: string}>({
query: ({game}) => `${game}/game.json`, query: ({game}) => {return {game, method: 'info', params: {}}},
}), }),
loadLevel: builder.query<LevelInfo, {game: string, world: string, level: number}>({ loadLevel: builder.query<LevelInfo, {game: string, world: string, level: number}>({
query: ({game, world, level}) => `${game}/level__${world}__${level}.json`, query: ({game, world, level}) => {return {game, method: "loadLevel", params: {world, level}}},
}), }),
loadInventoryOverview: builder.query<InventoryOverview, {game: string}>({ loadInventoryOverview: builder.query<InventoryOverview, {game: string}>({
query: ({game}) => `${game}/inventory.json`, query: ({game}) => {return {game, method: "loadInventoryOverview", params: {}}},
}), }),
loadDoc: builder.query<Doc, {game: string, name: string, type: "lemma"|"tactic"}>({ loadDoc: builder.query<Doc, {game: string, name: string, type: "lemma"|"tactic"}>({
query: ({game, type, name}) => `${game}/doc__${type}__${name}.json`, query: ({game, name, type}) => {return {game, method: "loadDoc", params: {name, type}}},
}), }),
}), }),
}) })
-41
View File
@@ -1,41 +0,0 @@
import React, { useState } from "react";
import { useAppDispatch, useAppSelector } from "../../hooks";
import {
PreferencesState,
setLayout as setPreferencesLayout,
setIsSavePreferences as setPreferencesIsSavePreferences,
getWindowDimensions,
AUTO_SWITCH_THRESHOLD
} from "../preferences";
const UsePreferences = () => {
const dispatch = useAppDispatch()
const [mobile, setMobile] = React.useState<boolean>()
const layout = useAppSelector((state) => state.preferences.layout);
const setLayout = (layout: PreferencesState["layout"]) => dispatch(setPreferencesLayout(layout))
const isSavePreferences = useAppSelector((state) => state.preferences.isSavePreferences);
const setIsSavePreferences = (isSave: boolean) => dispatch(setPreferencesIsSavePreferences(isSave))
const automaticallyAdjustLayout = () => {
const {width} = getWindowDimensions()
setMobile(width < AUTO_SWITCH_THRESHOLD)
}
React.useEffect(()=>{
if (layout === "auto"){
void automaticallyAdjustLayout()
window.addEventListener('resize', automaticallyAdjustLayout)
return () => window.removeEventListener('resize', automaticallyAdjustLayout)
} else {
setMobile(layout === "mobile")
}
}, [layout])
return {mobile, layout, isSavePreferences, setLayout, setIsSavePreferences}
}
export default UsePreferences;
-30
View File
@@ -36,33 +36,3 @@ export async function saveState(state: any) {
// Ignore // Ignore
} }
} }
const PREFERENCES_KEY = "preferences"
/** Load from browser storage */
export function loadPreferences() {
try {
const serializedState = localStorage.getItem(PREFERENCES_KEY);
return JSON.parse(serializedState)
} catch (e) {
return undefined;
}
}
export function savePreferences(state: any) {
try {
const serializedState = JSON.stringify(state)
localStorage.setItem(PREFERENCES_KEY, serializedState);
} catch (e) {
// Ignore
}
}
export function removePreferences() {
try {
localStorage.removeItem(PREFERENCES_KEY);
} catch (e) {
// Ignore
}
}
-35
View File
@@ -1,35 +0,0 @@
import { createSlice } from "@reduxjs/toolkit";
import { loadPreferences, removePreferences, savePreferences } from "./local_storage";
export interface PreferencesState {
layout: "mobile" | "auto" | "desktop";
isSavePreferences: boolean;
}
export function getWindowDimensions() {
const {innerWidth: width, innerHeight: height } = window
return {width, height}
}
export const AUTO_SWITCH_THRESHOLD = 800
const initialState: PreferencesState = loadPreferences() ??{
layout: "auto",
isSavePreferences: false
}
export const preferencesSlice = createSlice({
name: "preferences",
initialState,
reducers: {
setLayout: (state, action) => {
state.layout = action.payload;
},
setIsSavePreferences: (state, action) => {
state.isSavePreferences = action.payload;
},
},
});
export const { setLayout, setIsSavePreferences } = preferencesSlice.actions;
+34 -47
View File
@@ -26,8 +26,7 @@ export interface GameProgressState {
inventory: string[], inventory: string[],
difficulty: number, difficulty: number,
openedIntro: boolean, openedIntro: boolean,
data: WorldProgressState, data: WorldProgressState
typewriterMode?: boolean
} }
/** /**
@@ -53,22 +52,22 @@ const initalLevelProgressState: LevelProgressState = {code: "", completed: false
/** Add an empty skeleton with progress for the current game */ /** Add an empty skeleton with progress for the current game */
function addGameProgress (state: ProgressState, action: PayloadAction<{game: string}>) { function addGameProgress (state: ProgressState, action: PayloadAction<{game: string}>) {
if (!state.games[action.payload.game.toLowerCase()]) { if (!state.games[action.payload.game]) {
state.games[action.payload.game.toLowerCase()] = {inventory: [], openedIntro: true, data: {}, difficulty: DEFAULT_DIFFICULTY} state.games[action.payload.game] = {inventory: [], openedIntro: true, data: {}, difficulty: DEFAULT_DIFFICULTY}
} }
if (!state.games[action.payload.game.toLowerCase()].data) { if (!state.games[action.payload.game].data) {
state.games[action.payload.game.toLowerCase()].data = {} state.games[action.payload.game].data = {}
} }
} }
/** Add an empty skeleton with progress for the current level */ /** Add an empty skeleton with progress for the current level */
function addLevelProgress(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) { function addLevelProgress(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) {
addGameProgress(state, action) addGameProgress(state, action)
if (!state.games[action.payload.game.toLowerCase()].data[action.payload.world]) { if (!state.games[action.payload.game].data[action.payload.world]) {
state.games[action.payload.game.toLowerCase()].data[action.payload.world] = {} state.games[action.payload.game].data[action.payload.world] = {}
} }
if (!state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level]) { if (!state.games[action.payload.game].data[action.payload.world][action.payload.level]) {
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level] = {...initalLevelProgressState} state.games[action.payload.game].data[action.payload.world][action.payload.level] = {...initalLevelProgressState}
} }
} }
@@ -79,137 +78,125 @@ export const progressSlice = createSlice({
/** put edited code in the state and set completed to false */ /** put edited code in the state and set completed to false */
codeEdited(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, code: string}>) { codeEdited(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, code: string}>) {
addLevelProgress(state, action) addLevelProgress(state, action)
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level].code = action.payload.code state.games[action.payload.game].data[action.payload.world][action.payload.level].code = action.payload.code
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level].completed = false state.games[action.payload.game].data[action.payload.world][action.payload.level].completed = false
}, },
/** TODO: docstring */ /** TODO: docstring */
changedSelection(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, selections: Selection[]}>) { changedSelection(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, selections: Selection[]}>) {
addLevelProgress(state, action) addLevelProgress(state, action)
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level].selections = action.payload.selections state.games[action.payload.game].data[action.payload.world][action.payload.level].selections = action.payload.selections
}, },
/** mark level as completed */ /** mark level as completed */
levelCompleted(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) { levelCompleted(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) {
addLevelProgress(state, action) addLevelProgress(state, action)
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level].completed = true state.games[action.payload.game].data[action.payload.world][action.payload.level].completed = true
}, },
/** Set the list of rows where help is displayed */ /** Set the list of rows where help is displayed */
helpEdited(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, help: number[]}>) { helpEdited(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number, help: number[]}>) {
addLevelProgress(state, action) addLevelProgress(state, action)
console.debug(`!setting help to: ${action.payload.help}`) console.debug(`!setting help to: ${action.payload.help}`)
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level].help = action.payload.help state.games[action.payload.game].data[action.payload.world][action.payload.level].help = action.payload.help
}, },
/** delete all progress for this game */ /** delete all progress for this game */
deleteProgress(state: ProgressState, action: PayloadAction<{game: string}>) { deleteProgress(state: ProgressState, action: PayloadAction<{game: string}>) {
state.games[action.payload.game.toLowerCase()] = {inventory: [], data: {}, openedIntro: true, difficulty: DEFAULT_DIFFICULTY} state.games[action.payload.game] = {inventory: [], data: {}, openedIntro: true, difficulty: DEFAULT_DIFFICULTY}
}, },
/** delete progress for this level */ /** delete progress for this level */
deleteLevelProgress(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) { deleteLevelProgress(state: ProgressState, action: PayloadAction<{game: string, world: string, level: number}>) {
addLevelProgress(state, action) addLevelProgress(state, action)
state.games[action.payload.game.toLowerCase()].data[action.payload.world][action.payload.level] = initalLevelProgressState state.games[action.payload.game].data[action.payload.world][action.payload.level] = initalLevelProgressState
}, },
/** load progress, e.g. from external import */ /** load progress, e.g. from external import */
loadProgress(state: ProgressState, action: PayloadAction<{game: string, data:GameProgressState}>) { loadProgress(state: ProgressState, action: PayloadAction<{game: string, data:GameProgressState}>) {
console.debug(`setting data to:\n ${action.payload.data}`) console.debug(`setting data to:\n ${action.payload.data}`)
state.games[action.payload.game.toLowerCase()] = action.payload.data state.games[action.payload.game] = action.payload.data
}, },
/** set the current inventory */ /** set the current inventory */
changedInventory(state: ProgressState, action: PayloadAction<{game: string, inventory: string[]}>) { changedInventory(state: ProgressState, action: PayloadAction<{game: string, inventory: string[]}>) {
addGameProgress(state, action) addGameProgress(state, action)
state.games[action.payload.game.toLowerCase()].inventory = action.payload.inventory state.games[action.payload.game].inventory = action.payload.inventory
}, },
/** set the difficulty */ /** set the difficulty */
changedDifficulty(state: ProgressState, action: PayloadAction<{game: string, difficulty: number}>) { changedDifficulty(state: ProgressState, action: PayloadAction<{game: string, difficulty: number}>) {
addGameProgress(state, action) addGameProgress(state, action)
state.games[action.payload.game.toLowerCase()].difficulty = action.payload.difficulty state.games[action.payload.game].difficulty = action.payload.difficulty
}, },
/** set the difficulty */ /** set the difficulty */
changedOpenedIntro(state: ProgressState, action: PayloadAction<{game: string, openedIntro: boolean}>) { changedOpenedIntro(state: ProgressState, action: PayloadAction<{game: string, openedIntro: boolean}>) {
addGameProgress(state, action) addGameProgress(state, action)
state.games[action.payload.game.toLowerCase()].openedIntro = action.payload.openedIntro state.games[action.payload.game].openedIntro = action.payload.openedIntro
}, },
/** set the typewriter mode */
changeTypewriterMode(state: ProgressState, action: PayloadAction<{game: string, typewriterMode: boolean}>) {
addGameProgress(state, action)
state.games[action.payload.game.toLowerCase()].typewriterMode = action.payload.typewriterMode
}
} }
}) })
/** if the level does not exist, return default values */ /** if the level does not exist, return default values */
export function selectLevel(game: string, world: string, level: number) { export function selectLevel(game: string, world: string, level: number) {
return (state) =>{ return (state) =>{
if (!state.progress.games[game.toLowerCase()]) { return initalLevelProgressState } if (!state.progress.games[game]) { return initalLevelProgressState }
if (!state.progress.games[game.toLowerCase()].data[world]) { return initalLevelProgressState } if (!state.progress.games[game].data[world]) { return initalLevelProgressState }
if (!state.progress.games[game.toLowerCase()].data[world][level]) { return initalLevelProgressState } if (!state.progress.games[game].data[world][level]) { return initalLevelProgressState }
return state.progress.games[game.toLowerCase()].data[world][level] return state.progress.games[game].data[world][level]
} }
} }
/** return the code of the current level */ /** return the code of the current level */
export function selectCode(game: string, world: string, level: number) { export function selectCode(game: string, world: string, level: number) {
return (state) => { return (state) => {
return selectLevel(game.toLowerCase(), world, level)(state).code return selectLevel(game, world, level)(state).code
} }
} }
/** return the current inventory */ /** return the current inventory */
export function selectInventory(game: string) { export function selectInventory(game: string) {
return (state) => { return (state) => {
if (!state.progress.games[game.toLowerCase()]) { return [] } if (!state.progress.games[game]) { return [] }
return state.progress.games[game.toLowerCase()].inventory return state.progress.games[game].inventory
} }
} }
/** return the code of the current level */ /** return the code of the current level */
export function selectHelp(game: string, world: string, level: number) { export function selectHelp(game: string, world: string, level: number) {
return (state) => { return (state) => {
return selectLevel(game.toLowerCase(), world, level)(state).help return selectLevel(game, world, level)(state).help
} }
} }
/** return the selections made in the current level */ /** return the selections made in the current level */
export function selectSelections(game: string, world: string, level: number) { export function selectSelections(game: string, world: string, level: number) {
return (state) => { return (state) => {
return selectLevel(game.toLowerCase(), world, level)(state).selections return selectLevel(game, world, level)(state).selections
} }
} }
/** return whether the current level is clompleted */ /** return whether the current level is clompleted */
export function selectCompleted(game: string, world: string, level: number) { export function selectCompleted(game: string, world: string, level: number) {
return (state) => { return (state) => {
return selectLevel(game.toLowerCase(), world, level)(state).completed return selectLevel(game, world, level)(state).completed
} }
} }
/** return progress for the current game if it exists */ /** return progress for the current game if it exists */
export function selectProgress(game: string) { export function selectProgress(game: string) {
return (state) => { return (state) => {
return state.progress.games[game.toLowerCase()] ?? null return state.progress.games[game] ?? null
} }
} }
/** return difficulty for the current game if it exists */ /** return difficulty for the current game if it exists */
export function selectDifficulty(game: string) { export function selectDifficulty(game: string) {
return (state) => { return (state) => {
return state.progress.games[game.toLowerCase()]?.difficulty ?? DEFAULT_DIFFICULTY return state.progress.games[game]?.difficulty ?? DEFAULT_DIFFICULTY
} }
} }
/** return whether the intro has been read */ /** return whether the intro has been read */
export function selectOpenedIntro(game: string) { export function selectOpenedIntro(game: string) {
return (state) => { return (state) => {
return state.progress.games[game.toLowerCase()]?.openedIntro return state.progress.games[game]?.openedIntro
}
}
/** return typewriter mode for the current game if it exists */
export function selectTypewriterMode(game: string) {
return (state) => {
return state.progress.games[game.toLowerCase()]?.typewriterMode ?? true
} }
} }
/** Export actions to modify the progress */ /** Export actions to modify the progress */
export const { changedSelection, codeEdited, levelCompleted, deleteProgress, export const { changedSelection, codeEdited, levelCompleted, deleteProgress,
deleteLevelProgress, loadProgress, helpEdited, changedInventory, changedOpenedIntro, deleteLevelProgress, loadProgress, helpEdited, changedInventory, changedOpenedIntro,
changedDifficulty, changeTypewriterMode} = progressSlice.actions changedDifficulty } = progressSlice.actions
+6 -7
View File
@@ -7,19 +7,21 @@ import { debounce } from "debounce";
import { connection } from '../connection' import { connection } from '../connection'
import { apiSlice } from './api' import { apiSlice } from './api'
import { progressSlice } from './progress' import { progressSlice } from './progress'
import { preferencesSlice } from "./preferences" import { saveState } from "./local_storage";
import { saveState, savePreferences, removePreferences} from "./local_storage";
export const store = configureStore({ export const store = configureStore({
reducer: { reducer: {
[apiSlice.reducerPath]: apiSlice.reducer, [apiSlice.reducerPath]: apiSlice.reducer,
[progressSlice.name]: progressSlice.reducer, [progressSlice.name]: progressSlice.reducer,
[preferencesSlice.name]: preferencesSlice.reducer,
}, },
// Make connection available in thunks: // Make connection available in thunks:
middleware: getDefaultMiddleware => middleware: getDefaultMiddleware =>
getDefaultMiddleware().concat(apiSlice.middleware), getDefaultMiddleware({
thunk: {
extraArgument: { connection }
}
}).concat(apiSlice.middleware),
}); });
/** /**
@@ -29,9 +31,6 @@ export const store = configureStore({
store.subscribe( store.subscribe(
debounce(() => { debounce(() => {
saveState(store.getState()[progressSlice.name]); saveState(store.getState()[progressSlice.name]);
const preferencesState = store.getState()[preferencesSlice.name]
preferencesState.isSavePreferences ? savePreferences(preferencesState) : removePreferences()
}, 800) }, 800)
); );
+341
View File
@@ -0,0 +1,341 @@
import { DataCallback, AbstractMessageReader, MessageReader } from 'vscode-jsonrpc/lib/common/messageReader.js';
import { Message } from 'vscode-jsonrpc/lib/common/messages.js';
import { AbstractMessageWriter, MessageWriter } from 'vscode-jsonrpc/lib/common/messageWriter.js';
import { Emitter } from 'vscode-jsonrpc/lib/common/events.js';
import { Disposable, IWebSocket } from 'vscode-ws-jsonrpc/.';
declare var IO: any;
export class WasmWriter implements MessageWriter {
protected errorCount = 0;
errorEmitter
closeEmitter
constructor(private worker: Worker) {
this.errorEmitter = new Emitter()
this.closeEmitter = new Emitter()
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error, message, count) {
this.errorEmitter.fire([this.asError(error), message, count]);
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(undefined);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Writer received error. Reason: ${error.message}`);
}
}
end(): void {
}
async write(msg: Message): Promise<void> {
try {
const content = JSON.stringify(msg);
this.worker.postMessage(content)
} catch (e) {
this.errorCount++;
this.fireError(e, msg, this.errorCount);
}
}
}
export class WasmReader implements MessageReader {
protected state: 'initial' | 'listening' | 'closed' = 'initial';
protected callback: DataCallback | undefined;
protected readonly events: { message?: any, error?: any }[] = [];
constructor(private worker: Worker) {
this.worker.onmessage = (ev) => {
this.readMessage(ev.data)
}
// this.socket.onMessage(message =>
// this.readMessage(message)
// );
// this.socket.onError(error =>
// this.fireError(error)
// );
// this.socket.onClose((code, reason) => {
// if (code !== 1000) {
// const error: Error = {
// name: '' + code,
// message: `Error during socket reconnect: code = ${code}, reason = ${reason}`
// };
// this.fireError(error);
// }
// this.fireClose();
// });
this.errorEmitter = new Emitter()
this.closeEmitter = new Emitter()
this.partialMessageEmitter = new Emitter()
}
protected errorCount = 0;
errorEmitter
closeEmitter
partialMessageEmitter
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
get onClose() {
return this.closeEmitter.event;
}
get onPartialMessage() {
return this.partialMessageEmitter.event;
}
firePartialMessage(info) {
this.partialMessageEmitter.fire(info);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Reader received error. Reason: ${error.message ? error.message : 'unknown'}`);
}
}
listen(callback: DataCallback): Disposable {
if (this.state === 'initial') {
this.state = 'listening';
this.callback = callback;
while (this.events.length !== 0) {
const event = this.events.pop()!;
if (event.message) {
this.readMessage(event.message);
} else if (event.error) {
this.fireError(event.error);
} else {
this.fireClose();
}
}
}
return {
dispose: () => {
if (this.callback === callback) {
this.callback = undefined;
}
}
};
}
protected readMessage(message: any): void {
if (this.state === 'initial') {
this.events.splice(0, 0, { message });
} else if (this.state === 'listening') {
try {
const data = JSON.parse(message);
this.callback!(data);
} catch (err) {
const error: Error = {
name: '' + 400,
message: `Error during message parsing, reason = ${typeof err === 'object' ? (err as any).message : 'unknown'}`
};
this.fireError(error);
}
}
}
protected fireError(error: any): void {
if (this.state === 'initial') {
this.events.splice(0, 0, { error });
} else if (this.state === 'listening') {
this.errorEmitter.fire(this.asError(error));
}
}
protected fireClose(): void {
if (this.state === 'initial') {
this.events.splice(0, 0, {});
} else if (this.state === 'listening') {
this.closeEmitter.fire(undefined);
}
this.state = 'closed';
}
}
export class WebSocketMessageWriter implements MessageWriter {
protected errorCount = 0;
errorEmitter
closeEmitter
constructor(protected readonly socket: IWebSocket) {
this.errorEmitter = new Emitter();
this.closeEmitter = new Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error, message, count) {
this.errorEmitter.fire([this.asError(error), message, count]);
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(undefined);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Writer received error. Reason: ${(error.message) ? error.message : 'unknown'}`);
}
}
end(): void {
}
async write(msg: Message): Promise<void> {
console.log("WRITE",msg)
try {
const content = JSON.stringify(msg);
this.socket.send(content);
} catch (e) {
this.errorCount++;
this.fireError(e, msg, this.errorCount);
}
}
}
export class WebSocketMessageReader implements MessageReader {
protected state: 'initial' | 'listening' | 'closed' = 'initial';
protected callback: DataCallback | undefined;
protected readonly events: { message?: any, error?: any }[] = [];
errorEmitter
closeEmitter
partialMessageEmitter
constructor(protected readonly socket: IWebSocket) {
this.errorEmitter = new Emitter();
this.closeEmitter = new Emitter();
this.partialMessageEmitter = new Emitter();
this.socket.onMessage(message =>{
console.log("READ", message)
this.readMessage(message)
});
this.socket.onError(error =>
this.fireError(error)
);
this.socket.onClose((code, reason) => {
if (code !== 1000) {
const error: Error = {
name: '' + code,
message: `Error during socket reconnect: code = ${code}, reason = ${reason}`
};
this.fireError(error);
}
this.fireClose();
});
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
get onClose() {
return this.closeEmitter.event;
}
get onPartialMessage() {
return this.partialMessageEmitter.event;
}
firePartialMessage(info) {
this.partialMessageEmitter.fire(info);
}
asError(error) {
if (error instanceof Error) {
return error;
}
else {
return new Error(`Reader received error. Reason: ${(error.message) ? error.message : 'unknown'}`);
}
}
listen(callback: DataCallback): Disposable {
if (this.state === 'initial') {
this.state = 'listening';
this.callback = callback;
while (this.events.length !== 0) {
const event = this.events.pop()!;
if (event.message) {
this.readMessage(event.message);
} else if (event.error) {
this.fireError(event.error);
} else {
this.fireClose();
}
}
}
return {
dispose: () => {
if (this.callback === callback) {
this.callback = undefined;
}
}
};
}
protected readMessage(message: any): void {
if (this.state === 'initial') {
this.events.splice(0, 0, { message });
} else if (this.state === 'listening') {
try {
const data = JSON.parse(message);
this.callback!(data);
} catch (err) {
const error: Error = {
name: '' + 400,
message: `Error during message parsing, reason = ${typeof err === 'object' ? (err as any).message : 'unknown'}`
};
this.fireError(error);
}
}
}
protected fireError(error: any): void {
if (this.state === 'initial') {
this.events.splice(0, 0, { error });
} else if (this.state === 'listening') {
this.errorEmitter.fire(this.asError(error));
}
}
protected fireClose(): void {
if (this.state === 'initial') {
this.events.splice(0, 0, {});
} else if (this.state === 'listening') {
this.closeEmitter.fire(undefined);
}
this.state = 'closed';
}
}
+21
View File
@@ -0,0 +1,21 @@
import {useState, useEffect} from 'react'
function getWindowDimensions() {
const {innerWidth: width, innerHeight: height } = window
return {width, height}
}
export function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions())
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions())
}
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [])
return windowDimensions
}
+319 -54
View File
@@ -1,67 +1,332 @@
# Server # Creating a game.
The server is made out of two parts, named "relay" and "server". Ideally one takes the [NNG template](https://github.com/hhu-adam/NNG4) to create a new game.
The former, "relay", is the server which ## Game Structure
sets up a socket connection to the client, starts the lean servers to work on files and
relays messages between the lean server and the client. `index.mjs` is the file that needs to
be run, which is done for example using `pm2` or by calling `npm run start_server` or
`npm run production`, see more later.
The latter, "server", is the lean server which has two jobs. For one, it produces the "gameserver" A game consist of worlds which have multiple levels each. In the following we describe how to create a level file and how to combine these into a game.
executable which is the lean server that handles the files the player plays on. The second job
is to provide the lean commands which are used when creating a game. These are located in
`Commands.lean`.
### Level
## Integration into Games A level file is a lean file that imports at least `import GameServer.Commands` and starts with the following Lean commands.
Games need the "server" as a lake-dependency, which is done in the game's lakefile.
A game imports `GameServer.Commands` which provides to all the API required to
create a game.
In particular the lean command `MakeGame` compiles the entire game. Static information is
stored as JSON files in `.lake/gamedata` for faster loading, while other data is only
saved to lean env-extensions which the lean server has access to after loading the lean file.
For games to be run successfully, it is important that the "gameserver" executable inside
the game's `.lake` folder is actually built.
Currently, this happens through a lake-post-update-hook when calling `lake update -R` (in the game's folder), but if this fails, you can always build it manually by calling `lake build gameserver`.
(both commands are to be executed in the game's directory!)
## Modifying the server
### Starting the server
When using the [manual installation](running_locally.md#manual-installation) you can run the server
using
```lean
Game "NNG"
World "Addition"
Level 1
Title "The rfl tactic"
``` ```
Note that the levels inside a world must have consecutive numbering starting with `1`. The `Game`
and `World` strings can be anything, see below.
#### Statement
The core of a level is the `Statement`, which is the exercise that should be proven.
```lean
/-- For all natural numbers $n$, we have $0 + n = n$. -/
@[simp]
Statement MyNat.zero_add
(n : ℕ) : 0 + n = n := by
Hint "You can start a proof by `induction n`."
induction n with n hn
· Hint "This is the base case."
rw [add_zero]
rfl
· Hint "This is the induction hypothesis"
rw [add_succ]
Branch
simp
Hint "A branch is an alternative tactic sequence. Does not need to finish the proof."
rw [hn]
rfl
```
##### Proof
The proof must always be a tactic proof, i.e. `:= by` is a mandatory part of the syntax.
There are a few extra tactics that help you structuring the proof:
- `Hint`: You can use `Hint "text"` to display text if the goal state in-game matches
the one where `Hint` is placed. For more options about hints, see below.
- `Branch`: In the proof you can add a `Branch` that runs an alternative tactic sequence, which
helps setting `Hints` in different places. The `Branch` does not affect the main
proof and does not need to finish any goals.
- `Template`/`Hole`: Used to provide a sample proof template. Anything inside `Template`
will be copied into the editor with all `Hole`s replaced with `sorry`. Note that
having a `Template` will force the user to use Editor-mode for this level.
##### Statement Name (optional)
If you specify a name (`MyNat.zero_add`), this lemma will be available in future levels.
(Note that a future level must also import this level,
so that Lean knows about the added statement).
The name must be *fully qualified*. (TODO: is that still true? Did we implement namespaces?)
##### Doc Comment (optional)
There are three places where the documentation comment appears:
1. as doc comment when hovering over the theorem
2. as exercise description at the top of the level: ``Theorem `zero_add`: yada yada.``
3. in the inventory. This can be overwritten by using
`LemmaDoc MyNat.zero_add "different yada yada"` as one might want to add a more detailed
description there including examples etc.
Both latter points support Markdown (including katex).
##### Attributes (optional)
the `@[ attributes ]` prefix should work just like you know it from the `theorem` keyword.
#### Introduction/Conclusion
Optionally, you can add an `Introduction "some text"` and `Conclusion "some text"` to your level.
The introduction will be shown at the beginning, the conclusion is displayed once the level
is solved.
#### Theorems/Tactics/Definitions
Only enabled theorems/tactics/definitions (called "items" here) are available in a level.
To add a new item in a level, you can add
```lean
NewTactic rfl simp
NewLemma MyNat.add_zero MyNat.add_succ
NewDefinition Nat Pow Mul
```
Once added, items will be available in all future levels/worlds,
unless you disable them for a particular level with
```lean
DisabledTactic tauto
DisabledLemma MyNat.add_zero
```
or specify explicitly which items should be available with
```lean
OnlyTactic rw rfl apply
OnlyLemma MyNat.add_zero
```
Lastly, all items need documentation entries (which are imported in the level),
see more about that below. There is also explains the `LemmaTab` keyword.
### World
Multiple levels are combined into a world and the worlds are then added to the game. It is recommended that all levels of a world are inside one folder (e.g. `NNG/Levels/Addition/`) and
then there is one world file (`NNG/Levels/Addition.lean`) which contains the following
```lean
import NNG.Levels.Addition.Level_1
import NNG.Levels.Addition.Level_2
Game "NNG"
World "Addition"
Title "Addition World"
Introduction "some text"
```
The `Title` is the world's display title. The `Introduction` is displayed before loading level 1.
Note that all levels of a world should be imported by the world file.
BUG: A level **must not** be imported in a different world's level. Instead, you have to import an entire world there: `import NNG.Levels.Addition`
### Game
The Game itself (i.e. the main file of you lake project, `NNG.lean`) should import all worlds and have the following layout, concluding with `MakeGame`:
```lean
import NNG.Levels.Addition
import NNG.Levels.Multiplication
import NNG.Levels.Power
Game "NNG"
Title "Natural Number Game"
Introduction "some text"
MakeGame
```
The game will automatically compute the order of the worlds depending on the sample proofs of the Levels (ignoring anything inside a `Branch`). You can add additional dependencies manually by adding `Dependency PowerWorld → ImpossibleWorld` before `MakeGame`.
The order of worlds influences which tactics and lemmas will be unlocked in a given level.
`MakeGame` will display warnings about things in the game that need to be fixed, like missing
documentation or if a tactic is never introduced.
### Documentation
Each tactic, theorem, or definition (all called items here) that is introduced in the game
needs a documentation entry. These are statements of the following form:
```lean
LemmaDoc MyNat.add_squared as "add_squared" in "Pow"
"(missing)"
TacticDoc constructor
"(missing)"
DefinitionDoc One as "1"
"(missing)"
```
Notes:
* The lemma name must be **fully qualified**. The string display name can be arbitrary.
* Tactics must have their proper name. use `TacticDoc «have» ""` if it does not work
without french quotes.
* Definition names can be arbitrary. E.g. I used `DefinitionDoc Symbol.Fun as "fun x ↦ x" "(missing)"` once.
Moreover, the lemmas are in sorted in tabs (the `in "Pow`) part. In each level file, you
can define which tab is open when the level is loaded by adding `LemmaTab "Pow"`.
There will be features added to get automatic information from mathlib!
## Escaping
(TODO: Move)
Inside the doc comment you don't need to escape the backslashes:
```lean
/-- $\operatorname{succ}(n)$. notation for naturals is `\N`. -/
Statement ...
```
However, inside interpolated strings (e.g. in `Hint`, `Introduction` and `Conclusion`)
you do need to escape backslashes
with `\\` and `{` with `\{`:
```lean
Hint "This code has some $\\operatorname\{succ}(n)$ math. The value of `h` is {h}.
Notation for naturals is `\\N`."
```
## Game design
Here are some things you should consider designing a new game:
* A world with more than 16 levels will be displayed with the levels spiraling outwards,
it might be desirable to stay below that bound. Above 22 levels the spiral start getting out
of control.
# Running Games Locally
The installation instructions are not yet tested on Mac/Windows. Comments very welcome!
## VSCode Dev Containers
1. **Install Docker and Dev Containers** *(once)*:<br/>
See [official instructions](https://code.visualstudio.com/docs/devcontainers/containers#_getting-started).
Explicitly this means:
* Install docker engine if you have not yet: [Instructions](https://docs.docker.com/engine/install/).
I followed the "Server" instructions for linux.
* Note that on Linux you need to add your user to the `docker` group
([see instructions](https://docs.docker.com/engine/install/linux-postinstall/)) and probably reboot.
* Open the games folder in VSCode: `cd NNG4 && code .` or "Open Folder" within VSCode
* a message appears prompting you to install the "Dev Containers" extension (by Microsoft).
2. **Open Project in Dev Container** *(everytime)*:<br/>
Once you have the Dev Containers Extension installed, (re)open the project folder of your game in VSCode.
A message appears asking you to "Reopen in Container".
* The first start will take a while, ca. 2-10 minutes. After the first
start this should be very quickly.
* Once built, it should open a tab "Simple Browser" inside VSCode displaying
the game. (Alternatively, open http://localhost:3000 in your browser).
3. **Editing Files** *(everytime)*:<br/>
After editing some files in VSCode, open VSCode's terminal (View > Terminal) and run `lake build`.
Now you can reload your browser to see the changes.
### Errors
* If you don't get the pop-up, you might have disabled them and you can reenable it by
running the `remote-containers.showReopenInContainerNotificationReset` command in vscode.
* If the starting the container fails, in particular with a message `Error: network xyz not found`,
you might have deleted stuff from docker via your shell. Try deleting the container and image
explicitly in VSCode (left side, "Docker" icon). Then reopen vscode and let it rebuild the
container. (this will again take some time)
## Without Dev Containers
Install `nvm`:
```bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh | bash
```
then reopen bash and test with `command -v nvm` if it is available (Should print "nvm").
Now install node:
```bash
nvm install node
```
Clone the game (e.g. `NNG4` here):
```bash
git clone https://github.com/hhu-adam/NNG4.git
# or: git clone git@github.com:hhu-adam/NNG4.git
```
Download dependencies and build the game:
```bash
cd NNG4
lake update
lake exe cache get # if your game depends on mathlib
lake build
```
Clone the game repository into a directory next to the game:
```bash
cd ..
git clone https://github.com/leanprover-community/lean4game.git
# or: git clone git@github.com:leanprover-community/lean4game.git
```
The folders `NNG4` and `lean4game` must be in the same directory!
In `lean4game`, install dependencies:
```bash
cd lean4game
npm install
```
If you are developing a game other than `Robo` or `NNG4`, adapt the
code at the beginning of `lean4game/server/index.mjs`:
```typescript
const games = {
"g/hhu-adam/robo": {
dir: "../../../../Robo",
queueLength: 5
},
"g/hhu-adam/nng4": {
dir: "../../../../NNG4",
queueLength: 5
}
}
```
Run the game:
```bash
npm start npm start
``` ```
This way any changes to files in `client/` or `relay/` will cause the server to restart automatically. This takes a little time. Eventually, the server is available on http://localhost:3000/
and the game is available on http://localhost:3000/#/g/hhu-adam/NNG4.
Alternative, you can run `npm run build` followed by the commands ### Modifying the GameServer
When modifying the game engine itself (in particular the content in `lean4game/server`) you can test it live with this
setup by setting `export NODE_ENV=development` inside your local game before building it:
```bash
cd NNG4
export NODE_ENV=development
lake update
lake build
``` ```
npm run start_client This causes lake to search locally for the `GameServer` lake package instead of using the version from github.
npm run production
```
(in two separate terminals) to test the production mode of the server. This way it will only
change once you build and restart the server.
### Modifying the lean server
To test a modified lean server (i.e. content of `server/`), you can use the local dev setup and call
`lake update -R -Klean4game.local` in your game followed by `lake build`.
This will cause lake to look for the
local lean server as a dependency instead of the version it downloaded from git.
You can play a local game at https://localhost:3000/#/g/local/{FolderName} where you replace `{FolderName}` with the game folder name.
After modifications in `server/`, you will need to call `lake build gameserver` (called in `server/` or in your game's folder) to rebuild
the gameserver executable and
`lake build` (called in the game's folder) to rebuild the game.
-9
View File
@@ -1,9 +0,0 @@
# Changelog
## v4.5.0
### Breaking changes
* Fix (#183): local store accepts case insensitive URL. The game progress has previously been saved under case sensitive URLs. You might need to recover old progress from your browser storage.
## Other
+28 -50
View File
@@ -98,7 +98,7 @@ This introduction text is shown when one first enters a world.
1. Use the template above and make sure you import all levels of this world. 1. Use the template above and make sure you import all levels of this world.
1. In `Game.lean` import the world with `import Game.Levels.MyWorld` 1. In `Game.lean` import the world with `import Game.Levels.MyWorld`
Now you created a world with one level and added it🎉 The command `MakeGame` in `Game.lean` shows you any problems you might need to fix. Currently, it shows Now you created a world with one level and added it🎉 The command `MakeGame` in `Game.lean` shows you any problems you might need to fix. Currently it shows
```text ```text
No world introducing sorry, but required by MyWorld No world introducing sorry, but required by MyWorld
@@ -125,32 +125,23 @@ The player has an inventory with tactics, theorems, and definitions that unlock
```lean ```lean
NewTactic induction simp NewTactic induction simp
NewTheorem Nat.zero_mul NewLemma Nat.zero_mul
NewDefinition Pow NewDefinition Pow
``` ```
**Important:** All commands in this section 6a) expect the `Name` they take as input
to be **fully qualified**. For example `NewTheorem Nat.zero_mul` and not `NewTheorem zero_mul`.
#### Doc entries #### Doc entries
You'll see a warning about a missing Theorem documentation. You can fix it by adding doc-entries like the following somewhere above it. You'll see a warning about a missing Lemma documentation. You can fix it by adding doc-entries like the following somewhere above it.
```lean ```lean
/-- LemmaDoc Nat.zero_mul as "zero_mul" in "Mul"
some description "some description"
-/
TheoremDoc Nat.zero_mul as "zero_mul" in "Mul"
/--
some description
-/
TacticDoc simp TacticDoc simp
"some description"
/--
some description
-/
DefinitionDoc Pow as "^" DefinitionDoc Pow as "^"
"some description"
``` ```
(e.g. you could also create a file `Game/Doc/MyTheorems.lean`, add there your documentation and import it) (e.g. you could also create a file `Game/Doc/MyTheorems.lean`, add there your documentation and import it)
@@ -162,7 +153,7 @@ If you do not provide any content for the inventory, the game will try to find a
You have a few options to disable inventory items that have been unlocked in previous levels: You have a few options to disable inventory items that have been unlocked in previous levels:
```lean ```lean
DisabledTactic, DisabledTheorem, OnlyTactic, OnlyTheorem DisableTactic, DisableLemma, OnlyTactic, OnlyLemma
``` ```
have the same syntax as above. The former two disable items for this level, the latter two have the same syntax as above. The former two disable items for this level, the latter two
@@ -170,7 +161,7 @@ disable all items except the ones specified.
#### Theorem Tab #### Theorem Tab
Theorems are sorted into tabs. With `TheoremTab "Mul"` you specify which tab should be open by default in this level. Theorems are sorted into tabs. with `LemmaTab "Mul"` you specify which tab should be open by default in this level.
#### HiddenTactic #### HiddenTactic
@@ -185,14 +176,12 @@ and only `rw` would show up in the inventory.
### 6. b) Statement ### 6. b) Statement
The statement is the exercise of the level. The basics work the same as they would in `example` or `theorem`. Note however, that you **must** do a tactic proof, i.e. the `:= by` is a hard-coded part of the syntax The statement is the exercise of the level. the basics work the same as they would in `example` or `theorem`. Note however, that you **must** do a tactic proof, i.e. the `:= by` is a hard-coded part of the syntax
#### Name #### Name
You can give your exercise a name: `Statement my_first_exercise (n : Nat) ...`. If you do so, it will be added to the inventory and be available in future levels. You can give your exercise a name: `Statement my_first_exercise (n : Nat) ...`. If you do so, it will be added to the inventory and be available in future levels.
You can but a `Statement` inside namespaces like you would with `theorem`.
#### Doc String / Exercise statement #### Doc String / Exercise statement
Add a docstring that contains the exercise statement in natural language. If you do this, it will appear at the top of the exercise. It supports Latex. Add a docstring that contains the exercise statement in natural language. If you do this, it will appear at the top of the exercise. It supports Latex.
@@ -216,12 +205,12 @@ Statement my_simp_lemma ...
The proof must always be a tactic proof, i.e. `:= by` is a mandatory part of the syntax. The proof must always be a tactic proof, i.e. `:= by` is a mandatory part of the syntax.
There are a few extra tactics that help you with structuring the proof: There are a few extra tactics that help you structuring the proof:
- `Hint`: You can use `Hint "text"` to display text if the goal state in-game matches - `Hint`: You can use `Hint "text"` to display text if the goal state in-game matches
the one where `Hint` is placed. For more options about hints, see below. the one where `Hint` is placed. For more options about hints, see below.
- `Branch`: In the proof you can add a `Branch` that runs an alternative tactic sequence, which - `Branch`: In the proof you can add a `Branch` that runs an alternative tactic sequence, which
helps to set `Hints` in different places. The `Branch` does not affect the main helps setting `Hints` in different places. The `Branch` does not affect the main
proof and does not need to finish any goals. proof and does not need to finish any goals.
- `Template`/`Hole`: Used to provide a sample proof template. Anything inside `Template` - `Template`/`Hole`: Used to provide a sample proof template. Anything inside `Template`
will be copied into the editor with all `Hole`s replaced with `sorry`. Note that will be copied into the editor with all `Hole`s replaced with `sorry`. Note that
@@ -234,40 +223,29 @@ One thing to keep in mind is that the game will look at the main proof to figure
Most important for game development are probably the `Hints`. Most important for game development are probably the `Hints`.
The hints will be displayed whenever the player's current goal matches the goal the hint is The hints will be displayed whenever the player's current goal matches the goal the hint is
placed at inside the sample proof. You can use `Branch` to place hints in dead ends or alternative proof strands. placed at inside the sample proof. You can use `Branch` to place hints in dead ends or alternative proof strands. If you specify
Read [More about Hints](hints.md) for how they work and what the options are. ```
Hint (strict := true) "some hidden hint"
```
### 6. e) Extra: Images a hint only matches iff the assumptions match exactly one-to-one. (Otherwise, it does not care if there are additional assumptions in context)
You can add images on any layer of the game (i.e. game/world/level). These will be displayed in your game.
The images need to be placed in `images/` and you need to add a command like `Image "images/path/to/myWorldImage.png"` Further, you can choose to hide hints and only have them displayed when the player presses "More Help":
in one of the files you created in 2), 3), or 4) (i.e. game/world/level). ```
Hint (hidden := true) "some hidden hint"
```
NOTE: At present, only the images for a world are displayed. They appear in the introduction of the world. Lastly, you should put variable names in hints inside brackets:
```
Hint "now use `rw [{h}]` to use your assumption {h}."
```
That way, the game will replace it with the actual name the assumption has in the player's proof state.
## 7. Update your game ## 7. Update your game
In principle, it is as simple as modifying `lean-toolchain` to update your game to a new Lean version. However, you should read about the details in [Update An Existing Game](update_game.md). In principle, it is as simple as modifying `lean-toolchain` to update your game to a new Lean version. However, you should read about the details in [Update An Existing Game](https://github.com/leanprover-community/lean4game/blob/main/doc/update_game.md).
## 8. Publish your game
To publish your game on the official server, see [Publishing a game](publish_game.md)
There are a few more options you can add in `Game.lean` before the `MakeGame` command, which describe the tile that is visible on the server's landing page:
```lean
Languages "English"
CaptionShort "Game Template"
CaptionLong "You should use this game as a template for your own game and add your own levels."
Prerequisites "NNG"
CoverImage "images/cover.png"
```
* `Languages`: Currently only a single language (capital English name). The tile will show a corresponding flag.
* `CaptionShort`: One catchphrase. Appears above the image.
* `CaptionLong`: 2-4 sentences to describe the game.
* `Prerequisites` a list of other games you should play before this one, e.g. `Prerequisites "NNG" "STG"`. The game names are free-text.
* `CoverImage`: You can create a folder `images/` and put images there for the game to use. The maximal ratio is ca. 500x200 (W x H) but it might be cropped horizontally on narrow screens.
## Further Notes ## Further Notes
-89
View File
@@ -1,89 +0,0 @@
# Hints
Most important for game development are probably the "Hints". You can add Hints at any place in your proof using the `Hint` tactic
```
Statement .... := by
Hint "Hint to show at the start"
rw [h]
Hint "some tip after using rw"
...
```
Note that hints are only **context-aware but not history-aware**. In particular, they only look at the assumptions and the current goal. Player's might encounter hints in a different order - or not at all - if they decide to go for a unique proof idea. The `Branch` tactic helps to place hints outside the sample solution's proof.
## 1. When do hints show?
A hint will be displayed if the player's goal matches the one where the hint was placed in the
sample solutions and the entire context from the sample solutions is present in the
player's context. The player's context may contain additional items.
This means if you have multiple identical
subgoals, you should only place a single hint in one of them, and it will be displayed in
all of them.
However, identical (non-hidden) hints which where already present in the step
before are omitted. This is to allow a player to add new assumptions to context, for example
with `have`, without seeing the same hint over and over again.
Hidden hints are not filtered.
## 2. Alternative Proofs / `Branch`
You can use `Branch` to place hints
in dead ends or alternative proof strands.
A proof inside a `Branch`-block is normally evaluated by lean, but it's discarded at the end
so that no progress has been made on proofing the goal.
```
Statement .... := by
Hint "use `rw` or `rewrite`."
Branch
rewrite [h]
Hint "now you still need `rfl`"
rw [h]
```
## 3. Variables names
Put variables in the hint text inside brackets like this: `{h}`! This way the server can replace
the variable's name with the one the user actually used.
For example, if the sample proof contains
```
have h : True := trivial
Hint "Now use `rw [{h}]` to use your assumption `{h}`."
```
but the player writes `have g : True := trivial`, they will see a hint saying
"Now use `rw [g]` to use your assumption `g`."
## 4. Hidden hints
Some hints can be hidden, and only show after the user clicks on a button to get additional
help. You mark a hint as hidden with `(hidden := true)`:
```
Hint (hidden := true) "some hidden hint"
```
## 5. Strict context matching
If you use the attribute `(strict := true)` a hint is only shown if the entire context
matches exactly the one where the hint is placed. With `(hint := false)`, which is the default,
it does not matter if additional assumptions are present in the player's context.
```
Hint (strict := true) "now use `have` to create a new assumption."
```
You should probably use `(strict := true)` if you want to give fine-grained details about
tactics like `have` which do not modify the goal or any existing assumptions, but only
create new assumptions.
## 6. Formatting
You can add use markdown to format your hints, for example you can use KaTex: `$\\iff$`
TODO: Write a doc about latex/markdown options available.
-32
View File
@@ -1,32 +0,0 @@
# Publishing games
You can publish your game on the official [Lean Game Server](https://adam.math.hhu.de) in a few simple
steps.
## 1. Upload Game to github
First, you need your game in a public Github repository and make sure the github action has run.
You can check this by spotting the green checkmark on the start page, or by looking at the "Actions"
tab.
## 2. Import the game
You call the URL that's listed under "What's Next?" in the latest action run. Explicitly you call
the URL of the form
> adam.math.hhu.de/import/trigger/{USER}/{REPOSITORY}
where `{USER}` and `{REPOSITORY}` are replaced with the github user and repository name.
You should see a white screen which shows import updates and eventually reports "Done."
## 3. Play the game
Now you can immediately play the game at `adam.math.hhu.de/#/g/{USER}/{REPOSITORY}`!
## 4. Main page
Adding games to the main page happens manually by the server maintainers. Tell us if you want us
to add a tile for your game!
For example, you can [contact Jon on Zulip](https://leanprover.zulipchat.com/#narrow/dm/385895-Jon-Eugster). Or [via Email](https://www.math.hhu.de/en/lehrstuehle-/-personen-/-ansprechpartner/innen/lehrstuehle-des-mathematischen-instituts/lehrstuhl-fuer-algebraische-geometrie/team/jon-eugster).
+19 -33
View File
@@ -2,8 +2,6 @@
The installation instructions are not yet tested on Mac/Windows. Comments very welcome! The installation instructions are not yet tested on Mac/Windows. Comments very welcome!
Please also consult the [Troubleshooting Collection](troubleshoot.md), where some known pitfalls are collected.
There are several options to play a game locally: There are several options to play a game locally:
1. VSCode Dev Container: needs `docker` installed on your machine 1. VSCode Dev Container: needs `docker` installed on your machine
@@ -33,14 +31,24 @@ The template game [GameSkeleton](https://github.com/hhu-adam/GameSkeleton) conta
* The first start will take a while, ca. 2-15 minutes. After the first * The first start will take a while, ca. 2-15 minutes. After the first
start this should be very quickly. start this should be very quickly.
* Once built, you can open http://localhost:3000 in your browser, which should load the game. * Once built, you can open http://localhost:3000 in your browser. which should load the game.
3. **Editing Files** *(everytime)*:<br/> 3. **Editing Files** *(everytime)*:<br/>
After editing some Lean files in VSCode, open VSCode's terminal (View > Terminal) and run `lake build`. Now you can reload your browser to see the changes. After editing some Lean files in VSCode, open VSCode's terminal (View > Terminal) and run `lake build`. Now you can reload your browser to see the changes.
### Errors
* If you don't get the pop-up, you might have disabled them and you can reenable it by
running the `remote-containers.showReopenInContainerNotificationReset` command in vscode.
* If the starting the container fails, in particular with a message `Error: network xyz not found`,
you might have deleted stuff from docker via your shell. Try deleting the container and image
explicitely in VSCode (left side, "Docker" icon). Then reopen vscode and let it rebuild the
container. (this will again take some time)
* On a working dev container setup, http://localhost:3000 should directly redirect you to http://localhost:3000/#/g/local/game, try if the latter is accessible.
## Codespaces ## Codespaces
You can work on your game using Github codespaces (click "Code" and then "Codespaces" and then "create codespace on main"). It should run the game locally in the background. You can open it for example under "Ports" and clicking on "Open in Browser". You can work on your game using Github codespaces (click "Code" and then "Codespaces" and then "create codespace on main"). It it should run the game locally in the background. You can open it for example under "Ports" and clicking on "Open in Browser".
Note: You have to wait until npm started properly, which might take a good while. Note: You have to wait until npm started properly, which might take a good while.
@@ -77,11 +85,12 @@ git clone https://github.com/hhu-adam/GameSkeleton.git
Download dependencies and build the game: Download dependencies and build the game:
```bash ```bash
cd GameSkeleton cd GameSkeleton
lake update -R lake update
lake exe cache get # if your game depends on mathlib
lake build lake build
``` ```
Clone the server repository into a directory next to the game: Clone the game repository into a directory next to the game:
```bash ```bash
cd .. cd ..
git clone https://github.com/leanprover-community/lean4game.git git clone https://github.com/leanprover-community/lean4game.git
@@ -100,39 +109,16 @@ Run the game:
npm start npm start
``` ```
You should see a message like this:
```bash
[server] > lean4-game@0.1.0 start_server
[server] > (cd server && lake build) && (cd relay && cross-env NODE_ENV=development nodemon -e mjs --exec "node ./index.mjs")
[server]
[client]
[client] > lean4-game@0.1.0 start_client
[client] > cross-env NODE_ENV=development vite --host
[client]
[server] [nodemon] 3.0.#
[server] [nodemon] to restart at any time, enter `rs`
[server] [nodemon] watching path(s): *.*
[server] [nodemon] watching extensions: mjs
[server] [nodemon] starting `node ./index.mjs`
[client]
[client] VITE v4.5.1 ready in \#\#\# ms
[client]
[client] ➜ Local: http://localhost:3000/
[client] ➜ Network: http://###.###.###.##:3000/
[client] [vite-plugin-static-copy] Collected 7 items.
[server] (node:#####) [DEP0040] [server] Listening on 8080
```
This takes a little time. Eventually, the game is available on http://localhost:3000/#/g/local/GameSkeleton. Replace `GameSkeleton` with the folder name of your local game. This takes a little time. Eventually, the game is available on http://localhost:3000/#/g/local/GameSkeleton. Replace `GameSkeleton` with the folder name of your local game.
## Modifying the GameServer ## Modifying the GameServer
When modifying the game engine itself (in particular the content in `lean4game/server`) you can test it live with the same setup as above (manual installation) by using `lake update -R -Klean4game.local`: When modifying the game engine itself (in particular the content in `lean4game/server`) you can test it live with the same setup as above (manual installation) by setting `export LEAN4GAME=local` inside your local game before building it:
```bash ```bash
cd NNG4 cd NNG4
lake update -R -Klean4game.local export LEAN4GAME=local
lake update
lake build lake build
``` ```
This causes lake to search locally for the `GameServer` lake package instead of using the version from github. Therefore, you can the local copy of the edit `GameServer` in `../lean4game` and This causes lake to search locally for the `GameServer` lake package instead of using the version from github. Therefore, when you `lake build` your game, it will rebuild with the modified `GameServer`.
`lake build` will then directly use this modified copy to build your game.
-28
View File
@@ -1,28 +0,0 @@
# Notes for Server maintainer
In order to set up the server to allow imports, one needs to create a
[Github Access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens). A fine-grained access token with only reading rights for public
repos will suffice.
You need to set the environment variables `LEAN4GAME_GITHUB_USER` and `LEAN4GAME_GITHUB_TOKEN`
with your user name and access token. For example, you can set these in `ecosystem.config.cjs` if
you're using `pm2`
Then people can call:
> https://{website}/import/trigger/{owner}/{repo}
where you replace:
- website: The website your server runs on, e.g. `localhost:3000`
- owner, repo: The owner and repository name of the game you want to load from github.
will trigger to download the latest version of your game from github onto your server.
Once this import reports "Done", you should be able to play your game under:
> https://{website}/#/g/{owner}/{repo}
## Data management
Everything downloaded remains in the folder `lean4game/games`.
The subfolder `tmp` contains downloaded artifacts and can be deleted without loss.
The other folders should only contain the built lean-games, sorted by owner and repo.
-37
View File
@@ -1,37 +0,0 @@
# Troubleshooting
Here are some issues experienced by users.
- You can reset the lake projects involved (i.e. the `server/` folder here as well as your [game's folder](https://github.com/hhu-adam/GameSkeleton)) with the following commands:
```
cd [THE PROJECT]
rm -rf .lake/
lake update -R
lake build
```
If you experience problems related to Lean or lake, you should first try to reset it this way.
# VSCode Dev-Container
* If you don't get the pop-up, you might have disabled them, and you can reenable it by
running the `remote-containers.showReopenInContainerNotificationReset` command in vscode.
* If the starting the container fails, in particular with a message `Error: network xyz not found`,
you might have deleted stuff from docker via your shell. Try deleting the container and image
explicitly in VSCode (left side, "Docker" icon). Then reopen vscode and let it rebuild the
container. (this will again take some time)
* On a working dev container setup, http://localhost:3000 should directly redirect you to http://localhost:3000/#/g/local/game, try if the latter is accessible.
# Manual Installation
Here are known issues/pitfalls with the local setup using `npm`.
* If `CDPATH` is set on your mac/linux system, it might provide issues with `npm start` resulting in a server crash or blank screen. In particular `npm start` will display
```
[server] sh: line 0: cd: server: No such file or directory
[server] npm run start_server exited with code 1
```
As a fix you might need to delete your manually set `CDPATH` environment variable.
# Publication
Errors concerning uploads to the server.
* Your game overview loads but the server crashes on loading a level: Check your game's github action is identical to the [GameSkeleton's](https://github.com/hhu-adam/GameSkeleton/blob/main/.github/workflows/build.yml), in particular that there is a step about building the "`gameserver`-executable".
+11 -26
View File
@@ -9,44 +9,29 @@ Before you continue, make sure there [exists a `v4.X.0`-tag in this repo](https:
Then, depending on the setup you use, do one of the following: Then, depending on the setup you use, do one of the following:
* **Dev Container**: Rebuild the VSCode Devcontainer (without Cache!). * Dev Container: Rebuild the VSCode Devcontainer.
* **Local Setup**: in your game's folder run the following: * Local Setup: run `lake update` (followed by `lake exe cache get` if you depend on mathlib.)
``` * Gitpod/Codespaces: Create a fresh one
lake update -R
lake build
```
* Additionally, if you have a local copy of the server `lean4game`, This will update `lean4game` and `mathlib` in your project to the new lean version.
you should update this one to the matching version. Run the following in the folder `lean4game/`:
```
git fetch
git checkout {VERSION_TAG}
npm install
```
where `{VERSION_TAG}` is the tag from above of the form `v4.X.0`
* **Gitpod/Codespaces**: Create a fresh one
This will update your game (and the mathlib version you might be using) to the new lean version.
## Newest developing setup ## Newest developing setup
There are a few files in your game repository which are used for the developing setup There are a few files in your game repository which are used for the developing setup
(dev container/codespaces/gitpod). If you need to update your developing setup, for example because it doesn't work (dev container/codespaces/gitpod). If you need to update your're developing setup, for example because it doesn't work
anymore, you will need to copy the relevant files from the [GameSkeleton](https://github.com/hhu-adam/GameSkeleton) template into your game repo. anymore, you will need to copy the relevant files from the [GameSkeleton](https://github.com/hhu-adam/GameSkeleton) template into your game repo.
The relevant files are: The relevant files are:
``` ```
.devcontainer/
.docker/
.github/
.gitpod/
.vscode/
lakefile.lean lakefile.lean
.devcontainer/**
.docker/**
.gitpod
.vscode/**
``` ```
simply copy them from the `GameSkeleton` into your game and proceed as above, simply copy them from the `GameSkeleton` into your game.
i.e. `lake update -R && lake build`.
(Note: You should not need to modify any of these files, with the exception of the `lakefile.lean`, (Note: You should not need to modify any of these files, with the exception of the `lakefile.lean`,
where you need to add any dependencies of your game, or remove mathlib if you don't need it.) where you need to add any dependencies of your game.)
+3 -5
View File
@@ -2,12 +2,10 @@
module.exports = { module.exports = {
apps : [{ apps : [{
name : "lean4game", name : "lean4game",
script : "relay/index.mjs", script : "server/index.mjs",
env: { env: {
LEAN4GAME_GITHUB_USER: "", NODE_ENV: "production",
LEAN4GAME_GITHUB_TOKEN: "", PORT: 8002
NODE_ENV: "production",
PORT: 8002
}, },
}] }]
} }
+1
View File
@@ -33,6 +33,7 @@
</p> </p>
</div> </div>
</noscript> </noscript>
<script src="coi-serviceworker.js"></script>
<script type="module" src="/client/src/index.tsx"></script> <script type="module" src="/client/src/index.tsx"></script>
</body> </body>
+2596 -1893
View File
File diff suppressed because it is too large Load Diff
+6 -12
View File
@@ -1,7 +1,6 @@
{ {
"name": "lean4-game", "name": "lean4-game",
"version": "0.1.0", "version": "0.1.0",
"type": "module",
"private": true, "private": true,
"homepage": ".", "homepage": ".",
"dependencies": { "dependencies": {
@@ -10,10 +9,6 @@
"@emotion/styled": "^11.10.5", "@emotion/styled": "^11.10.5",
"@fontsource/roboto": "^4.5.8", "@fontsource/roboto": "^4.5.8",
"@fontsource/roboto-mono": "^4.5.8", "@fontsource/roboto-mono": "^4.5.8",
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-regular-svg-icons": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/react-fontawesome": "^0.2.0",
"@leanprover/infoview": "^0.4.3", "@leanprover/infoview": "^0.4.3",
"@mui/icons-material": "^5.11.0", "@mui/icons-material": "^5.11.0",
"@mui/material": "^5.11.1", "@mui/material": "^5.11.1",
@@ -21,6 +16,7 @@
"@types/cytoscape": "^3.19.9", "@types/cytoscape": "^3.19.9",
"@types/react-router-dom": "^5.3.3", "@types/react-router-dom": "^5.3.3",
"@vitejs/plugin-react-swc": "^3.4.0", "@vitejs/plugin-react-swc": "^3.4.0",
"coi-serviceworker": "^0.1.7",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"cytoscape": "^3.23.0", "cytoscape": "^3.23.0",
"cytoscape-elk": "^2.1.0", "cytoscape-elk": "^2.1.0",
@@ -28,8 +24,8 @@
"debounce": "^1.2.1", "debounce": "^1.2.1",
"express": "^4.18.2", "express": "^4.18.2",
"lean4-infoview": "https://gitpkg.now.sh/leanprover/vscode-lean4/lean4-infoview?de0062c", "lean4-infoview": "https://gitpkg.now.sh/leanprover/vscode-lean4/lean4-infoview?de0062c",
"lean4web": "github:hhu-adam/lean4web#414d9e62638a392fca278761b4c61a1d2e138bc7", "lean4web": "github:hhu-adam/lean4web",
"octokit": "^3.1.2", "octokit": "^2.0.14",
"path-browserify": "^1.0.1", "path-browserify": "^1.0.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
@@ -41,7 +37,6 @@
"rehype-katex": "^6.0.2", "rehype-katex": "^6.0.2",
"remark-gfm": "^3.0.1", "remark-gfm": "^3.0.1",
"remark-math": "^5.1.1", "remark-math": "^5.1.1",
"request": "^2.88.2",
"request-progress": "^3.0.0", "request-progress": "^3.0.0",
"vite": "^4.5.0", "vite": "^4.5.0",
"vite-plugin-static-copy": "^0.17.0", "vite-plugin-static-copy": "^0.17.0",
@@ -58,7 +53,7 @@
"concurrently": "^7.6.0", "concurrently": "^7.6.0",
"css-loader": "^6.7.3", "css-loader": "^6.7.3",
"file-loader": "^6.2.0", "file-loader": "^6.2.0",
"nodemon": "^3.0.1", "nodemon": "^2.0.20",
"react-refresh": "^0.14.0", "react-refresh": "^0.14.0",
"style-loader": "^3.3.1", "style-loader": "^3.3.1",
"ts-loader": "^9.4.2", "ts-loader": "^9.4.2",
@@ -67,13 +62,12 @@
}, },
"scripts": { "scripts": {
"start": "concurrently -n server,client -c blue,green \"npm run start_server\" \"npm run start_client\"", "start": "concurrently -n server,client -c blue,green \"npm run start_server\" \"npm run start_client\"",
"start_server": "(cd server && lake build) && (cd relay && cross-env NODE_ENV=development nodemon -e mjs --exec \"node ./index.mjs\")", "start_server": "cd server && lake build && cross-env NODE_ENV=development nodemon -e mjs --exec \"node ./index.mjs\"",
"start_client": "cross-env NODE_ENV=development vite --host", "start_client": "cross-env NODE_ENV=development vite --host",
"build": "npm run build_server && npm run build_client", "build": "npm run build_server && npm run build_client",
"preview": "vite preview",
"build_server": "cd server && lake build", "build_server": "cd server && lake build",
"build_client": "cross-env NODE_ENV=production vite build", "build_client": "cross-env NODE_ENV=production vite build",
"production": "cross-env NODE_ENV=production node relay/index.mjs" "production": "cross-env NODE_ENV=production node server/index.mjs"
}, },
"eslintConfig": { "eslintConfig": {
"extends": [ "extends": [
-34
View File
@@ -1,34 +0,0 @@
#/bin/bash
ARTIFACT_ID=$1
OWNER=$2
REPO=$3
# mkdir -p games
cd games
# mkdir -p tmp
mkdir -p ${OWNER}
echo "Unpacking ZIP."
unzip -o tmp/${OWNER}_${REPO}_${ARTIFACT_ID}.zip -d tmp/${OWNER}_${REPO}_${ARTIFACT_ID}
echo "Unpacking game."
# exit the npm project to avoid reloading. TODO: Where should we actually save these?
echo "Delete old version of the game"
rm -rf ${OWNER}/${REPO}
mkdir -p ${OWNER}/${REPO}
for f in tmp/${OWNER}_${REPO}_${ARTIFACT_ID}/* #Should only be one file
do
echo "Unpacking $f"
#tar -xvzf $f -C games/${OWNER}/${REPO}
unzip -q -o $f -d ${OWNER}/${REPO}
done
# Delete temporary files
rm -f tmp/${OWNER}_${REPO}_${ARTIFACT_ID}.zip
rm -fr tmp/${OWNER}_${REPO}_${ARTIFACT_ID}
+3
View File
@@ -0,0 +1,3 @@
.lake
adam
lakefile32.olean
+8 -12
View File
@@ -1,17 +1,13 @@
import GameServer.FileWorker import Lean.Server.Watchdog
import GameServer.Commands import GameServer.Commands
import GameServer.Game
-- TODO: The only reason we import `Commands` is so that it gets built to on `lake build` Game "TestGame"
-- should we have a different solution? Title "Hello Test"
unsafe def main : List String → IO UInt32 := fun args => do World "Test"
let e ← IO.getStderr Level 1
Lean.enableInitializersExecution Statement : 1 = 1 := sorry
-- TODO: remove this argument MakeGame
if args[0]? == some "--server" then
GameServer.FileWorker.workerMain {} args
else
e.putStrLn s!"Expected `--server`"
return 1
+341 -199
View File
@@ -1,12 +1,23 @@
import GameServer.Helpers import GameServer.EnvExtensions
import GameServer.Inventory
import GameServer.Options
import GameServer.SaveData
open Lean Meta Elab Command open Lean Meta Elab Command
set_option autoImplicit false set_option autoImplicit false
/-- Let `MakeGame` print the reasons why the worlds depend on each other. -/
register_option lean4game.showDependencyReasons : Bool := {
defValue := false
descr := "show reasons for calculated world dependencies."
}
/-- Let `MakeGame` print the reasons why the worlds depend on each other.
Note: currently unused in favour of setting `set_option trace.debug true`. -/
register_option lean4game.verbose : Bool := {
defValue := false
descr := "display more info messages to help developing the game."
}
/-! # Game metadata -/ /-! # Game metadata -/
/-- Switch to the specified `Game` (and create it if non-existent). Example: `Game "NNG"` -/ /-- Switch to the specified `Game` (and create it if non-existent). Example: `Game "NNG"` -/
@@ -35,101 +46,147 @@ elab "Title" t:str : command => do
match ← getCurLayer with match ← getCurLayer with
| .Level => modifyCurLevel fun level => pure {level with title := t.getString} | .Level => modifyCurLevel fun level => pure {level with title := t.getString}
| .World => modifyCurWorld fun world => pure {world with title := t.getString} | .World => modifyCurWorld fun world => pure {world with title := t.getString}
| .Game => modifyCurGame fun game => pure {game with | .Game => modifyCurGame fun game => pure {game with title := t.getString}
title := t.getString
tile := {game.tile with title := t.getString}}
/-- Define the introduction of the current game/world/level. -/ /-- Define the introduction of the current game/world/level. -/
elab "Introduction" t:str : command => do elab "Introduction" t:str : command => do
let intro := t.getString
match ← getCurLayer with match ← getCurLayer with
| .Level => modifyCurLevel fun level => pure {level with introduction := intro} | .Level => modifyCurLevel fun level => pure {level with introduction := t.getString}
| .World => modifyCurWorld fun world => pure {world with introduction := intro} | .World => modifyCurWorld fun world => pure {world with introduction := t.getString}
| .Game => modifyCurGame fun game => pure {game with introduction := intro} | .Game => modifyCurGame fun game => pure {game with introduction := t.getString}
/-- Define the info of the current game. Used for e.g. credits -/ /-- Define the info of the current game. Used for e.g. credits -/
elab "Info" t:str : command => do elab "Info" t:str : command => do
let info:= t.getString
match ← getCurLayer with match ← getCurLayer with
| .Level => | .Level => pure ()
logError "Can't use `Info` in a level!" | .World => pure ()
pure () | .Game => modifyCurGame fun game => pure {game with info := t.getString}
| .World =>
logError "Can't use `Info` in a world"
pure ()
| .Game => modifyCurGame fun game => pure {game with info := info}
/-- Provide the location of the image for the current game/world/level.
Paths are relative to the lean project's root. -/
elab "Image" t:str : command => do
let file := t.getString
if not <| ← System.FilePath.pathExists file then
logWarningAt t s!"Make sure the cover image '{file}' exists."
if not <| file.startsWith "images/" then
logWarningAt t s!"The file name should start with `images/`. Make sure all images are in that folder."
match ← getCurLayer with
| .Level =>
logWarning "Level-images not implemented yet" -- TODO
modifyCurLevel fun level => pure {level with image := file}
| .World =>
modifyCurWorld fun world => pure {world with image := file}
| .Game =>
logWarning "Main image of the game not implemented yet" -- TODO
modifyCurGame fun game => pure {game with image := file}
/-- Define the conclusion of the current game or current level if some /-- Define the conclusion of the current game or current level if some
building a level. -/ building a level. -/
elab "Conclusion" t:str : command => do elab "Conclusion" t:str : command => do
let conclusion := t.getString
match ← getCurLayer with match ← getCurLayer with
| .Level => modifyCurLevel fun level => pure {level with conclusion := conclusion} | .Level => modifyCurLevel fun level => pure {level with conclusion := t.getString}
| .World => modifyCurWorld fun world => pure {world with conclusion := conclusion} | .World => modifyCurWorld fun world => pure {world with conclusion := t.getString}
| .Game => modifyCurGame fun game => pure {game with conclusion := conclusion} | .Game => modifyCurGame fun game => pure {game with conclusion := t.getString}
/-- A list of games that should be played before this one. Example `Prerequisites "NNG" "STG"`. -/
elab "Prerequisites" t:str* : command => do
modifyCurGame fun game => pure {game with
tile := {game.tile with prerequisites := t.map (·.getString) |>.toList}}
/-- Short caption for the game (1 sentence) -/
elab "CaptionShort" t:str : command => do
let caption := t.getString
modifyCurGame fun game => pure {game with
tile := {game.tile with short := caption}}
/-- More detailed description what the game is about (2-4 sentences). -/
elab "CaptionLong" t:str : command => do
let caption := t.getString
modifyCurGame fun game => pure {game with
tile := {game.tile with long := caption}}
/-- A list of Languages the game is translated to. For example `Languages "German" "English"`.
NOTE: For the time being, only a single language is supported.
-/
elab "Languages" t:str* : command => do
modifyCurGame fun game => pure {game with
tile := {game.tile with languages := t.map (·.getString) |>.toList}}
/-- The Image of the game (optional). TODO: Not impementeds -/
elab "CoverImage" t:str : command => do
let file := t.getString
if not <| ← System.FilePath.pathExists file then
logWarningAt t s!"Make sure the cover image '{file}' exists."
if not <| file.startsWith "images/" then
logWarningAt t s!"The file name should start with `images/`. Make sure all images are in that folder."
modifyCurGame fun game => pure {game with
tile := {game.tile with image := file}}
/-! # Inventory /-! # Inventory
The inventory contains docs for tactics, theorems, and definitions. These are all locked The inventory contains docs for tactics, lemmas, and definitions. These are all locked
in the first level and get enabled during the game. in the first level and get enabled during the game.
-/ -/
/-! ## Doc entries -/ /-! ## Doc entries -/
/-- Copied from `Mathlib.Tactic.HelpCmd`.
Gets the initial string token in a parser description. For example, for a declaration like
`syntax "bla" "baz" term : tactic`, it returns `some "bla"`. Returns `none` for syntax declarations
that don't start with a string constant. -/
partial def getHeadTk (e : Expr) : Option String :=
match (Expr.withApp e λ e a => (e.constName?.getD Name.anonymous, a)) with
| (``ParserDescr.node, #[_, _, p]) => getHeadTk p
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "withPosition")), p]) => getHeadTk p
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "atomic")), p]) => getHeadTk p
| (``ParserDescr.binary, #[.app _ (.lit (.strVal "andthen")), p, _]) => getHeadTk p
| (``ParserDescr.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk
| (``ParserDescr.symbol, #[.lit (.strVal tk)]) => some tk
| (``Parser.withAntiquot, #[_, p]) => getHeadTk p
| (``Parser.leadingNode, #[_, _, p]) => getHeadTk p
| (``HAndThen.hAndThen, #[_, _, _, _, p, _]) => getHeadTk p
| (``Parser.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk
| (``Parser.symbol, #[.lit (.strVal tk)]) => some tk
| _ => none
/-- Modified from `#help` in `Mathlib.Tactic.HelpCmd` -/
def getTacticDocstring (env : Environment) (name: Name) : CommandElabM (Option String) := do
let name := name.toString (escape := false)
let mut decls : Lean.RBMap String (Array SyntaxNodeKind) compare := {}
let catName : Name := `tactic
let catStx : Ident := mkIdent catName -- TODO
let some cat := (Parser.parserExtension.getState env).categories.find? catName
| throwErrorAt catStx "{catStx} is not a syntax category"
liftTermElabM <| Term.addCategoryInfo catStx catName
for (k, _) in cat.kinds do
let mut used := false
if let some tk := do getHeadTk (← (← env.find? k).value?) then
let tk := tk.trim
if name ≠ tk then -- was `!name.isPrefixOf tk`
continue
used := true
decls := decls.insert tk ((decls.findD tk #[]).push k)
for (_name, ks) in decls do
for k in ks do
if let some doc ← findDocString? env k then
return doc
logWarning <| m!"Could not find a docstring for tactic {name}, consider adding one " ++
m!"using `TacticDoc {name} \"some doc\"`"
return none
/-- Retrieve the docstring associated to an inventory item. For Tactics, this
is not guaranteed to work. -/
def getDocstring (env : Environment) (name : Name) (type : InventoryType) :
CommandElabM (Option String) :=
match type with
-- for tactics it's a lookup following mathlib's `#help`. not guaranteed to be the correct one.
| .Tactic => getTacticDocstring env name
| .Lemma => findDocString? env name
-- TODO: for definitions not implemented yet, does it work?
| .Definition => findDocString? env name
/-- Checks if `inventoryTemplateExt` contains an entry with `(type, name)` and yields
a warning otherwise. If `template` is provided, it will add such an entry instead of yielding a
warning.
`ref` is the syntax piece. If `name` is not provided, it will use `ident.getId`.
I used this workaround, because I needed a new name (with correct namespace etc)
to be used, and I don't know how to create a new ident with same position but different name.
-/
def checkInventoryDoc (type : InventoryType) (ref : Ident) (name : Name := ref.getId)
(template : Option String := none) : CommandElabM Unit := do
-- note: `name` is an `Ident` (instead of `Name`) for the log messages.
let env ← getEnv
let n := name
-- Find a key with matching `(type, name)`.
match (inventoryTemplateExt.getState env).findIdx?
(fun x => x.name == n && x.type == type) with
-- Nothing to do if the entry exists
| some _ => pure ()
| none =>
match template with
-- Warn about missing documentation
| none =>
let docstring ← match (← getDocstring env name type) with
| some ds =>
logInfoAt ref (m!"Missing {type} Documentation. Using existing docstring. " ++
m!"Add {name}\nAdd `{type}Doc {name}` somewhere above this statement.")
pure s!"*(lean docstring)*\\\n{ds}"
| none =>
logWarningAt ref (m!"Missing {type} Documentation: {name}\nAdd `{type}Doc {name}` " ++
m!"somewhere above this statement.")
pure "(missing)"
-- We just add a dummy entry
modifyEnv (inventoryTemplateExt.addEntry · {
type := type
name := name
category := if type == .Lemma then s!"{n.getPrefix}" else ""
content := docstring})
-- Add the default documentation
| some s =>
modifyEnv (inventoryTemplateExt.addEntry · {
type := type
name := name
category := if type == .Lemma then s!"{n.getPrefix}" else ""
content := s })
logInfoAt ref (m!"Missing {type} Documentation: {name}, used default (e.g. provided " ++
m!"docstring) instead. If you want to write a different description, add " ++
m!"`{type}Doc {name}` somewhere above this statement.")
/-- Documentation entry of a tactic. Example: /-- Documentation entry of a tactic. Example:
``` ```
@@ -139,40 +196,37 @@ TacticDoc rw "`rw` stands for rewrite, etc. "
* The identifier is the tactics name. Some need to be escaped like `«have»`. * The identifier is the tactics name. Some need to be escaped like `«have»`.
* The description is a string supporting Markdown. * The description is a string supporting Markdown.
-/ -/
elab doc:docComment ? "TacticDoc" name:ident content:str ? : command => do elab "TacticDoc" name:ident content:str : command =>
let doc ← parseDocCommentLegacy doc content
modifyEnv (inventoryTemplateExt.addEntry · { modifyEnv (inventoryTemplateExt.addEntry · {
type := .Tactic type := .Tactic
name := name.getId name := name.getId
displayName := name.getId.toString displayName := name.getId.toString
content := doc }) content := content.getString })
/-- Documentation entry of a theorem. Example: /-- Documentation entry of a lemma. Example:
``` ```
TheoremDoc Nat.succ_pos as "succ_pos" in "Nat" "says `0 < n.succ`, etc." LemmaDoc Nat.succ_pos as "succ_pos" in "Nat" "says `0 < n.succ`, etc."
``` ```
* The first identifier is used in the commands `[New/Only/Disabled]Theorem`. * The first identifier is used in the commands `[New/Only/Disabled]Lemma`.
It is preferably the true name of the theorem. However, this is not required. It is preferably the true name of the lemma. However, this is not required.
* The string following `as` is the displayed name (in the Inventory). * The string following `as` is the displayed name (in the Inventory).
* The identifier after `in` is the category to group theorems by (in the Inventory). * The identifier after `in` is the category to group lemmas by (in the Inventory).
* The description is a string supporting Markdown. * The description is a string supporting Markdown.
Use `[[mathlib_doc]]` in the string to insert a link to the mathlib doc page. This requires Use `[[mathlib_doc]]` in the string to insert a link to the mathlib doc page. This requires
The theorem/definition to have the same fully qualified name as in mathlib. The lemma/definition to have the same fully qualified name as in mathlib.
-/ -/
elab doc:docComment ? "TheoremDoc" name:ident "as" displayName:str "in" category:str content:str ? : elab "LemmaDoc" name:ident "as" displayName:str "in" category:str content:str : command =>
command => do
let doc ← parseDocCommentLegacy doc content
modifyEnv (inventoryTemplateExt.addEntry · { modifyEnv (inventoryTemplateExt.addEntry · {
type := .Lemma type := .Lemma
name := name.getId name := name.getId
category := category.getString category := category.getString
displayName := displayName.getString displayName := displayName.getString
content := doc }) content := content.getString })
-- TODO: Catch the following behaviour. -- TODO: Catch the following behaviour.
-- 1. if `TheoremDoc` appears in the same file as `Statement`, it will silently use -- 1. if `LemmaDoc` appears in the same file as `Statement`, it will silently use
-- it but display the info that it wasn't found in `Statement` -- it but display the info that it wasn't found in `Statement`
-- 2. if it appears in a later file, however, it will silently not do anything and keep -- 2. if it appears in a later file, however, it will silently not do anything and keep
-- the first one. -- the first one.
@@ -190,25 +244,37 @@ DefinitionDoc Function.Bijective as "Bijective" "defined as `Injective f ∧ Sur
* The description is a string supporting Markdown. * The description is a string supporting Markdown.
Use `[[mathlib_doc]]` in the string to insert a link to the mathlib doc page. This requires Use `[[mathlib_doc]]` in the string to insert a link to the mathlib doc page. This requires
The theorem/definition to have the same fully qualified name as in mathlib. The lemma/definition to have the same fully qualified name as in mathlib.
-/ -/
elab doc:docComment ? "DefinitionDoc" name:ident "as" displayName:str template:str ? : command => do elab "DefinitionDoc" name:ident "as" displayName:str template:str : command =>
let doc ← parseDocCommentLegacy doc template
modifyEnv (inventoryTemplateExt.addEntry · { modifyEnv (inventoryTemplateExt.addEntry · {
type := .Definition type := .Definition
name := name.getId, name := name.getId,
displayName := displayName.getString, displayName := displayName.getString,
content := doc }) content := template.getString })
/-! ## Add inventory items -/ /-! ## Add inventory items -/
def checkCommandNotDuplicated (items : Array Name) (cmd := "Command") : CommandElabM Unit := do def getStatement (name : Name) : CommandElabM MessageData := do
if ¬ items.isEmpty then return ← addMessageContextPartial (.ofPPFormat { pp := fun
logWarning s!"You should only use one `{cmd}` per level, but it takes multiple arguments: `{cmd} obj₁ obj₂ obj₃`!" | some ctx => ctx.runMetaM <| PrettyPrinter.ppSignature name
| none => return "that's a bug." })
-- Note: We use `String` because we can't send `MessageData` as json, but
-- `MessageData` might be better for interactive highlighting.
/-- Get a string of the form `my_lemma (n : ℕ) : n + n = 2 * n`.
Note: A statement like `theorem abc : ∀ x : Nat, x ≥ 0` would be turned into
`theorem abc (x : Nat) : x ≥ 0` by `PrettyPrinter.ppSignature`. -/
def getStatementString (name : Name) : CommandElabM String := do
try
return ← (← getStatement name).toString
catch
| _ => throwError m!"Could not find {name} in context."
-- TODO: I think it would be nicer to unresolve Namespaces as much as possible.
/-- Declare tactics that are introduced by this level. -/ /-- Declare tactics that are introduced by this level. -/
elab "NewTactic" args:ident* : command => do elab "NewTactic" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).tactics.new) "NewTactic"
for name in ↑args do for name in ↑args do
checkInventoryDoc .Tactic name -- TODO: Add (template := "[docstring]") checkInventoryDoc .Tactic name -- TODO: Add (template := "[docstring]")
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
@@ -216,16 +282,14 @@ elab "NewTactic" args:ident* : command => do
/-- Declare tactics that are introduced by this level but do not show up in inventory. -/ /-- Declare tactics that are introduced by this level but do not show up in inventory. -/
elab "NewHiddenTactic" args:ident* : command => do elab "NewHiddenTactic" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).tactics.hidden) "NewHiddenTactic"
for name in ↑args do for name in ↑args do
checkInventoryDoc .Tactic name (template := "") checkInventoryDoc .Tactic name (template := "")
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
tactics := {level.tactics with new := level.tactics.new ++ args.map (·.getId), tactics := {level.tactics with new := level.tactics.new ++ args.map (·.getId),
hidden := level.tactics.hidden ++ args.map (·.getId)}} hidden := level.tactics.hidden ++ args.map (·.getId)}}
/-- Declare theorems that are introduced by this level. -/ /-- Declare lemmas that are introduced by this level. -/
elab "NewTheorem" args:ident* : command => do elab "NewLemma" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).lemmas.new) "NewTheorem"
for name in ↑args do for name in ↑args do
try let _decl ← getConstInfo name.getId catch try let _decl ← getConstInfo name.getId catch
| _ => logErrorAt name m!"unknown identifier '{name}'." | _ => logErrorAt name m!"unknown identifier '{name}'."
@@ -235,7 +299,6 @@ elab "NewTheorem" args:ident* : command => do
/-- Declare definitions that are introduced by this level. -/ /-- Declare definitions that are introduced by this level. -/
elab "NewDefinition" args:ident* : command => do elab "NewDefinition" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).definitions.new) "NewDefinition"
for name in ↑args do checkInventoryDoc .Definition name -- TODO: Add (template := "[mathlib]") for name in ↑args do checkInventoryDoc .Definition name -- TODO: Add (template := "[mathlib]")
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
definitions := {level.definitions with new := args.map (·.getId)}} definitions := {level.definitions with new := args.map (·.getId)}}
@@ -243,36 +306,31 @@ elab "NewDefinition" args:ident* : command => do
/-- Declare tactics that are temporarily disabled in this level. /-- Declare tactics that are temporarily disabled in this level.
This is ignored if `OnlyTactic` is set. -/ This is ignored if `OnlyTactic` is set. -/
elab "DisabledTactic" args:ident* : command => do elab "DisabledTactic" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).tactics.disabled) "DisabledTactic"
for name in ↑args do checkInventoryDoc .Tactic name for name in ↑args do checkInventoryDoc .Tactic name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
tactics := {level.tactics with disabled := args.map (·.getId)}} tactics := {level.tactics with disabled := args.map (·.getId)}}
/-- Declare theorems that are temporarily disabled in this level. /-- Declare lemmas that are temporarily disabled in this level.
This is ignored if `OnlyTheorem` is set. -/ This is ignored if `OnlyLemma` is set. -/
elab "DisabledTheorem" args:ident* : command => do elab "DisabledLemma" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).lemmas.disabled) "DisabledTheorem"
for name in ↑args do checkInventoryDoc .Lemma name for name in ↑args do checkInventoryDoc .Lemma name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
lemmas := {level.lemmas with disabled := args.map (·.getId)}} lemmas := {level.lemmas with disabled := args.map (·.getId)}}
/-- Declare definitions that are temporarily disabled in this level -/ /-- Declare definitions that are temporarily disabled in this level -/
elab "DisabledDefinition" args:ident* : command => do elab "DisabledDefinition" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).definitions.disabled) "DisabledDefinition"
for name in ↑args do checkInventoryDoc .Definition name for name in ↑args do checkInventoryDoc .Definition name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
definitions := {level.definitions with disabled := args.map (·.getId)}} definitions := {level.definitions with disabled := args.map (·.getId)}}
/-- Temporarily disable all tactics except the ones declared here -/ /-- Temporarily disable all tactics except the ones declared here -/
elab "OnlyTactic" args:ident* : command => do elab "OnlyTactic" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).tactics.only) "OnlyTactic"
for name in ↑args do checkInventoryDoc .Tactic name for name in ↑args do checkInventoryDoc .Tactic name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
tactics := {level.tactics with only := args.map (·.getId)}} tactics := {level.tactics with only := args.map (·.getId)}}
/-- Temporarily disable all theorems except the ones declared here -/ /-- Temporarily disable all lemmas except the ones declared here -/
elab "OnlyTheorem" args:ident* : command => do elab "OnlyLemma" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).lemmas.only) "OnlyTheorem"
for name in ↑args do checkInventoryDoc .Lemma name for name in ↑args do checkInventoryDoc .Lemma name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
lemmas := {level.lemmas with only := args.map (·.getId)}} lemmas := {level.lemmas with only := args.map (·.getId)}}
@@ -280,66 +338,65 @@ elab "OnlyTheorem" args:ident* : command => do
/-- Temporarily disable all definitions except the ones declared here. /-- Temporarily disable all definitions except the ones declared here.
This is ignored if `OnlyDefinition` is set. -/ This is ignored if `OnlyDefinition` is set. -/
elab "OnlyDefinition" args:ident* : command => do elab "OnlyDefinition" args:ident* : command => do
checkCommandNotDuplicated ((←getCurLevel).definitions.only) "OnlyDefinition"
for name in ↑args do checkInventoryDoc .Definition name for name in ↑args do checkInventoryDoc .Definition name
modifyCurLevel fun level => pure {level with modifyCurLevel fun level => pure {level with
definitions := {level.definitions with only := args.map (·.getId)}} definitions := {level.definitions with only := args.map (·.getId)}}
/-- Define which tab of Lemmas is opened by default. Usage: `TheoremTab "Nat"`. /-- Define which tab of Lemmas is opened by default. Usage: `LemmaTab "Nat"`.
If omitted, the current tab will remain open. -/ If omitted, the current tab will remain open. -/
elab "TheoremTab" category:str : command => elab "LemmaTab" category:str : command =>
modifyCurLevel fun level => pure {level with lemmaTab := category.getString}
/-! DEPRECATED -/
elab doc:docComment ? "LemmaDoc" name:ident "as" displayName:str "in" category:str content:str ? :
command => do
logWarning "Deprecated. Has been renamed to `TheoremDoc`"
let doc ← parseDocCommentLegacy doc content
modifyEnv (inventoryTemplateExt.addEntry · {
type := .Lemma
name := name.getId
category := category.getString
displayName := displayName.getString
content := doc })
elab "NewLemma" args:ident* : command => do
logWarning "Deprecated. Has been renamed to `NewTheorem`"
checkCommandNotDuplicated ((←getCurLevel).lemmas.new) "NewLemma"
for name in ↑args do
try let _decl ← getConstInfo name.getId catch
| _ => logErrorAt name m!"unknown identifier '{name}'."
checkInventoryDoc .Lemma name -- TODO: Add (template := "[mathlib]")
modifyCurLevel fun level => pure {level with
lemmas := {level.lemmas with new := args.map (·.getId)}}
elab "DisabledLemma" args:ident* : command => do
logWarning "Deprecated. Has been renamed to `DisabledTheorem`"
checkCommandNotDuplicated ((←getCurLevel).lemmas.disabled) "DisabledLemma"
for name in ↑args do checkInventoryDoc .Lemma name
modifyCurLevel fun level => pure {level with
lemmas := {level.lemmas with disabled := args.map (·.getId)}}
elab "OnlyLemma" args:ident* : command => do
logWarning "Deprecated. Has been renamed to `OnlyTheorem`"
checkCommandNotDuplicated ((←getCurLevel).lemmas.only) "OnlyLemma"
for name in ↑args do checkInventoryDoc .Lemma name
modifyCurLevel fun level => pure {level with
lemmas := {level.lemmas with only := args.map (·.getId)}}
elab "LemmaTab" category:str : command => do
logWarning "Deprecated. Has been renamed to `TheoremTab`"
modifyCurLevel fun level => pure {level with lemmaTab := category.getString} modifyCurLevel fun level => pure {level with lemmaTab := category.getString}
/-! # Exercise Statement -/ /-! # Exercise Statement -/
/-- A `attr := ...` option for `Statement`. Add attributes to the defined theorem. -/
syntax statementAttr := "(" &"attr" ":=" Parser.Term.attrInstance,* ")"
-- TODO
-- TODO: Reuse the following code for checking available tactics in user code:
structure UsedInventory where
(tactics : HashSet Name := {})
(definitions : HashSet Name := {})
(lemmas : HashSet Name := {})
partial def collectUsedInventory (stx : Syntax) (acc : UsedInventory := {}) : CommandElabM UsedInventory := do
match stx with
| .missing => return acc
| .node _info kind args =>
if kind == `GameServer.Tactic.Hint || kind == `GameServer.Tactic.Branch then return acc
return ← args.foldlM (fun acc arg => collectUsedInventory arg acc) acc
| .atom _info val =>
-- ignore syntax elements that do not start with a letter
-- and ignore some standard keywords
let allowed := ["with", "fun", "at", "only", "by"]
if 0 < val.length ∧ val.data[0]!.isAlpha ∧ not (allowed.contains val) then
let val := val.dropRightWhile (fun c => c == '!' || c == '?') -- treat `simp?` and `simp!` like `simp`
return {acc with tactics := acc.tactics.insert val}
else
return acc
| .ident _info _rawVal val _preresolved =>
let ns ←
try resolveGlobalConst (mkIdent val)
catch | _ => pure [] -- catch "unknown constant" error
return ← ns.foldlM (fun acc n => do
if let some (.thmInfo ..) := (← getEnv).find? n then
return {acc with lemmas := acc.lemmas.insertMany ns}
else
return {acc with definitions := acc.definitions.insertMany ns}
) acc
-- #check expandOptDocComment?
/-- Define the statement of the current level. -/ /-- Define the statement of the current level. -/
elab doc:docComment ? attrs:Parser.Term.attributes ? elab doc:docComment ? attrs:Parser.Term.attributes ?
"Statement" statementName:ident ? sig:declSig val:declVal : command => do "Statement" statementName:ident ? sig:declSig val:declVal : command => do
let lvlIdx ← getCurLevelIdx let lvlIdx ← getCurLevelIdx
let docContent ← parseDocComment doc let docContent : Option String := match doc with
| none => none
| some s => match s.raw[1] with
| .atom _ val => val.dropRight 2 |>.trim -- some (val.extract 0 (val.endPos - ⟨2⟩))
| _ => none --panic "not implemented error message" --throwErrorAt s "unexpected doc string{indentD s.raw[1]}"
-- Save the messages before evaluation of the proof. -- Save the messages before evaluation of the proof.
let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} }) let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} })
@@ -440,6 +497,23 @@ elab doc:docComment ? attrs:Parser.Term.attributes ?
/-! # Hints -/ /-! # Hints -/
syntax hintArg := atomic(" (" (&"strict" <|> &"hidden") " := " withoutPosition(term) ")")
/-- Remove any spaces at the beginning of a new line -/
partial def removeIndentation (s : String) : String :=
let rec loop (i : String.Pos) (acc : String) (removeSpaces := false) : String :=
let c := s.get i
let i := s.next i
if s.atEnd i then
acc.push c
else if removeSpaces && c == ' ' then
loop i acc (removeSpaces := true)
else if c == '\n' then
loop i (acc.push c) (removeSpaces := true)
else
loop i (acc.push c)
loop ⟨0⟩ ""
/-- A tactic that can be used inside `Statement`s to indicate in which proof states players should /-- A tactic that can be used inside `Statement`s to indicate in which proof states players should
see hints. The tactic does not affect the goal state. see hints. The tactic does not affect the goal state.
-/ -/
@@ -552,7 +626,6 @@ elab "Template" tacs:tacticSeq : tactic => do
modifyLevel (←getCurLevelId) fun level => do modifyLevel (←getCurLevelId) fun level => do
return {level with template := s!"{template}"} return {level with template := s!"{template}"}
-- TODO: Notes for testing if a declaration has the simp attribute -- TODO: Notes for testing if a declaration has the simp attribute
-- -- Test: From zulip -- -- Test: From zulip
@@ -571,6 +644,98 @@ elab "Template" tacs:tacticSeq : tactic => do
/-! # Make Game -/ /-! # Make Game -/
def GameLevel.getInventory (level : GameLevel) : InventoryType → InventoryInfo
| .Tactic => level.tactics
| .Definition => level.definitions
| .Lemma => level.lemmas
def GameLevel.setComputedInventory (level : GameLevel) :
InventoryType → Array InventoryTile → GameLevel
| .Tactic, v => {level with tactics := {level.tactics with tiles := v}}
| .Definition, v => {level with definitions := {level.definitions with tiles := v}}
| .Lemma, v => {level with lemmas := {level.lemmas with tiles := v}}
partial def removeTransitiveAux (id : Name) (arrows : HashMap Name (HashSet Name))
(newArrows : HashMap Name (HashSet Name)) (decendants : HashMap Name (HashSet Name)) :
HashMap Name (HashSet Name) × HashMap Name (HashSet Name) := Id.run do
match (newArrows.find? id, decendants.find? id) with
| (some _, some _) => return (newArrows, decendants)
| _ =>
let mut newArr := newArrows
let mut desc := decendants
desc := desc.insert id {} -- mark as worked in case of loops
newArr := newArr.insert id {} -- mark as worked in case of loops
let children := arrows.findD id {}
let mut trimmedChildren := children
let mut theseDescs := children
for child in children do
(newArr, desc) := removeTransitiveAux child arrows newArr desc
let childDescs := desc.findD child {}
theseDescs := theseDescs.insertMany childDescs
for d in childDescs do
trimmedChildren := trimmedChildren.erase d
desc := desc.insert id theseDescs
newArr := newArr.insert id trimmedChildren
return (newArr, desc)
def removeTransitive (arrows : HashMap Name (HashSet Name)) : CommandElabM (HashMap Name (HashSet Name)) := do
let mut newArr := {}
let mut desc := {}
for id in arrows.toArray.map Prod.fst do
(newArr, desc) := removeTransitiveAux id arrows newArr desc
if (desc.findD id {}).contains id then
logError <| m!"Loop at {id}. " ++
m!"This should not happen and probably means that `findLoops` has a bug."
-- DEBUG:
-- for ⟨x, hx⟩ in desc.toList do
-- m := m ++ m!"{x}: {hx.toList}\n"
-- logError m
return newArr
/-- The recursive part of `findLoops`. Finds loops that appear as successors of `node`.
For performance reason it returns a HashSet of visited
nodes as well. This is filled with all nodes ever looked at as they cannot be
part of a loop anymore. -/
partial def findLoopsAux (arrows : HashMap Name (HashSet Name)) (node : Name)
(path : Array Name := #[]) (visited : HashSet Name := {}) :
Array Name × HashSet Name := Id.run do
let mut visited := visited
match path.getIdx? node with
| some i =>
-- Found a loop: `node` is already the iᵗʰ element of the path
return (path.extract i path.size, visited.insert node)
| none =>
for successor in arrows.findD node {} do
-- If we already visited the successor, it cannot be part of a loop anymore
if visited.contains successor then
continue
-- Find any loop involving `successor`
let (loop, _) := findLoopsAux arrows successor (path.push node) visited
visited := visited.insert successor
-- No loop found in the dependants of `successor`
if loop.isEmpty then
continue
-- Found a loop, return it
return (loop, visited)
return (#[], visited.insert node)
/-- Find a loop in the graph and return it. Returns `[]` if there are no loops. -/
partial def findLoops (arrows : HashMap Name (HashSet Name)) : List Name := Id.run do
let mut visited : HashSet Name := {}
for node in arrows.toArray.map (·.1) do
-- Skip a node if it was already visited
if visited.contains node then
continue
-- `findLoopsAux` returns a loop or `[]` together with a set of nodes it visited on its
-- search starting from `node`
let (loop, moreVisited) := (findLoopsAux arrows node (visited := visited))
visited := moreVisited
if !loop.isEmpty then
return loop.toList
return []
/-- The worlds of a game are joint by dependencies. These are /-- The worlds of a game are joint by dependencies. These are
automatically computed but can also be defined with the syntax automatically computed but can also be defined with the syntax
`Dependency World₁ → World₂ → World₃`. -/ `Dependency World₁ → World₂ → World₃`. -/
@@ -645,12 +810,8 @@ elab "MakeGame" : command => do
-- Items that should not be displayed in inventory -- Items that should not be displayed in inventory
let mut hiddenItems : HashSet Name := {} let mut hiddenItems : HashSet Name := {}
let allWorlds := game.worlds.nodes.toArray
let nrWorlds := allWorlds.size
let mut nrLevels := 0
-- Calculate which "items" are used/new in which world -- Calculate which "items" are used/new in which world
for (worldId, world) in allWorlds do for (worldId, world) in game.worlds.nodes.toArray do
let mut usedItems : HashSet Name := {} let mut usedItems : HashSet Name := {}
let mut newItems : HashSet Name := {} let mut newItems : HashSet Name := {}
for inventoryType in #[.Tactic, .Definition, .Lemma] do for inventoryType in #[.Tactic, .Definition, .Lemma] do
@@ -689,12 +850,9 @@ elab "MakeGame" : command => do
-- logInfo m!"{worldId} uses: {usedItems.toList}" -- logInfo m!"{worldId} uses: {usedItems.toList}"
-- logInfo m!"{worldId} introduces: {newItems.toList}" -- logInfo m!"{worldId} introduces: {newItems.toList}"
-- Moreover, count the number of levels in the game
nrLevels := nrLevels + world.levels.toArray.size
/- for each "item" this is a HashSet of `worldId`s that introduce this item -/ /- for each "item" this is a HashSet of `worldId`s that introduce this item -/
let mut worldsWithNewItem : HashMap Name (HashSet Name) := {} let mut worldsWithNewItem : HashMap Name (HashSet Name) := {}
for (worldId, _world) in allWorlds do for (worldId, _world) in game.worlds.nodes.toArray do
for newItem in newItemsInWorld.findD worldId {} do for newItem in newItemsInWorld.findD worldId {} do
worldsWithNewItem := worldsWithNewItem.insert newItem $ worldsWithNewItem := worldsWithNewItem.insert newItem $
(worldsWithNewItem.findD newItem {}).insert worldId (worldsWithNewItem.findD newItem {}).insert worldId
@@ -706,7 +864,7 @@ elab "MakeGame" : command => do
let mut dependencyReasons : HashMap (Name × Name) (HashSet Name) := {} let mut dependencyReasons : HashMap (Name × Name) (HashSet Name) := {}
-- Calculate world dependency graph `game.worlds` -- Calculate world dependency graph `game.worlds`
for (dependentWorldId, _dependentWorld) in allWorlds do for (dependentWorldId, _dependentWorld) in game.worlds.nodes.toArray do
let mut dependsOnWorlds : HashSet Name := {} let mut dependsOnWorlds : HashSet Name := {}
-- Adding manual dependencies that were specified via the `Dependency` command. -- Adding manual dependencies that were specified via the `Dependency` command.
for (sourceId, targetId) in game.worlds.edges do for (sourceId, targetId) in game.worlds.edges do
@@ -757,25 +915,14 @@ elab "MakeGame" : command => do
logError m!"{w1} depends on {w2} because of {items.toList}." logError m!"{w1} depends on {w2} because of {items.toList}."
else else
worldDependsOnWorlds ← removeTransitive worldDependsOnWorlds worldDependsOnWorlds ← removeTransitive worldDependsOnWorlds
-- need to delete all existing edges as they are already present in `worldDependsOnWorlds`.
modifyCurGame fun game =>
pure {game with worlds := {game.worlds with edges := Array.empty}}
for (dependentWorldId, worldIds) in worldDependsOnWorlds.toArray do for (dependentWorldId, worldIds) in worldDependsOnWorlds.toArray do
modifyCurGame fun game => modifyCurGame fun game =>
pure {game with worlds := {game.worlds with pure {game with worlds := {game.worlds with
edges := game.worlds.edges.append (worldIds.toArray.map fun wid => (wid, dependentWorldId))}} edges := game.worlds.edges.append (worldIds.toArray.map fun wid => (wid, dependentWorldId))}}
-- Add the number of levels and worlds to the tile for the landing page
modifyCurGame fun game => pure {game with tile := {game.tile with
levels := nrLevels
worlds := nrWorlds }}
-- Apparently we need to reload `game` to get the changes to `game.worlds` we just made -- Apparently we need to reload `game` to get the changes to `game.worlds` we just made
let game ← getCurGame let game ← getCurGame
let mut allItemsByType : HashMap InventoryType (HashSet Name) := {}
-- Compute which inventory items are available in which level: -- Compute which inventory items are available in which level:
for inventoryType in #[.Tactic, .Definition, .Lemma] do for inventoryType in #[.Tactic, .Definition, .Lemma] do
@@ -837,7 +984,6 @@ elab "MakeGame" : command => do
name := item name := item
displayName := data.displayName displayName := data.displayName
category := data.category category := data.category
altTitle := data.statement
hidden := hiddenItems.contains item }) hidden := hiddenItems.contains item })
@@ -857,7 +1003,6 @@ elab "MakeGame" : command => do
displayName := data.displayName displayName := data.displayName
category := data.category category := data.category
locked := false locked := false
altTitle := data.statement
hidden := hiddenItems.contains item } hidden := hiddenItems.contains item }
itemsInWorld := itemsInWorld.insert worldId items itemsInWorld := itemsInWorld.insert worldId items
@@ -877,8 +1022,7 @@ elab "MakeGame" : command => do
displayName := data.displayName displayName := data.displayName
category := data.category category := data.category
locked := false locked := false
altTitle := data.statement hidden := levelInfo.hidden.contains item }
hidden := hiddenItems.contains item }
-- add the exercise statement from the previous level -- add the exercise statement from the previous level
-- if it was named -- if it was named
@@ -891,7 +1035,6 @@ elab "MakeGame" : command => do
name := name name := name
displayName := data.displayName displayName := data.displayName
category := data.category category := data.category
altTitle := data.statement
locked := false } locked := false }
-- add marks for `disabled` and `new` lemmas here, so that they only apply to -- add marks for `disabled` and `new` lemmas here, so that they only apply to
@@ -909,18 +1052,17 @@ elab "MakeGame" : command => do
modifyLevel ⟨← getCurGameId, worldId, levelId⟩ fun level => do modifyLevel ⟨← getCurGameId, worldId, levelId⟩ fun level => do
return level.setComputedInventory inventoryType itemsArray return level.setComputedInventory inventoryType itemsArray
allItemsByType := allItemsByType.insert inventoryType allItems
let getTiles (type : InventoryType) : CommandElabM (Array InventoryTile) := do /-! # Debugging tools -/
(allItemsByType.findD type {}).toArray.mapM (fun name => do
let some item ← getInventoryItem? name type
| throwError "Expected item to exist: {name}"
return item.toTile)
let inventory : InventoryOverview := {
lemmas := (← getTiles .Lemma).map (fun tile => {tile with hidden := hiddenItems.contains tile.name})
tactics := (← getTiles .Tactic).map (fun tile => {tile with hidden := hiddenItems.contains tile.name})
definitions := (← getTiles .Definition).map (fun tile => {tile with hidden := hiddenItems.contains tile.name})
lemmaTab := none
}
saveGameData allItemsByType inventory -- /-- Print current game for debugging purposes. -/
-- elab "PrintCurGame" : command => do
-- logInfo (toJson (← getCurGame))
/-- Print current level for debugging purposes. -/
elab "PrintCurLevel" : command => do
logInfo (repr (← getCurLevel))
/-- Print levels for debugging purposes. -/
elab "PrintLevels" : command => do
logInfo $ repr $ (← getCurWorld).levels.toArray
+3 -117
View File
@@ -106,16 +106,8 @@ structure InventoryTile where
new := false new := false
/-- hide the item in the inventory display -/ /-- hide the item in the inventory display -/
hidden := false hidden := false
/-- hover text -/
altTitle : String := default
deriving ToJson, FromJson, Repr, Inhabited deriving ToJson, FromJson, Repr, Inhabited
def InventoryItem.toTile (item : InventoryItem) : InventoryTile := {
name := item.name,
displayName := item.displayName
category := item.category
}
/-- The extension that stores the doc templates. Note that you can only add, but never modify /-- The extension that stores the doc templates. Note that you can only add, but never modify
entries! -/ entries! -/
initialize inventoryTemplateExt : initialize inventoryTemplateExt :
@@ -143,18 +135,7 @@ def getInventoryItem? [Monad m] [MonadEnv m] (n : Name) (type : InventoryType) :
m (Option InventoryItem) := do m (Option InventoryItem) := do
return (inventoryExt.getState (← getEnv)).find? (fun x => x.name == n && x.type == type) return (inventoryExt.getState (← getEnv)).find? (fun x => x.name == n && x.type == type)
structure InventoryOverview where
tactics : Array InventoryTile
lemmas : Array InventoryTile
definitions : Array InventoryTile
lemmaTab : Option String
deriving ToJson, FromJson
-- TODO: Reuse the following code for checking available tactics in user code:
structure UsedInventory where
(tactics : HashSet Name := {})
(definitions : HashSet Name := {})
(lemmas : HashSet Name := {})
/-! ## Environment extensions for game specification -/ /-! ## Environment extensions for game specification -/
@@ -273,63 +254,8 @@ structure GameLevel where
lemmas: InventoryInfo := default lemmas: InventoryInfo := default
/-- A proof template that is printed in an empty editor. -/ /-- A proof template that is printed in an empty editor. -/
template: Option String := none template: Option String := none
/-- The image for this level. -/ deriving Inhabited, Repr
image : String := default
deriving Inhabited, Repr
/-- Json-encodable version of `GameLevel`
Fields:
- description: Lemma in mathematical language.
- descriptionGoal: Lemma printed as Lean-Code.
-/
structure LevelInfo where
index : Nat
title : String
tactics : Array InventoryTile
lemmas : Array InventoryTile
definitions : Array InventoryTile
introduction : String
conclusion : String
descrText : Option String := none
descrFormat : String := ""
lemmaTab : Option String
module : Name
displayName : Option String
statementName : Option String
template : Option String
image: Option String
deriving ToJson, FromJson
def GameLevel.toInfo (lvl : GameLevel) (env : Environment) : LevelInfo :=
{ index := lvl.index,
title := lvl.title,
tactics := lvl.tactics.tiles,
lemmas := lvl.lemmas.tiles,
definitions := lvl.definitions.tiles,
descrText := lvl.descrText,
descrFormat := lvl.descrFormat --toExpr <| format (lvl.goal.raw) --toString <| Syntax.formatStx (lvl.goal.raw) --Syntax.formatStx (lvl.goal.raw) , -- TODO
introduction := lvl.introduction
conclusion := lvl.conclusion
lemmaTab := match lvl.lemmaTab with
| some tab => tab
| none =>
-- Try to set the lemma tab to the category of the first added lemma
match lvl.lemmas.tiles.find? (·.new) with
| some tile => tile.category
| none => none
statementName := lvl.statementName.toString
module := lvl.module
displayName := match lvl.statementName with
| .anonymous => none
| name => match (inventoryExt.getState env).find?
(fun x => x.name == name && x.type == .Lemma) with
| some n => n.displayName
| none => name.toString
-- Note: we could call `.find!` because we check in `Statement` that the
-- lemma doc must exist.
template := lvl.template
image := lvl.image
}
/-! ## World -/ /-! ## World -/
@@ -345,46 +271,17 @@ structure World where
conclusion : String := default conclusion : String := default
/-- The levels of the world. -/ /-- The levels of the world. -/
levels: HashMap Nat GameLevel := default levels: HashMap Nat GameLevel := default
/-- The introduction image of the world. -/
image: String := default
deriving Inhabited deriving Inhabited
instance : ToJson World := ⟨ instance : ToJson World := ⟨
fun world => Json.mkObj [ fun world => Json.mkObj [
("name", toJson world.name), ("name", toJson world.name),
("title", world.title), ("title", world.title),
("introduction", world.introduction), ("introduction", world.introduction)]
("image", world.image)]
⟩ ⟩
/-! ## Game -/ /-! ## Game -/
/-- A tile as they are displayed on the servers landing page. -/
structure GameTile where
/-- The title of the game -/
title: String
/-- One catch phrase about the game -/
short: String := default
/-- One paragraph description what the game is about -/
long: String := default
/-- List of languages the game supports
TODO: What's the expectected format
TODO: Must be a list with a single language currently
-/
languages: List String := default
/-- A list of games which this one builds upon -/
prerequisites: List String := default
/-- Number of worlds in the game -/
worlds: Nat := default
/-- Number of levels in the game -/
levels: Nat := default
/-- A cover image of the game
TODO: What's the format? -/
image: String := default
deriving Inhabited, ToJson, FromJson
structure Game where structure Game where
/-- Internal name of the game. -/ /-- Internal name of the game. -/
name : Name name : Name
@@ -399,18 +296,7 @@ structure Game where
/-- TODO: currently unused. -/ /-- TODO: currently unused. -/
authors : List String := default authors : List String := default
worlds : Graph Name World := default worlds : Graph Name World := default
/-- The tile displayed on the server's landing page. -/ deriving Inhabited, ToJson
tile : GameTile := default
/-- The path to the background image of the world. -/
image : String := default
deriving Inhabited, ToJson, FromJson
def getGameJson (game : «Game») : Json := Id.run do
let gameJson : Json := toJson game
-- Add world sizes to Json object
let worldSize := game.worlds.nodes.toList.map (fun (n, w) => (n.toString, w.levels.size))
let gameJson := gameJson.mergeObj (Json.mkObj [("worldSize", Json.mkObj worldSize)])
return gameJson
/-! ## Game environment extension -/ /-! ## Game environment extension -/
+282 -390
View File
@@ -1,11 +1,8 @@
/- This file is adapted from `Lean/Server/FileWorker.lean`. -/ /- This file is mostly copied from `Lean/Server/FileWorker.lean`. -/
import Lean.Server.FileWorker import Lean.Server.FileWorker
import GameServer.Game import GameServer.Game
import GameServer.ImportModules
import GameServer.SaveData
namespace MyModule namespace MyModule
open Lean open Lean
open Elab open Elab
open Parser open Parser
@@ -19,7 +16,7 @@ private def mkEOI (pos : String.Pos) : Syntax :=
mkNode ``Command.eoi #[atom] mkNode ``Command.eoi #[atom]
partial def parseTactic (inputCtx : InputContext) (pmctx : ParserModuleContext) partial def parseTactic (inputCtx : InputContext) (pmctx : ParserModuleContext)
(mps : ModuleParserState) (messages : MessageLog) : (mps : ModuleParserState) (messages : MessageLog) (couldBeEndSnap : Bool) :
Syntax × ModuleParserState × MessageLog × String.Pos := Id.run do Syntax × ModuleParserState × MessageLog × String.Pos := Id.run do
let mut pos := mps.pos let mut pos := mps.pos
let mut recovering := mps.recovering let mut recovering := mps.recovering
@@ -49,8 +46,7 @@ partial def parseTactic (inputCtx : InputContext) (pmctx : ParserModuleContext)
end MyModule end MyModule
namespace GameServer.FileWorker namespace MyServer.FileWorker
open Lean open Lean
open Lean.Server open Lean.Server
open Lean.Server.FileWorker open Lean.Server.FileWorker
@@ -59,147 +55,88 @@ open IO
open Snapshots open Snapshots
open JsonRpc open JsonRpc
/--
Game-specific state to be packed on top of the `Lean.Server.FileWorker.WorkerState`
used by the lean server.
-/
structure WorkerState :=
/--
Collection of items which are considered unlocked.
Tactics and theorems are mixed together.
-/
inventory : Array String
/--
Difficulty determines whether tactics/theorems can be locked.
* 0: do not check
* 1: give warnings when locked items are used
* 2: give errors when locked items are used
-/
difficulty : Nat
/--
`levelInfo` contains all the (static) information about the level which is not influenced
by the user's progress.
-/
levelInfo : LevelInfo
deriving ToJson, FromJson
/--
Pack the `GameServer.FileWorker.WorkerState` on top of the normal worker monad
`Server.FileWorker.WorkerM`.
-/
abbrev WorkerM := StateT WorkerState Server.FileWorker.WorkerM
section Elab section Elab
/-- Add a message. use `(severity := .warning)` to specify the severity-/
def addMessage (info : SourceInfo) (inputCtx : Parser.InputContext)
(severity := MessageSeverity.warning) (s : MessageData) :
Elab.Command.CommandElabM Unit := do
modify fun st => { st with
messages := st.messages.add {
fileName := inputCtx.fileName
severity := severity
pos := inputCtx.fileMap.toPosition (info.getPos?.getD 0)
data := s }}
/-- Deprecated! -/
def addErrorMessage (info : SourceInfo) (inputCtx : Parser.InputContext) (s : MessageData) : def addErrorMessage (info : SourceInfo) (inputCtx : Parser.InputContext) (s : MessageData) :
Elab.Command.CommandElabM Unit := do Elab.Command.CommandElabM Unit := do
modify fun st => { st with modify fun st => { st with
messages := st.messages.add { messages := st.messages.add {
fileName := inputCtx.fileName fileName := inputCtx.fileName
severity := MessageSeverity.error severity := MessageSeverity.error
pos := inputCtx.fileMap.toPosition (info.getPos?.getD 0) pos := inputCtx.fileMap.toPosition (info.getPos?.getD 0)
data := s }} data := s
}
}
-- TODO: use HashSet for allowed tactics? -- TODO: use HashSet for allowed tactics?
/-- /-- Find all tactics in syntax object that are forbidden according to a
Find all tactics in syntax object that are forbidden according to a set `allowed` of allowed tactics. -/
set `allowed` of allowed tactics. partial def findForbiddenTactics (inputCtx : Parser.InputContext)
-/ (levelParams : Game.DidOpenLevelParams) (stx : Syntax) :
partial def findForbiddenTactics (inputCtx : Parser.InputContext) (workerState : WorkerState) Elab.Command.CommandElabM Unit := do
(stx : Syntax) : Elab.Command.CommandElabM Unit := do
let levelInfo := workerState.levelInfo
-- Parse the syntax object and look for tactics and declarations.
match stx with match stx with
| .missing => return () | .missing => return ()
| .node _info _kind args => | .node _info _kind args =>
-- Go inside a node.
for arg in args do for arg in args do
findForbiddenTactics inputCtx workerState arg findForbiddenTactics inputCtx levelParams arg
| .atom info val => | .atom info val =>
-- Atoms might be tactic names or other keywords. -- ignore syntax elements that do not start with a letter
-- Note: We whitelisted known keywords because we cannot -- and ignore "with" keyword
-- distinguish keywords from tactic names. let allowed := ["with", "fun", "at", "only", "by", "to"]
let allowed := ["with", "fun", "at", "only", "by", "to", "generalizing", "says"]
-- Ignore syntax elements that do not start with a letter or are listed above.
if 0 < val.length ∧ val.data[0]!.isAlpha ∧ not (allowed.contains val) then if 0 < val.length ∧ val.data[0]!.isAlpha ∧ not (allowed.contains val) then
-- Treat `simp?` and `simp!` like `simp` let val := val.dropRightWhile (fun c => c == '!' || c == '?') -- treat `simp?` and `simp!` like `simp`
let val := val.dropRightWhile (fun c => c == '!' || c == '?') match levelParams.tactics.find? (·.name.toString == val) with
match levelInfo.tactics.find? (·.name.toString == val) with
| none => | none =>
-- Tactic will never be introduced in the game. -- Note: This case means that the tactic will never be introduced in the game.
match workerState.inventory.find? (· == val) with match levelParams.inventory.find? (· == val) with
| some _ =>
-- Tactic is in the inventory, allow it.
-- Note: This case shouldn't be possible...
pure ()
| none => | none =>
-- Tactic is not in the inventory. addWarningMessage info s!"You have not unlocked the tactic '{val}' yet!"
addMessageByDifficulty info s!"The tactic '{val}' is not available in this game!" | some _ => pure () -- tactic is in the inventory, allow it.
| some tac => | some tac =>
-- Tactic is introduced at some point in the game. if tac.locked then
if tac.disabled then match levelParams.inventory.find? (· == val) with
-- Tactic is disabled in this level.
addMessageByDifficulty info s!"The tactic '{val}' is disabled in this level!"
else if tac.locked then
match workerState.inventory.find? (· == val) with
| none => | none =>
-- Tactic is marked as locked and not in the inventory. addWarningMessage info s!"You have not unlocked the tactic '{val}' yet!"
addMessageByDifficulty info s!"You have not unlocked the tactic '{val}' yet!" | some _ => pure () -- tactic is in the inventory, allow it.
| some _ => else if tac.disabled then
-- Tactic is in the inventory, allow it. addWarningMessage info s!"The tactic '{val}' is disabled in this level!"
pure ()
| .ident info _rawVal val _preresolved => | .ident info _rawVal val _preresolved =>
-- Try to resolve the name let ns ←
let ns ← try resolveGlobalConst (mkIdent val)
try resolveGlobalConst (mkIdent val) catch | _ => pure [] -- catch "unknown constant" error
-- Catch "unknown constant" error for n in ns do
catch | _ => pure [] let some (.thmInfo ..) := (← getEnv).find? n
for n in ns do | return () -- not a theorem -> ignore
let some (.thmInfo ..) := (← getEnv).find? n
-- Not a theorem, no checks needed.
| return ()
if some n = levelInfo.statementName then
-- Forbid the theorem we are proving currently -- Forbid the theorem we are proving currently
addMessage info inputCtx (severity := .error) if n = levelParams.statementName then
s!"Structural recursion: you can't use '{n}' to proof itself!" addErrorMessage info inputCtx s!"Structural recursion: you can't use '{n}' to proof itself!"
let theoremsAndDefs := levelInfo.lemmas ++ levelInfo.definitions
match theoremsAndDefs.find? (·.name == n) with
| none =>
-- Theorem will never be introduced in this game
addMessageByDifficulty info s!"You have not unlocked the theorem/definition '{n}' yet!"
| some thm =>
-- Theorem is introduced at some point in the game.
if thm.disabled then
-- Theorem is disabled in this level.
addMessageByDifficulty info s!"The theorem/definition '{n}' is disabled in this level!"
else if thm.locked then
-- Theorem is still locked.
addMessageByDifficulty info s!"You have not unlocked the theorem/definition '{n}' yet!"
where addMessageByDifficulty (info : SourceInfo) (s : MessageData) := let lemmasAndDefs := levelParams.lemmas ++ levelParams.definitions
-- See `GameServer.FileWorker.WorkerState.difficulty`. Send nothing/warnings/errors match lemmasAndDefs.find? (fun l => l.name == n) with
-- deppending on difficulty. | none => addWarningMessage info s!"You have not unlocked the lemma/definition '{n}' yet!"
let difficulty := workerState.difficulty | some lem =>
if lem.locked then
addWarningMessage info s!"You have not unlocked the lemma/definition '{n}' yet!"
else if lem.disabled then
addWarningMessage info s!"The lemma/definition '{n}' is disabled in this level!"
where addWarningMessage (info : SourceInfo) (s : MessageData) :=
let difficulty := levelParams.difficulty
if difficulty > 0 then if difficulty > 0 then
addMessage info inputCtx (if difficulty > 1 then .error else .warning) s modify fun st => { st with
messages := st.messages.add {
fileName := inputCtx.fileName
severity := if difficulty > 1 then MessageSeverity.error else MessageSeverity.warning
pos := inputCtx.fileMap.toPosition (info.getPos?.getD 0)
data := s
}
}
else pure () else pure ()
-- where addErrorMessage (info : SourceInfo) (s : MessageData) :=
-- pure ()
open Elab Meta Expr in open Elab Meta Expr in
def compileProof (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets : Bool) def compileProof (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets : Bool)
(couldBeEndSnap : Bool) (gameWorkerState : WorkerState) (couldBeEndSnap : Bool) (levelParams : Game.DidOpenLevelParams)
(initParams : Lsp.InitializeParams) : IO Snapshot := do (initParams : Lsp.InitializeParams) : IO Snapshot := do
-- Recognize end snap -- Recognize end snap
if inputCtx.input.atEnd snap.mpState.pos ∧ couldBeEndSnap then if inputCtx.input.atEnd snap.mpState.pos ∧ couldBeEndSnap then
@@ -230,7 +167,7 @@ def compileProof (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets
Elab.Command.catchExceptions Elab.Command.catchExceptions
(getResetInfoTrees *> do (getResetInfoTrees *> do
let some level ← GameServer.getLevelByFileName? initParams inputCtx.fileName let some level ← GameServer.getLevelByFileName? initParams inputCtx.fileName
| panic! s!"Level not found: {inputCtx.fileName} / {GameServer.levelIdFromFileName? initParams inputCtx.fileName}" | throwError "Level not found: {inputCtx.fileName}"
let scope := level.scope let scope := level.scope
-- use open namespaces and options as in the level file -- use open namespaces and options as in the level file
@@ -248,12 +185,12 @@ def compileProof (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets
currNamespace := scope.currNamespace, currNamespace := scope.currNamespace,
openDecls := scope.openDecls } openDecls := scope.openDecls }
let (tacticStx, cmdParserState, msgLog, endOfWhitespace) := let (tacticStx, cmdParserState, msgLog, endOfWhitespace) :=
MyModule.parseTactic inputCtx pmctx snap.mpState snap.msgLog MyModule.parseTactic inputCtx pmctx snap.mpState snap.msgLog couldBeEndSnap
modify (fun s => { s with messages := msgLog }) modify (fun s => { s with messages := msgLog })
parseResultRef.set (tacticStx, cmdParserState) parseResultRef.set (tacticStx, cmdParserState)
-- Check for forbidden tactics -- Check for forbidden tactics
findForbiddenTactics inputCtx gameWorkerState tacticStx findForbiddenTactics inputCtx levelParams tacticStx
-- Insert invisible `skip` command to make sure we always display the initial goal -- Insert invisible `skip` command to make sure we always display the initial goal
let skip := Syntax.node (.original default 0 default endOfWhitespace) ``Lean.Parser.Tactic.skip #[] let skip := Syntax.node (.original default 0 default endOfWhitespace) ``Lean.Parser.Tactic.skip #[]
@@ -281,7 +218,6 @@ def compileProof (inputCtx : Parser.InputContext) (snap : Snapshot) (hasWidgets
} }
let (tacticStx, cmdParserState) ← parseResultRef.get let (tacticStx, cmdParserState) ← parseResultRef.get
if tacticStx.isMissing then throwServerError "Tactic execution went wrong. No stx found."
let postCmdSnap : Snapshot := { let postCmdSnap : Snapshot := {
beginPos := tacticStx.getPos?.getD 0 beginPos := tacticStx.getPos?.getD 0
@@ -333,7 +269,7 @@ where
/-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/
private def nextSnap (ctx : WorkerContext) (m : DocumentMeta) (cancelTk : CancelToken) private def nextSnap (ctx : WorkerContext) (m : DocumentMeta) (cancelTk : CancelToken)
(gameWorkerState : WorkerState) (initParams : Lsp.InitializeParams) (levelParams : Game.DidOpenLevelParams) (initParams : Lsp.InitializeParams)
: AsyncElabM (Option Snapshot) := do : AsyncElabM (Option Snapshot) := do
cancelTk.check cancelTk.check
let s ← get let s ← get
@@ -351,7 +287,7 @@ where
-- we can see the current goal even on an empty document -- we can see the current goal even on an empty document
let couldBeEndSnap := s.snaps.size > 1 let couldBeEndSnap := s.snaps.size > 1
let snap ← compileProof m.mkInputContext lastSnap ctx.clientHasWidgets couldBeEndSnap let snap ← compileProof m.mkInputContext lastSnap ctx.clientHasWidgets couldBeEndSnap
gameWorkerState initParams levelParams initParams
set { s with snaps := s.snaps.push snap } set { s with snaps := s.snaps.push snap }
-- TODO(MH): check for interrupt with increased precision -- TODO(MH): check for interrupt with increased precision
cancelTk.check cancelTk.check
@@ -373,7 +309,7 @@ where
/-- Elaborates all commands after the last snap (at least the header snap is assumed to exist), emitting the diagnostics into `hOut`. -/ /-- Elaborates all commands after the last snap (at least the header snap is assumed to exist), emitting the diagnostics into `hOut`. -/
def unfoldSnaps (m : DocumentMeta) (snaps : Array Snapshot) (cancelTk : CancelToken) def unfoldSnaps (m : DocumentMeta) (snaps : Array Snapshot) (cancelTk : CancelToken)
(startAfterMs : UInt32) (gameWorkerState : WorkerState) (startAfterMs : UInt32) (levelParams : Game.DidOpenLevelParams)
: ReaderT WorkerContext IO (AsyncList ElabTaskError Snapshot) := do : ReaderT WorkerContext IO (AsyncList ElabTaskError Snapshot) := do
let ctx ← read let ctx ← read
let some headerSnap := snaps[0]? | panic! "empty snapshots" let some headerSnap := snaps[0]? | panic! "empty snapshots"
@@ -389,278 +325,257 @@ where
publishIleanInfoUpdate m ctx.hOut snaps publishIleanInfoUpdate m ctx.hOut snaps
return AsyncList.ofList snaps.toList ++ AsyncList.delayed (← EIO.asTask (ε := ElabTaskError) (prio := .dedicated) do return AsyncList.ofList snaps.toList ++ AsyncList.delayed (← EIO.asTask (ε := ElabTaskError) (prio := .dedicated) do
IO.sleep startAfterMs IO.sleep startAfterMs
AsyncList.unfoldAsync (nextSnap ctx m cancelTk gameWorkerState ctx.initParams) { snaps }) AsyncList.unfoldAsync (nextSnap ctx m cancelTk levelParams ctx.initParams) { snaps })
end Elab end Elab
structure GameWorkerState :=
(levelParams : Game.DidOpenLevelParams)
abbrev GameWorkerM := StateT GameWorkerState Server.FileWorker.WorkerM
section Updates section Updates
/-- Given the new document, updates editable doc state. -/ /-- Given the new document, updates editable doc state. -/
def updateDocument (newMeta : DocumentMeta) : WorkerM Unit := do def updateDocument (newMeta : DocumentMeta) : GameWorkerM Unit := do
let s ← get let s ← get
let ctx ← read let levelParams := s.levelParams
let oldDoc := (← StateT.lift get).doc let ctx ← read
oldDoc.cancelTk.set let oldDoc := (← StateT.lift get).doc
let initHeaderStx := (← StateT.lift get).initHeaderStx oldDoc.cancelTk.set
let (newHeaderStx, newMpState, _) ← Parser.parseHeader newMeta.mkInputContext let initHeaderStx := (← StateT.lift get).initHeaderStx
let cancelTk ← CancelToken.new let (newHeaderStx, newMpState, _) ← Parser.parseHeader newMeta.mkInputContext
let headSnapTask := oldDoc.cmdSnaps.waitHead? let cancelTk ← CancelToken.new
let newSnaps ← if initHeaderStx != newHeaderStx then let headSnapTask := oldDoc.cmdSnaps.waitHead?
EIO.asTask (ε := ElabTaskError) (prio := .dedicated) do let newSnaps ← if initHeaderStx != newHeaderStx then
IO.sleep ctx.initParams.editDelay.toUInt32 EIO.asTask (ε := ElabTaskError) (prio := .dedicated) do
cancelTk.check IO.sleep ctx.initParams.editDelay.toUInt32
IO.Process.exit 2 cancelTk.check
else EIO.mapTask (ε := ElabTaskError) (t := headSnapTask) (prio := .dedicated) fun headSnap?? => do IO.Process.exit 2
-- There is always at least one snapshot absent exceptions else EIO.mapTask (ε := ElabTaskError) (t := headSnapTask) (prio := .dedicated) fun headSnap?? => do
let some headSnap ← MonadExcept.ofExcept headSnap?? | panic! "empty snapshots" -- There is always at least one snapshot absent exceptions
let newHeaderSnap := { headSnap with stx := newHeaderStx, mpState := newMpState } let some headSnap ← MonadExcept.ofExcept headSnap?? | panic! "empty snapshots"
let changePos := oldDoc.meta.text.source.firstDiffPos newMeta.text.source let newHeaderSnap := { headSnap with stx := newHeaderStx, mpState := newMpState }
-- Ignore exceptions, we are only interested in the successful snapshots let changePos := oldDoc.meta.text.source.firstDiffPos newMeta.text.source
let (cmdSnaps, _) ← oldDoc.cmdSnaps.getFinishedPrefix -- Ignore exceptions, we are only interested in the successful snapshots
-- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only let (cmdSnaps, _) ← oldDoc.cmdSnaps.getFinishedPrefix
-- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only
let mut validSnaps ← pure (cmdSnaps.takeWhile (fun s => s.endPos < changePos)) -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead.
if h : validSnaps.length ≤ 1 then let mut validSnaps ← pure (cmdSnaps.takeWhile (fun s => s.endPos < changePos))
validSnaps := [newHeaderSnap] if h : validSnaps.length ≤ 1 then
else validSnaps := [newHeaderSnap]
/- When at least one valid non-header snap exists, it may happen that a change does not fall else
within the syntactic range of that last snap but still modifies it by appending tokens. /- When at least one valid non-header snap exists, it may happen that a change does not fall
We check for this here. We do not currently handle crazy grammars in which an appended within the syntactic range of that last snap but still modifies it by appending tokens.
token can merge two or more previous commands into one. To do so would require reparsing We check for this here. We do not currently handle crazy grammars in which an appended
the entire file. -/ token can merge two or more previous commands into one. To do so would require reparsing
have : validSnaps.length ≥ 2 := Nat.gt_of_not_le h the entire file. -/
let mut lastSnap := validSnaps.getLast (by subst ·; simp at h) have : validSnaps.length ≥ 2 := Nat.gt_of_not_le h
let preLastSnap := let mut lastSnap := validSnaps.getLast (by subst ·; simp at h)
have : 0 < validSnaps.length := Nat.lt_of_lt_of_le (by decide) this let preLastSnap :=
have : validSnaps.length - 2 < validSnaps.length := Nat.sub_lt this (by decide) have : 0 < validSnaps.length := Nat.lt_of_lt_of_le (by decide) this
validSnaps[validSnaps.length - 2] have : validSnaps.length - 2 < validSnaps.length := Nat.sub_lt this (by decide)
let newLastStx ← parseNextCmd newMeta.mkInputContext preLastSnap validSnaps[validSnaps.length - 2]
if newLastStx != lastSnap.stx then let newLastStx ← parseNextCmd newMeta.mkInputContext preLastSnap
validSnaps := validSnaps.dropLast if newLastStx != lastSnap.stx then
-- wait for a bit, giving the initial `cancelTk.check` in `nextCmdSnap` time to trigger validSnaps := validSnaps.dropLast
-- before kicking off any expensive elaboration (TODO: make expensive elaboration cancelable) -- wait for a bit, giving the initial `cancelTk.check` in `nextCmdSnap` time to trigger
unfoldSnaps newMeta validSnaps.toArray cancelTk s ctx -- before kicking off any expensive elaboration (TODO: make expensive elaboration cancelable)
(startAfterMs := ctx.initParams.editDelay.toUInt32) unfoldSnaps newMeta validSnaps.toArray cancelTk levelParams ctx
StateT.lift <| modify fun st => { st with (startAfterMs := ctx.initParams.editDelay.toUInt32)
doc := { meta := newMeta, cmdSnaps := AsyncList.delayed newSnaps, cancelTk }} StateT.lift <| modify fun st => { st with
doc := { meta := newMeta, cmdSnaps := AsyncList.delayed newSnaps, cancelTk }}
end Updates end Updates
section Initialization section Initialization
def DocumentMeta.mkInputContext (doc : DocumentMeta) : Parser.InputContext where def DocumentMeta.mkInputContext (doc : DocumentMeta) : Parser.InputContext where
input := "" -- No header! input := "" -- No header!
fileName := (System.Uri.fileUriToPath? doc.uri).getD doc.uri |>.toString fileName := (System.Uri.fileUriToPath? doc.uri).getD doc.uri |>.toString
fileMap := default fileMap := default
def compileHeader (m : DocumentMeta) (hOut : FS.Stream) (opts : Options) (hasWidgets : Bool) def mkHeaderTask (m : DocumentMeta) (hOut : FS.Stream) (paths : List System.FilePath)
(gameDir : String) (module : Name): (env : Environment) (opts : Options) (hasWidgets : Bool) :
IO (Syntax × Task (Except Error (Snapshot × SearchPath))) := do IO (Syntax × Task (Except Error (Snapshot × SearchPath))) := do
-- Determine search paths of the game project by running `lake env printenv LEAN_PATH`. -- use empty header
let out ← IO.Process.output let (headerStx, headerParserState, msgLog) ← Parser.parseHeader
{ cwd := gameDir, cmd := "lake", args := #["env","printenv","LEAN_PATH"] } {m.mkInputContext with
if out.exitCode != 0 then input := ""
throwServerError s!"Error while running Lake: {out.stderr}" fileMap := FileMap.ofString ""}
(headerStx, ·) <$> EIO.asTask do
let mut srcSearchPath : SearchPath := paths --← initSrcSearchPath (← getBuildDir)
let headerEnv := env
let mut headerEnv := headerEnv
try
if let some path := System.Uri.fileUriToPath? m.uri then
headerEnv := headerEnv.setMainModule (← moduleNameOfFileName path none)
catch _ => pure ()
let cmdState := Elab.Command.mkState headerEnv {} opts
let cmdState := { cmdState with infoState := {
enabled := true
trees := #[Elab.InfoTree.context ({
env := headerEnv
fileMap := m.text
ngen := { namePrefix := `_worker }
}) (Elab.InfoTree.node
(Elab.Info.ofCommandInfo { elaborator := `header, stx := headerStx })
(headerStx[1].getArgs.toList.map (fun importStx =>
Elab.InfoTree.node (Elab.Info.ofCommandInfo {
elaborator := `import
stx := importStx
}) #[].toPArray'
)).toPArray'
)].toPArray'
}}
let headerSnap := {
beginPos := 0
stx := headerStx
mpState := {}
cmdState := cmdState
interactiveDiags := ← cmdState.messages.msgs.mapM (Widget.msgToInteractiveDiagnostic m.text · hasWidgets)
tacticCache := (← IO.mkRef {})
}
publishDiagnostics m headerSnap.diagnostics.toArray hOut
return (headerSnap, srcSearchPath)
-- Make the paths relative to the current directory def compileHeader (m : DocumentMeta) (hOut : FS.Stream) (opts : Options) (hasWidgets : Bool)
let paths : List System.FilePath := System.SearchPath.parse out.stdout.trim (levelParams : Game.DidOpenLevelParams) :
let currentDir ← IO.currentDir IO (Syntax × Task (Except Error (Snapshot × SearchPath))) := do
let paths := paths.map fun p => currentDir / (gameDir : System.FilePath) / p -- Determine search paths of the game project by running `lake env printenv LEAN_PATH`.
let out ← IO.Process.output
{ cwd := levelParams.gameDir, cmd := "lake", args := #["env","printenv","LEAN_PATH"] }
if out.exitCode != 0 then
throwServerError s!"Error while running Lake: {out.stderr}"
-- Set the search path -- Make the paths relative to the current directory
Lean.searchPathRef.set paths let paths : List System.FilePath := System.SearchPath.parse out.stdout.trim
let currentDir ← IO.currentDir
let paths := paths.map fun p => currentDir / (levelParams.gameDir : System.FilePath) / p
let env ← importModules' #[{ module := `Init : Import }, { module := module : Import }] -- Set the search path
Lean.searchPathRef.set paths
-- use empty header let env ← importModules #[{ module := `Init : Import }, { module := levelParams.levelModule : Import }] {} 0
let (headerStx, headerParserState, msgLog) ← Parser.parseHeader -- return (env, paths)
{m.mkInputContext with mkHeaderTask m hOut paths env opts hasWidgets
input := ""
fileMap := FileMap.ofString ""}
(headerStx, ·) <$> EIO.asTask do
let mut srcSearchPath : SearchPath := paths --← initSrcSearchPath (← getBuildDir)
let headerEnv := env
let mut headerEnv := headerEnv
try
if let some path := System.Uri.fileUriToPath? m.uri then
headerEnv := headerEnv.setMainModule (← moduleNameOfFileName path none)
catch _ => pure ()
let cmdState := Elab.Command.mkState headerEnv {} opts
let cmdState := { cmdState with infoState := {
enabled := true
trees := #[Elab.InfoTree.context ({
env := headerEnv
fileMap := m.text
ngen := { namePrefix := `_worker }
}) (Elab.InfoTree.node
(Elab.Info.ofCommandInfo { elaborator := `header, stx := headerStx })
(headerStx[1].getArgs.toList.map (fun importStx =>
Elab.InfoTree.node (Elab.Info.ofCommandInfo {
elaborator := `import
stx := importStx
}) #[].toPArray'
)).toPArray'
)].toPArray'
}}
let headerSnap := {
beginPos := 0
stx := headerStx
mpState := {}
cmdState := cmdState
interactiveDiags := ← cmdState.messages.msgs.mapM (Widget.msgToInteractiveDiagnostic m.text · hasWidgets)
tacticCache := (← IO.mkRef {})
}
publishDiagnostics m headerSnap.diagnostics.toArray hOut
return (headerSnap, srcSearchPath)
def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) (initParams : InitializeParams) (opts : Options) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) (initParams : InitializeParams) (opts : Options)
(gameDir : String) (gameWorkerState : WorkerState) : IO (WorkerContext × Server.FileWorker.WorkerState) := do (levelParams : Game.DidOpenLevelParams) : IO (WorkerContext × WorkerState) := do
let clientHasWidgets := initParams.initializationOptions?.bind (·.hasWidgets?) |>.getD false let clientHasWidgets := initParams.initializationOptions?.bind (·.hasWidgets?) |>.getD false
let (headerStx, headerTask) ← compileHeader meta o opts (hasWidgets := clientHasWidgets)
let (headerStx, headerTask) ← compileHeader meta o opts (hasWidgets := clientHasWidgets) levelParams
gameDir gameWorkerState.levelInfo.module let cancelTk ← CancelToken.new
let cancelTk ← CancelToken.new let ctx :=
let ctx := { hIn := i
{ hIn := i hOut := o
hOut := o hLog := e
hLog := e headerTask
headerTask initParams
initParams clientHasWidgets
clientHasWidgets }
} let cmdSnaps ← EIO.mapTask (t := headerTask) (match · with
let cmdSnaps ← EIO.mapTask (t := headerTask) (match · with | Except.ok (s, _) => unfoldSnaps meta #[s] cancelTk levelParams ctx (startAfterMs := 0)
| Except.ok (s, _) => unfoldSnaps meta #[s] cancelTk gameWorkerState ctx (startAfterMs := 0) | Except.error e => throw (e : ElabTaskError))
| Except.error e => throw (e : ElabTaskError)) let doc : EditableDocument := { meta, cmdSnaps := AsyncList.delayed cmdSnaps, cancelTk }
let doc : EditableDocument := { meta, cmdSnaps := AsyncList.delayed cmdSnaps, cancelTk } return (ctx,
return (ctx, { doc := doc
{ doc := doc initHeaderStx := headerStx
initHeaderStx := headerStx pendingRequests := RBMap.empty
currHeaderStx := headerStx rpcSessions := RBMap.empty
importCachingTask? := none })
pendingRequests := RBMap.empty
rpcSessions := RBMap.empty
})
end Initialization end Initialization
section NotificationHandling section NotificationHandling
def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do def handleDidChange (p : DidChangeTextDocumentParams) : GameWorkerM Unit := do
let docId := p.textDocument let docId := p.textDocument
let changes := p.contentChanges let changes := p.contentChanges
let oldDoc := (← StateT.lift get).doc let oldDoc := (← StateT.lift get).doc
let some newVersion ← pure docId.version? let some newVersion ← pure docId.version?
| throwServerError "Expected version number" | throwServerError "Expected version number"
if newVersion ≤ oldDoc.meta.version then if newVersion ≤ oldDoc.meta.version then
-- TODO(WN): This happens on restart sometimes. -- TODO(WN): This happens on restart sometimes.
IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}"
else if ¬ changes.isEmpty then else if ¬ changes.isEmpty then
let newDocText := foldDocumentChanges changes oldDoc.meta.text let newDocText := foldDocumentChanges changes oldDoc.meta.text
updateDocument ⟨docId.uri, newVersion, newDocText, .always⟩ updateDocument ⟨docId.uri, newVersion, newDocText, .always⟩
end NotificationHandling end NotificationHandling
section MessageHandling section MessageHandling
def handleNotification (method : String) (params : Json) : GameWorkerM Unit := do
/-- let handle := fun paramType [FromJson paramType] (handler : paramType → GameWorkerM Unit) =>
Modified notification handler. (StateT.lift <| parseParams paramType params) >>= handler
match method with
Compare to `Lean.Server.FileWorker.handleNotification`. | "textDocument/didChange" => handle DidChangeTextDocumentParams (handleDidChange)
We use the modified `WorkerM` and use our custom `handleDidChange`. | "$/cancelRequest" => handle CancelParams (handleCancelRequest ·)
| "$/lean/rpc/release" => handle RpcReleaseParams (handleRpcRelease ·)
-/ | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (handleRpcKeepAlive ·)
def handleNotification (method : String) (params : Json) : WorkerM Unit := do | _ => throwServerError s!"Got unsupported notification method: {method}"
let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) =>
(StateT.lift <| parseParams paramType params) >>= handler
match method with
-- Modified `textDocument/didChange`, using a custom `handleDidChange`
| "textDocument/didChange" => handle DidChangeTextDocumentParams (handleDidChange)
-- unmodified
| "$/cancelRequest" => handle CancelParams (handleCancelRequest ·)
-- unmodified
| "$/lean/rpc/release" => handle RpcReleaseParams (handleRpcRelease ·)
-- unmodified
| "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (handleRpcKeepAlive ·)
-- New. TODO: What is this for?
| "$/setTrace" => pure ()
| _ => throwServerError s!"Got unsupported notification method: {method}"
end MessageHandling end MessageHandling
section MainLoop section MainLoop
partial def mainLoop1 (msg : JsonRpc.Message): GameWorkerM Bool := do
let mut st ← StateT.lift get
let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit))
: IO PendingRequestMap := do
if (← hasFinished task) then
/- Handler tasks are constructed so that the only possible errors here
are failures of writing a response into the stream. -/
if let Except.error e := task.get then
throwServerError s!"Failed responding to request {id}: {e}"
pure <| acc.erase id
else pure acc
let pendingRequests ← st.pendingRequests.foldM (fun acc id task => filterFinishedTasks acc id task) st.pendingRequests
st := { st with pendingRequests }
/-- -- Opportunistically (i.e. when we wake up on messages) check if any RPC session has expired.
Erase finished tasks if there are no errors. for (id, seshRef) in st.rpcSessions do
-/ let sesh ← seshRef.get
private def filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) if (← sesh.hasExpired) then
(task : Task (Except IO.Error Unit)) : IO PendingRequestMap := do st := { st with rpcSessions := st.rpcSessions.erase id }
if (← hasFinished task) then
/- Handler tasks are constructed so that the only possible errors here
are failures of writing a response into the stream. -/
if let Except.error e := task.get then
throwServerError s!"Failed responding to request {id}: {e}"
pure <| acc.erase id
else pure acc
/-- set st
The main-loop. match msg with
-/ | Message.request id method (some params) =>
partial def mainLoop : WorkerM Unit := do handleRequest id method (toJson params)
return false
| Message.notification "exit" none =>
let doc := st.doc
doc.cancelTk.set
return true
| Message.notification "$/game/setInventory" params =>
let p := (← parseParams Game.SetInventoryParams (toJson params))
let s ← get
set {s with levelParams := {s.levelParams with
inventory := p.inventory,
difficulty := p.difficulty}}
return false
| Message.notification method (some params) =>
handleNotification method (toJson params)
return false
| _ => throwServerError "Got invalid JSON-RPC message"
partial def mainLoop : GameWorkerM Unit := do
let ctx ← read let ctx ← read
let mut st ← StateT.lift get
let msg ← ctx.hIn.readLspMessage let msg ← ctx.hIn.readLspMessage
let pendingRequests ← st.pendingRequests.foldM (fun acc id task => if not (← mainLoop1 msg) then
filterFinishedTasks acc id task) st.pendingRequests
st := { st with pendingRequests }
-- Opportunistically (i.e. when we wake up on messages) check if any RPC session has expired.
for (id, seshRef) in st.rpcSessions do
let sesh ← seshRef.get
if (← sesh.hasExpired) then
st := { st with rpcSessions := st.rpcSessions.erase id }
set st
-- Process the RPC-message and restart main-loop.
match msg with
| Message.request id "shutdown" none =>
ctx.hOut.writeLspResponse ⟨id, Json.null⟩
mainLoop mainLoop
| Message.request id method (some params) =>
-- Requests are handled by the unmodified lean server.
handleRequest id method (toJson params)
mainLoop
| Message.notification "exit" none =>
let doc := st.doc
doc.cancelTk.set
return ()
| Message.notification method (some params) =>
-- Custom notification handler
handleNotification method (toJson params)
mainLoop
| _ =>
throwServerError s!"Got invalid JSON-RPC message: {toJson msg}"
end MainLoop end MainLoop
def initAndRunWorker (i o e : FS.Stream) (opts : Options) : IO UInt32 := do
def initAndRunWorker (i o e : FS.Stream) (opts : Options) (gameDir : String) : IO UInt32 := do
let i ← maybeTee "fwIn.txt" false i let i ← maybeTee "fwIn.txt" false i
let o ← maybeTee "fwOut.txt" true o let o ← maybeTee "fwOut.txt" true o
let initRequest ← i.readLspRequestAs "initialize" Game.InitializeParams let initParams ← i.readLspRequestAs "initialize" InitializeParams
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := Watchdog.mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 Game Server"
version? := "0.1.1"
}
: InitializeResult
}
}
discard $ i.readLspNotificationAs "initialized" InitializedParams
let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams
let ⟨_, levelParams⟩ ← i.readLspNotificationAs "$/game/didOpenLevel" Game.DidOpenLevelParams
let doc := param.textDocument let doc := param.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following /- NOTE(WN): `toFileMap` marks line beginnings as immediately following
@@ -672,25 +587,9 @@ def initAndRunWorker (i o e : FS.Stream) (opts : Options) (gameDir : String) : I
let e := e.withPrefix s!"[{param.textDocument.uri}] " let e := e.withPrefix s!"[{param.textDocument.uri}] "
let _ ← IO.setStderr e let _ ← IO.setStderr e
try try
let game ← loadGameData gameDir let (ctx, st) ← initializeWorker meta i o e initParams.param opts levelParams
-- TODO: We misuse the `rootUri` field to the gameName
let rootUri? : Option String := some (toString game.name)
let initParams := {initRequest.param.toLeanInternal with rootUri?}
let some (levelId : LevelId) := GameServer.levelIdFromFileName?
initParams meta.mkInputContext.fileName
| throwServerError s!"Could not determine level ID: {meta.mkInputContext.fileName}"
let levelInfo ← loadLevelData gameDir levelId.world levelId.level
let some initializationOptions := initRequest.param.initializationOptions?
| throwServerError "no initialization options found"
let gameWorkerState : WorkerState := {
inventory := initializationOptions.inventory
difficulty := initializationOptions.difficulty
levelInfo
}
let (ctx, st) ← initializeWorker meta i o e initParams opts gameDir gameWorkerState
-- Run the main loop
let _ ← StateRefT'.run (s := st) <| ReaderT.run (r := ctx) <| let _ ← StateRefT'.run (s := st) <| ReaderT.run (r := ctx) <|
StateT.run (s := gameWorkerState) <| (mainLoop) StateT.run (s := {levelParams := levelParams}) <| (mainLoop)
return (0 : UInt32) return (0 : UInt32)
catch e => catch e =>
IO.eprintln e IO.eprintln e
@@ -700,21 +599,14 @@ def initAndRunWorker (i o e : FS.Stream) (opts : Options) (gameDir : String) : I
message := e.toString }] o message := e.toString }] o
return (1 : UInt32) return (1 : UInt32)
/-- def workerMain (opts : Options) : IO UInt32 := do
The main function. Simply wrapping `initAndRunWorker`.
TODO: The first arg `args[0]` is always expected to be `--server`. We could drop this completely.
-/
def workerMain (opts : Options) (args : List String): IO UInt32 := do
let i ← IO.getStdin let i ← IO.getStdin
let o ← IO.getStdout let o ← IO.getStdout
let e ← IO.getStderr let e ← IO.getStderr
try try
let some gameDir := args[1]? | throwServerError "Expected second argument: gameDir" let exitCode ← initAndRunWorker i o e opts
let exitCode ← initAndRunWorker i o e opts gameDir -- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, but we definitely don't
-- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, -- want to do that in the case of the worker processes, which can produce non-terminating tasks evaluating user code
-- but we definitely don't want to do that in the case of the worker processes,
-- which can produce non-terminating tasks evaluating user code.
o.flush o.flush
e.flush e.flush
IO.Process.exit exitCode.toUInt8 IO.Process.exit exitCode.toUInt8
@@ -722,4 +614,4 @@ def workerMain (opts : Options) (args : List String): IO UInt32 := do
e.putStrLn s!"worker initialization error: {err}" e.putStrLn s!"worker initialization error: {err}"
return (1 : UInt32) return (1 : UInt32)
end GameServer.FileWorker end MyServer.FileWorker
+216 -45
View File
@@ -25,56 +25,227 @@ open Lsp
open JsonRpc open JsonRpc
open IO open IO
/- Game-specific version of `InitializeParams` that allows for extra options: -/ def getGame (game : Name): GameServerM Json := do
let some game ← getGame? game
| throwServerError "Game not found"
let gameJson : Json := toJson game
-- Add world sizes to Json object
let worldSize := game.worlds.nodes.toList.map (fun (n, w) => (n.toString, w.levels.size))
let gameJson := gameJson.mergeObj (Json.mkObj [("worldSize", Json.mkObj worldSize)])
return gameJson
structure InitializationOptions extends Lean.Lsp.InitializationOptions := /--
difficulty : Nat Fields:
inventory : Array String - description: Lemma in mathematical language.
- descriptionGoal: Lemma printed as Lean-Code.
-/
structure LevelInfo where
index : Nat
title : String
tactics : Array InventoryTile
lemmas : Array InventoryTile
definitions : Array InventoryTile
introduction : String
conclusion : String
descrText : Option String := none
descrFormat : String := ""
lemmaTab : Option String
displayName : Option String
statementName : Option String
template : Option String
deriving ToJson, FromJson
structure InventoryOverview where
tactics : Array InventoryTile
lemmas : Array InventoryTile
definitions : Array InventoryTile
lemmaTab : Option String
deriving ToJson, FromJson
structure LoadLevelParams where
world : Name
level : Nat
deriving ToJson, FromJson deriving ToJson, FromJson
structure InitializeParams where -- structure LoadTemplateParams where
processId? : Option Int := none -- world : Name
clientInfo? : Option ClientInfo := none -- level : Nat
/- We don't support the deprecated rootPath -- deriving ToJson, FromJson
(rootPath? : Option String) -/
rootUri? : Option String := none
initializationOptions? : Option InitializationOptions := none
capabilities : ClientCapabilities
/-- If omitted, we default to off. -/
trace : Trace := Trace.off
workspaceFolders? : Option (Array WorkspaceFolder) := none
deriving ToJson
instance : FromJson InitializeParams where structure DidOpenLevelParams where
fromJson? j := do uri : String
let processId? := j.getObjValAs? Int "processId" gameDir : String
let clientInfo? := j.getObjValAs? ClientInfo "clientInfo" levelModule : Name
let rootUri? := j.getObjValAs? String "rootUri" tactics : Array InventoryTile
let initializationOptions? := j.getObjValAs? InitializationOptions "initializationOptions" lemmas : Array InventoryTile
let capabilities ← j.getObjValAs? ClientCapabilities "capabilities" definitions : Array InventoryTile
let trace := (j.getObjValAs? Trace "trace").toOption.getD Trace.off inventory : Array String
let workspaceFolders? := j.getObjValAs? (Array WorkspaceFolder) "workspaceFolders" /--
return ⟨ Check for tactics/theorems that are not unlocked.
processId?.toOption, 0: no check
clientInfo?.toOption, 1: give warnings
rootUri?.toOption, 2: give errors
initializationOptions?.toOption, -/
capabilities, difficulty : Nat
trace, /-- The name of the theorem to be proven in this level. -/
workspaceFolders?.toOption⟩ statementName : Name
deriving ToJson, FromJson
def InitializeParams.toLeanInternal (p : InitializeParams) : Lean.Lsp.InitializeParams := structure LoadDocParams where
{ name : Name
processId? := p.processId? type : InventoryType
clientInfo? := p.clientInfo? deriving ToJson, FromJson
rootUri? := p.rootUri?
initializationOptions? := p.initializationOptions?.map fun o => { structure SetInventoryParams where
editDelay? := o.editDelay? inventory : Array String
hasWidgets? := o.hasWidgets? difficulty : Nat
deriving ToJson, FromJson
def handleDidOpenLevel (params : Json) : GameServerM Unit := do
let p ← parseParams _ params
let m := p.textDocument
-- Execute the regular handling of the `didOpen` event
handleDidOpen p
let fw ← findFileWorker! m.uri
-- let s ← get
let c ← read
let some lvl ← GameServer.getLevelByFileName? c.initParams ((System.Uri.fileUriToPath? m.uri).getD m.uri |>.toString)
| do
c.hLog.putStr s!"Level not found: {m.uri} {c.initParams.rootUri?}"
c.hLog.flush
-- Send an extra notification to the file worker to inform it about the level data
let s ← get
fw.stdin.writeLspNotification {
method := "$/game/didOpenLevel"
param := {
uri := m.uri
gameDir := s.gameDir
levelModule := lvl.module
tactics := lvl.tactics.tiles
lemmas := lvl.lemmas.tiles
definitions := lvl.definitions.tiles
inventory := s.inventory
difficulty := s.difficulty
statementName := lvl.statementName
: DidOpenLevelParams
}
} }
capabilities := p.capabilities
trace := p.trace
workspaceFolders? := p.workspaceFolders? partial def handleServerEvent (ev : ServerEvent) : GameServerM Bool := do
} match ev with
| ServerEvent.clientMsg msg =>
match msg with
| Message.request id "info" _ =>
let s ← get
let c ← read
c.hOut.writeLspResponse ⟨id, (← getGame s.game)⟩
return true
| Message.request id "loadLevel" params =>
let p ← parseParams LoadLevelParams (toJson params)
let s ← get
let c ← read
let some lvl ← getLevel? {game := s.game, world := p.world, level := p.level}
| do
c.hOut.writeLspResponseError ⟨id, .invalidParams, s!"Level not found: world {p.world}, level {p.level}", none⟩
return true
let env ← getEnv
let levelInfo : LevelInfo :=
{ index := lvl.index,
title := lvl.title,
tactics := lvl.tactics.tiles,
lemmas := lvl.lemmas.tiles,
definitions := lvl.definitions.tiles,
descrText := lvl.descrText,
descrFormat := lvl.descrFormat --toExpr <| format (lvl.goal.raw) --toString <| Syntax.formatStx (lvl.goal.raw) --Syntax.formatStx (lvl.goal.raw) , -- TODO
introduction := lvl.introduction
conclusion := lvl.conclusion
lemmaTab := match lvl.lemmaTab with
| some tab => tab
| none =>
-- Try to set the lemma tab to the category of the first added lemma
match lvl.lemmas.tiles.find? (·.new) with
| some tile => tile.category
| none => none
statementName := lvl.statementName.toString
displayName := match lvl.statementName with
| .anonymous => none
| name => match (inventoryExt.getState env).find?
(fun x => x.name == name && x.type == .Lemma) with
| some n => n.displayName
| none => name.toString
-- Note: we could call `.find!` because we check in `Statement` that the
-- lemma doc must exist.
template := lvl.template
}
c.hOut.writeLspResponse ⟨id, ToJson.toJson levelInfo⟩
return true
-- | Message.request id "loadTemplate" params =>
-- let p ← parseParams LoadTemplateParams (toJson params)
-- let s ← get
-- let c ← read
-- let some game ← getGame? s.game
-- | throwServerError "Game not found"
-- let some world := game.worlds.nodes.find? p.world
-- | throwServerError "World not found"
-- let mut templates : Array <| Option String := #[]
-- for (_, level) in world.levels.toArray do
-- templates := templates.push level.template
-- c.hOut.writeLspResponse ⟨id, ToJson.toJson templates⟩
-- return true
| Message.request id "loadDoc" params =>
let p ← parseParams LoadDocParams (toJson params)
let c ← read
let some doc ← getInventoryItem? p.name p.type
| do
c.hOut.writeLspResponseError ⟨id, .invalidParams,
s!"Documentation not found: {p.name}", none⟩
return true
-- TODO: not necessary at all?
-- Here we only need to convert the fields that were not `String` in the `InventoryDocEntry`
-- let doc : InventoryItem := { doc with
-- name := doc.name.toString }
c.hOut.writeLspResponse ⟨id, ToJson.toJson doc⟩
return true
| Message.notification "$/game/setInventory" params =>
let p := (← parseParams SetInventoryParams (toJson params))
let s ← get
set {s with inventory := p.inventory, difficulty := p.difficulty}
let st ← read
let workers ← st.fileWorkersRef.get
for (_, fw) in workers do
fw.stdin.writeLspMessage msg
return true
| Message.request id "loadInventoryOverview" _ =>
let s ← get
let some game ← getGame? s.game
| return false
-- All Levels have the same tiles, so we just load them from level 1 of an arbitrary world
-- and reset `new`, `disabled` and `unlocked`.
-- Note: as we allow worlds without any levels (for developing), we might need
-- to try until we find the first world with levels.
for ⟨worldId, _⟩ in game.worlds.nodes.toList do
let some lvl ← getLevel? {game := s.game, world := worldId, level := 1}
| do continue
let inventory : InventoryOverview := {
tactics := lvl.tactics.tiles.map
({ · with locked := true, disabled := false, new := false }),
lemmas := lvl.lemmas.tiles.map
({ · with locked := true, disabled := false, new := false }),
definitions := lvl.definitions.tiles.map
({ · with locked := true, disabled := false, new := false }),
lemmaTab := none
}
let c ← read
c.hOut.writeLspResponse ⟨id, ToJson.toJson inventory⟩
return true
return false
| _ => return false
| _ => return false
end Game end Game
-8
View File
@@ -18,14 +18,6 @@ instance [ToJson β] : ToJson (Graph Name β) := {
] ]
} }
-- Just a dummy implementation for now:
instance : FromJson (Graph Name β) := {
fromJson? := fun _ => .ok {
nodes := {}
edges := {}
}
}
instance : EmptyCollection (Graph α β) := ⟨default⟩ instance : EmptyCollection (Graph α β) := ⟨default⟩
def Graph.insertNode (g : Graph α β) (a : α) (b : β) := def Graph.insertNode (g : Graph α β) (a : α) (b : β) :=
-190
View File
@@ -1,190 +0,0 @@
import Lean
/-! This document contains various things which cluttered `Commands.lean`. -/
open Lean Meta Elab Command
syntax hintArg := atomic(" (" (&"strict" <|> &"hidden") " := " withoutPosition(term) ")")
/-! ## Doc Comment Parsing -/
/-- Read a doc comment and get its content. Return `""` if no doc comment available. -/
def parseDocComment! (doc: Option (TSyntax `Lean.Parser.Command.docComment)) :
CommandElabM String := do
match doc with
| none =>
logWarning "Add a text to this command with `/-- yada yada -/ MyCommand`!"
pure ""
| some s => match s.raw[1] with
| .atom _ val => pure <| val.dropRight 2 |>.trim -- some (val.extract 0 (val.endPos - ⟨2⟩))
| _ => pure "" --panic "not implemented error message" --throwErrorAt s "unexpected doc string{indentD s.raw[1]}"
/-- Read a doc comment and get its content. Return `none` if no doc comment available. -/
def parseDocComment (doc: Option (TSyntax `Lean.Parser.Command.docComment)) :
CommandElabM <| Option String := do
match doc with
| none => pure none
| some _ => parseDocComment! doc
/-- TODO: This is only used to provide some backwards compatibility and you can
replace `parseDocCommentLegacy` with `parseDocComment` in the future. -/
def parseDocCommentLegacy (doc: Option (TSyntax `Lean.Parser.Command.docComment))
(t : Option (TSyntax `str)) : CommandElabM <| String := do
match doc with
| none =>
match t with
| none =>
pure <| ← parseDocComment! doc
| some t =>
logWarningAt t "You should use the new Syntax:
/-- yada yada -/
YourCommand
instead of
YourCommand \"yada yada\"
"
pure t.getString
| some _ =>
match t with
| none =>
pure <| ← parseDocComment! doc
| some t =>
logErrorAt t "You must not provide both, a docstring and a string following the command!
Only use
/-- yada yada -/
YourCommand
and remove the string following it!"
pure <| ← parseDocComment! doc
/-! ## Statement string -/
def getStatement (name : Name) : CommandElabM MessageData := do
return ← addMessageContextPartial (.ofPPFormat { pp := fun
| some ctx => ctx.runMetaM <| PrettyPrinter.ppSignature name
| none => return "that's a bug." })
-- Note: We use `String` because we can't send `MessageData` as json, but
-- `MessageData` might be better for interactive highlighting.
/-- Get a string of the form `my_lemma (n : ℕ) : n + n = 2 * n`.
Note: A statement like `theorem abc : ∀ x : Nat, x ≥ 0` would be turned into
`theorem abc (x : Nat) : x ≥ 0` by `PrettyPrinter.ppSignature`. -/
def getStatementString (name : Name) : CommandElabM String := do
try
return ← (← getStatement name).toString
catch
| _ => throwError m!"Could not find {name} in context."
-- TODO: I think it would be nicer to unresolve Namespaces as much as possible.
/-- A `attr := ...` option for `Statement`. Add attributes to the defined theorem. -/
syntax statementAttr := "(" &"attr" ":=" Parser.Term.attrInstance,* ")"
-- TODO
/-- Remove any spaces at the beginning of a new line -/
partial def removeIndentation (s : String) : String :=
let rec loop (i : String.Pos) (acc : String) (removeSpaces := false) : String :=
let c := s.get i
let i := s.next i
if s.atEnd i then
acc.push c
else if removeSpaces && c == ' ' then
loop i acc (removeSpaces := true)
else if c == '\n' then
loop i (acc.push c) (removeSpaces := true)
else
loop i (acc.push c)
loop ⟨0⟩ ""
/-! ## Loops in Graph-like construct
TODO: Why are we not using graphs here but our own construct `HashMap Name (HashSet Name)`?
-/
partial def removeTransitiveAux (id : Name) (arrows : HashMap Name (HashSet Name))
(newArrows : HashMap Name (HashSet Name)) (decendants : HashMap Name (HashSet Name)) :
HashMap Name (HashSet Name) × HashMap Name (HashSet Name) := Id.run do
match (newArrows.find? id, decendants.find? id) with
| (some _, some _) => return (newArrows, decendants)
| _ =>
let mut newArr := newArrows
let mut desc := decendants
desc := desc.insert id {} -- mark as worked in case of loops
newArr := newArr.insert id {} -- mark as worked in case of loops
let children := arrows.findD id {}
let mut trimmedChildren := children
let mut theseDescs := children
for child in children do
(newArr, desc) := removeTransitiveAux child arrows newArr desc
let childDescs := desc.findD child {}
theseDescs := theseDescs.insertMany childDescs
for d in childDescs do
trimmedChildren := trimmedChildren.erase d
desc := desc.insert id theseDescs
newArr := newArr.insert id trimmedChildren
return (newArr, desc)
def removeTransitive (arrows : HashMap Name (HashSet Name)) : CommandElabM (HashMap Name (HashSet Name)) := do
let mut newArr := {}
let mut desc := {}
for id in arrows.toArray.map Prod.fst do
(newArr, desc) := removeTransitiveAux id arrows newArr desc
if (desc.findD id {}).contains id then
logError <| m!"Loop at {id}. " ++
m!"This should not happen and probably means that `findLoops` has a bug."
-- DEBUG:
-- for ⟨x, hx⟩ in desc.toList do
-- m := m ++ m!"{x}: {hx.toList}\n"
-- logError m
return newArr
/-- The recursive part of `findLoops`. Finds loops that appear as successors of `node`.
For performance reason it returns a HashSet of visited
nodes as well. This is filled with all nodes ever looked at as they cannot be
part of a loop anymore. -/
partial def findLoopsAux (arrows : HashMap Name (HashSet Name)) (node : Name)
(path : Array Name := #[]) (visited : HashSet Name := {}) :
Array Name × HashSet Name := Id.run do
let mut visited := visited
match path.getIdx? node with
| some i =>
-- Found a loop: `node` is already the iᵗʰ element of the path
return (path.extract i path.size, visited.insert node)
| none =>
for successor in arrows.findD node {} do
-- If we already visited the successor, it cannot be part of a loop anymore
if visited.contains successor then
continue
-- Find any loop involving `successor`
let (loop, _) := findLoopsAux arrows successor (path.push node) visited
visited := visited.insert successor
-- No loop found in the dependants of `successor`
if loop.isEmpty then
continue
-- Found a loop, return it
return (loop, visited)
return (#[], visited.insert node)
/-- Find a loop in the graph and return it. Returns `[]` if there are no loops. -/
partial def findLoops (arrows : HashMap Name (HashSet Name)) : List Name := Id.run do
let mut visited : HashSet Name := {}
for node in arrows.toArray.map (·.1) do
-- Skip a node if it was already visited
if visited.contains node then
continue
-- `findLoopsAux` returns a loop or `[]` together with a set of nodes it visited on its
-- search starting from `node`
let (loop, moreVisited) := (findLoopsAux arrows node (visited := visited))
visited := moreVisited
if !loop.isEmpty then
return loop.toList
return []
-108
View File
@@ -1,108 +0,0 @@
import Lean.Environment
import Std.Tactic.OpenPrivate
import Lean.Data.Lsp.Communication
open Lean
inductive LoadingKind := | finalizeExtensions | loadConstants
deriving ToJson
structure LoadingParams : Type where
counter : Nat
kind : LoadingKind
deriving ToJson
-- Code adapted from `Lean/Environment.lean`
partial def importModulesCore' (imports : Array Import) : ImportStateM Unit := do
for i in imports do
if i.runtimeOnly || (← get).moduleNameSet.contains i.module then
continue
modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module }
let mFile ← findOLean i.module
unless (← mFile.pathExists) do
throw <| IO.userError s!"object file '{mFile}' of module {i.module} does not exist"
let (mod, region) ← readModuleData mFile
importModulesCore' mod.imports
modify fun s => { s with
moduleData := s.moduleData.push mod
regions := s.regions.push region
moduleNames := s.moduleNames.push i.module
}
open private mkInitialExtensionStates Environment.mk setImportedEntries finalizePersistentExtensions
ensureExtensionsArraySize from Lean.Environment
private partial def finalizePersistentExtensions' (env : Environment) (mods : Array ModuleData) (opts : Options) : IO Environment := do
loop 0 env
where
loop (i : Nat) (env : Environment) : IO Environment := do
(← IO.getStdout).writeLspNotification {
method := "$/game/loading",
param := {counter := i, kind := .finalizeExtensions : LoadingParams} }
-- Recall that the size of the array stored `persistentEnvExtensionRef` may increase when we import user-defined environment extensions.
let pExtDescrs ← persistentEnvExtensionsRef.get
if i < pExtDescrs.size then
let extDescr := pExtDescrs[i]!
let s := extDescr.toEnvExtension.getState env
let prevSize := (← persistentEnvExtensionsRef.get).size
let prevAttrSize ← getNumBuiltinAttributes
let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts }
let mut env := extDescr.toEnvExtension.setState env { s with state := newState }
env ← ensureExtensionsArraySize env
if (← persistentEnvExtensionsRef.get).size > prevSize || (← getNumBuiltinAttributes) > prevAttrSize then
-- This branch is executed when `pExtDescrs[i]` is the extension associated with the `init` attribute, and
-- a user-defined persistent extension is imported.
-- Thus, we invoke `setImportedEntries` to update the array `importedEntries` with the entries for the new extensions.
env ← setImportedEntries env mods prevSize
-- See comment at `updateEnvAttributesRef`
env ← updateEnvAttributes env
loop (i + 1) env
else
return env
def finalizeImport' (s : ImportState) (imports : Array Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := do
let numConsts := s.moduleData.foldl (init := 0) fun numConsts mod =>
numConsts + mod.constants.size + mod.extraConstNames.size
let mut const2ModIdx : HashMap Name ModuleIdx := mkHashMap (capacity := numConsts)
let mut constantMap : HashMap Name ConstantInfo := mkHashMap (capacity := numConsts)
for h:modIdx in [0:s.moduleData.size] do
if modIdx % 100 = 0 then
let percentage := modIdx * 100 / s.moduleData.size
(← IO.getStdout).writeLspNotification {
method := "$/game/loading",
param := {counter := percentage, kind := .loadConstants : LoadingParams} }
let mod := s.moduleData[modIdx]'h.upper
for cname in mod.constNames, cinfo in mod.constants do
match constantMap.insert' cname cinfo with
| (constantMap', replaced) =>
constantMap := constantMap'
if replaced then
throwAlreadyImported s const2ModIdx modIdx cname
const2ModIdx := const2ModIdx.insert cname modIdx
for cname in mod.extraConstNames do
const2ModIdx := const2ModIdx.insert cname modIdx
let constants : ConstMap := SMap.fromHashMap constantMap false
let exts ← mkInitialExtensionStates
let env : Environment := Environment.mk
(const2ModIdx := const2ModIdx)
(constants := constants)
(extraConstNames := {})
(extensions := exts)
(header := {
quotInit := !imports.isEmpty -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel
imports := imports
regions := s.regions
moduleNames := s.moduleNames
moduleData := s.moduleData
})
let env ← setImportedEntries env s.moduleData
finalizePersistentExtensions' env s.moduleData opts
def importModules' (imports : Array Import) : IO Environment := do
withImporting do
let (_, s) ← importModulesCore' imports |>.run
let env ← finalizeImport' s imports {} 0
return env
-152
View File
@@ -1,152 +0,0 @@
import Lean
import GameServer.EnvExtensions
open Lean Elab Command
/-- Copied from `Mathlib.Tactic.HelpCmd`.
Gets the initial string token in a parser description. For example, for a declaration like
`syntax "bla" "baz" term : tactic`, it returns `some "bla"`. Returns `none` for syntax declarations
that don't start with a string constant. -/
partial def getHeadTk (e : Expr) : Option String :=
match (Expr.withApp e λ e a => (e.constName?.getD Name.anonymous, a)) with
| (``ParserDescr.node, #[_, _, p]) => getHeadTk p
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "withPosition")), p]) => getHeadTk p
| (``ParserDescr.unary, #[.app _ (.lit (.strVal "atomic")), p]) => getHeadTk p
| (``ParserDescr.binary, #[.app _ (.lit (.strVal "andthen")), p, _]) => getHeadTk p
| (``ParserDescr.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk
| (``ParserDescr.symbol, #[.lit (.strVal tk)]) => some tk
| (``Parser.withAntiquot, #[_, p]) => getHeadTk p
| (``Parser.leadingNode, #[_, _, p]) => getHeadTk p
| (``HAndThen.hAndThen, #[_, _, _, _, p, _]) => getHeadTk p
| (``Parser.nonReservedSymbol, #[.lit (.strVal tk), _]) => some tk
| (``Parser.symbol, #[.lit (.strVal tk)]) => some tk
| _ => none
/-! ## Doc entries -/
/-- Modified from `#help` in `Mathlib.Tactic.HelpCmd` -/
def getTacticDocstring (env : Environment) (name: Name) : CommandElabM (Option String) := do
let name := name.toString (escape := false)
let mut decls : Lean.RBMap String (Array SyntaxNodeKind) compare := {}
let catName : Name := `tactic
let catStx : Ident := mkIdent catName -- TODO
let some cat := (Parser.parserExtension.getState env).categories.find? catName
| throwErrorAt catStx "{catStx} is not a syntax category"
liftTermElabM <| Term.addCategoryInfo catStx catName
for (k, _) in cat.kinds do
let mut used := false
if let some tk := do getHeadTk (← (← env.find? k).value?) then
let tk := tk.trim
if name ≠ tk then -- was `!name.isPrefixOf tk`
continue
used := true
decls := decls.insert tk ((decls.findD tk #[]).push k)
for (_name, ks) in decls do
for k in ks do
if let some doc ← findDocString? env k then
return doc
logWarning <| m!"Could not find a docstring for tactic {name}, consider adding one " ++
m!"using `TacticDoc {name} \"some doc\"`"
return none
/-- Retrieve the docstring associated to an inventory item. For Tactics, this
is not guaranteed to work. -/
def getDocstring (env : Environment) (name : Name) (type : InventoryType) :
CommandElabM (Option String) :=
match type with
-- for tactics it's a lookup following mathlib's `#help`. not guaranteed to be the correct one.
| .Tactic => getTacticDocstring env name
| .Lemma => findDocString? env name
-- TODO: for definitions not implemented yet, does it work?
| .Definition => findDocString? env name
/-- Checks if `inventoryTemplateExt` contains an entry with `(type, name)` and yields
a warning otherwise. If `template` is provided, it will add such an entry instead of yielding a
warning.
`ref` is the syntax piece. If `name` is not provided, it will use `ident.getId`.
I used this workaround, because I needed a new name (with correct namespace etc)
to be used, and I don't know how to create a new ident with same position but different name.
-/
def checkInventoryDoc (type : InventoryType) (ref : Ident) (name : Name := ref.getId)
(template : Option String := none) : CommandElabM Unit := do
-- note: `name` is an `Ident` (instead of `Name`) for the log messages.
let env ← getEnv
let n := name
-- Find a key with matching `(type, name)`.
match (inventoryTemplateExt.getState env).findIdx?
(fun x => x.name == n && x.type == type) with
-- Nothing to do if the entry exists
| some _ => pure ()
| none =>
match template with
-- Warn about missing documentation
| none =>
let docstring ← match (← getDocstring env name type) with
| some ds =>
logInfoAt ref (m!"Missing {type} Documentation. Using existing docstring. " ++
m!"Add {name}\nAdd `{type}Doc {name}` somewhere above this statement.")
pure s!"*(lean docstring)*\\\n{ds}"
| none =>
logWarningAt ref (m!"Missing {type} Documentation: {name}\nAdd `{type}Doc {name}` " ++
m!"somewhere above this statement.")
pure "(missing)"
-- We just add a dummy entry
modifyEnv (inventoryTemplateExt.addEntry · {
type := type
name := name
category := if type == .Lemma then s!"{n.getPrefix}" else ""
content := docstring})
-- Add the default documentation
| some s =>
modifyEnv (inventoryTemplateExt.addEntry · {
type := type
name := name
category := if type == .Lemma then s!"{n.getPrefix}" else ""
content := s })
logInfoAt ref (m!"Missing {type} Documentation: {name}, used default (e.g. provided " ++
m!"docstring) instead. If you want to write a different description, add " ++
m!"`{type}Doc {name}` somewhere above this statement.")
partial def collectUsedInventory (stx : Syntax) (acc : UsedInventory := {}) : CommandElabM UsedInventory := do
match stx with
| .missing => return acc
| .node _info kind args =>
if kind == `GameServer.Tactic.Hint || kind == `GameServer.Tactic.Branch then return acc
return ← args.foldlM (fun acc arg => collectUsedInventory arg acc) acc
| .atom _info val =>
-- ignore syntax elements that do not start with a letter
-- and ignore some standard keywords
let allowed := ["with", "fun", "at", "only", "by"]
if 0 < val.length ∧ val.data[0]!.isAlpha ∧ not (allowed.contains val) then
let val := val.dropRightWhile (fun c => c == '!' || c == '?') -- treat `simp?` and `simp!` like `simp`
return {acc with tactics := acc.tactics.insert val}
else
return acc
| .ident _info _rawVal val _preresolved =>
let ns ←
try resolveGlobalConst (mkIdent val)
catch | _ => pure [] -- catch "unknown constant" error
return ← ns.foldlM (fun acc n => do
if let some (.thmInfo ..) := (← getEnv).find? n then
return {acc with lemmas := acc.lemmas.insertMany ns}
else
return {acc with definitions := acc.definitions.insertMany ns}
) acc
-- #check expandOptDocComment?
def GameLevel.getInventory (level : GameLevel) : InventoryType → InventoryInfo
| .Tactic => level.tactics
| .Definition => level.definitions
| .Lemma => level.lemmas
def GameLevel.setComputedInventory (level : GameLevel) :
InventoryType → Array InventoryTile → GameLevel
| .Tactic, v => {level with tactics := {level.tactics with tiles := v}}
| .Definition, v => {level with definitions := {level.definitions with tiles := v}}
| .Lemma, v => {level with lemmas := {level.lemmas with tiles := v}}
-17
View File
@@ -1,17 +0,0 @@
import Lean
/-! This document contains custom options available in the game. -/
/-- Let `MakeGame` print the reasons why the worlds depend on each other. -/
register_option lean4game.showDependencyReasons : Bool := {
defValue := false
descr := "show reasons for calculated world dependencies."
}
/-- Let `MakeGame` print the reasons why the worlds depend on each other.
Note: currently unused in favour of setting `set_option trace.debug true`. -/
register_option lean4game.verbose : Bool := {
defValue := false
descr := "display more info messages to help developing the game."
}
+10 -11
View File
@@ -46,8 +46,8 @@ partial def matchExpr (pattern : Expr) (e : Expr) (bij : FVarBijection := {}) :
| .bvar i1, .bvar i2 => if i1 == i2 then bij else none | .bvar i1, .bvar i2 => if i1 == i2 then bij else none
| .fvar i1, .fvar i2 => bij.insert? i1 i2 | .fvar i1, .fvar i2 => bij.insert? i1 i2
| .mvar _, .mvar _ => bij | .mvar _, .mvar _ => bij
| .sort _u1, .sort _u2 => bij -- TODO? | .sort u1, .sort u2 => bij -- TODO?
| .const n1 _ls1, .const n2 _ls2 => | .const n1 ls1, .const n2 ls2 =>
if n1 == n2 then bij else none -- && (← (ls1.zip ls2).allM fun (l1, l2) => Meta.isLevelDefEq l1 l2) if n1 == n2 then bij else none -- && (← (ls1.zip ls2).allM fun (l1, l2) => Meta.isLevelDefEq l1 l2)
| .app f1 a1, .app f2 a2 => | .app f1 a1, .app f2 a2 =>
some bij some bij
@@ -78,7 +78,7 @@ partial def matchExpr (pattern : Expr) (e : Expr) (bij : FVarBijection := {}) :
| _, _ => none | _, _ => none
/-- Check if each fvar in `patterns` has a matching fvar in `fvars` -/ /-- Check if each fvar in `patterns` has a matching fvar in `fvars` -/
def matchDecls (patterns : Array Expr) (fvars : Array Expr) (strict := true) (initBij : FVarBijection := {}) : MetaM (Option FVarBijection) := do def matchDecls (patterns : Array Expr) (fvars : Array Expr) (strict := true) (initBij : FVarBijection := {}) : MetaM Bool := do
-- We iterate through the array backwards hoping that this will find us faster results -- We iterate through the array backwards hoping that this will find us faster results
-- TODO: implement backtracking -- TODO: implement backtracking
let mut bij := initBij let mut bij := initBij
@@ -97,11 +97,11 @@ def matchDecls (patterns : Array Expr) (fvars : Array Expr) (strict := true) (in
-- usedFvars := usedFvars.set! (fvars.size - j - 1) true -- usedFvars := usedFvars.set! (fvars.size - j - 1) true
bij := bij'.insert pattern.fvarId! fvar.fvarId! bij := bij'.insert pattern.fvarId! fvar.fvarId!
break break
if ! bij.forward.contains pattern.fvarId! then return none if ! bij.forward.contains pattern.fvarId! then return false
if !strict || fvars.all (fun fvar => bij.backward.contains fvar.fvarId!) if strict then
then return some bij return fvars.all (fun fvar => bij.backward.contains fvar.fvarId!)
else return none return true
unsafe def evalHintMessageUnsafe : Expr → MetaM (Array Expr → MessageData) := unsafe def evalHintMessageUnsafe : Expr → MetaM (Array Expr → MessageData) :=
evalExpr (Array Expr → MessageData) evalExpr (Array Expr → MessageData)
@@ -122,11 +122,10 @@ def findHints (goal : MVarId) (doc : FileWorker.EditableDocument) (initParams :
if let some fvarBij := matchExpr (← instantiateMVars $ hintGoal) (← instantiateMVars $ ← inferType $ mkMVar goal) if let some fvarBij := matchExpr (← instantiateMVars $ hintGoal) (← instantiateMVars $ ← inferType $ mkMVar goal)
then then
let lctx := (← goal.getDecl).lctx let lctx := (← goal.getDecl).lctx
if let some bij ← matchDecls hintFVars lctx.getFVars (strict := hint.strict) (initBij := fvarBij) if ← matchDecls hintFVars lctx.getFVars (strict := hint.strict) (initBij := fvarBij)
then then
let userFVars := hintFVars.map fun v => bij.forward.findD v.fvarId! v.fvarId! let text := (← evalHintMessage hint.text) hintFVars
let text := (← evalHintMessage hint.text) (userFVars.map Expr.fvar) let ctx := {env := ← getEnv, mctx := ← getMCtx, lctx := ← getLCtx, opts := {}}
let ctx := {env := ← getEnv, mctx := ← getMCtx, lctx := lctx, opts := {}}
let text ← (MessageData.withContext ctx text).toString let text ← (MessageData.withContext ctx text).toString
return some { text := text, hidden := hint.hidden } return some { text := text, hidden := hint.hidden }
else return none else return none
-78
View File
@@ -1,78 +0,0 @@
import GameServer.EnvExtensions
open Lean Meta Elab Command
/-! ## Copy images -/
open IO.FS System FilePath in
/-- Copies the folder `images/` to `.lake/gamedata/images/` -/
def copyImages : IO Unit := do
let target : FilePath := ".lake" / "gamedata"
if ← FilePath.pathExists "images" then
for file in ← walkDir "images" do
let outFile := target.join file
-- create the directories
if ← file.isDir then
createDirAll outFile
else
if let some parent := outFile.parent then
createDirAll parent
-- copy file
let content ← readBinFile file
writeBinFile outFile content
namespace GameData
def gameDataPath : System.FilePath := ".lake" / "gamedata"
def gameFileName := s!"game.json"
def docFileName := fun (inventoryType : InventoryType) (name : Name) => s!"doc__{inventoryType}__{name}.json"
def levelFileName := fun (worldId : Name) (levelId : Nat) => s!"level__{worldId}__{levelId}.json"
def inventoryFileName := s!"inventory.json"
end GameData
open GameData in
-- TODO: register all of this as ToJson instance?
def saveGameData (allItemsByType : HashMap InventoryType (HashSet Name))
(inventory : InventoryOverview): CommandElabM Unit := do
let game ← getCurGame
let env ← getEnv
let path := (← IO.currentDir) / gameDataPath
if ← path.isDir then
IO.FS.removeDirAll path
IO.FS.createDirAll path
-- copy the images folder
copyImages
for (worldId, world) in game.worlds.nodes.toArray do
for (levelId, level) in world.levels.toArray do
IO.FS.writeFile (path / levelFileName worldId levelId) (toString (toJson (level.toInfo env)))
IO.FS.writeFile (path / gameFileName) (toString (getGameJson game))
for inventoryType in [InventoryType.Lemma, .Tactic, .Definition] do
for name in allItemsByType.findD inventoryType {} do
let some item ← getInventoryItem? name inventoryType
| throwError "Expected item to exist: {name}"
IO.FS.writeFile (path / docFileName inventoryType name) (toString (toJson item))
IO.FS.writeFile (path / inventoryFileName) (toString (toJson inventory))
open GameData
def loadData (f : System.FilePath) (α : Type) [FromJson α] : IO α := do
let str ← IO.FS.readFile f
let json ← match Json.parse str with
| .ok v => pure v
| .error e => throw (IO.userError e)
let data ← match fromJson? json with
| .ok v => pure v
| .error e => throw (IO.userError e)
return data
def loadGameData (gameDir : System.FilePath) : IO Game :=
loadData (gameDir / gameDataPath / gameFileName) Game
def loadLevelData (gameDir : System.FilePath) (worldId : Name) (levelId : Nat) : IO LevelInfo :=
loadData (gameDir / gameDataPath / levelFileName worldId levelId) LevelInfo
+257
View File
@@ -0,0 +1,257 @@
import Lean.Server.Watchdog
import GameServer.FileWorker
import GameServer.EnvExtensions
import GameServer.Game
namespace WasmServer.Watchdog
open Lean
open Server
open Watchdog
open IO
open Lsp
open JsonRpc
open System.Uri
open MyServer.FileWorker
structure WasmFileState :=
fileWorkerState : FileWorker.WorkerState
gameWorkerState : GameWorkerState
headerTask : Task (Except Error (Snapshots.Snapshot × SearchPath))
structure WasmServerState :=
initParams? : Option InitializeParams
gameServerState : GameServerState
fileState : HashMap String WasmFileState := {}
def wasmSearchPath : SearchPath := ["/lib", "/gamelib"]
@[export game_make_state]
unsafe def makeState : IO WasmServerState := do
let e ← IO.getStderr
try
Lean.enableInitializersExecution
searchPathRef.set wasmSearchPath
let env ← importModules #[
{ module := `GameServer : Import }
] {} 0
let state : GameServerState := {
env,
game := `TestGame,
gameDir := "test",
inventory := #[]
difficulty := 0
}
return ⟨none, state, {}⟩
catch err =>
e.putStrLn s!"Import error: {err}"
throw err
def readMessage (s : String) : IO JsonRpc.Message := do
let j ← ofExcept (Json.parse s)
let m ← match fromJson? j with
| Except.ok (m : JsonRpc.Message) => pure m
| Except.error inner => throw $ userError s!"JSON '{j.compress}' did not have the format of a JSON-RPC message.\n{inner}"
return m
def readLspRequestAs (s : String) (expectedMethod : String) (α : Type) [FromJson α] : IO (Request α) := do
let m ← readMessage s
match m with
| Message.request id method params? =>
if method = expectedMethod then
let j := toJson params?
match fromJson? j with
| Except.ok v => pure $ JsonRpc.Request.mk id expectedMethod (v : α)
| Except.error inner => throw $ userError s!"Unexpected param '{j.compress}' for method '{expectedMethod}'\n{inner}"
else
throw $ userError s!"Expected method '{expectedMethod}', got method '{method}'"
| _ => throw $ userError s!"Expected JSON-RPC request, got: '{(toJson m).compress}'"
def initializeServer (id : RequestID) : IO Unit := do
let o ← IO.getStdout
o.writeLspResponse {
id := id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 Game Server"
version? := "0.1.1"
}
: InitializeResult
}
}
return ()
def mkServerContext (state : WasmServerState) : IO ServerContext := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
let srcSearchPath ← searchPathRef.get
let references ← IO.mkRef (← loadReferences)
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let workerPath := "no-worker-path"
let some initParams := state.initParams?
| throwServerError "no yet initialized"
return {
hIn := i
hOut := o
hLog := e
args := []
fileWorkersRef := fileWorkersRef
initParams
workerPath
srcSearchPath
references
}
def runGameServerM (state : WasmServerState) (x : GameServerM α) : IO (α × WasmServerState) := do
let (res, gameServerState) ← ReaderT.run
(StateT.run x state.gameServerState)
(← mkServerContext state)
return (res, {state with gameServerState})
def mkWorkerContext (state : WasmServerState) (headerTask : Task (Except Error (Snapshots.Snapshot × SearchPath))) :
IO FileWorker.WorkerContext := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
let some initParams := state.initParams?
| throwServerError "no yet initialized"
let clientHasWidgets := initParams.initializationOptions?.bind (·.hasWidgets?) |>.getD false
return {
hIn := i
hOut := o
hLog := e
headerTask := headerTask
initParams := initParams
clientHasWidgets
}
def runGameWorkerM (state : WasmServerState) (fileState : WasmFileState) (x : GameWorkerM α) :
IO (α × WasmFileState) := do
let s := fileState.fileWorkerState
let ctx ← mkWorkerContext state fileState.headerTask
let ((res, gameWorkerState), s) ← StateRefT'.run (s := s) <| ReaderT.run (r := ctx) <|
StateT.run (s := fileState.gameWorkerState) <| x
let fileState := {fileState with gameWorkerState := gameWorkerState, fileWorkerState := s}
return (res, fileState)
def parseParams {paramType : Type} [FromJson paramType] (params : Json) : IO paramType :=
match fromJson? params with
| Except.ok parsed => pure parsed
| Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}"
def requestWorkerUri (method : String) (params : Json) : IO (Option DocumentUri) := do
if method == "$/lean/rpc/connect" then
let ps : Lsp.RpcConnectParams ← parseParams params
pure <| fileSource ps
else match (← routeLspRequest method params) with
| Except.error e =>
throwServerError e.message
| Except.ok uri => pure uri
open FileWorker in
def handleDidOpen (params : DidOpenTextDocumentParams) (state : WasmServerState) : IO WasmServerState := do
let some initParams := state.initParams?
| throwServerError "no yet initialized"
let (_, state) ← runGameServerM state do
let some lvl ← GameServer.getLevelByFileName? initParams
((System.Uri.fileUriToPath? params.textDocument.uri).getD params.textDocument.uri |>.toString)
| throwServerError s!"Level not found: {params.textDocument.uri} | {initParams.rootUri?}"
let env ← importModules #[
{ module := lvl.module : Import }
] {} 0
(← getStderr).putStr "Import for level completed"
let doc := params.textDocument
let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap, .always⟩
let clientHasWidgets := initParams.initializationOptions?.bind (·.hasWidgets?) |>.getD false
let (headerStx, headerTask) ← mkHeaderTask meta (← getStdout) wasmSearchPath env {} clientHasWidgets
let cancelTk ← CancelToken.new
let levelParams := {
uri := meta.uri
gameDir := state.gameServerState.gameDir
levelModule := lvl.module
tactics := lvl.tactics.tiles
lemmas := lvl.lemmas.tiles
definitions := lvl.definitions.tiles
inventory := state.gameServerState.inventory
difficulty := state.gameServerState.difficulty
statementName := lvl.statementName
: Game.DidOpenLevelParams
}
let ctx ← mkWorkerContext state headerTask
let cmdSnaps ← EIO.mapTask (t := headerTask) (match · with
| Except.ok (s, _) => unfoldSnaps meta #[s] cancelTk levelParams ctx (startAfterMs := 0)
| Except.error e => throw (e : ElabTaskError))
let doc : EditableDocument := { meta, cmdSnaps := AsyncList.delayed cmdSnaps, cancelTk }
let s : WasmFileState := {
fileWorkerState := {
doc := doc
initHeaderStx := headerStx
pendingRequests := RBMap.empty
rpcSessions := RBMap.empty
}
gameWorkerState := { levelParams }
headerTask
}
let fileState := state.fileState.insert params.textDocument.uri s
return {state with fileState}
return state
@[export game_send_message]
unsafe def sendMessage (s : String) (state : WasmServerState) : IO WasmServerState := do
let e ← IO.getStderr
try
let m ← readMessage s
match m with
| Message.request id "initialize" (some params) =>
let p : InitializeParams ← parseParams (toJson params)
initializeServer id
let p := {p with rootUri? := some (toString state.gameServerState.game)}
return {state with initParams? := some p}
| _ =>
let (isGameEv, state) ← runGameServerM state (Game.handleServerEvent (.clientMsg m))
if isGameEv then
return state
else
match m with
| Message.notification method (some params) =>
let handle := (fun α [FromJson α] (handler : α → WasmServerState → IO WasmServerState)
=> parseParams (toJson params) >>= (handler · state))
match method with --TODO
| "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen
-- | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
-- | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose
-- | "workspace/didChangeWatchedFiles" => handle DidChangeWatchedFilesParams handleDidChangeWatchedFiles
-- | "$/cancelRequest" => handle CancelParams handleCancelRequest
-- | "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method)
-- | "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method)
-- | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method)
| _ => return state
| Message.request id method (some params) =>
let some uri ← requestWorkerUri method (toJson params)
| throwServerError s!"Could not find Uri for request: {method}"
let some fileState := state.fileState.find? uri
| throwServerError s!"File not open: {uri}"
let (_, fileState) ← runGameWorkerM state fileState do
MyServer.FileWorker.mainLoop1 m
let fileState := state.fileState.insert uri fileState
return {state with fileState}
| Message.responseError _ _ e .. =>
throwServerError s!"Unhandled response error: {e}"
| _ => throwServerError "Got invalid JSON-RPC message"
-- match m with
-- | _ =>
-- e.putStrLn s!"Expected JSON-RPC request, got: '{(toJson m).compress}'"
-- return state
catch err =>
e.putStrLn s!"Server error: {err}"
return state
+158
View File
@@ -0,0 +1,158 @@
/- This file is mostly copied from `Lean/Server/Watchdog.lean`. -/
import Lean.Server.Watchdog
import GameServer.Game
namespace MyServer.Watchdog
open Lean
open Server
open Watchdog
open IO
open Lsp
open JsonRpc
open System.Uri
partial def mainLoop (clientTask : Task ServerEvent) : GameServerM Unit := do
let st ← read
let workers ← st.fileWorkersRef.get
let mut workerTasks := #[]
for (_, fw) in workers do
if let WorkerState.running := fw.state then
workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw)
let ev ← IO.waitAny (clientTask :: workerTasks.toList)
if ← Game.handleServerEvent ev then -- handle Game requests
mainLoop (←runClientTask)
else
match ev with
| ServerEvent.clientMsg msg =>
match msg with
| Message.request id "shutdown" _ =>
shutdown
st.hOut.writeLspResponse ⟨id, Json.null⟩
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop (←runClientTask)
| Message.response .. =>
-- TODO: handle client responses
mainLoop (←runClientTask)
| Message.responseError _ _ e .. =>
throwServerError s!"Unhandled response error: {e}"
| Message.notification method (some params) =>
if method == "textDocument/didOpen" then
-- for lean4game, we need to pass in extra information when a level is opened:
Game.handleDidOpenLevel (← parseParams _ (toJson params))
else
handleNotification method (toJson params)
mainLoop (←runClientTask)
| _ => throwServerError "Got invalid JSON-RPC message"
| ServerEvent.clientError e => throw e
| ServerEvent.workerEvent fw ev =>
match ev with
| WorkerEvent.ioError e =>
throwServerError s!"IO error while processing events for {fw.doc.uri}: {e}"
| WorkerEvent.crashed _ =>
handleCrash fw.doc.uri #[]
mainLoop clientTask
| WorkerEvent.terminated =>
throwServerError "Internal server error: got termination event for worker that should have been removed"
| .importsChanged =>
startFileWorker fw.doc
mainLoop clientTask
def initAndRunWatchdogAux : GameServerM Unit := do
let st ← read
try
discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams
let clientTask ← runClientTask
mainLoop clientTask
catch err =>
shutdown
throw err
/- NOTE(WN): It looks like instead of sending the `exit` notification,
VSCode just closes the stream. In that case, pretend we got an `exit`. -/
let Message.notification "exit" none ←
try st.hIn.readLspMessage
catch _ => pure (Message.notification "exit" none)
| throwServerError "Got `shutdown` request, expected an `exit` notification"
def createEnv (gameDir : String) (module : String) : IO Environment := do
-- Determine search paths of the game project by running `lake env printenv LEAN_PATH`.
let out ← IO.Process.output
{ cwd := gameDir, cmd := "lake", args := #["env","printenv","LEAN_PATH"] }
if out.exitCode != 0 then
throwServerError s!"Error while running Lake: {out.stderr}"
-- Make the paths relative to the current directory
let paths : List System.FilePath := System.SearchPath.parse out.stdout.trim
let currentDir ← IO.currentDir
let paths := paths.map fun p => currentDir / (gameDir : System.FilePath) / p
-- Set the search path
Lean.searchPathRef.set paths
let env ← importModules #[{ module := `Init : Import }, { module := module : Import }] {} 0
return env
def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do
if args.length < 2 then
throwServerError s!"Expected 1-3 command line arguments in addition to `--server`:
game directory, the name of the main module (optional), and the name of the game (optional)."
let gameDir := args[1]!
let module := if args.length < 3 then defaultGameModule else args[2]!
let gameName := if args.length < 4 then defaultGameName else args[3]!
let workerPath := "./gameserver"
-- TODO: Do the following commands slow us down?
let srcSearchPath ← initSrcSearchPath (← getBuildDir)
let references ← IO.mkRef (← loadReferences)
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let i ← maybeTee "wdIn.txt" false i
let o ← maybeTee "wdOut.txt" true o
let e ← maybeTee "wdErr.txt" true e
let state := {
env := ← createEnv gameDir module,
game := gameName,
gameDir := gameDir,
inventory := #[]
difficulty := 0
}
let initRequest ← i.readLspRequestAs "initialize" InitializeParams
-- We misuse the `rootUri` field to the gameName
let rootUri? := gameName
let initRequest := {initRequest with param := {initRequest.param with rootUri?}}
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 Game Server"
version? := "0.1.1"
}
: InitializeResult
}
}
let context : ServerContext := {
hIn := i
hOut := o
hLog := e
args := args
fileWorkersRef := fileWorkersRef
initParams := initRequest.param
workerPath
srcSearchPath
references
}
discard $ ReaderT.run (StateT.run initAndRunWatchdogAux state) context
def watchdogMain (args : List String) : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWatchdog args i o e
return 0
catch err =>
e.putStrLn s!"Watchdog error: {err}"
return 1
end MyServer.Watchdog
+23
View File
@@ -0,0 +1,23 @@
import GameServer.FileWorker
import GameServer.Watchdog
import GameServer.WasmServer
import GameServer.Commands
-- TODO: The only reason we import `Commands` is so that it gets built to on `lake build`
-- should we have a different solution?
unsafe def main : List String → IO UInt32 := fun args => do
let e ← IO.getStderr
Lean.enableInitializersExecution
if args[0]? == some "--server" then
MyServer.Watchdog.watchdogMain args
else if args[0]? == some "--worker" then
MyServer.FileWorker.workerMain {}
else
e.putStrLn s!"Expected `--server` or `--worker`"
return 1
-- TODO: Potentially it could be useful to pass in the `gameName` via the websocket connection
+5 -10
View File
@@ -1,17 +1,12 @@
#/bin/bash #/bin/bash
# Note: This fails if there is no default toolchain installed
ELAN_HOME=$(lake env printenv ELAN_HOME) ELAN_HOME=$(lake env printenv ELAN_HOME)
# $1 : the game directory
# $2 : the lean4game folder
# $3 : the gameserver executable
(exec bwrap\ (exec bwrap\
--bind $2 /lean4game \ --ro-bind ../../lean4game /lean4game \
--bind $1 /game \ --ro-bind ../../$1 /game \
--bind $ELAN_HOME /elan \ --ro-bind $ELAN_HOME /elan \
--bind /usr /usr \ --ro-bind /usr /usr \
--dev /dev \ --dev /dev \
--proc /proc \ --proc /proc \
--symlink usr/lib /lib\ --symlink usr/lib /lib\
@@ -27,6 +22,6 @@ ELAN_HOME=$(lake env printenv ELAN_HOME)
--unshare-uts \ --unshare-uts \
--unshare-cgroup \ --unshare-cgroup \
--die-with-parent \ --die-with-parent \
--chdir "/game/.lake/packages/GameServer/server/.lake/build/bin/" \ --chdir "/lean4game/server/build/bin/" \
./gameserver --server /game ./gameserver --server /game
) )
+20 -31
View File
@@ -11,7 +11,6 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
const TOKEN = process.env.LEAN4GAME_GITHUB_TOKEN const TOKEN = process.env.LEAN4GAME_GITHUB_TOKEN
const USERNAME = process.env.LEAN4GAME_GITHUB_USER
const octokit = new Octokit({ const octokit = new Octokit({
auth: TOKEN auth: TOKEN
}) })
@@ -42,10 +41,9 @@ async function download(id, url, dest) {
requestProgress(request({ requestProgress(request({
url, url,
headers: { headers: {
'accept': 'application/vnd.github+json', 'User-Agent': 'abentkamp',
'User-Agent': USERNAME,
'X-GitHub-Api-Version': '2022-11-28', 'X-GitHub-Api-Version': '2022-11-28',
'Authorization': 'Bearer ' + TOKEN 'Authorization': 'Bearer '+TOKEN
} }
})) }))
.on('progress', function (state) { .on('progress', function (state) {
@@ -78,44 +76,35 @@ async function doImport (owner, repo, id) {
.reduce((acc, cur) => acc.created_at < cur.created_at ? cur : acc) .reduce((acc, cur) => acc.created_at < cur.created_at ? cur : acc)
artifactId = artifact.id artifactId = artifact.id
const url = artifact.archive_download_url const url = artifact.archive_download_url
// Make sure the download folder exists if (!fs.existsSync("tmp")){
if (!fs.existsSync(path.join(__dirname, "..", "games"))){ fs.mkdirSync("tmp");
fs.mkdirSync(path.join(__dirname, "..", "games"));
}
if (!fs.existsSync(path.join(__dirname, "..", "games", "tmp"))){
fs.mkdirSync(path.join(__dirname, "..", "games", "tmp"));
} }
progress[id].output += `Download from ${url}\n` progress[id].output += `Download from ${url}\n`
await download(id, url, path.join(__dirname, "..", "games", "tmp", `${owner.toLowerCase()}_${repo.toLowerCase()}_${artifactId}.zip`)) await download(id, url, `tmp/artifact_${artifactId}.zip`)
progress[id].output += `Download finished.\n` progress[id].output += `Download finished.\n`
await runProcess(id, "/bin/bash", [`${__dirname}/unpack.sh`, artifactId],".")
await runProcess(id, "/bin/bash", [path.join(__dirname, "unpack.sh"), artifactId, owner.toLowerCase(), repo.toLowerCase()], path.join(__dirname, "..")) let manifest = fs.readFileSync(`tmp/artifact_${artifactId}_inner/manifest.json`);
manifest = JSON.parse(manifest);
if (manifest.length !== 1) {
// let manifest = fs.readFileSync(`tmp/artifact_${artifactId}_inner/manifest.json`); throw `Unexpected manifest: ${JSON.stringify(manifest)}`
// manifest = JSON.parse(manifest); }
// if (manifest.length !== 1) { manifest[0].RepoTags = [`g/${owner.toLowerCase()}/${repo.toLowerCase()}:latest`]
// throw `Unexpected manifest: ${JSON.stringify(manifest)}` fs.writeFileSync(`tmp/artifact_${artifactId}_inner/manifest.json`, JSON.stringify(manifest));
// } await runProcess(id, "tar", ["-cvf", `../archive_${artifactId}.tar`, "."], `tmp/artifact_${artifactId}_inner/`)
// manifest[0].RepoTags = [`g/${owner.toLowerCase()}/${repo.toLowerCase()}:latest`] await runProcess(id, "docker", ["load", "-i", `tmp/archive_${artifactId}.tar`])
// fs.writeFileSync(`tmp/artifact_${artifactId}_inner/manifest.json`, JSON.stringify(manifest));
// await runProcess(id, "tar", ["-cvf", `../archive_${artifactId}.tar`, "."], `tmp/artifact_${artifactId}_inner/`)
// // await runProcess(id, "docker", ["load", "-i", `tmp/archive_${artifactId}.tar`])
progress[id].done = true progress[id].done = true
progress[id].output += `Done!\n` progress[id].output += `Done.\n`
progress[id].output += `Play the game at: {your website}/#/g/${owner}/${repo}\n`
} catch (e) { } catch (e) {
progress[id].output += `Error: ${e.toString()}\n${e.stack}` progress[id].output += `Error: ${e.toString()}\n${e.stack}`
} finally { } finally {
// clean-up temp. files
if (artifactId) { if (artifactId) {
fs.rmSync(path.join(__dirname, "..", "games", "tmp", `${owner}_${repo}_${artifactId}.zip`), {force: true, recursive: false}); fs.rmSync(`tmp/artifact_${artifactId}.zip`, {force: true, recursive: true});
fs.rmSync(path.join(__dirname, "..", "games", "tmp", `${owner}_${repo}_${artifactId}`), {force: true, recursive: true}); fs.rmSync(`tmp/artifact_${artifactId}`, {force: true, recursive: true});
fs.rmSync(`tmp/artifact_${artifactId}_inner`, {force: true, recursive: true});
fs.rmSync(`tmp/archive_${artifactId}.tar`, {force: true, recursive: true});
} }
progress[id].done = true progress[id].done = true
} }
await new Promise(resolve => setTimeout(resolve, 10000))
} }
export const importTrigger = (req, res) => { export const importTrigger = (req, res) => {
+57 -88
View File
@@ -6,21 +6,25 @@ import * as url from 'url';
import * as rpc from 'vscode-ws-jsonrpc'; import * as rpc from 'vscode-ws-jsonrpc';
import * as jsonrpcserver from 'vscode-ws-jsonrpc/server'; import * as jsonrpcserver from 'vscode-ws-jsonrpc/server';
import os from 'os'; import os from 'os';
import fs from 'fs';
import anonymize from 'ip-anonymize'; import anonymize from 'ip-anonymize';
import { importTrigger, importStatus } from './import.mjs' // import { importTrigger, importStatus } from './import.mjs'
// import fs from 'fs' // import fs from 'fs'
/** /**
* Add a game here if the server should keep a queue of pre-loaded games ready at all times.
*
* IMPORTANT! Tags here need to be lower case!
*/ */
const queueLength = { const games = {
"g/hhu-adam/robo": 2, "g/hhu-adam/robo": {
"g/hhu-adam/nng4": 5, dir: "Robo",
"g/djvelleman/stg4": 0, queueLength: 5
"g/trequetrum/lean4game-logic": 0, },
"g/hhu-adam/nng4": {
dir: "NNG4",
queueLength: 5
},
"g/hhu-adam/nng4-old": {
dir: "NNG4-OLD",
queueLength: 0
}
} }
const __filename = url.fileURLToPath(import.meta.url); const __filename = url.fileURLToPath(import.meta.url);
@@ -32,18 +36,11 @@ const PORT = process.env.PORT || 8080;
var router = express.Router(); var router = express.Router();
router.get('/import/status/:owner/:repo', importStatus) // router.get('/import/status/:owner/:repo', importStatus)
router.get('/import/trigger/:owner/:repo', importTrigger) // router.get('/import/trigger/:owner/:repo', importTrigger)
const server = app const server = app
.use(express.static(path.join(__dirname, '..', 'client', 'dist'))) // TODO: add a dist folder from inside the game .use(express.static(path.join(__dirname, '../client/dist/')))
.use('/data/g/:owner/:repo/*', (req, res, next) => {
const owner = req.params.owner;
const repo = req.params.repo
const filename = req.params[0];
req.url = filename;
express.static(path.join(getGameDir(owner,repo),".lake","gamedata"))(req, res, next);
})
.use('/', router) .use('/', router)
.listen(PORT, () => console.log(`Listening on ${PORT}`)); .listen(PORT, () => console.log(`Listening on ${PORT}`));
@@ -57,61 +54,41 @@ const isDevelopment = environment === 'development'
/** We keep queues of started Lean Server processes to be ready when a user arrives */ /** We keep queues of started Lean Server processes to be ready when a user arrives */
const queue = {} const queue = {}
function getTag(owner, repo) { function tag(owner, repo) {
return `g/${owner.toLowerCase()}/${repo.toLowerCase()}` return `g/${owner.toLowerCase()}/${repo.toLowerCase()}`
} }
function getGameDir(owner, repo) { function startServerProcess(owner, repo) {
owner = owner.toLowerCase() let game_dir = (owner == 'local') ?
repo : games[tag(owner, repo)]?.dir
if (owner == 'local') { if (owner == 'local') {
if(!isDevelopment) { if(!isDevelopment) {
console.error(`No local games in production mode.`) console.error(`No local games in production mode.`)
return "" return
}
} else {
if(!fs.existsSync(path.join(__dirname, '..', 'games'))) {
console.error(`Did not find the following folder: ${path.join(__dirname, '..', 'games')}`)
console.error('Did you already import any games?')
return ""
} }
// TODO: This test does not work
// if (!fs.existsSync(path.join("../", game_dir))) {
// console.error(`Game folder does not exists: ${game_dir}`)
// return
// }
} }
let game_dir = (owner == 'local') ? if (!game_dir) {
path.join(__dirname, '..', '..', repo) : // note: here we need `repo` to be case sensitive console.error(`Unknown game: ${tag(owner, repo)}`)
path.join(__dirname, '..', 'games', `${owner}`, `${repo.toLowerCase()}`) return
if(!fs.existsSync(game_dir)) {
console.error(`Game '${game_dir}' does not exist!`)
return ""
} }
return game_dir;
}
function startServerProcess(owner, repo) {
let game_dir = getGameDir(owner, repo)
if (!game_dir) return;
let serverProcess let serverProcess
if (isDevelopment) { if (isDevelopment) {
let args = ["--server", game_dir] let args = ["--server", path.join("../../../../", game_dir)]
let binDir = path.join(game_dir, ".lake", "packages", "GameServer", "server", ".lake", "build", "bin") serverProcess = cp.spawn("./gameserver", args,
// Note: `cwd` is important to be the `bin` directory as `Watchdog` calls `./gameserver` again { cwd: path.join(__dirname, "./build/bin/") })
if (fs.existsSync(binDir)) {
// Try to use the game's own copy of `gameserver`.
serverProcess = cp.spawn("./gameserver", args, { cwd: binDir })
} else {
// If the game is built with `-Klean4game.local` there is no copy in the lake packages.
serverProcess = cp.spawn("./gameserver", args,
{ cwd: path.join(__dirname, "..", "server", ".lake", "build", "bin") })
}
} else { } else {
serverProcess = cp.spawn("./bubblewrap.sh", serverProcess = cp.spawn("./bubblewrap.sh",
[ game_dir, path.join(__dirname, '..')], [game_dir],
{ cwd: __dirname }) { cwd: __dirname })
} }
serverProcess.on('error', error => serverProcess.on('error', error =>
console.error(`Launching Lean Server failed: ${error}`) console.error(`Launching Lean Server failed: ${error}`)
) )
@@ -124,21 +101,15 @@ function startServerProcess(owner, repo) {
} }
/** start Lean Server processes to refill the queue */ /** start Lean Server processes to refill the queue */
function fillQueue(tag) { function fillQueue(owner, repo) {
while (queue[tag].length < queueLength[tag]) { while (queue[tag(owner, repo)].length < games[tag(owner, repo)].queueLength) {
let serverProcess const serverProcess = startServerProcess(tag(owner, repo))
serverProcess = startServerProcess(tag) queue[tag(owner, repo)].push(serverProcess)
if (serverProcess == null) {
console.error('serverProcess was undefined/null')
return
} }
queue[tag].push(serverProcess)
}
} }
// // TODO: We disabled queue for now
// if (!isDevelopment) { // Don't use queue in development // if (!isDevelopment) { // Don't use queue in development
// for (let tag in queueLength) { // for (let tag in games) {
// queue[tag] = [] // queue[tag] = []
// fillQueue(tag) // fillQueue(tag)
// } // }
@@ -151,21 +122,19 @@ wss.addListener("connection", function(ws, req) {
if (!reRes) { console.error(`Connection refused because of invalid URL: ${req.url}`); return; } if (!reRes) { console.error(`Connection refused because of invalid URL: ${req.url}`); return; }
const owner = reRes[1] const owner = reRes[1]
const repo = reRes[2] const repo = reRes[2]
// const tag = `g/${owner.toLowerCase()}/${repo.toLowerCase()}`
const tag = getTag(owner, repo) // // TODO
// if (isDevelopment && process.env.DEV_CONTAINER) {
// tag = `g/local/game`
// }
let ps let ps;
if (!queue[tag] || queue[tag].length == 0) { if (!queue[tag(owner, repo)] || queue[tag(owner, repo)].length == 0) {
ps = startServerProcess(owner, repo) ps = startServerProcess(owner, repo)
} else { } else {
console.info('Got process from the queue') ps = queue[tag(owner, repo)].shift() // Pick the first Lean process; it's likely to be ready immediately
ps = queue[tag].shift() // Pick the first Lean process; it's likely to be ready immediately fillQueue(owner, repo)
fillQueue(tag)
}
if (ps == null) {
console.error('server process is undefined/null')
return
} }
socketCounter += 1; socketCounter += 1;
@@ -178,14 +147,14 @@ wss.addListener("connection", function(ws, req) {
onClose: (cb) => { ws.on("close", cb) }, onClose: (cb) => { ws.on("close", cb) },
send: (data, cb) => { ws.send(data,cb) } send: (data, cb) => { ws.send(data,cb) }
} }
const reader = new rpc.WebSocketMessageReader(socket) const reader = new rpc.WebSocketMessageReader(socket);
const writer = new rpc.WebSocketMessageWriter(socket) const writer = new rpc.WebSocketMessageWriter(socket);
const socketConnection = jsonrpcserver.createConnection(reader, writer, () => ws.close()) const socketConnection = jsonrpcserver.createConnection(reader, writer, () => ws.close())
const serverConnection = jsonrpcserver.createProcessStreamConnection(ps) const serverConnection = jsonrpcserver.createProcessStreamConnection(ps);
socketConnection.forward(serverConnection, message => { socketConnection.forward(serverConnection, message => {
if (isDevelopment) {console.log(`CLIENT: ${JSON.stringify(message)}`)} if (isDevelopment) {console.log(`CLIENT: ${JSON.stringify(message)}`)}
return message; return message;
}) });
serverConnection.forward(socketConnection, message => { serverConnection.forward(socketConnection, message => {
if (isDevelopment) {console.log(`SERVER: ${JSON.stringify(message)}`)} if (isDevelopment) {console.log(`SERVER: ${JSON.stringify(message)}`)}
return message; return message;
@@ -196,9 +165,9 @@ wss.addListener("connection", function(ws, req) {
ws.on('close', () => { ws.on('close', () => {
console.log(`[${new Date()}] Socket closed - ${ip}`) console.log(`[${new Date()}] Socket closed - ${ip}`)
socketCounter -= 1 socketCounter -= 1;
}) })
socketConnection.onClose(() => serverConnection.dispose()) socketConnection.onClose(() => serverConnection.dispose());
serverConnection.onClose(() => socketConnection.dispose()) serverConnection.onClose(() => socketConnection.dispose());
}) })
+4 -14
View File
@@ -1,14 +1,4 @@
{"version": 7, {"version": 6,
"packagesDir": ".lake/packages", "packagesDir": "lake-packages",
"packages": "packages": [],
[{"url": "https://github.com/leanprover/std4.git", "name": "GameServer"}
"type": "git",
"subDir": null,
"rev": "08ec2584b1892869e3a5f4122b029989bcb4ca79",
"name": "std",
"manifestFile": "lake-manifest.json",
"inputRev": "v4.5.0",
"inherited": false,
"configFile": "lakefile.lean"}],
"name": "GameServer",
"lakeDir": ".lake"}
+2 -16
View File
@@ -3,25 +3,11 @@ open Lake DSL
package GameServer package GameServer
-- Using this assumes that each dependency has a tag of the form `v4.X.0`. @[default_target]
def leanVersion : String := s!"v{Lean.versionString}"
require std from git "https://github.com/leanprover/std4.git" @ leanVersion
lean_lib GameServer lean_lib GameServer
@[default_target] @[default_target]
lean_exe gameserver { lean_exe gameserver {
root := `GameServer root := `Main
supportInterpreter := true supportInterpreter := true
} }
/--
When a package depending on GameServer updates its dependencies,
build the `gameserver` executable.
-/
post_update pkg do
let rootPkg ← getRootPackage
if rootPkg.name = pkg.name then
return -- do not run in GameServer itself
discard <| runBuild gameserver.build >>= (·.await)
+15
View File
@@ -0,0 +1,15 @@
import Lake
open Lake DSL
package GameServer {
buildDir := ".lake/build32"
}
@[default_target]
lean_lib GameServer
@[default_target]
lean_exe gameserver {
root := `Main
supportInterpreter := true
}
+1 -1
View File
@@ -1 +1 @@
leanprover/lean4:v4.5.0 leanprover/lean4:v4.3.0-rc2
+58
View File
@@ -0,0 +1,58 @@
#include <stdio.h>
#include <lean/lean.h>
extern lean_object* game_send_message(lean_object*, lean_object*, lean_object*);
extern lean_object* game_make_state(lean_object*);
// see https://leanprover.github.io/lean4/doc/dev/ffi.html#initialization
extern void lean_initialize_runtime_module();
extern void lean_initialize();
extern void lean_io_mark_end_initialization();
extern lean_object * initialize_GameServer_WasmServer(uint8_t builtin, lean_object *);
lean_object * state;
lean_object * io_world;
void main() {
lean_initialize_runtime_module();
lean_initialize();
lean_object * res;
// use same default as for Lean executables
uint8_t builtin = 1;
io_world = lean_io_mk_world();
res = initialize_GameServer_WasmServer(builtin, io_world);
if (lean_io_result_is_ok(res)) {
lean_dec(res);
} else {
lean_io_result_show_error(res);
lean_dec(res);
return; // do not access Lean declarations if initialization failed
}
lean_init_task_manager();
lean_io_mark_end_initialization();
res = game_make_state(io_world);
if (lean_io_result_is_ok(res)) {
state = lean_io_result_get_value(res);
lean_inc(state);
lean_dec(res);
} else {
lean_io_result_show_error(res);
lean_dec(res);
return; // do not access Lean declarations if initialization failed
}
}
void send_message(char* msg){
lean_object * s = lean_mk_string(msg);
lean_object * res = game_send_message(s, state, io_world);
if (lean_io_result_is_ok(res)) {
state = lean_io_result_get_value(res);
lean_inc(state);
lean_dec(res);
} else {
lean_io_result_show_error(res);
lean_dec(res);
}
}
+13
View File
@@ -0,0 +1,13 @@
#/bin/bash
ARTIFACT_ID=$1
echo "Unpacking ZIP."
unzip -o tmp/artifact_${ARTIFACT_ID}.zip -d tmp/artifact_${ARTIFACT_ID}
echo "Unpacking TAR."
for f in tmp/artifact_${ARTIFACT_ID}/* #Should only be one file
do
echo "Unpacking $f"
mkdir tmp/artifact_${ARTIFACT_ID}_inner
tar -xvf $f -C tmp/artifact_${ARTIFACT_ID}_inner
done
+1 -1
View File
@@ -12,5 +12,5 @@
"experimentalDecorators": true, "experimentalDecorators": true,
"allowSyntheticDefaultImports": true, "allowSyntheticDefaultImports": true,
}, },
"exclude": ["server", "relay"] "exclude": ["server"]
} }
+4 -15
View File
@@ -5,12 +5,6 @@ import svgr from "vite-plugin-svgr"
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
//root: 'client/src',
build: {
// Relative to the root
// Note: This has to match the path in `relay/index.mjs`
outDir: 'client/dist',
},
plugins: [ plugins: [
react(), react(),
svgr({ svgr({
@@ -23,14 +17,15 @@ export default defineConfig({
{ {
src: 'node_modules/@leanprover/infoview/dist/*.production.min.js', src: 'node_modules/@leanprover/infoview/dist/*.production.min.js',
dest: '.' dest: '.'
},
{
src: 'node_modules/coi-serviceworker/coi-serviceworker.js',
dest: '.'
} }
] ]
}) })
], ],
publicDir: "client/public", publicDir: "client/public",
optimizeDeps: {
exclude: ['games']
},
server: { server: {
port: 3000, port: 3000,
proxy: { proxy: {
@@ -38,12 +33,6 @@ export default defineConfig({
target: 'ws://localhost:8080', target: 'ws://localhost:8080',
ws: true ws: true
}, },
'/import': {
target: 'http://localhost:8080',
},
'/data': {
target: 'http://localhost:8080',
},
} }
}, },
resolve: { resolve: {
Executable
+37
View File
@@ -0,0 +1,37 @@
#!/bin/bash
cd server
mkdir -p .lake/toolchains
if [ ! -f .lake/toolchains/lean-4.3.0-rc2-linux_wasm32.tar.zst ]
then
wget -P .lake/toolchains https://github.com/leanprover/lean4/releases/download/v4.3.0-rc2/lean-4.3.0-rc2-linux_wasm32.tar.zst
tar --use-compress-program=unzstd -xvf .lake/toolchains/lean-4.3.0-rc2-linux_wasm32.tar.zst -C .lake/toolchains
fi
if [ ! -f .lake/toolchains/lean-4.3.0-rc2-linux_x86.tar.zst ]
then
wget -P .lake/toolchains https://github.com/leanprover/lean4/releases/download/v4.3.0-rc2/lean-4.3.0-rc2-linux_x86.tar.zst
tar --use-compress-program=unzstd -xvf .lake/toolchains/lean-4.3.0-rc2-linux_x86.tar.zst -C .lake/toolchains
fi
# Linking will fail, but that's ok. We only need the c files.
.lake/toolchains/lean-4.3.0-rc2-linux_x86/bin/lake build -f=lakefile32.lean
lake build
OUT_DIR=../client/public
LEAN_SYSROOT=.lake/toolchains/lean-4.3.0-rc2-linux_wasm32
LEAN_LIBDIR=$LEAN_SYSROOT/lib/lean
emcc -o $OUT_DIR/server.js main.c -I $LEAN_SYSROOT/include -L $LEAN_LIBDIR .lake/build/ir/GameServer/*.c -lInit -lLean -lleancpp -lleanrt \
-sFORCE_FILESYSTEM -lnodefs.js -s EXIT_RUNTIME=0 -s MAIN_MODULE=1 -s LINKABLE=1 -s EXPORT_ALL=1 -s ALLOW_MEMORY_GROWTH=1 -fwasm-exceptions -pthread -flto \
-sPTHREAD_POOL_SIZE_STRICT=2 \
--preload-file "${LEAN_SYSROOT}/lib/lean/Init"@/lib/Init \
--preload-file "${LEAN_SYSROOT}/lib/lean/Init.olean"@/lib/Init.olean \
--preload-file "${LEAN_SYSROOT}/lib/lean/Init.ilean"@/lib/Init.ilean \
--preload-file "${LEAN_SYSROOT}/lib/lean/Lean"@/lib/Lean \
--preload-file "${LEAN_SYSROOT}/lib/lean/Lean.olean"@/lib/Lean.olean \
--preload-file "${LEAN_SYSROOT}/lib/lean/Lean.ilean"@/lib/Lean.ilean \
--preload-file "./.lake/build32/lib"@/gamelib
+106
View File
@@ -0,0 +1,106 @@
const path = require("path");
const webpack = require('webpack');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const WebpackShellPluginNext = require('webpack-shell-plugin-next');
module.exports = env => {
const single_game = process.env.LEAN4GAME_SINGLE_GAME
const environment = process.env.NODE_ENV
const isDevelopment = environment === 'development'
const babelOptions = {
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
plugins: [
isDevelopment && require.resolve('react-refresh/babel'),
].filter(Boolean),
};
global.$RefreshReg$ = () => {};
global.$RefreshSig$ = () => () => {};
return {
entry: [single_game ? "./client/src/index_local.tsx" : "./client/src/index.tsx"],
mode: isDevelopment ? 'development' : 'production',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: [/server/, /node_modules/],
use: [{
loader: require.resolve('babel-loader'),
options: babelOptions,
}]
},
{
test: /\.tsx?$/,
use: [{
loader: 'ts-loader',
options: { allowTsInNodeModules: true }
}],
// exclude: /node_modules(?!\/(lean4web|lean4|lean4-infoview))/,
// Allow .ts imports from node_modules/lean4web and node_modules/lean4
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(jpg|png)$/,
use: {
loader: 'file-loader',
},
},
]
},
resolve: {
extensions: ["*", ".js", ".jsx", ".tsx", ".ts"],
fallback: {
"http": require.resolve("stream-http") ,
"path": require.resolve("path-browserify")
},
},
output: {
path: path.resolve(__dirname, "client/dist/"),
filename: "bundle.js",
},
devServer: {
proxy: {
'/websocket': {
target: 'ws://localhost:8080',
ws: true
},
'/import': {
target: 'http://localhost:3000',
router: () => 'http://localhost:8080',
},
},
static: path.join(__dirname, 'client/public/'),
port: 3000,
hot: true,
},
devtool: "source-map",
plugins: [
!isDevelopment && new WebpackShellPluginNext({
onBuildEnd:{
scripts: [
// It's hard to set up webpack to copy the index.html correctly,
// so we copy it explicitly after every build:
'cp client/public/index.html client/dist/',
// Similarly, I haven't been able to load `onigasm.wasm` properly:
'cp client/public/onigasm.wasm client/dist/',],
blocking: false,
parallel: true
}
}),
isDevelopment && new ReactRefreshWebpackPlugin(),
].filter(Boolean),
// Webpack is not happy about the dynamically loaded widget code in the function
// `dynamicallyLoadComponent` in `infoview/userWidget.tsx`. If we want to support
// dynamically loaded widget code, we need to make sure that the files are available.
ignoreWarnings: [/Critical dependency: the request of a dependency is an expression/]
};
}