Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove $ get/set syntax #51

Merged
merged 8 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 0 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,6 @@ set-timeout set-interval

## Coding in Insitux

Like any programming language it is written down as _code_. Insitux takes your
code and follows it like complex instructions.
You and the Insitux app talk to each other in these ways:

| what | direction of data | example |
| ------ | ------------------------ | ----------------------------- |
| code | goes into the app | `(+ 2 2)` |
| return | comes out of the app | `4` |
| set | writes data | `($day.cycle_speed 100)` |
| get | reads data | `$day.cycle_speed` |
| exe | data goes both in an out | `(util.fire [0 0 0] [0 1 0])` |

### Writing the code

Most code is written as _expressions_ like `(+ 2 2)`. As you can see, values are
Expand Down Expand Up @@ -1138,16 +1126,6 @@ It can also be used as an identity function (i.e. `val`).

- Parameters take precedence over lets, vars, and functions.

- Insitux implementations are advised to support this behaviour:

```clj
($test.ing 123) → 123
$test.ing → 123
(ing "$test") → 123
(ing "$test" 456) → 456
$test.ing → 456
```

### Functions

**Named functions**
Expand Down
8 changes: 6 additions & 2 deletions integrations/web-example.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
<title>Example</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="../out/insitux-web.js" type="module"></script>
<script src="../dist/insitux.min.js" type="module"></script>
<script type="text/insitux">
(inner-html "body" "Hello!")
(let hits (to-num (or (js "localStorage.getItem('hits')") 0))
hits (inc hits)
body (str "Hello! You have visited this page " hits " time" ((= 1 hits) "" "s") "."))
(js (str "localStorage.setItem('hits', " hits ")"))
(inner-html "body" body)
</script>
</head>
<body></body>
Expand Down
15 changes: 12 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "insitux",
"version": "24.10.21",
"version": "24.10.30",
"description": "Extensible scripting language written in portable TypeScript.",
"main": "dist/invoker.js",
"types": "dist/invoker.d.ts",
Expand Down
28 changes: 1 addition & 27 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const insituxVersion = 241021;
export const insituxVersion = 241030;
import { asBoo } from "./checks";
import { arityCheck, keyOpErr, numOpErr, typeCheck, typeErr } from "./checks";
import { isLetter, isDigit, isSpace, isPunc } from "./checks";
Expand Down Expand Up @@ -1417,22 +1417,6 @@ function getExe(
if (name in ctx.env.vars) {
return getExe(ctx, ctx.env.vars[name], errCtx);
}
if (starts(name, "$")) {
return (params: Val[]) => {
if (!len(params)) {
_throw(monoArityError(op.t, errCtx));
}
if (!ctx.set) {
const m = `"set" feature not implemented on this platform`;
return _throw([{ e: "External", m, errCtx }]);
}
const err = ctx.set(substr(name, 1), params[0]);
if (err) {
_throw([{ e: "External", m: err, errCtx }]);
}
return params[0];
};
}
return (params: Val[]) => {
if (!ctx.exe) {
const m = `operation "${name}" does not exist"`;
Expand Down Expand Up @@ -1648,16 +1632,6 @@ function exeFunc(
stack.push(ctx.env.vars[name]);
} else if (name in ctx.env.funcs) {
stack.push(_fun(name));
} else if (starts(name, "$")) {
if (!ctx.get) {
const m = `"get" feature not implemented on this platform`;
return _throw([{ e: "External", m, errCtx }]);
}
const valAndErr = ctx.get(substr(name, 1));
if ("err" in valAndErr) {
return _throw([{ e: "External", m: valAndErr.err, errCtx }]);
}
stack.push(valAndErr);
} else {
_throw([{ e: "Reference", m: `"${name}" did not exist`, errCtx }]);
}
Expand Down
29 changes: 0 additions & 29 deletions src/repl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,42 +348,13 @@ function makeFunctions(
//#endregion

//#region Context
const env = new Map<string, Val>();

function get(key: string): ValOrErr {
return env.has(key) ? env.get(key)! : { err: `key ${key} not found` };
}

function set(key: string, val: Val) {
env.set(key, val);
return undefined;
}

const ctx: Ctx = {
...defaultCtx,
get,
set,
functions: {},
print(str, withNewLine) {
process.stdout.write(`\x1b[32m${str}\x1b[0m${withNewLine ? "\n" : ""}`);
},
exe,
};

function exe(name: string, args: Val[]): ValOrErr {
if (args.length) {
const a = args[0];
if (a.t === "str" && a.v.startsWith("$")) {
if (args.length === 1) {
return get(`${a.v.substring(1)}.${name}`);
} else {
set(`${a.v.substring(1)}.${name}`, args[1]);
return args[1];
}
}
}
return { err: `operation "${name}" does not exist` };
}
//#endregion

//#region REPL IO
Expand Down
26 changes: 2 additions & 24 deletions src/test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,7 @@
import { concat, round, getTimeMs, len, padEnd, trim } from "./poly-fills";
import { Ctx, Env, Val, ValOrErr, InvokeResult } from "./types";

type State = { dict: Map<string, Val>; output: string };

function get(state: State, key: string): ValOrErr {
if (!state.dict.has(key)) {
return { err: `"${key}" not found.` };
}
return state.dict.get(key)!;
}

function set(state: State, key: string, val: Val): string | undefined {
state.dict.set(key, val);
return undefined;
}
type State = { output: string };

function exe(state: State, name: string, args: Val[]): ValOrErr {
const nullVal: Val = { t: "null", v: undefined };
Expand Down Expand Up @@ -501,11 +489,6 @@ const tests: {
out: `{"1" 4, "2" 4}`,
},
//Test environment functions
{
name: "set get",
code: `[($globals.time_offset 5.5) $globals.time_offset]`,
out: `[5.5 5.5]`,
},
{ name: "exe", code: `(test.function 123)`, out: `123\nnull` },
//Syntax errors
{ name: "Empty parens", code: `()`, err: ["Parse"] },
Expand Down Expand Up @@ -569,16 +552,11 @@ export function doTests(
}[] = [];
for (let t = 0; t < len(tests); ++t) {
const { name, code, err, out } = tests[t];
const state: State = {
dict: new Map<string, Val>(),
output: "",
};
const state: State = { output: "" };
const env: Env = { funcs: {}, vars: {}, mocks: {} };
const startTime = getTimeMs();
const valOrErrs = invoke(
{
get: (key: string) => get(state, key),
set: (key: string, val: Val) => set(state, key, val),
print: (str, withNewLine) => {
state.output += str + (withNewLine ? "\n" : "");
},
Expand Down
5 changes: 0 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,6 @@ export type Env = {

/** A context supplied with an Insitux invocation to provide its environment. */
export type Ctx = {
/** Called to set an external variable, returning nothing or an error. */
set?: (key: string, val: Val) => undefined | string;
/** Called to retrieve an external variable,
* returning the value or an error. */
get?: (key: string) => ValOrErr;
/** Called to print data out of Insitux. */
print: (str: string, withNewline: boolean) => void;
/** Extra function definitions to make available within this invocation */
Expand Down
27 changes: 0 additions & 27 deletions src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,6 @@ import { Ctx, defaultCtx, ExternalFunctions, Val, ValOrErr } from "./types";
import { num, str, val2str, _nul, _str, _num, _boo } from "./val";
import { jsToIx } from "./val-translate";

let state = new Map<string, Val>();

const get = (key: string): ValOrErr =>
state.has(key) ? state.get(key)! : _nul();
const set = (key: string, val: Val) => {
state.set(key, val);
localStorage.setItem("insitux-state", JSON.stringify([...state.entries()]));
return undefined;
};

function exe(name: string, args: Val[]): ValOrErr {
if (args.length && args[0].t == "str" && args[0].v.startsWith("$")) {
if (args.length === 1) {
return get(`${args[0].v.substring(1)}.${name}`);
} else {
set(`${args[0].v.substring(1)}.${name}`, args[1]);
return args[1];
}
}
return { err: `operation ${name} does not exist` };
}

const invokeFunction = (ctx: Ctx, name: string, args: Val[]) => {
alertErrors(functionInvoker(ctx, name, args, false));
};
Expand Down Expand Up @@ -238,9 +216,6 @@ const functions: ExternalFunctions = {

const ctx: Ctx = {
...defaultCtx,
exe,
get,
set,
print: str => console.log(str),
functions,
};
Expand All @@ -253,8 +228,6 @@ const loadScript = async (scriptEl: HTMLScriptElement) => {
};

window.onload = async () => {
const savedState = localStorage.getItem("insitux-state");
state = new Map<string, Val>(savedState ? JSON.parse(savedState) : []);
const scripts = Array.from(document.querySelectorAll("script")).filter(
el => el.type === "text/insitux",
);
Expand Down
Loading