From 2900d22cdc8ceadbea4be86595b73aa0ff08cae9 Mon Sep 17 00:00:00 2001 From: syuilo Date: Tue, 30 Apr 2019 12:38:07 +0900 Subject: [PATCH 01/19] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 266525277..9c01e8a54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ mongodb: * MisskeyPagesに 複数行テキスト入力 を追加 * MisskeyPagesに 投稿フォーム を追加 * MisskeyPagesに 変換系関数 を追加 +* MisskeyPagesに 環境変数 URL を追加 * MisskeyPagesでボタンやスイッチなどのテキストに変数使えるように ### Fixes From e6cdf1b995a9be710ebbf2954a541e9848918394 Mon Sep 17 00:00:00 2001 From: MeiMei <30769358+mei23@users.noreply.github.com> Date: Tue, 30 Apr 2019 15:53:13 +0900 Subject: [PATCH 02/19] =?UTF-8?q?Fix:=20mention=20(=E3=81=82=E3=81=AA?= =?UTF-8?q?=E3=81=9F=E5=AE=9B=E3=81=A6)=20streaming=20=E3=81=AB=E3=83=9F?= =?UTF-8?q?=E3=83=A5=E3=83=BC=E3=83=88=E3=81=8C=E5=8A=B9=E3=81=8B=E3=81=AA?= =?UTF-8?q?=E3=81=84=20(#4823)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/server/api/stream/channels/main.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/server/api/stream/channels/main.ts b/src/server/api/stream/channels/main.ts index 1100f87ac..5abe10878 100644 --- a/src/server/api/stream/channels/main.ts +++ b/src/server/api/stream/channels/main.ts @@ -22,6 +22,7 @@ export default class extends Channel { break; } case 'mention': { + if (mute.map(m => m.muteeId).includes(body.userId)) return; if (body.isHidden) return; break; } From 1903aaf351e171b3c92b2420fffd5d6eeaf1ad49 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 04:44:46 +0900 Subject: [PATCH 03/19] Improve API doc Fix #4825 --- src/models/repositories/page.ts | 46 +++++++++++++++++++++++++++++++ src/server/api/kinds.ts | 4 ++- src/server/api/openapi/schemas.ts | 2 ++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/models/repositories/page.ts b/src/models/repositories/page.ts index cbe385568..2293edbc0 100644 --- a/src/models/repositories/page.ts +++ b/src/models/repositories/page.ts @@ -84,5 +84,51 @@ export const packedPageSchema = { type: types.object, optional: bool.false, nullable: bool.false, properties: { + id: { + type: types.string, + optional: bool.false, nullable: bool.false, + format: 'id', + example: 'xxxxxxxxxx', + }, + createdAt: { + type: types.string, + optional: bool.false, nullable: bool.false, + format: 'date-time', + }, + updatedAt: { + type: types.string, + optional: bool.false, nullable: bool.false, + format: 'date-time', + }, + title: { + type: types.string, + optional: bool.false, nullable: bool.false, + }, + name: { + type: types.string, + optional: bool.false, nullable: bool.false, + }, + summary: { + type: types.string, + optional: bool.false, nullable: bool.true, + }, + content: { + type: types.array, + optional: bool.false, nullable: bool.false, + }, + variables: { + type: types.array, + optional: bool.false, nullable: bool.false, + }, + userId: { + type: types.string, + optional: bool.false, nullable: bool.false, + format: 'id', + }, + user: { + type: types.object, + ref: 'User', + optional: bool.false, nullable: bool.false, + }, } }; diff --git a/src/server/api/kinds.ts b/src/server/api/kinds.ts index 03ed3e7cd..99c379558 100644 --- a/src/server/api/kinds.ts +++ b/src/server/api/kinds.ts @@ -18,5 +18,7 @@ export const kinds = [ 'write:notifications', 'read:reactions', 'write:reactions', - 'write:votes' + 'write:votes', + 'read:pages', + 'write:pages', ]; diff --git a/src/server/api/openapi/schemas.ts b/src/server/api/openapi/schemas.ts index 34e6f8947..229d10af2 100644 --- a/src/server/api/openapi/schemas.ts +++ b/src/server/api/openapi/schemas.ts @@ -12,6 +12,7 @@ import { packedMutingSchema } from '../../../models/repositories/muting'; import { packedBlockingSchema } from '../../../models/repositories/blocking'; import { packedNoteReactionSchema } from '../../../models/repositories/note-reaction'; import { packedHashtagSchema } from '../../../models/repositories/hashtag'; +import { packedPageSchema } from '../../../models/repositories/page'; export function convertSchemaToOpenApiSchema(schema: Schema) { const res: any = schema; @@ -76,4 +77,5 @@ export const schemas = { Blocking: convertSchemaToOpenApiSchema(packedBlockingSchema), NoteReaction: convertSchemaToOpenApiSchema(packedNoteReactionSchema), Hashtag: convertSchemaToOpenApiSchema(packedHashtagSchema), + Page: convertSchemaToOpenApiSchema(packedPageSchema), }; From d0c8d537f59a1e25394407f963be78de2d80f0fa Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 09:15:29 +0900 Subject: [PATCH 04/19] Refactor --- src/client/app/common/scripts/aiscript.ts | 30 +++++++++++------------ 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 99caec8c1..765d740e2 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -80,16 +80,22 @@ const funcDefs = { dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, }; +const literalDefs = { + text: { out: 'string', category: 'value', icon: faQuoteRight, }, + multiLineText: { out: 'string', category: 'value', icon: faAlignLeft, }, + textList: { out: 'stringArray', category: 'value', icon: faList, }, + number: { out: 'number', category: 'value', icon: faSortNumericUp, }, + ref: { out: null, category: 'value', icon: faSuperscript, }, + in: { out: null, category: 'value', icon: faSuperscript, }, + fn: { out: 'function', category: 'value', icon: faSuperscript, }, +}; + const blockDefs = [ - { type: 'text', out: 'string', category: 'value', icon: faQuoteRight, }, - { type: 'multiLineText', out: 'string', category: 'value', icon: faAlignLeft, }, - { type: 'textList', out: 'stringArray', category: 'value', icon: faList, }, - { type: 'number', out: 'number', category: 'value', icon: faSortNumericUp, }, - { type: 'ref', out: null, category: 'value', icon: faSuperscript, }, - { type: 'in', out: null, category: 'value', icon: faSuperscript, }, - { type: 'fn', out: 'function', category: 'value', icon: faSuperscript, }, + ...Object.entries(literalDefs).map(([k, v]) => ({ + type: k, out: v.out, category: v.category, icon: v.icon + })), ...Object.entries(funcDefs).map(([k, v]) => ({ - type: k, out: v.out || null, category: v.category, icon: v.icon + type: k, out: v.out, category: v.category, icon: v.icon })) ]; @@ -170,13 +176,7 @@ export class AiScript { @autobind public static isLiteralBlock(v: Block) { if (v.type === null) return true; - if (v.type === 'text') return true; - if (v.type === 'multiLineText') return true; - if (v.type === 'textList') return true; - if (v.type === 'number') return true; - if (v.type === 'ref') return true; - if (v.type === 'fn') return true; - if (v.type === 'in') return true; + if (literalDefs[v.type]) return true; return false; } From 10216af48a90293b5471ff771509bcdc18bdda08 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 10:05:33 +0900 Subject: [PATCH 05/19] Improve MisskeyPages --- locales/ja-JP.yml | 8 +++- src/client/app/common/scripts/aiscript.ts | 43 +++++++++++++++---- .../page-editor/page-editor.script-block.vue | 18 +++++--- 3 files changed, 54 insertions(+), 15 deletions(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index cd29135bd..adc3d1891 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -2036,12 +2036,18 @@ pages: _numberToString: arg1: "数値" ref: "変数" - in: "引数" + in: "スロット入力" _in: arg1: "スロット番号" fn: "関数" _fn: + slots: "スロット" + slots-info: "スロットひとつひとつを改行で区切ってください" arg1: "出力" + for: "繰り返し" + _for: + arg1: "回数" + arg2: "処理" typeError: "スロット{slot}は\"{expect}\"を受け付けますが、\"{actual}\"が入れられています!" thereIsEmptySlot: "スロット{slot}が空です!" types: diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 765d740e2..975531dfa 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -27,18 +27,27 @@ import { faDice, faSortNumericUp, faExchangeAlt, + faRecycle, } from '@fortawesome/free-solid-svg-icons'; import { faFlag } from '@fortawesome/free-regular-svg-icons'; import { version } from '../../config'; -export type Block = { +export type Block = { id: string; type: string; args: Block[]; - value: any; + value: V; }; +type FnBlock = Block<{ + slots: { + name: string; + type: Type; + }[]; + expression: Block; +}>; + export type Variable = Block & { name: string; }; @@ -53,6 +62,7 @@ type TypeError = { const funcDefs = { if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, + for: { in: ['number', 'function'], out: 0, category: 'flow', icon: faRecycle, }, not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, @@ -99,6 +109,10 @@ const blockDefs = [ })) ]; +function isFnBlock(block: Block): block is FnBlock { + return block.type === 'fn'; +} + type PageVar = { name: string; value: any; type: Type; }; const envVarsDef = { @@ -326,7 +340,7 @@ export class AiScript { @autobind private interpolate(str: string, values: { name: string, value: any }[]) { return str.replace(/\{(.+?)\}/g, match => { - const v = this.getVariableValue(match.slice(1, -1).trim(), values); + const v = this.getVarVal(match.slice(1, -1).trim(), values); return v == null ? 'NULL' : v.toString(); }); } @@ -378,23 +392,23 @@ export class AiScript { } if (block.type === 'ref') { - return this.getVariableValue(block.value, values); + return this.getVarVal(block.value, values); } if (block.type === 'in') { return slotArg[block.value]; } - if (block.type === 'fn') { // ユーザー関数定義 + if (isFnBlock(block)) { // ユーザー関数定義 return { - slots: block.value.slots, + slots: block.value.slots.map(x => x.name), exec: slotArg => this.evaluate(block.value.expression, values, slotArg) }; } if (block.type.startsWith('fn:')) { // ユーザー関数呼び出し const fnName = block.type.split(':')[1]; - const fn = this.getVariableValue(fnName, values); + const fn = this.getVarVal(fnName, values); for (let i = 0; i < fn.slots.length; i++) { const name = fn.slots[i]; slotArg[name] = this.evaluate(block.args[i], values); @@ -418,6 +432,14 @@ export class AiScript { or: (a, b) => a || b, and: (a, b) => a && b, if: (bool, a, b) => bool ? a : b, + for: (times, fn) => { + const result = []; + for (let i = 0; i < times; i++) { + slotArg[fn.slots[0]] = i + 1; + result.push(fn.exec(slotArg)); + } + return result; + }, add: (a, b) => a + b, subtract: (a, b) => a - b, multiply: (a, b) => a * b, @@ -449,8 +471,13 @@ export class AiScript { return fn(...args); } + /** + * 指定した名前の変数の値を取得します + * @param name 変数名 + * @param values ユーザー定義変数のリスト + */ @autobind - private getVariableValue(name: string, values: { name: string, value: any }[]): any { + private getVarVal(name: string, values: { name: string, value: any }[]): any { const v = values.find(v => v.name === name); if (v) { return v.value; diff --git a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue index 9554c75d0..2f78f7de3 100644 --- a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue +++ b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue @@ -35,15 +35,18 @@
-
- +
+ + {{ $t('script.blocks._fn.slots') }} + +
- +
@@ -118,7 +121,10 @@ export default Vue.extend({ watch: { slots() { - this.value.value.slots = this.slots.split('\n'); + this.value.value.slots = this.slots.split('\n').map(x => ({ + name: x, + type: null + })); } }, @@ -129,7 +135,7 @@ export default Vue.extend({ created() { if (this.value.value == null) Vue.set(this.value, 'value', null); - if (this.value.value && this.value.value.slots) this.slots = this.value.value.slots.join('\n'); + if (this.value.value && this.value.value.slots) this.slots = this.value.value.slots.map(x => x.name).join('\n'); this.$watch('value.type', (t) => { this.warn = null; From d0af2c2a98b0ae5abc9a13cba1626e29ad4236f7 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 10:37:25 +0900 Subject: [PATCH 06/19] Improve MisskeyPages --- locales/ja-JP.yml | 21 ++++++++++++++++ src/client/app/common/scripts/aiscript.ts | 29 ++++++++++++++++++----- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index adc3d1891..558408ce2 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -1952,6 +1952,14 @@ pages: strReverse: "テキストを反転" _strReverse: arg1: "テキスト" + strConcat: "2つのテキストを連結" + _strConcat: + arg1: "テキスト1" + arg2: "テキスト2" + join: "テキストを連結" + _join: + arg1: "リスト" + arg2: "区切り" add: "+ 足す" _add: arg1: "A" @@ -2028,6 +2036,19 @@ pages: dailyRandomPick: "リストからランダムに選択 (ユーザーごとに日替わり)" _dailyRandomPick: arg1: "リスト" + seedRandom: "ランダム (シード)" + _seedRandom: + arg1: "シード" + arg2: "確率" + seedRannum: "乱数 (シード)" + _seedRannum: + arg1: "シード" + arg2: "最小" + arg3: "最大" + seedRandomPick: "リストからランダムに選択 (シード)" + _seedRandomPick: + arg1: "シード" + arg2: "リスト" number: "数" stringToNumber: "テキストを数値に" _stringToNumber: diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 975531dfa..70edce9b7 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -62,7 +62,7 @@ type TypeError = { const funcDefs = { if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, - for: { in: ['number', 'function'], out: 0, category: 'flow', icon: faRecycle, }, + for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, @@ -80,14 +80,19 @@ const funcDefs = { strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, + strConcat: { in: ['string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, + join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, rannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, dailyRannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, + seedRannum: { in: [null, 'number', 'number'], out: 'number', category: 'random', icon: faDice, }, random: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, dailyRandom: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, + seedRandom: { in: [null, 'number'], out: 'boolean', category: 'random', icon: faDice, }, randomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, + seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, }; const literalDefs = { @@ -130,6 +135,8 @@ const envVarsDef = { MY_NOTES_COUNT: 'number', MY_FOLLOWERS_COUNT: 'number', MY_FOLLOWING_COUNT: 'number', + SEED: null, + YMD: 'string', }; export class AiScript { @@ -149,6 +156,8 @@ export class AiScript { this.pageVars = pageVars; this.opts = opts; + const date = new Date(); + this.envVars = { AI: 'kawaii', VERSION: version, @@ -164,6 +173,8 @@ export class AiScript { MY_NOTES_COUNT: opts.user ? opts.user.notesCount : 0, MY_FOLLOWERS_COUNT: opts.user ? opts.user.followersCount : 0, MY_FOLLOWING_COUNT: opts.user ? opts.user.followingCount : 0, + SEED: opts.randomSeed ? opts.randomSeed : '', + YMD: `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}` }; } @@ -185,6 +196,7 @@ export class AiScript { @autobind public updateRandomSeed(seed: string) { this.opts.randomSeed = seed; + this.envVars.SEED = seed; } @autobind @@ -279,7 +291,7 @@ export class AiScript { } const envVar = AiScript.envVarsDef[v.value]; - if (envVar) { + if (envVar !== undefined) { return envVar; } @@ -328,7 +340,7 @@ export class AiScript { @autobind public getEnvVarsByType(type: Type | null): string[] { if (type == null) return Object.keys(AiScript.envVarsDef); - return Object.entries(AiScript.envVarsDef).filter(([k, v]) => type === v).map(([k, v]) => k); + return Object.entries(AiScript.envVarsDef).filter(([k, v]) => v === null || type === v).map(([k, v]) => k); } @autobind @@ -384,7 +396,7 @@ export class AiScript { } if (block.type === 'text' || block.type === 'multiLineText') { - return this.interpolate(block.value, values); + return this.interpolate(block.value || '', values); } if (block.type === 'textList') { @@ -419,7 +431,7 @@ export class AiScript { if (block.args === undefined) return null; const date = new Date(); - const day = `${this.opts.visitor ? this.opts.visitor.id : ''} ${date.getFullYear()}/${date.getMonth()}/${date.getDate()}`; + const day = `${this.opts.visitor ? this.opts.visitor.id : ''} ${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`; const funcs: { [p in keyof typeof funcDefs]: any } = { not: (a) => !a, @@ -448,6 +460,8 @@ export class AiScript { strPick: (a, b) => a[b - 1], strReplace: (a, b, c) => a.split(b).join(c), strReverse: (a) => a.split('').reverse().join(''), + strConcat: (a, b) => a + b, + join: (texts, separator) => texts.join(separator || ''), stringToNumber: (a) => parseInt(a), numberToString: (a) => a.toString(), random: (probability) => Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * 100) < probability, @@ -456,6 +470,9 @@ export class AiScript { dailyRandom: (probability) => Math.floor(seedrandom(`${day}:${block.id}`)() * 100) < probability, dailyRannum: (min, max) => min + Math.floor(seedrandom(`${day}:${block.id}`)() * (max - min + 1)), dailyRandomPick: (list) => list[Math.floor(seedrandom(`${day}:${block.id}`)() * list.length)], + seedRandom: (seed, probability) => Math.floor(seedrandom(seed)() * 100) < probability, + seedRannum: (seed, min, max) => min + Math.floor(seedrandom(seed)() * (max - min + 1)), + seedRandomPick: (seed, list) => list[Math.floor(seedrandom(seed)() * list.length)], }; const fnName = block.type; @@ -488,7 +505,7 @@ export class AiScript { return pageVar.value; } - if (AiScript.envVarsDef[name]) { + if (AiScript.envVarsDef[name] !== undefined) { return this.envVars[name]; } From 52ebf2055e0d6a238796ceacf92a7073bf007127 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 14:54:34 +0900 Subject: [PATCH 07/19] Improve AiScript --- locales/ja-JP.yml | 5 +- src/client/app/common/scripts/aiscript.ts | 134 +++++++++--------- .../page-editor/page-editor.script-block.vue | 9 +- .../components/page-editor/page-editor.vue | 1 + .../app/common/views/pages/page/page.if.vue | 2 +- .../app/common/views/pages/page/page.vue | 4 +- 6 files changed, 80 insertions(+), 75 deletions(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index 558408ce2..fa5e1e147 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -1853,6 +1853,7 @@ pages: variables-info: "変数を使うことで動的なページを作成できます。テキスト内で { 変数名 } と書くとそこに変数の値を埋め込めます。例えば Hello { thing } world! というテキストで、変数(thing)の値が ai だった場合、テキストは Hello ai world! になります。" variables-info2: "変数の評価(値を算出すること)は上から下に行われるので、ある変数の中で自分より下の変数を参照することはできません。例えば上から A、B、C と3つの変数を定義したとき、Cの中でABを参照することはできますが、Aの中でBCを参照することはできません。" variables-info3: "ユーザーからの入力を受け取るには、ページに「ユーザー入力」ブロックを設置し、「変数名」に入力を格納したい変数名を設定します(変数は自動で作成されます)。その変数を使ってユーザー入力に応じた動作を行えます。" + variables-info4: "関数を使うと、値の算出処理を再利用可能な形にまとめることができます。関数を作るには、「関数」タイプの変数を作成します。関数にはスロット(引数)を設定することができ、スロットの値は関数内で変数として利用可能です。また、AiScript標準で関数を引数に取る関数(高階関数と呼ばれます)も存在します。関数は予め定義しておくほかに、このような高階関数のスロットに即席でセットすることもできます。" more-details: "詳しい説明" title: "タイトル" url: "ページURL" @@ -2057,9 +2058,6 @@ pages: _numberToString: arg1: "数値" ref: "変数" - in: "スロット入力" - _in: - arg1: "スロット番号" fn: "関数" _fn: slots: "スロット" @@ -2080,3 +2078,4 @@ pages: emptySlot: "空のスロット" enviromentVariables: "環境変数" pageVariables: "ページ要素" + argVariables: "入力スロット" diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 70edce9b7..1c4fe217c 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -101,7 +101,6 @@ const literalDefs = { textList: { out: 'stringArray', category: 'value', icon: faList, }, number: { out: 'number', category: 'value', icon: faSortNumericUp, }, ref: { out: null, category: 'value', icon: faSuperscript, }, - in: { out: null, category: 'value', icon: faSuperscript, }, fn: { out: 'function', category: 'value', icon: faSuperscript, }, }; @@ -139,6 +138,50 @@ const envVarsDef = { YMD: 'string', }; +class AiScriptError extends Error { + constructor(...params) { + super(...params); + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, AiScriptError); + } + } +} + +class Scope { + private layerdStates: Record[]; + public name: string; + + constructor(layerdStates: Scope['layerdStates'], name?: Scope['name']) { + this.layerdStates = layerdStates; + this.name = name || 'anonymous'; + } + + @autobind + public createChildScope(states: Record, name?: Scope['name']): Scope { + const layer = [states, ...this.layerdStates]; + return new Scope(layer, name); + } + + /** + * 指定した名前の変数の値を取得します + * @param name 変数名 + */ + @autobind + public getState(name: string): any { + for (const later of this.layerdStates) { + const state = later[name]; + if (state !== undefined) { + return state; + } + } + + throw new AiScriptError( + `No such variable '${name}' in scope '${this.name}'`); + } +} + export class AiScript { private variables: Variable[]; private pageVars: PageVar[]; @@ -298,7 +341,7 @@ export class AiScript { return null; } if (v.type === 'fn') return null; // todo - if (v.type === 'in') return null; // todo + if (v.type.startsWith('fn:')) return null; // todo const generic: Type[] = []; @@ -350,43 +393,34 @@ export class AiScript { } @autobind - private interpolate(str: string, values: { name: string, value: any }[]) { + private interpolate(str: string, scope: Scope) { return str.replace(/\{(.+?)\}/g, match => { - const v = this.getVarVal(match.slice(1, -1).trim(), values); + const v = scope.getState(match.slice(1, -1).trim()); return v == null ? 'NULL' : v.toString(); }); } @autobind - public evaluateVars() { - const values: { name: string, value: any }[] = []; + public evaluateVars(): Record { + const values: Record = {}; - for (const v of this.variables) { - values.push({ - name: v.name, - value: this.evaluate(v, values) - }); + for (const [k, v] of Object.entries(this.envVars)) { + values[k] = v; } for (const v of this.pageVars) { - values.push({ - name: v.name, - value: v.value - }); + values[v.name] = v.value; } - for (const [k, v] of Object.entries(this.envVars)) { - values.push({ - name: k, - value: v - }); + for (const v of this.variables) { + values[v.name] = this.evaluate(v, new Scope([values])); } return values; } @autobind - private evaluate(block: Block, values: { name: string, value: any }[], slotArg: Record = {}): any { + private evaluate(block: Block, scope: Scope): any { if (block.type === null) { return null; } @@ -396,7 +430,7 @@ export class AiScript { } if (block.type === 'text' || block.type === 'multiLineText') { - return this.interpolate(block.value || '', values); + return this.interpolate(block.value || '', scope); } if (block.type === 'textList') { @@ -404,28 +438,27 @@ export class AiScript { } if (block.type === 'ref') { - return this.getVarVal(block.value, values); - } - - if (block.type === 'in') { - return slotArg[block.value]; + return scope.getState(block.value); } if (isFnBlock(block)) { // ユーザー関数定義 return { slots: block.value.slots.map(x => x.name), - exec: slotArg => this.evaluate(block.value.expression, values, slotArg) + exec: slotArg => { + return this.evaluate(block.value.expression, scope.createChildScope(slotArg, block.id)); + } }; } if (block.type.startsWith('fn:')) { // ユーザー関数呼び出し const fnName = block.type.split(':')[1]; - const fn = this.getVarVal(fnName, values); + const fn = scope.getState(fnName); + const args = {}; for (let i = 0; i < fn.slots.length; i++) { const name = fn.slots[i]; - slotArg[name] = this.evaluate(block.args[i], values); + args[name] = this.evaluate(block.args[i], scope); } - return fn.exec(slotArg); + return fn.exec(args); } if (block.args === undefined) return null; @@ -447,8 +480,9 @@ export class AiScript { for: (times, fn) => { const result = []; for (let i = 0; i < times; i++) { - slotArg[fn.slots[0]] = i + 1; - result.push(fn.exec(slotArg)); + result.push(fn.exec({ + [fn.slots[0]]: i + 1 + })); } return result; }, @@ -476,40 +510,12 @@ export class AiScript { }; const fnName = block.type; - const fn = funcs[fnName]; if (fn == null) { - console.error('Unknown function: ' + fnName); - throw new Error('Unknown function: ' + fnName); + throw new AiScriptError(`No such function '${fnName}'`); + } else { + return fn(...block.args.map(x => this.evaluate(x, scope))); } - - const args = block.args.map(x => this.evaluate(x, values, slotArg)); - - return fn(...args); - } - - /** - * 指定した名前の変数の値を取得します - * @param name 変数名 - * @param values ユーザー定義変数のリスト - */ - @autobind - private getVarVal(name: string, values: { name: string, value: any }[]): any { - const v = values.find(v => v.name === name); - if (v) { - return v.value; - } - - const pageVar = this.pageVars.find(v => v.name === name); - if (pageVar) { - return pageVar.value; - } - - if (AiScript.envVarsDef[name] !== undefined) { - return this.envVars[name]; - } - - throw new Error(`Script: No such variable '${name}'`); } @autobind diff --git a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue index 2f78f7de3..7a3942ec8 100644 --- a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue +++ b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue @@ -25,6 +25,9 @@
-
- -
{{ $t('script.blocks._fn.slots') }} @@ -115,6 +113,7 @@ export default Vue.extend({ }, typeText(): any { if (this.value.type === null) return null; + if (this.value.type.startsWith('fn:')) return this.value.type.split(':')[1]; return this.$t(`script.blocks.${this.value.type}`); }, }, diff --git a/src/client/app/common/views/components/page-editor/page-editor.vue b/src/client/app/common/views/components/page-editor/page-editor.vue index f8959fb0f..8007970be 100644 --- a/src/client/app/common/views/components/page-editor/page-editor.vue +++ b/src/client/app/common/views/components/page-editor/page-editor.vue @@ -77,6 +77,7 @@ diff --git a/src/client/app/common/views/pages/page/page.if.vue b/src/client/app/common/views/pages/page/page.if.vue index 9dbeaf64f..417ef0c55 100644 --- a/src/client/app/common/views/pages/page/page.if.vue +++ b/src/client/app/common/views/pages/page/page.if.vue @@ -1,5 +1,5 @@ diff --git a/src/client/app/common/views/pages/page/page.vue b/src/client/app/common/views/pages/page/page.vue index 88598d352..27e9a7aec 100644 --- a/src/client/app/common/views/pages/page/page.vue +++ b/src/client/app/common/views/pages/page/page.vue @@ -27,7 +27,7 @@ import { url } from '../../../../config'; class Script { public aiScript: AiScript; - public vars: any; + public vars: Record; constructor(aiScript) { this.aiScript = aiScript; @@ -41,7 +41,7 @@ class Script { public interpolate(str: string) { if (str == null) return null; return str.replace(/\{(.+?)\}/g, match => { - const v = this.vars.find(x => x.name === match.slice(1, -1).trim()).value; + const v = this.vars[match.slice(1, -1).trim()]; return v == null ? 'NULL' : v.toString(); }); } From b6c50d63a032c589232e17e5537dd3518c0a601d Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 15:04:26 +0900 Subject: [PATCH 08/19] Update ja-JP.yml --- locales/ja-JP.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index fa5e1e147..238f4256d 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -2050,7 +2050,7 @@ pages: _seedRandomPick: arg1: "シード" arg2: "リスト" - number: "数" + number: "数値" stringToNumber: "テキストを数値に" _stringToNumber: arg1: "テキスト" From 4747ae8b61f6adba07ce30831063344a72c7d629 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 15:17:24 +0900 Subject: [PATCH 09/19] Improve AiScript --- src/client/app/common/scripts/aiscript.ts | 12 +++++++++--- .../app/common/scripts/collect-page-vars.ts | 8 ++++---- .../common/views/pages/page/page.button.vue | 4 ++-- .../views/pages/page/page.number-input.vue | 2 +- .../common/views/pages/page/page.switch.vue | 2 +- .../views/pages/page/page.text-input.vue | 2 +- .../views/pages/page/page.textarea-input.vue | 2 +- .../app/common/views/pages/page/page.vue | 18 +++++++++++++----- 8 files changed, 32 insertions(+), 18 deletions(-) diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 1c4fe217c..1e486c455 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -139,8 +139,12 @@ const envVarsDef = { }; class AiScriptError extends Error { - constructor(...params) { - super(...params); + public info?: any; + + constructor(message: string, info?: any) { + super(message); + + this.info = info; // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { @@ -178,7 +182,9 @@ class Scope { } throw new AiScriptError( - `No such variable '${name}' in scope '${this.name}'`); + `No such variable '${name}' in scope '${this.name}'`, { + scope: this.layerdStates + }); } } diff --git a/src/client/app/common/scripts/collect-page-vars.ts b/src/client/app/common/scripts/collect-page-vars.ts index 92727ce6d..683f9b73a 100644 --- a/src/client/app/common/scripts/collect-page-vars.ts +++ b/src/client/app/common/scripts/collect-page-vars.ts @@ -6,25 +6,25 @@ export function collectPageVars(content) { pageVars.push({ name: x.name, type: 'string', - value: x.default + value: x.default || '' }); } else if (x.type === 'textareaInput') { pageVars.push({ name: x.name, type: 'string', - value: x.default + value: x.default || '' }); } else if (x.type === 'numberInput') { pageVars.push({ name: x.name, type: 'number', - value: x.default + value: x.default || 0 }); } else if (x.type === 'switch') { pageVars.push({ name: x.name, type: 'boolean', - value: x.default + value: x.default || false }); } else if (x.children) { collect(x.children); diff --git a/src/client/app/common/views/pages/page/page.button.vue b/src/client/app/common/views/pages/page/page.button.vue index b77d856d5..3747be96c 100644 --- a/src/client/app/common/views/pages/page/page.button.vue +++ b/src/client/app/common/views/pages/page/page.button.vue @@ -20,13 +20,13 @@ export default Vue.extend({ methods: { click() { if (this.value.action === 'dialog') { - this.script.reEval(); + this.script.eval(); this.$root.dialog({ text: this.script.interpolate(this.value.content) }); } else if (this.value.action === 'resetRandom') { this.script.aiScript.updateRandomSeed(Math.random()); - this.script.reEval(); + this.script.eval(); } } } diff --git a/src/client/app/common/views/pages/page/page.number-input.vue b/src/client/app/common/views/pages/page/page.number-input.vue index 51d538c36..31da37330 100644 --- a/src/client/app/common/views/pages/page/page.number-input.vue +++ b/src/client/app/common/views/pages/page/page.number-input.vue @@ -26,7 +26,7 @@ export default Vue.extend({ watch: { v() { this.script.aiScript.updatePageVar(this.value.name, this.v); - this.script.reEval(); + this.script.eval(); } } }); diff --git a/src/client/app/common/views/pages/page/page.switch.vue b/src/client/app/common/views/pages/page/page.switch.vue index a401e5dfb..53695f1b3 100644 --- a/src/client/app/common/views/pages/page/page.switch.vue +++ b/src/client/app/common/views/pages/page/page.switch.vue @@ -26,7 +26,7 @@ export default Vue.extend({ watch: { v() { this.script.aiScript.updatePageVar(this.value.name, this.v); - this.script.reEval(); + this.script.eval(); } } }); diff --git a/src/client/app/common/views/pages/page/page.text-input.vue b/src/client/app/common/views/pages/page/page.text-input.vue index 3d659edd5..cf917dd5a 100644 --- a/src/client/app/common/views/pages/page/page.text-input.vue +++ b/src/client/app/common/views/pages/page/page.text-input.vue @@ -26,7 +26,7 @@ export default Vue.extend({ watch: { v() { this.script.aiScript.updatePageVar(this.value.name, this.v); - this.script.reEval(); + this.script.eval(); } } }); diff --git a/src/client/app/common/views/pages/page/page.textarea-input.vue b/src/client/app/common/views/pages/page/page.textarea-input.vue index fd8174c27..eece59fef 100644 --- a/src/client/app/common/views/pages/page/page.textarea-input.vue +++ b/src/client/app/common/views/pages/page/page.textarea-input.vue @@ -26,7 +26,7 @@ export default Vue.extend({ watch: { v() { this.script.aiScript.updatePageVar(this.value.name, this.v); - this.script.reEval(); + this.script.eval(); } } }); diff --git a/src/client/app/common/views/pages/page/page.vue b/src/client/app/common/views/pages/page/page.vue index 27e9a7aec..5852cb0b8 100644 --- a/src/client/app/common/views/pages/page/page.vue +++ b/src/client/app/common/views/pages/page/page.vue @@ -27,15 +27,21 @@ import { url } from '../../../../config'; class Script { public aiScript: AiScript; + private onError: any; public vars: Record; - constructor(aiScript) { + constructor(aiScript, onError) { this.aiScript = aiScript; - this.vars = this.aiScript.evaluateVars(); + this.onError = onError; + this.eval(); } - public reEval() { - this.vars = this.aiScript.evaluateVars(); + public eval() { + try { + this.vars = this.aiScript.evaluateVars(); + } catch (e) { + this.onError(e); + } } public interpolate(str: string) { @@ -86,7 +92,9 @@ export default Vue.extend({ visitor: this.$store.state.i, page: page, url: url - })); + }), e => { + console.dir(e); + }); }); }, From ca6fc9cd792b1e0de662790a4421315287b7807b Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 16:07:05 +0900 Subject: [PATCH 10/19] Remove strConcat function --- locales/ja-JP.yml | 4 ---- src/client/app/common/scripts/aiscript.ts | 2 -- 2 files changed, 6 deletions(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index 238f4256d..a61be19d5 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -1953,10 +1953,6 @@ pages: strReverse: "テキストを反転" _strReverse: arg1: "テキスト" - strConcat: "2つのテキストを連結" - _strConcat: - arg1: "テキスト1" - arg2: "テキスト2" join: "テキストを連結" _join: arg1: "リスト" diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index 1e486c455..a6fedcae0 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -80,7 +80,6 @@ const funcDefs = { strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, - strConcat: { in: ['string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, @@ -500,7 +499,6 @@ export class AiScript { strPick: (a, b) => a[b - 1], strReplace: (a, b, c) => a.split(b).join(c), strReverse: (a) => a.split('').reverse().join(''), - strConcat: (a, b) => a + b, join: (texts, separator) => texts.join(separator || ''), stringToNumber: (a) => parseInt(a), numberToString: (a) => a.toString(), From 3444b9c9c8520b25f9680a702a2d35ee1a770196 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 16:33:54 +0900 Subject: [PATCH 11/19] Add splitStrByLine function --- locales/ja-JP.yml | 3 ++ src/client/app/common/scripts/aiscript.ts | 64 ++++++++++++----------- 2 files changed, 36 insertions(+), 31 deletions(-) diff --git a/locales/ja-JP.yml b/locales/ja-JP.yml index a61be19d5..00ec4e662 100644 --- a/locales/ja-JP.yml +++ b/locales/ja-JP.yml @@ -2053,6 +2053,9 @@ pages: numberToString: "数値をテキストに" _numberToString: arg1: "数値" + splitStrByLine: "テキストを行で分割" + _splitStrByLine: + arg1: "テキスト" ref: "変数" fn: "関数" _fn: diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts index a6fedcae0..e94a5fa3f 100644 --- a/src/client/app/common/scripts/aiscript.ts +++ b/src/client/app/common/scripts/aiscript.ts @@ -61,37 +61,38 @@ type TypeError = { }; const funcDefs = { - if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, - for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, - not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - add: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faPlus, }, - subtract: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faMinus, }, - multiply: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faTimes, }, - divide: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faDivide, }, - eq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faEquals, }, - notEq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faNotEqual, }, - gt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThan, }, - lt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThan, }, - gtEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThanEqual, }, - ltEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThanEqual, }, - strLen: { in: ['string'], out: 'number', category: 'text', icon: faQuoteRight, }, - strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, - strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, - strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, - join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, - stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, - numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, - rannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, - dailyRannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, - seedRannum: { in: [null, 'number', 'number'], out: 'number', category: 'random', icon: faDice, }, - random: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, - dailyRandom: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, - seedRandom: { in: [null, 'number'], out: 'boolean', category: 'random', icon: faDice, }, - randomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, - dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, - seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, + if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, + for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, + not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + add: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faPlus, }, + subtract: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faMinus, }, + multiply: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faTimes, }, + divide: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faDivide, }, + eq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faEquals, }, + notEq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faNotEqual, }, + gt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThan, }, + lt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThan, }, + gtEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThanEqual, }, + ltEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThanEqual, }, + strLen: { in: ['string'], out: 'number', category: 'text', icon: faQuoteRight, }, + strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, + strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, + strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, + join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, + stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, + numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, + splitStrByLine: { in: ['string'], out: 'stringArray', category: 'convert', icon: faExchangeAlt, }, + rannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, + dailyRannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, + seedRannum: { in: [null, 'number', 'number'], out: 'number', category: 'random', icon: faDice, }, + random: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, + dailyRandom: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, + seedRandom: { in: [null, 'number'], out: 'boolean', category: 'random', icon: faDice, }, + randomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, + dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, + seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, }; const literalDefs = { @@ -502,6 +503,7 @@ export class AiScript { join: (texts, separator) => texts.join(separator || ''), stringToNumber: (a) => parseInt(a), numberToString: (a) => a.toString(), + splitStrByLine: (a) => a.split('\n'), random: (probability) => Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * 100) < probability, rannum: (min, max) => min + Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * (max - min + 1)), randomPick: (list) => list[Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * list.length)], From c3cd6ad2d221c9b5050ce465b9c97268da7a6ec5 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 18:33:11 +0900 Subject: [PATCH 12/19] Refactoring --- src/client/app/common/scripts/aiscript.ts | 543 ------------------ .../page-editor/page-editor.script-block.vue | 13 +- .../components/page-editor/page-editor.vue | 11 +- .../app/common/views/pages/page/page.vue | 6 +- src/misc/aiscript/evaluator.ts | 250 ++++++++ src/misc/aiscript/index.ts | 131 +++++ src/misc/aiscript/type-checker.ts | 176 ++++++ 7 files changed, 572 insertions(+), 558 deletions(-) delete mode 100644 src/client/app/common/scripts/aiscript.ts create mode 100644 src/misc/aiscript/evaluator.ts create mode 100644 src/misc/aiscript/index.ts create mode 100644 src/misc/aiscript/type-checker.ts diff --git a/src/client/app/common/scripts/aiscript.ts b/src/client/app/common/scripts/aiscript.ts deleted file mode 100644 index e94a5fa3f..000000000 --- a/src/client/app/common/scripts/aiscript.ts +++ /dev/null @@ -1,543 +0,0 @@ -/** - * AiScript - * evaluator & type checker - */ - -import autobind from 'autobind-decorator'; -import * as seedrandom from 'seedrandom'; - -import { - faSuperscript, - faAlignLeft, - faShareAlt, - faSquareRootAlt, - faPlus, - faMinus, - faTimes, - faDivide, - faList, - faQuoteRight, - faEquals, - faGreaterThan, - faLessThan, - faGreaterThanEqual, - faLessThanEqual, - faExclamation, - faNotEqual, - faDice, - faSortNumericUp, - faExchangeAlt, - faRecycle, -} from '@fortawesome/free-solid-svg-icons'; -import { faFlag } from '@fortawesome/free-regular-svg-icons'; - -import { version } from '../../config'; - -export type Block = { - id: string; - type: string; - args: Block[]; - value: V; -}; - -type FnBlock = Block<{ - slots: { - name: string; - type: Type; - }[]; - expression: Block; -}>; - -export type Variable = Block & { - name: string; -}; - -type Type = 'string' | 'number' | 'boolean' | 'stringArray'; - -type TypeError = { - arg: number; - expect: Type; - actual: Type; -}; - -const funcDefs = { - if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, - for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, - not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, - add: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faPlus, }, - subtract: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faMinus, }, - multiply: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faTimes, }, - divide: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faDivide, }, - eq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faEquals, }, - notEq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faNotEqual, }, - gt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThan, }, - lt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThan, }, - gtEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThanEqual, }, - ltEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThanEqual, }, - strLen: { in: ['string'], out: 'number', category: 'text', icon: faQuoteRight, }, - strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, - strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, - strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, - join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, - stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, - numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, - splitStrByLine: { in: ['string'], out: 'stringArray', category: 'convert', icon: faExchangeAlt, }, - rannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, - dailyRannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, - seedRannum: { in: [null, 'number', 'number'], out: 'number', category: 'random', icon: faDice, }, - random: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, - dailyRandom: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, - seedRandom: { in: [null, 'number'], out: 'boolean', category: 'random', icon: faDice, }, - randomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, - dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, - seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, -}; - -const literalDefs = { - text: { out: 'string', category: 'value', icon: faQuoteRight, }, - multiLineText: { out: 'string', category: 'value', icon: faAlignLeft, }, - textList: { out: 'stringArray', category: 'value', icon: faList, }, - number: { out: 'number', category: 'value', icon: faSortNumericUp, }, - ref: { out: null, category: 'value', icon: faSuperscript, }, - fn: { out: 'function', category: 'value', icon: faSuperscript, }, -}; - -const blockDefs = [ - ...Object.entries(literalDefs).map(([k, v]) => ({ - type: k, out: v.out, category: v.category, icon: v.icon - })), - ...Object.entries(funcDefs).map(([k, v]) => ({ - type: k, out: v.out, category: v.category, icon: v.icon - })) -]; - -function isFnBlock(block: Block): block is FnBlock { - return block.type === 'fn'; -} - -type PageVar = { name: string; value: any; type: Type; }; - -const envVarsDef = { - AI: 'string', - URL: 'string', - VERSION: 'string', - LOGIN: 'boolean', - NAME: 'string', - USERNAME: 'string', - USERID: 'string', - NOTES_COUNT: 'number', - FOLLOWERS_COUNT: 'number', - FOLLOWING_COUNT: 'number', - IS_CAT: 'boolean', - MY_NOTES_COUNT: 'number', - MY_FOLLOWERS_COUNT: 'number', - MY_FOLLOWING_COUNT: 'number', - SEED: null, - YMD: 'string', -}; - -class AiScriptError extends Error { - public info?: any; - - constructor(message: string, info?: any) { - super(message); - - this.info = info; - - // Maintains proper stack trace for where our error was thrown (only available on V8) - if (Error.captureStackTrace) { - Error.captureStackTrace(this, AiScriptError); - } - } -} - -class Scope { - private layerdStates: Record[]; - public name: string; - - constructor(layerdStates: Scope['layerdStates'], name?: Scope['name']) { - this.layerdStates = layerdStates; - this.name = name || 'anonymous'; - } - - @autobind - public createChildScope(states: Record, name?: Scope['name']): Scope { - const layer = [states, ...this.layerdStates]; - return new Scope(layer, name); - } - - /** - * 指定した名前の変数の値を取得します - * @param name 変数名 - */ - @autobind - public getState(name: string): any { - for (const later of this.layerdStates) { - const state = later[name]; - if (state !== undefined) { - return state; - } - } - - throw new AiScriptError( - `No such variable '${name}' in scope '${this.name}'`, { - scope: this.layerdStates - }); - } -} - -export class AiScript { - private variables: Variable[]; - private pageVars: PageVar[]; - private envVars: Record; - - public static envVarsDef = envVarsDef; - public static blockDefs = blockDefs; - public static funcDefs = funcDefs; - private opts: { - randomSeed?: string; user?: any; visitor?: any; page?: any; url?: string; - }; - - constructor(variables: Variable[] = [], pageVars: PageVar[] = [], opts: AiScript['opts'] = {}) { - this.variables = variables; - this.pageVars = pageVars; - this.opts = opts; - - const date = new Date(); - - this.envVars = { - AI: 'kawaii', - VERSION: version, - URL: opts.page ? `${opts.url}/@${opts.page.user.username}/pages/${opts.page.name}` : '', - LOGIN: opts.visitor != null, - NAME: opts.visitor ? opts.visitor.name : '', - USERNAME: opts.visitor ? opts.visitor.username : '', - USERID: opts.visitor ? opts.visitor.id : '', - NOTES_COUNT: opts.visitor ? opts.visitor.notesCount : 0, - FOLLOWERS_COUNT: opts.visitor ? opts.visitor.followersCount : 0, - FOLLOWING_COUNT: opts.visitor ? opts.visitor.followingCount : 0, - IS_CAT: opts.visitor ? opts.visitor.isCat : false, - MY_NOTES_COUNT: opts.user ? opts.user.notesCount : 0, - MY_FOLLOWERS_COUNT: opts.user ? opts.user.followersCount : 0, - MY_FOLLOWING_COUNT: opts.user ? opts.user.followingCount : 0, - SEED: opts.randomSeed ? opts.randomSeed : '', - YMD: `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}` - }; - } - - @autobind - public injectVars(vars: Variable[]) { - this.variables = vars; - } - - @autobind - public injectPageVars(pageVars: PageVar[]) { - this.pageVars = pageVars; - } - - @autobind - public updatePageVar(name: string, value: any) { - this.pageVars.find(v => v.name === name).value = value; - } - - @autobind - public updateRandomSeed(seed: string) { - this.opts.randomSeed = seed; - this.envVars.SEED = seed; - } - - @autobind - public static isLiteralBlock(v: Block) { - if (v.type === null) return true; - if (literalDefs[v.type]) return true; - return false; - } - - @autobind - public typeCheck(v: Block): TypeError | null { - if (AiScript.isLiteralBlock(v)) return null; - - const def = AiScript.funcDefs[v.type]; - if (def == null) { - throw new Error('Unknown type: ' + v.type); - } - - const generic: Type[] = []; - - for (let i = 0; i < def.in.length; i++) { - const arg = def.in[i]; - const type = this.typeInference(v.args[i]); - if (type === null) continue; - - if (typeof arg === 'number') { - if (generic[arg] === undefined) { - generic[arg] = type; - } else if (type !== generic[arg]) { - return { - arg: i, - expect: generic[arg], - actual: type - }; - } - } else if (type !== arg) { - return { - arg: i, - expect: arg, - actual: type - }; - } - } - - return null; - } - - @autobind - public getExpectedType(v: Block, slot: number): Type | null { - const def = AiScript.funcDefs[v.type]; - if (def == null) { - throw new Error('Unknown type: ' + v.type); - } - - const generic: Type[] = []; - - for (let i = 0; i < def.in.length; i++) { - const arg = def.in[i]; - const type = this.typeInference(v.args[i]); - if (type === null) continue; - - if (typeof arg === 'number') { - if (generic[arg] === undefined) { - generic[arg] = type; - } - } - } - - if (typeof def.in[slot] === 'number') { - return generic[def.in[slot]] || null; - } else { - return def.in[slot]; - } - } - - @autobind - public typeInference(v: Block): Type | null { - if (v.type === null) return null; - if (v.type === 'text') return 'string'; - if (v.type === 'multiLineText') return 'string'; - if (v.type === 'textList') return 'stringArray'; - if (v.type === 'number') return 'number'; - if (v.type === 'ref') { - const variable = this.variables.find(va => va.name === v.value); - if (variable) { - return this.typeInference(variable); - } - - const pageVar = this.pageVars.find(va => va.name === v.value); - if (pageVar) { - return pageVar.type; - } - - const envVar = AiScript.envVarsDef[v.value]; - if (envVar !== undefined) { - return envVar; - } - - return null; - } - if (v.type === 'fn') return null; // todo - if (v.type.startsWith('fn:')) return null; // todo - - const generic: Type[] = []; - - const def = AiScript.funcDefs[v.type]; - - for (let i = 0; i < def.in.length; i++) { - const arg = def.in[i]; - if (typeof arg === 'number') { - const type = this.typeInference(v.args[i]); - - if (generic[arg] === undefined) { - generic[arg] = type; - } else { - if (type !== generic[arg]) { - generic[arg] = null; - } - } - } - } - - if (typeof def.out === 'number') { - return generic[def.out]; - } else { - return def.out; - } - } - - @autobind - public getVarsByType(type: Type | null): Variable[] { - if (type == null) return this.variables; - return this.variables.filter(x => (this.typeInference(x) === null) || (this.typeInference(x) === type)); - } - - @autobind - public getVarByName(name: string): Variable { - return this.variables.find(x => x.name === name); - } - - @autobind - public getEnvVarsByType(type: Type | null): string[] { - if (type == null) return Object.keys(AiScript.envVarsDef); - return Object.entries(AiScript.envVarsDef).filter(([k, v]) => v === null || type === v).map(([k, v]) => k); - } - - @autobind - public getPageVarsByType(type: Type | null): string[] { - if (type == null) return this.pageVars.map(v => v.name); - return this.pageVars.filter(v => type === v.type).map(v => v.name); - } - - @autobind - private interpolate(str: string, scope: Scope) { - return str.replace(/\{(.+?)\}/g, match => { - const v = scope.getState(match.slice(1, -1).trim()); - return v == null ? 'NULL' : v.toString(); - }); - } - - @autobind - public evaluateVars(): Record { - const values: Record = {}; - - for (const [k, v] of Object.entries(this.envVars)) { - values[k] = v; - } - - for (const v of this.pageVars) { - values[v.name] = v.value; - } - - for (const v of this.variables) { - values[v.name] = this.evaluate(v, new Scope([values])); - } - - return values; - } - - @autobind - private evaluate(block: Block, scope: Scope): any { - if (block.type === null) { - return null; - } - - if (block.type === 'number') { - return parseInt(block.value, 10); - } - - if (block.type === 'text' || block.type === 'multiLineText') { - return this.interpolate(block.value || '', scope); - } - - if (block.type === 'textList') { - return block.value.trim().split('\n'); - } - - if (block.type === 'ref') { - return scope.getState(block.value); - } - - if (isFnBlock(block)) { // ユーザー関数定義 - return { - slots: block.value.slots.map(x => x.name), - exec: slotArg => { - return this.evaluate(block.value.expression, scope.createChildScope(slotArg, block.id)); - } - }; - } - - if (block.type.startsWith('fn:')) { // ユーザー関数呼び出し - const fnName = block.type.split(':')[1]; - const fn = scope.getState(fnName); - const args = {}; - for (let i = 0; i < fn.slots.length; i++) { - const name = fn.slots[i]; - args[name] = this.evaluate(block.args[i], scope); - } - return fn.exec(args); - } - - if (block.args === undefined) return null; - - const date = new Date(); - const day = `${this.opts.visitor ? this.opts.visitor.id : ''} ${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`; - - const funcs: { [p in keyof typeof funcDefs]: any } = { - not: (a) => !a, - eq: (a, b) => a === b, - notEq: (a, b) => a !== b, - gt: (a, b) => a > b, - lt: (a, b) => a < b, - gtEq: (a, b) => a >= b, - ltEq: (a, b) => a <= b, - or: (a, b) => a || b, - and: (a, b) => a && b, - if: (bool, a, b) => bool ? a : b, - for: (times, fn) => { - const result = []; - for (let i = 0; i < times; i++) { - result.push(fn.exec({ - [fn.slots[0]]: i + 1 - })); - } - return result; - }, - add: (a, b) => a + b, - subtract: (a, b) => a - b, - multiply: (a, b) => a * b, - divide: (a, b) => a / b, - strLen: (a) => a.length, - strPick: (a, b) => a[b - 1], - strReplace: (a, b, c) => a.split(b).join(c), - strReverse: (a) => a.split('').reverse().join(''), - join: (texts, separator) => texts.join(separator || ''), - stringToNumber: (a) => parseInt(a), - numberToString: (a) => a.toString(), - splitStrByLine: (a) => a.split('\n'), - random: (probability) => Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * 100) < probability, - rannum: (min, max) => min + Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * (max - min + 1)), - randomPick: (list) => list[Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * list.length)], - dailyRandom: (probability) => Math.floor(seedrandom(`${day}:${block.id}`)() * 100) < probability, - dailyRannum: (min, max) => min + Math.floor(seedrandom(`${day}:${block.id}`)() * (max - min + 1)), - dailyRandomPick: (list) => list[Math.floor(seedrandom(`${day}:${block.id}`)() * list.length)], - seedRandom: (seed, probability) => Math.floor(seedrandom(seed)() * 100) < probability, - seedRannum: (seed, min, max) => min + Math.floor(seedrandom(seed)() * (max - min + 1)), - seedRandomPick: (seed, list) => list[Math.floor(seedrandom(seed)() * list.length)], - }; - - const fnName = block.type; - const fn = funcs[fnName]; - if (fn == null) { - throw new AiScriptError(`No such function '${fnName}'`); - } else { - return fn(...block.args.map(x => this.evaluate(x, scope))); - } - } - - @autobind - public isUsedName(name: string) { - if (this.variables.some(v => v.name === name)) { - return true; - } - - if (this.pageVars.some(v => v.name === name)) { - return true; - } - - if (AiScript.envVarsDef[name]) { - return true; - } - - return false; - } -} diff --git a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue index 7a3942ec8..a145c37ed 100644 --- a/src/client/app/common/views/components/page-editor/page-editor.script-block.vue +++ b/src/client/app/common/views/components/page-editor/page-editor.script-block.vue @@ -57,7 +57,7 @@ import Vue from 'vue'; import i18n from '../../../../i18n'; import XContainer from './page-editor.container.vue'; import { faSuperscript, faPencilAlt, faSquareRootAlt } from '@fortawesome/free-solid-svg-icons'; -import { AiScript } from '../../../scripts/aiscript'; +import { isLiteralBlock, funcDefs, blockDefs } from '../../../../../../misc/aiscript/index'; import * as uuid from 'uuid'; export default Vue.extend({ @@ -97,7 +97,6 @@ export default Vue.extend({ data() { return { - AiScript, error: null, warn: null, slots: '', @@ -109,7 +108,7 @@ export default Vue.extend({ icon(): any { if (this.value.type === null) return null; if (this.value.type.startsWith('fn:')) return null; - return AiScript.blockDefs.find(x => x.type === this.value.type).icon; + return blockDefs.find(x => x.type === this.value.type).icon; }, typeText(): any { if (this.value.type === null) return null; @@ -160,17 +159,17 @@ export default Vue.extend({ return; } - if (AiScript.isLiteralBlock(this.value)) return; + if (isLiteralBlock(this.value)) return; const empties = []; - for (let i = 0; i < AiScript.funcDefs[this.value.type].in.length; i++) { + for (let i = 0; i < funcDefs[this.value.type].in.length; i++) { const id = uuid.v4(); empties.push({ id, type: null }); } Vue.set(this.value, 'args', empties); - for (let i = 0; i < AiScript.funcDefs[this.value.type].in.length; i++) { - const inType = AiScript.funcDefs[this.value.type].in[i]; + for (let i = 0; i < funcDefs[this.value.type].in.length; i++) { + const inType = funcDefs[this.value.type].in[i]; if (typeof inType !== 'number') { if (inType === 'number') this.value.args[i].type = 'number'; if (inType === 'string') this.value.args[i].type = 'text'; diff --git a/src/client/app/common/views/components/page-editor/page-editor.vue b/src/client/app/common/views/components/page-editor/page-editor.vue index 8007970be..7e0268098 100644 --- a/src/client/app/common/views/components/page-editor/page-editor.vue +++ b/src/client/app/common/views/components/page-editor/page-editor.vue @@ -92,7 +92,8 @@ import { faSave, faStickyNote, faTrashAlt } from '@fortawesome/free-regular-svg- import XVariable from './page-editor.script-block.vue'; import XBlock from './page-editor.block.vue'; import * as uuid from 'uuid'; -import { AiScript } from '../../../scripts/aiscript'; +import { blockDefs } from '../../../../../../misc/aiscript/index'; +import { ASTypeChecker } from '../../../../../../misc/aiscript/type-checker'; import { url } from '../../../../config'; import { collectPageVars } from '../../../scripts/collect-page-vars'; @@ -150,14 +151,14 @@ export default Vue.extend({ }, created() { - this.aiScript = new AiScript(); + this.aiScript = new ASTypeChecker(); this.$watch('variables', () => { - this.aiScript.injectVars(this.variables); + this.aiScript.variables = this.variables; }, { deep: true }); this.$watch('content', () => { - this.aiScript.injectPageVars(collectPageVars(this.content)); + this.aiScript.pageVars = collectPageVars(this.content); }, { deep: true }); if (this.page) { @@ -352,7 +353,7 @@ export default Vue.extend({ getScriptBlockList(type: string = null) { const list = []; - const blocks = AiScript.blockDefs.filter(block => type === null || block.out === null || block.out === type); + const blocks = blockDefs.filter(block => type === null || block.out === null || block.out === type); for (const block of blocks) { const category = list.find(x => x.category === block.category); diff --git a/src/client/app/common/views/pages/page/page.vue b/src/client/app/common/views/pages/page/page.vue index 5852cb0b8..4f83aa176 100644 --- a/src/client/app/common/views/pages/page/page.vue +++ b/src/client/app/common/views/pages/page/page.vue @@ -21,12 +21,12 @@ import i18n from '../../../../i18n'; import { faICursor, faPlus, faSquareRootAlt } from '@fortawesome/free-solid-svg-icons'; import { faSave, faStickyNote } from '@fortawesome/free-regular-svg-icons'; import XBlock from './page.block.vue'; -import { AiScript } from '../../../scripts/aiscript'; +import { ASEvaluator } from '../../../../../../misc/aiscript/evaluator'; import { collectPageVars } from '../../../scripts/collect-page-vars'; import { url } from '../../../../config'; class Script { - public aiScript: AiScript; + public aiScript: ASEvaluator; private onError: any; public vars: Record; @@ -86,7 +86,7 @@ export default Vue.extend({ }).then(page => { this.page = page; const pageVars = this.getPageVars(); - this.script = new Script(new AiScript(this.page.variables, pageVars, { + this.script = new Script(new ASEvaluator(this.page.variables, pageVars, { randomSeed: Math.random(), user: page.user, visitor: this.$store.state.i, diff --git a/src/misc/aiscript/evaluator.ts b/src/misc/aiscript/evaluator.ts new file mode 100644 index 000000000..0de924e81 --- /dev/null +++ b/src/misc/aiscript/evaluator.ts @@ -0,0 +1,250 @@ +import autobind from 'autobind-decorator'; +import * as seedrandom from 'seedrandom'; +import { Variable, PageVar, envVarsDef, funcDefs, Block, isFnBlock } from '.'; + +type Fn = { + slots: string[]; + exec: (args: Record) => ReturnType; +}; + +class AiScriptError extends Error { + public info?: any; + + constructor(message: string, info?: any) { + super(message); + + this.info = info; + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, AiScriptError); + } + } +} + +class Scope { + private layerdStates: Record[]; + public name: string; + + constructor(layerdStates: Scope['layerdStates'], name?: Scope['name']) { + this.layerdStates = layerdStates; + this.name = name || 'anonymous'; + } + + @autobind + public createChildScope(states: Record, name?: Scope['name']): Scope { + const layer = [states, ...this.layerdStates]; + return new Scope(layer, name); + } + + /** + * 指定した名前の変数の値を取得します + * @param name 変数名 + */ + @autobind + public getState(name: string): any { + for (const later of this.layerdStates) { + const state = later[name]; + if (state !== undefined) { + return state; + } + } + + throw new AiScriptError( + `No such variable '${name}' in scope '${this.name}'`, { + scope: this.layerdStates + }); + } +} + +/** + * AiScript evaluator + */ +export class ASEvaluator { + private variables: Variable[]; + private pageVars: PageVar[]; + private envVars: Record; + + private opts: { + randomSeed: string; user?: any; visitor?: any; page?: any; url?: string; version: string; + }; + + constructor(variables: Variable[], pageVars: PageVar[], opts: ASEvaluator['opts']) { + this.variables = variables; + this.pageVars = pageVars; + this.opts = opts; + + const date = new Date(); + + this.envVars = { + AI: 'kawaii', + VERSION: opts.version, + URL: opts.page ? `${opts.url}/@${opts.page.user.username}/pages/${opts.page.name}` : '', + LOGIN: opts.visitor != null, + NAME: opts.visitor ? opts.visitor.name : '', + USERNAME: opts.visitor ? opts.visitor.username : '', + USERID: opts.visitor ? opts.visitor.id : '', + NOTES_COUNT: opts.visitor ? opts.visitor.notesCount : 0, + FOLLOWERS_COUNT: opts.visitor ? opts.visitor.followersCount : 0, + FOLLOWING_COUNT: opts.visitor ? opts.visitor.followingCount : 0, + IS_CAT: opts.visitor ? opts.visitor.isCat : false, + MY_NOTES_COUNT: opts.user ? opts.user.notesCount : 0, + MY_FOLLOWERS_COUNT: opts.user ? opts.user.followersCount : 0, + MY_FOLLOWING_COUNT: opts.user ? opts.user.followingCount : 0, + SEED: opts.randomSeed ? opts.randomSeed : '', + YMD: `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}` + }; + } + + @autobind + public updatePageVar(name: string, value: any) { + const pageVar = this.pageVars.find(v => v.name === name); + if (pageVar !== undefined) { + pageVar.value = value; + } else { + throw new AiScriptError(`No such page var '${name}'`); + } + } + + @autobind + public updateRandomSeed(seed: string) { + this.opts.randomSeed = seed; + this.envVars.SEED = seed; + } + + @autobind + public getVarByName(name: string): Variable { + const v = this.variables.find(x => x.name === name); + if (v !== undefined) { + return v; + } else { + throw new AiScriptError(`No such variable '${name}'`); + } + } + + @autobind + private interpolate(str: string, scope: Scope) { + return str.replace(/\{(.+?)\}/g, match => { + const v = scope.getState(match.slice(1, -1).trim()); + return v == null ? 'NULL' : v.toString(); + }); + } + + @autobind + public evaluateVars(): Record { + const values: Record = {}; + + for (const [k, v] of Object.entries(this.envVars)) { + values[k] = v; + } + + for (const v of this.pageVars) { + values[v.name] = v.value; + } + + for (const v of this.variables) { + values[v.name] = this.evaluate(v, new Scope([values])); + } + + return values; + } + + @autobind + private evaluate(block: Block, scope: Scope): any { + if (block.type === null) { + return null; + } + + if (block.type === 'number') { + return parseInt(block.value, 10); + } + + if (block.type === 'text' || block.type === 'multiLineText') { + return this.interpolate(block.value || '', scope); + } + + if (block.type === 'textList') { + return block.value.trim().split('\n'); + } + + if (block.type === 'ref') { + return scope.getState(block.value); + } + + if (isFnBlock(block)) { // ユーザー関数定義 + return { + slots: block.value.slots.map(x => x.name), + exec: (slotArg: Record) => { + return this.evaluate(block.value.expression, scope.createChildScope(slotArg, block.id)); + } + } as Fn; + } + + if (block.type.startsWith('fn:')) { // ユーザー関数呼び出し + const fnName = block.type.split(':')[1]; + const fn = scope.getState(fnName); + const args = {} as Record; + for (let i = 0; i < fn.slots.length; i++) { + const name = fn.slots[i]; + args[name] = this.evaluate(block.args[i], scope); + } + return fn.exec(args); + } + + if (block.args === undefined) return null; + + const date = new Date(); + const day = `${this.opts.visitor ? this.opts.visitor.id : ''} ${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`; + + const funcs: { [p in keyof typeof funcDefs]: Function } = { + not: (a: boolean) => !a, + or: (a: boolean, b: boolean) => a || b, + and: (a: boolean, b: boolean) => a && b, + eq: (a: any, b: any) => a === b, + notEq: (a: any, b: any) => a !== b, + gt: (a: number, b: number) => a > b, + lt: (a: number, b: number) => a < b, + gtEq: (a: number, b: number) => a >= b, + ltEq: (a: number, b: number) => a <= b, + if: (bool: boolean, a: any, b: any) => bool ? a : b, + for: (times: number, fn: Fn) => { + const result = []; + for (let i = 0; i < times; i++) { + result.push(fn.exec({ + [fn.slots[0]]: i + 1 + })); + } + return result; + }, + add: (a: number, b: number) => a + b, + subtract: (a: number, b: number) => a - b, + multiply: (a: number, b: number) => a * b, + divide: (a: number, b: number) => a / b, + strLen: (a: string) => a.length, + strPick: (a: string, b: number) => a[b - 1], + strReplace: (a: string, b: string, c: string) => a.split(b).join(c), + strReverse: (a: string) => a.split('').reverse().join(''), + join: (texts: string[], separator: string) => texts.join(separator || ''), + stringToNumber: (a: string) => parseInt(a), + numberToString: (a: number) => a.toString(), + splitStrByLine: (a: string) => a.split('\n'), + random: (probability: number) => Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * 100) < probability, + rannum: (min: number, max: number) => min + Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * (max - min + 1)), + randomPick: (list: any[]) => list[Math.floor(seedrandom(`${this.opts.randomSeed}:${block.id}`)() * list.length)], + dailyRandom: (probability: number) => Math.floor(seedrandom(`${day}:${block.id}`)() * 100) < probability, + dailyRannum: (min: number, max: number) => min + Math.floor(seedrandom(`${day}:${block.id}`)() * (max - min + 1)), + dailyRandomPick: (list: any[]) => list[Math.floor(seedrandom(`${day}:${block.id}`)() * list.length)], + seedRandom: (seed: any, probability: number) => Math.floor(seedrandom(seed)() * 100) < probability, + seedRannum: (seed: any, min: number, max: number) => min + Math.floor(seedrandom(seed)() * (max - min + 1)), + seedRandomPick: (seed: any, list: any[]) => list[Math.floor(seedrandom(seed)() * list.length)], + }; + + const fnName = block.type; + const fn = (funcs as any)[fnName]; + if (fn == null) { + throw new AiScriptError(`No such function '${fnName}'`); + } else { + return fn(...block.args.map(x => this.evaluate(x, scope))); + } + } +} diff --git a/src/misc/aiscript/index.ts b/src/misc/aiscript/index.ts new file mode 100644 index 000000000..d36c27f94 --- /dev/null +++ b/src/misc/aiscript/index.ts @@ -0,0 +1,131 @@ +/** + * AiScript + */ + +import { + faSuperscript, + faAlignLeft, + faShareAlt, + faPlus, + faMinus, + faTimes, + faDivide, + faList, + faQuoteRight, + faEquals, + faGreaterThan, + faLessThan, + faGreaterThanEqual, + faLessThanEqual, + faNotEqual, + faDice, + faSortNumericUp, + faExchangeAlt, + faRecycle, +} from '@fortawesome/free-solid-svg-icons'; +import { faFlag } from '@fortawesome/free-regular-svg-icons'; + +export type Block = { + id: string; + type: string; + args: Block[]; + value: V; +}; + +export type FnBlock = Block<{ + slots: { + name: string; + type: Type; + }[]; + expression: Block; +}>; + +export type Variable = Block & { + name: string; +}; + +export type Type = 'string' | 'number' | 'boolean' | 'stringArray'; + +export const funcDefs = { + if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, + for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, + not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + or: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + and: { in: ['boolean', 'boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, + add: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faPlus, }, + subtract: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faMinus, }, + multiply: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faTimes, }, + divide: { in: ['number', 'number'], out: 'number', category: 'operation', icon: faDivide, }, + eq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faEquals, }, + notEq: { in: [0, 0], out: 'boolean', category: 'comparison', icon: faNotEqual, }, + gt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThan, }, + lt: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThan, }, + gtEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faGreaterThanEqual, }, + ltEq: { in: ['number', 'number'], out: 'boolean', category: 'comparison', icon: faLessThanEqual, }, + strLen: { in: ['string'], out: 'number', category: 'text', icon: faQuoteRight, }, + strPick: { in: ['string', 'number'], out: 'string', category: 'text', icon: faQuoteRight, }, + strReplace: { in: ['string', 'string', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, + strReverse: { in: ['string'], out: 'string', category: 'text', icon: faQuoteRight, }, + join: { in: ['stringArray', 'string'], out: 'string', category: 'text', icon: faQuoteRight, }, + stringToNumber: { in: ['string'], out: 'number', category: 'convert', icon: faExchangeAlt, }, + numberToString: { in: ['number'], out: 'string', category: 'convert', icon: faExchangeAlt, }, + splitStrByLine: { in: ['string'], out: 'stringArray', category: 'convert', icon: faExchangeAlt, }, + rannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, + dailyRannum: { in: ['number', 'number'], out: 'number', category: 'random', icon: faDice, }, + seedRannum: { in: [null, 'number', 'number'], out: 'number', category: 'random', icon: faDice, }, + random: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, + dailyRandom: { in: ['number'], out: 'boolean', category: 'random', icon: faDice, }, + seedRandom: { in: [null, 'number'], out: 'boolean', category: 'random', icon: faDice, }, + randomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, + dailyRandomPick: { in: [0], out: 0, category: 'random', icon: faDice, }, + seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, +}; + +export const literalDefs = { + text: { out: 'string', category: 'value', icon: faQuoteRight, }, + multiLineText: { out: 'string', category: 'value', icon: faAlignLeft, }, + textList: { out: 'stringArray', category: 'value', icon: faList, }, + number: { out: 'number', category: 'value', icon: faSortNumericUp, }, + ref: { out: null, category: 'value', icon: faSuperscript, }, + fn: { out: 'function', category: 'value', icon: faSuperscript, }, +}; + +export const blockDefs = [ + ...Object.entries(literalDefs).map(([k, v]) => ({ + type: k, out: v.out, category: v.category, icon: v.icon + })), + ...Object.entries(funcDefs).map(([k, v]) => ({ + type: k, out: v.out, category: v.category, icon: v.icon + })) +]; + +export function isFnBlock(block: Block): block is FnBlock { + return block.type === 'fn'; +} + +export type PageVar = { name: string; value: any; type: Type; }; + +export const envVarsDef = { + AI: 'string', + URL: 'string', + VERSION: 'string', + LOGIN: 'boolean', + NAME: 'string', + USERNAME: 'string', + USERID: 'string', + NOTES_COUNT: 'number', + FOLLOWERS_COUNT: 'number', + FOLLOWING_COUNT: 'number', + IS_CAT: 'boolean', + MY_NOTES_COUNT: 'number', + MY_FOLLOWERS_COUNT: 'number', + MY_FOLLOWING_COUNT: 'number', + SEED: null, + YMD: 'string', +}; + +export function isLiteralBlock(v: Block) { + if (v.type === null) return true; + if (literalDefs[v.type]) return true; + return false; +} diff --git a/src/misc/aiscript/type-checker.ts b/src/misc/aiscript/type-checker.ts new file mode 100644 index 000000000..4b8582ed7 --- /dev/null +++ b/src/misc/aiscript/type-checker.ts @@ -0,0 +1,176 @@ +import autobind from 'autobind-decorator'; +import { Type, Block, funcDefs, envVarsDef, Variable, PageVar, isLiteralBlock } from '.'; + +type TypeError = { + arg: number; + expect: Type; + actual: Type; +}; + +/** + * AiScript type checker + */ +export class ASTypeChecker { + public variables: Variable[]; + public pageVars: PageVar[]; + + constructor(variables: ASTypeChecker['variables'] = [], pageVars: ASTypeChecker['pageVars'] = []) { + this.variables = variables; + this.pageVars = pageVars; + } + + @autobind + public typeCheck(v: Block): TypeError | null { + if (isLiteralBlock(v)) return null; + + const def = funcDefs[v.type]; + if (def == null) { + throw new Error('Unknown type: ' + v.type); + } + + const generic: Type[] = []; + + for (let i = 0; i < def.in.length; i++) { + const arg = def.in[i]; + const type = this.typeInference(v.args[i]); + if (type === null) continue; + + if (typeof arg === 'number') { + if (generic[arg] === undefined) { + generic[arg] = type; + } else if (type !== generic[arg]) { + return { + arg: i, + expect: generic[arg], + actual: type + }; + } + } else if (type !== arg) { + return { + arg: i, + expect: arg, + actual: type + }; + } + } + + return null; + } + + @autobind + public getExpectedType(v: Block, slot: number): Type | null { + const def = funcDefs[v.type]; + if (def == null) { + throw new Error('Unknown type: ' + v.type); + } + + const generic: Type[] = []; + + for (let i = 0; i < def.in.length; i++) { + const arg = def.in[i]; + const type = this.typeInference(v.args[i]); + if (type === null) continue; + + if (typeof arg === 'number') { + if (generic[arg] === undefined) { + generic[arg] = type; + } + } + } + + if (typeof def.in[slot] === 'number') { + return generic[def.in[slot]] || null; + } else { + return def.in[slot]; + } + } + + @autobind + public typeInference(v: Block): Type | null { + if (v.type === null) return null; + if (v.type === 'text') return 'string'; + if (v.type === 'multiLineText') return 'string'; + if (v.type === 'textList') return 'stringArray'; + if (v.type === 'number') return 'number'; + if (v.type === 'ref') { + const variable = this.variables.find(va => va.name === v.value); + if (variable) { + return this.typeInference(variable); + } + + const pageVar = this.pageVars.find(va => va.name === v.value); + if (pageVar) { + return pageVar.type; + } + + const envVar = envVarsDef[v.value]; + if (envVar !== undefined) { + return envVar; + } + + return null; + } + if (v.type === 'fn') return null; // todo + if (v.type.startsWith('fn:')) return null; // todo + + const generic: Type[] = []; + + const def = funcDefs[v.type]; + + for (let i = 0; i < def.in.length; i++) { + const arg = def.in[i]; + if (typeof arg === 'number') { + const type = this.typeInference(v.args[i]); + + if (generic[arg] === undefined) { + generic[arg] = type; + } else { + if (type !== generic[arg]) { + generic[arg] = null; + } + } + } + } + + if (typeof def.out === 'number') { + return generic[def.out]; + } else { + return def.out; + } + } + + @autobind + public getVarsByType(type: Type | null): Variable[] { + if (type == null) return this.variables; + return this.variables.filter(x => (this.typeInference(x) === null) || (this.typeInference(x) === type)); + } + + @autobind + public getEnvVarsByType(type: Type | null): string[] { + if (type == null) return Object.keys(envVarsDef); + return Object.entries(envVarsDef).filter(([k, v]) => v === null || type === v).map(([k, v]) => k); + } + + @autobind + public getPageVarsByType(type: Type | null): string[] { + if (type == null) return this.pageVars.map(v => v.name); + return this.pageVars.filter(v => type === v.type).map(v => v.name); + } + + @autobind + public isUsedName(name: string) { + if (this.variables.some(v => v.name === name)) { + return true; + } + + if (this.pageVars.some(v => v.name === name)) { + return true; + } + + if (envVarsDef[name]) { + return true; + } + + return false; + } +} From 8b13e3c32792f1bfa82a6d86d2838e689682243d Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 19:20:47 +0900 Subject: [PATCH 13/19] Refactor --- src/misc/aiscript/type-checker.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/misc/aiscript/type-checker.ts b/src/misc/aiscript/type-checker.ts index 4b8582ed7..35dee36bf 100644 --- a/src/misc/aiscript/type-checker.ts +++ b/src/misc/aiscript/type-checker.ts @@ -32,7 +32,7 @@ export class ASTypeChecker { for (let i = 0; i < def.in.length; i++) { const arg = def.in[i]; - const type = this.typeInference(v.args[i]); + const type = this.infer(v.args[i]); if (type === null) continue; if (typeof arg === 'number') { @@ -68,7 +68,7 @@ export class ASTypeChecker { for (let i = 0; i < def.in.length; i++) { const arg = def.in[i]; - const type = this.typeInference(v.args[i]); + const type = this.infer(v.args[i]); if (type === null) continue; if (typeof arg === 'number') { @@ -86,7 +86,7 @@ export class ASTypeChecker { } @autobind - public typeInference(v: Block): Type | null { + public infer(v: Block): Type | null { if (v.type === null) return null; if (v.type === 'text') return 'string'; if (v.type === 'multiLineText') return 'string'; @@ -95,7 +95,7 @@ export class ASTypeChecker { if (v.type === 'ref') { const variable = this.variables.find(va => va.name === v.value); if (variable) { - return this.typeInference(variable); + return this.infer(variable); } const pageVar = this.pageVars.find(va => va.name === v.value); @@ -120,7 +120,7 @@ export class ASTypeChecker { for (let i = 0; i < def.in.length; i++) { const arg = def.in[i]; if (typeof arg === 'number') { - const type = this.typeInference(v.args[i]); + const type = this.infer(v.args[i]); if (generic[arg] === undefined) { generic[arg] = type; @@ -142,7 +142,7 @@ export class ASTypeChecker { @autobind public getVarsByType(type: Type | null): Variable[] { if (type == null) return this.variables; - return this.variables.filter(x => (this.typeInference(x) === null) || (this.typeInference(x) === type)); + return this.variables.filter(x => (this.infer(x) === null) || (this.infer(x) === type)); } @autobind From a9fc176c3c85920fd56f261a30db59c19108b644 Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 19:31:34 +0900 Subject: [PATCH 14/19] Fix types --- src/misc/aiscript/index.ts | 8 ++++---- src/misc/aiscript/type-checker.ts | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/misc/aiscript/index.ts b/src/misc/aiscript/index.ts index d36c27f94..16f80830f 100644 --- a/src/misc/aiscript/index.ts +++ b/src/misc/aiscript/index.ts @@ -44,9 +44,9 @@ export type Variable = Block & { name: string; }; -export type Type = 'string' | 'number' | 'boolean' | 'stringArray'; +export type Type = 'string' | 'number' | 'boolean' | 'stringArray' | null; -export const funcDefs = { +export const funcDefs: Record = { if: { in: ['boolean', 0, 0], out: 0, category: 'flow', icon: faShareAlt, }, for: { in: ['number', 'function'], out: null, category: 'flow', icon: faRecycle, }, not: { in: ['boolean'], out: 'boolean', category: 'logical', icon: faFlag, }, @@ -81,7 +81,7 @@ export const funcDefs = { seedRandomPick: { in: [null, 0], out: 0, category: 'random', icon: faDice, }, }; -export const literalDefs = { +export const literalDefs: Record = { text: { out: 'string', category: 'value', icon: faQuoteRight, }, multiLineText: { out: 'string', category: 'value', icon: faAlignLeft, }, textList: { out: 'stringArray', category: 'value', icon: faList, }, @@ -105,7 +105,7 @@ export function isFnBlock(block: Block): block is FnBlock { export type PageVar = { name: string; value: any; type: Type; }; -export const envVarsDef = { +export const envVarsDef: Record = { AI: 'string', URL: 'string', VERSION: 'string', diff --git a/src/misc/aiscript/type-checker.ts b/src/misc/aiscript/type-checker.ts index 35dee36bf..c40c844ea 100644 --- a/src/misc/aiscript/type-checker.ts +++ b/src/misc/aiscript/type-checker.ts @@ -58,7 +58,7 @@ export class ASTypeChecker { } @autobind - public getExpectedType(v: Block, slot: number): Type | null { + public getExpectedType(v: Block, slot: number): Type { const def = funcDefs[v.type]; if (def == null) { throw new Error('Unknown type: ' + v.type); @@ -86,7 +86,7 @@ export class ASTypeChecker { } @autobind - public infer(v: Block): Type | null { + public infer(v: Block): Type { if (v.type === null) return null; if (v.type === 'text') return 'string'; if (v.type === 'multiLineText') return 'string'; @@ -140,19 +140,19 @@ export class ASTypeChecker { } @autobind - public getVarsByType(type: Type | null): Variable[] { + public getVarsByType(type: Type): Variable[] { if (type == null) return this.variables; return this.variables.filter(x => (this.infer(x) === null) || (this.infer(x) === type)); } @autobind - public getEnvVarsByType(type: Type | null): string[] { + public getEnvVarsByType(type: Type): string[] { if (type == null) return Object.keys(envVarsDef); return Object.entries(envVarsDef).filter(([k, v]) => v === null || type === v).map(([k, v]) => k); } @autobind - public getPageVarsByType(type: Type | null): string[] { + public getPageVarsByType(type: Type): string[] { if (type == null) return this.pageVars.map(v => v.name); return this.pageVars.filter(v => type === v.type).map(v => v.name); } From 76f37671b4269fd48a8756d9529362177dc3dd6b Mon Sep 17 00:00:00 2001 From: syuilo Date: Wed, 1 May 2019 19:45:05 +0900 Subject: [PATCH 15/19] :art: --- .../page-editor/els/page-editor.el.number-input.vue | 6 +++--- .../components/page-editor/els/page-editor.el.switch.vue | 6 +++--- .../page-editor/els/page-editor.el.text-input.vue | 6 +++--- .../page-editor/els/page-editor.el.textarea-input.vue | 6 +++--- .../components/page-editor/page-editor.script-block.vue | 4 ++-- .../common/views/components/page-editor/page-editor.vue | 6 +++--- src/client/app/common/views/pages/page/page.vue | 4 ++-- src/misc/aiscript/index.ts | 7 ++++--- 8 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/client/app/common/views/components/page-editor/els/page-editor.el.number-input.vue b/src/client/app/common/views/components/page-editor/els/page-editor.el.number-input.vue index aff6cf6b6..923f4ea33 100644 --- a/src/client/app/common/views/components/page-editor/els/page-editor.el.number-input.vue +++ b/src/client/app/common/views/components/page-editor/els/page-editor.el.number-input.vue @@ -3,7 +3,7 @@
- {{ $t('blocks._numberInput.name') }} + {{ $t('blocks._numberInput.name') }} {{ $t('blocks._numberInput.text') }} {{ $t('blocks._numberInput.default') }}
@@ -12,7 +12,7 @@