From 69b76c5b960366d5730718d9321a9239d665cb30 Mon Sep 17 00:00:00 2001 From: Taisuke Fukuno Date: Sun, 15 Dec 2024 11:33:43 +0900 Subject: [PATCH] add impl constant --- DNCL3.js | 9 +++++++++ DNCL3.test.js | 5 +++++ README.md | 2 +- examples/const.dncl3 | 2 ++ 4 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 examples/const.dncl3 diff --git a/DNCL3.js b/DNCL3.js index ce84018..514752b 100644 --- a/DNCL3.js +++ b/DNCL3.js @@ -5,6 +5,14 @@ const reserved = [ const isNumber = (c) => "0123456789".indexOf(c) >= 0; const isOperator = (c) => "+-*/%=!<>,".indexOf(c) >= 0; +const isUpperAlphabet = (c) => "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(c) >= 0; + +const isConstantName = (s) => { + for (const c of s) { + if (!isUpperAlphabet(c) && c != "_") return false; + } + return true; +}; export class DNCL3 { constructor(s, callbackoutput) { @@ -276,6 +284,7 @@ export class DNCL3 { const op = this.getToken(); if (op.type != "operator" || op.operator != "=") throw new Error("代入は変数の後に = で続ける必要があります"); const val = this.getExpression(); + if (isConstantName(token2.name) && this.vars[token2.name] !== undefined) throw new Error("定数には再代入できません"); this.vars[token2.name] = val; const op2 = this.getToken(); diff --git a/DNCL3.test.js b/DNCL3.test.js index ea884f2..08d6a0c 100644 --- a/DNCL3.test.js +++ b/DNCL3.test.js @@ -17,3 +17,8 @@ Deno.test("var", () => { t.assertEquals(run("a = 1\nb = 2\nc = a + b\nprint c"), ["3"]); t.assertEquals(run(`a = "1"\nb = "2"\nc = a + b\nprint c`), ["12"]); }); +Deno.test("const", () => { + t.assertEquals(run("A = 1\nprint A"), ["1"]); + t.assertThrows(() => run("A = 1\nA = 2")); + t.assertEquals(run("Aa = 1\nAa = 2\nprint Aa"), ["2"]); +}); diff --git a/README.md b/README.md index 746766a..0f6c8b9 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ deno run -A DNCL3.example.js bmi ``` ※ TODO: 下記は未実装です -- 定数 / 配列 / input / 複数行if / while / do / until / for / function / return +- 配列 / input / 複数行if / while / do / until / for / function / return ## 1 変数と値 diff --git a/examples/const.dncl3 b/examples/const.dncl3 new file mode 100644 index 0000000..eafd61c --- /dev/null +++ b/examples/const.dncl3 @@ -0,0 +1,2 @@ +A = 3.2 +A = 5