nadesiko3 3.7.20 → 3.7.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/batch/command.txt +483 -445
  2. package/batch/jsplugin2text.nako3 +1 -1
  3. package/batch/pickup_command.nako3 +12 -0
  4. package/core/command/snako.mts +5 -1
  5. package/core/deno/snako.ts +5 -1
  6. package/core/package-lock.json +382 -21
  7. package/core/package.json +4 -4
  8. package/core/src/README.md +98 -0
  9. package/core/src/nako3.mts +178 -614
  10. package/core/src/nako_basic_plugins.mts +39 -0
  11. package/core/src/nako_core_version.mts +2 -2
  12. package/core/src/nako_csv.mts +0 -1
  13. package/core/src/nako_event.mts +49 -0
  14. package/core/src/nako_gen.mts +291 -202
  15. package/core/src/nako_indent_inline.mts +2 -2
  16. package/core/src/nako_lex_rules.mts +1 -1
  17. package/core/src/nako_parser3.mts +106 -165
  18. package/core/src/nako_parser_async.mts +97 -0
  19. package/core/src/nako_parser_base.mts +4 -55
  20. package/core/src/nako_parser_message.mts +105 -0
  21. package/core/src/nako_parser_operator.mts +93 -0
  22. package/core/src/nako_plugin_manager.mts +260 -0
  23. package/core/src/nako_require.mts +292 -0
  24. package/core/src/nako_runner.mts +191 -0
  25. package/core/src/nako_tokenizer.mts +221 -0
  26. package/core/src/plugin_csv.mts +1 -1
  27. package/core/src/plugin_system.mts +34 -3259
  28. package/core/src/plugin_system_array.mts +699 -0
  29. package/core/src/plugin_system_datetime.mts +368 -0
  30. package/core/src/plugin_system_debug.mts +403 -0
  31. package/core/src/plugin_system_dict.mts +85 -0
  32. package/core/src/plugin_system_json.mts +73 -0
  33. package/core/src/plugin_system_math.mts +383 -0
  34. package/core/src/plugin_system_regexp.mts +120 -0
  35. package/core/src/plugin_system_stdio.mts +86 -0
  36. package/core/src/plugin_system_string.mts +666 -0
  37. package/core/src/plugin_system_timer.mts +152 -0
  38. package/core/src/plugin_system_types.mts +151 -0
  39. package/core/src/plugin_system_url.mts +193 -0
  40. package/core/src/plugin_toml.mts +3 -3
  41. package/core/test/fixtures/README.md +39 -0
  42. package/core/test/fixtures/make_parser_ast_golden.mjs +31 -0
  43. package/core/test/fixtures/parser_ast_golden.json +8027 -0
  44. package/core/test/fixtures/parser_corpus.mjs +120 -0
  45. package/core/test/indent_test.mjs +6 -0
  46. package/core/test/nako_basic_plugins_test.mjs +44 -0
  47. package/core/test/nako_event_test.mjs +85 -0
  48. package/core/test/nako_gen_perf_test.mjs +178 -0
  49. package/core/test/nako_parser_async_test.mjs +112 -0
  50. package/core/test/nako_parser_test.mjs +160 -0
  51. package/core/test/nako_plugin_manager_test.mjs +185 -0
  52. package/core/test/nako_require_test.mjs +153 -0
  53. package/core/test/nako_runner_test.mjs +114 -0
  54. package/core/test/nako_tokenizer_test.mjs +115 -0
  55. package/core/test/plugin_system_debug_test.mjs +141 -0
  56. package/core/test/plugin_system_split_test.mjs +179 -0
  57. package/core/test/plugin_system_test.mjs +6 -0
  58. package/core/tsconfig.json +0 -1
  59. package/package.json +24 -34
  60. package/release/_hash.txt +40 -40
  61. package/release/_script-tags.txt +16 -16
  62. package/release/command.json +1 -1
  63. package/release/command.json.js +1 -1
  64. package/release/command_cnako3.json +1 -1
  65. package/release/command_list.json +1 -1
  66. package/release/edit_main.js +6 -6
  67. package/release/edit_main.js.map +3 -3
  68. package/release/editor.js +6 -6
  69. package/release/plugin_datetime.js +1 -1
  70. package/release/plugin_datetime.js.map +3 -3
  71. package/release/plugin_keigo.js.map +3 -3
  72. package/release/plugin_markup.js +47 -47
  73. package/release/plugin_markup.js.map +3 -3
  74. package/release/plugin_weykturtle3d.js +1 -1
  75. package/release/plugin_weykturtle3d.js.map +3 -3
  76. package/release/version.js +2 -2
  77. package/release/version_main.js +2 -2
  78. package/release/version_main.js.map +2 -2
  79. package/release/wnako3.js +187 -214
  80. package/release/wnako3.js.map +4 -4
  81. package/release/wnako3webworker.js +172 -199
  82. package/release/wnako3webworker.js.map +4 -4
  83. package/src/cnako3mod.mjs +8 -4
  84. package/src/cnako3mod.mts +8 -4
  85. package/src/nako_version.mjs +2 -2
  86. package/src/nako_version.mts +2 -2
  87. package/src/plugin_browser_ajax.mjs +4 -4
  88. package/src/plugin_browser_ajax.mts +4 -4
  89. package/src/plugin_browser_audio.mjs +10 -10
  90. package/src/plugin_browser_audio.mts +10 -10
  91. package/src/plugin_browser_camera.mjs +4 -4
  92. package/src/plugin_browser_camera.mts +4 -4
  93. package/src/plugin_browser_canvas.mjs +2 -2
  94. package/src/plugin_browser_canvas.mts +2 -2
  95. package/src/plugin_browser_crypto.mjs +3 -3
  96. package/src/plugin_browser_crypto.mts +3 -3
  97. package/src/plugin_browser_dom_event.mjs +1 -1
  98. package/src/plugin_browser_dom_event.mts +1 -1
  99. package/src/plugin_browser_geolocation.mjs +1 -1
  100. package/src/plugin_browser_geolocation.mts +1 -1
  101. package/src/plugin_browser_hotkey.mjs +1 -1
  102. package/src/plugin_browser_hotkey.mts +1 -1
  103. package/src/plugin_browser_html.mjs +1 -1
  104. package/src/plugin_browser_html.mts +1 -1
  105. package/src/plugin_browser_location.mjs +1 -1
  106. package/src/plugin_browser_location.mts +1 -1
  107. package/src/plugin_browser_speech.mjs +1 -1
  108. package/src/plugin_browser_speech.mts +1 -1
  109. package/src/plugin_browser_storage.mjs +2 -2
  110. package/src/plugin_browser_storage.mts +2 -2
  111. package/src/plugin_httpserver.mjs +186 -15
  112. package/src/plugin_httpserver.mts +178 -12
  113. package/src/plugin_keigo.mjs +2 -2
  114. package/src/plugin_keigo.mts +2 -2
  115. package/src/plugin_node.mjs +48 -49
  116. package/src/plugin_node.mts +53 -54
  117. package/src/plugin_weykturtle3d.mjs +56 -56
  118. package/src/plugin_weykturtle3d.mts +56 -56
  119. package/src/wnako3.mjs +1 -1
  120. package/src/wnako3.mts +1 -1
  121. package/src/wnako3_editor.mjs +5 -5
  122. package/src/wnako3_editor.mts +5 -5
  123. package/src/wnako3mod.mjs +5 -2
  124. package/src/wnako3mod.mts +5 -2
  125. package/test/common/wnako3mod_test.mjs +48 -0
  126. package/test/node/package_json_test.mjs +17 -0
  127. package/test/node/plugin_httpserver_test.mjs +239 -0
  128. package/tools/nako3server/index.nako3 +4 -2
  129. package/core/src/nako3.mjs +0 -1021
  130. package/core/src/nako_ast.mjs +0 -4
  131. package/core/src/nako_colors.mjs +0 -77
  132. package/core/src/nako_core_version.mjs +0 -8
  133. package/core/src/nako_csv.mjs +0 -193
  134. package/core/src/nako_errors.mjs +0 -166
  135. package/core/src/nako_from_dncl.mjs +0 -285
  136. package/core/src/nako_from_dncl2.mjs +0 -347
  137. package/core/src/nako_gen.mjs +0 -2500
  138. package/core/src/nako_global.mjs +0 -138
  139. package/core/src/nako_indent.mjs +0 -442
  140. package/core/src/nako_indent_chars.mjs +0 -29
  141. package/core/src/nako_indent_inline.mjs +0 -361
  142. package/core/src/nako_josi_list.mjs +0 -47
  143. package/core/src/nako_lex_rules.mjs +0 -319
  144. package/core/src/nako_lexer.mjs +0 -794
  145. package/core/src/nako_logger.mjs +0 -221
  146. package/core/src/nako_parser3.mjs +0 -3250
  147. package/core/src/nako_parser_base.mjs +0 -403
  148. package/core/src/nako_parser_const.mjs +0 -37
  149. package/core/src/nako_prepare.mjs +0 -329
  150. package/core/src/nako_reserved_words.mjs +0 -42
  151. package/core/src/nako_source_mapping.mjs +0 -207
  152. package/core/src/nako_test.mjs +0 -37
  153. package/core/src/nako_token.mjs +0 -1
  154. package/core/src/nako_tools.mjs +0 -53
  155. package/core/src/nako_types.mjs +0 -14
  156. package/core/src/plugin_api.mjs +0 -4
  157. package/core/src/plugin_csv.mjs +0 -97
  158. package/core/src/plugin_math.mjs +0 -352
  159. package/core/src/plugin_promise.mjs +0 -102
  160. package/core/src/plugin_system.mjs +0 -3810
  161. package/core/src/plugin_test.mjs +0 -52
  162. package/core/src/plugin_toml.mjs +0 -39
@@ -1,6 +1,6 @@
1
-
2
-
3
-
1
+
2
+
3
+
4
4
  // deno-lint-ignore-file no-explicit-any
5
5
  /**
6
6
  * nadesiko v3
@@ -11,57 +11,28 @@ import { Ast, AstBlocks } from './nako_ast.mjs'
11
11
  // parser / lexer
12
12
  import { NakoParser } from './nako_parser3.mjs'
13
13
  import { NakoLexer } from './nako_lexer.mjs'
14
- import { NakoPrepare } from './nako_prepare.mjs'
15
14
  import { NakoGen, generateJS, NakoGenOptions, NakoGenResult } from './nako_gen.mjs'
16
- import { convertInlineIndent, convertIndentSyntax } from './nako_indent_inline.mjs'
17
- import { convertDNCL } from './nako_from_dncl.mjs'
18
- import { convertDNCL2 } from './nako_from_dncl2.mjs'
19
- import { SourceMappingOfTokenization, SourceMappingOfIndentSyntax, OffsetToLineColumn, subtractSourceMapByPreCodeLength } from './nako_source_mapping.mjs'
20
- import { NakoLexerError, NakoImportError, NakoSyntaxError, InternalLexerError } from './nako_errors.mjs'
15
+ import { NakoSyntaxError } from './nako_errors.mjs'
21
16
  import { NakoLogger } from './nako_logger.mjs'
22
17
  import { NakoGlobal } from './nako_global.mjs'
18
+ // 取り込み文(require)の処理 / プラグイン管理 (#2360)
19
+ import { Dependencies, LoaderTool, listRequireStatements, NakoRequireHost, NakoRequireLoader, NakoRequireScanner } from './nako_require.mjs'
20
+ import { NakoPluginHost, NakoPluginManager } from './nako_plugin_manager.mjs'
21
+ // 字句解析 / 実行 / イベント / 基本プラグイン (#2360)
22
+ import { LexResult, NakoTokenizer } from './nako_tokenizer.mjs'
23
+ import { NakoRunner, NakoRunnerHost, newCompilerOptions } from './nako_runner.mjs'
24
+ import { NakoEventEmitter } from './nako_event.mjs'
25
+ import { registerBasicPlugins } from './nako_basic_plugins.mjs'
23
26
  // version info
24
27
  import coreVersion from './nako_core_version.mjs'
25
- // basic plugins
26
- import PluginSystem from './plugin_system.mjs'
27
- import PluginMath from './plugin_math.mjs'
28
- import PluginCSV from './plugin_csv.mjs'
29
- import PluginPromise from './plugin_promise.mjs'
30
- import PluginTOML from './plugin_toml.mjs'
31
- import PluginTest from './plugin_test.mjs'
32
-
33
- const cloneAsJSON = (x: any): any => JSON.parse(JSON.stringify(x))
34
- const PLUGIN_MIN_VERSION_INT = 600 // = minor * 100 + patch
35
28
 
36
29
  export interface NakoCompilerOption {
37
30
  useBasicPlugin: boolean;
38
31
  }
39
32
 
40
- /** インタプリタに「取り込み」文を追加するために用意するオブジェクト */
41
- export interface LoaderToolTask<T> {
42
- task: Promise<T>;
43
- }
44
- export interface LoaderTool {
45
- // type: 'nako3' | 'js' | 'invalid' | 'mjs'
46
- resolvePath: (name: string, token: Token, fromFile: string) => { type: string, filePath: string };
47
- readNako3: (filePath: string, token: Token) => LoaderToolTask<string>;
48
- readJs: (filePath: string, token: Token) => LoaderToolTask<any>;
49
- }
50
-
51
- interface DependenciesItem {
52
- tokens: Token[];
53
- alias: Set<string>;
54
- addPluginFile: () => void;
55
- funclist: any;
56
- moduleExport: any;
57
- }
58
- type Dependencies = { [key:string]:DependenciesItem }
59
-
60
- interface LexResult {
61
- commentTokens: Token[];
62
- tokens: Token[];
63
- requireTokens: Token[];
64
- }
33
+ // 分離したモジュールの型・関数は、外部から `nako3.mjs` 経由で参照されているため再エクスポートする (#2360)
34
+ export type { LoaderTool, LoaderToolTask, Dependencies, DependenciesItem } from './nako_require.mjs'
35
+ export { newCompilerOptions } from './nako_runner.mjs'
65
36
 
66
37
  type NakoVars = Map<string, any>
67
38
 
@@ -69,43 +40,33 @@ export interface NakoResetOption {
69
40
  needToClearPlugin: boolean
70
41
  }
71
42
 
72
- /** コンパイラ実行オプションを生成 */
73
- export function newCompilerOptions(initObj: Partial<CompilerOptions> = {}): CompilerOptions {
74
- if (typeof initObj !== 'object') { initObj = {} }
75
- initObj.testOnly = initObj.testOnly || false
76
- initObj.resetEnv = initObj.resetEnv || false
77
- initObj.resetAll = initObj.resetAll || false
78
- initObj.preCode = initObj.preCode || ''
79
- initObj.nakoGlobal = initObj.nakoGlobal || null
80
- return initObj as CompilerOptions
81
- }
82
-
83
43
  /** なでしこコンパイラ */
84
44
  export class NakoCompiler {
85
45
  private nakoFuncList: FuncList
86
46
  private funclist: FuncList
87
47
  private moduleExport: ExportMap
88
- private pluginFunclist: Record<string, FuncListItem>
89
- private pluginfiles: Record<string, any>
90
- private commandlist: Set<string>
91
- private prepare: NakoPrepare
92
48
  private parser: NakoParser
93
- private lexer: NakoLexer
94
- private dependencies: Dependencies
49
+ /** プラグイン管理 (#2360) */
50
+ private pluginManager: NakoPluginManager
51
+ /** 取り込み文の処理 (#2360) */
52
+ private requireLoader: NakoRequireLoader
53
+ /** 字句解析 (#2360) */
54
+ private tokenizer: NakoTokenizer
55
+ /** プログラムの実行 (#2360) */
56
+ private runner: NakoRunner
57
+ /** イベント管理 (#2360) */
58
+ protected events: NakoEventEmitter
95
59
  private usedFuncs: Set<string>
96
60
  private codeGenerateor: {[key: string]: any}
97
61
  protected logger: NakoLogger
98
- protected eventList: NakoEvent[]
99
62
  // global objects
100
63
  __varslist: NakoVars[]
101
64
  __locals: NakoVars
102
-
65
+
103
66
  __self: NakoCompiler
104
67
  __vars: NakoVars
105
68
  __v0: NakoVars
106
69
  __v1: NakoVars
107
- __globals: NakoGlobal[]
108
- __globalObj: NakoGlobal|null // 現在のNakoGlobalオブジェクト
109
70
  __module: Record<string, Record<string, FuncListItem>>
110
71
  numFailures: number // エラーレポートの数を記録
111
72
  public version: string
@@ -131,37 +92,60 @@ export class NakoCompiler {
131
92
  // バージョンを設定
132
93
  this.version = coreVersion.version
133
94
  this.coreVersion = coreVersion.version
134
- this.__globals = [] // 生成した NakoGlobal のインスタンスを保持
135
- this.__globalObj = null
136
- this.__module = {} // requireなどで取り込んだモジュールの一覧
137
- this.pluginFunclist = {} // プラグインで定義された関数
138
95
  this.funclist = this.newVaiables() // プラグインで定義された関数 + ユーザーが定義した関数
139
96
  this.moduleExport = this.newVaiables()
140
- this.pluginfiles = {} // 取り込んだファイル一覧
141
- this.commandlist = new Set() // プラグインで定義された定数・変数・関数の名前
142
97
  this.nakoFuncList = this.newVaiables() // __v1に配置するJavaScriptのコードで定義された関数
143
- this.eventList = [] // 実行前に環境を変更するためのイベント
144
98
  this.codeGenerateor = {} // コードジェネレータ
145
99
  this.debugOption = { useDebug: false, waitTime: 0 }
146
100
 
147
101
  this.logger = new NakoLogger()
148
102
  this.filename = 'main.nako3'
149
103
 
150
- /**
151
- * 取り込み文を置換するためのオブジェクト。
152
- * 正規化されたファイル名がキーになり、取り込み文の引数に指定された正規化されていないファイル名はaliasに入れられる。
153
- * JavaScriptファイルによるプラグインの場合、contentは空文字列。
154
- * funclistはシンタックスハイライトの高速化のために事前に取り出した、ファイルが定義する関数名のリスト。
155
- */
156
- this.dependencies = {}
104
+ // 実行前に環境を変更するためのイベント (#2360)
105
+ this.events = new NakoEventEmitter()
106
+
107
+ // プラグイン管理を生成する (#2360)
108
+ const pluginHost: NakoPluginHost = {
109
+ getFuncList: () => this.funclist, // reset() で差し替わるため、その都度参照する
110
+ getSysVars: () => this.__varslist[0],
111
+ getLogger: () => this.logger
112
+ }
113
+ this.pluginManager = new NakoPluginManager(pluginHost)
114
+ // requireなどで取り込んだモジュールの一覧(プラグイン管理と同じオブジェクトを共有する)
115
+ this.__module = this.pluginManager.modules
116
+
117
+ // 取り込み文の処理を生成する (#2360)
118
+ const requireHost: NakoRequireHost = {
119
+ rawtokenize: (code, line, filename, preCode) => this.rawtokenize(code, line, filename, preCode),
120
+ addPluginFromFile: (fpath, po, persistent) => this.addPluginFromFile(fpath, po, persistent),
121
+ getLogger: () => this.logger,
122
+ // 名前空間(modList)を汚さないように、取り込み文の検出には別のコンパイラを使う
123
+ createScanner: (): NakoRequireScanner => new NakoCompiler({ useBasicPlugin: true }),
124
+ countFailure: () => { this.numFailures++ }
125
+ }
126
+ this.requireLoader = new NakoRequireLoader(requireHost)
127
+
128
+ // 実行部を生成する (#2360)
129
+ const runnerHost: NakoRunnerHost = {
130
+ compileFromCode: (code, filename, opts) => this.compileFromCode(code, filename, opts),
131
+ createNakoGlobal: (gen: NakoGen, guid: number) => new NakoGlobal(this, gen, guid),
132
+ getLogger: () => this.logger,
133
+ fireEvent: (eventName, event) => { this.events.fire(eventName, event) }
134
+ }
135
+ this.runner = new NakoRunner(runnerHost)
136
+
157
137
  this.usedFuncs = new Set()
158
138
  this.numFailures = 0
159
139
 
160
140
  if (options.useBasicPlugin) { this.addBasicPlugins() }
161
141
  // 必要なオブジェクトを覚えておく
162
- this.prepare = NakoPrepare.getInstance()
163
142
  this.parser = new NakoParser(this.logger)
164
- this.lexer = new NakoLexer(this.logger)
143
+ // 字句解析を生成する (#2360)
144
+ this.tokenizer = new NakoTokenizer({
145
+ getLogger: () => this.logger,
146
+ replaceRequireStatements: (tokens, includeGuard) => this.replaceRequireStatements(tokens, includeGuard),
147
+ removeRequireStatements: (tokens) => this.removeRequireStatements(tokens)
148
+ })
165
149
  // 関数一覧を設定
166
150
  this.lexer.setFuncList(this.funclist)
167
151
  this.lexer.setModuleExport(this.moduleExport)
@@ -171,9 +155,37 @@ export class NakoCompiler {
171
155
  this.josiList = JSON.parse(JSON.stringify(this.lexer.josiList))
172
156
  }
173
157
 
158
+ /** 字句解析器(実体は NakoTokenizer が所有する) */
159
+ private get lexer (): NakoLexer {
160
+ return this.tokenizer.lexer
161
+ }
162
+
163
+ /** 実行前に環境を変更するためのイベント一覧 */
164
+ protected get eventList (): NakoEvent[] {
165
+ return this.events.getEventList()
166
+ }
167
+
168
+ /** 生成した NakoGlobal のインスタンスを保持 */
169
+ get __globals (): NakoGlobal[] {
170
+ return this.runner.globals
171
+ }
172
+
173
+ set __globals (values: NakoGlobal[]) {
174
+ this.runner.globals = values
175
+ }
176
+
177
+ /** 現在のNakoGlobalオブジェクト */
178
+ get __globalObj (): NakoGlobal|null {
179
+ return this.runner.currentGlobal
180
+ }
181
+
182
+ set __globalObj (value: NakoGlobal|null) {
183
+ this.runner.currentGlobal = value
184
+ }
185
+
174
186
  /** モジュール(名前空間)の一覧を取得する */
175
187
  getModList(): string[] {
176
- return this.lexer.modList
188
+ return this.tokenizer.getModList()
177
189
  }
178
190
 
179
191
  getLogger(): NakoLogger {
@@ -189,19 +201,26 @@ export class NakoCompiler {
189
201
  }
190
202
 
191
203
  getPluginfiles(): Record<string, any> {
192
- return this.pluginfiles
204
+ return this.pluginManager.pluginfiles
205
+ }
206
+
207
+ /**
208
+ * 取り込み文を置換するためのオブジェクト。
209
+ * 正規化されたファイル名がキーになり、取り込み文の引数に指定された正規化されていないファイル名はaliasに入れられる。
210
+ * JavaScriptファイルによるプラグインの場合、contentは空文字列。
211
+ * funclistはシンタックスハイライトの高速化のために事前に取り出した、ファイルが定義する関数名のリスト。
212
+ * (エディタのシンタックスハイライトから参照される)
213
+ */
214
+ get dependencies (): Dependencies {
215
+ return this.requireLoader.dependencies
193
216
  }
194
217
 
195
218
  /**
196
219
  * 基本的なプラグインを追加する
220
+ * (プラグインの一覧は nako_basic_plugins.mts にある)
197
221
  */
198
222
  addBasicPlugins() {
199
- this.addPlugin(PluginSystem)
200
- this.addPlugin(PluginMath)
201
- this.addPlugin(PluginPromise)
202
- this.addPlugin(PluginTest)
203
- this.addPlugin(PluginCSV)
204
- this.addPlugin(PluginTOML)
223
+ registerBasicPlugins(this)
205
224
  }
206
225
 
207
226
  /**
@@ -214,175 +233,31 @@ export class NakoCompiler {
214
233
 
215
234
  /**
216
235
  * ファイル内のrequire文の位置を列挙する。出力の配列はstartでソートされている。
236
+ * (実体は nako_require.mts の listRequireStatements)
217
237
  * @param {Token[]} tokens rawtokenizeの出力
218
238
  */
219
- static listRequireStatements(tokens: Token[]): Token[] {
220
- const requireStatements: Token[] = []
221
- for (let i = 0; i + 2 < tokens.length; i++) {
222
- // not (string|string_ex) '取り込み'
223
- if (!(tokens[i].type === 'not' &&
224
- (tokens[i + 1].type === 'string' || tokens[i + 1].type === 'string_ex') &&
225
- tokens[i + 2].value === '取込')) {
226
- continue
227
- }
228
- // 取り込むライブラリ
229
- let filename = String(tokens[i + 1].value) + ''
230
- // 全角コロン「:」を半角コロン「:」に正規化する(「貯蔵庫:」「拡張プラグイン:」の記法に対応 #2282)
231
- filename = filename.replace(/^(貯蔵庫|拡張プラグイン):/, '$1:')
232
- // 『取り込む』文で「拡張プラグイン:」機構を追加する #139
233
- // (ex) !『貯蔵庫:ojyo-sama.nako3』を取り込む → https://n3s.nadesi.com/plain/ojyo-sama.nako3
234
- if (filename.startsWith('貯蔵庫:') || filename.startsWith('貯蔵庫:')) {
235
- filename = `https://n3s.nadesi.com/plain/${filename.substring(4)}`
236
- }
237
- // (ex) !『拡張プラグイン:music.js@1.0.2』を取り込む → https://cdn.jsdelivr.net/npm/nadesiko3-music@1.0.2/nadesiko3-music.js
238
- if (filename.startsWith('拡張プラグイン:') || filename.startsWith('拡張プラグイン:')) {
239
- const name = filename.substring('拡張プラグイン:'.length)
240
- const m = name.match(/^([a-zA-Z0-9_-]+)\.(js|mjs|nako3)(@[0-9.]+)?$/)
241
- if (m) {
242
- let basename = m[1]
243
- const ext = m[2]
244
- const version = m[3] || '@latest'
245
- if (ext === 'js' || ext === 'mjs') {
246
- // JSプラグイン
247
- if (!basename.startsWith('nadesiko3-')) {
248
- basename = `nadesiko3-${basename}`
249
- }
250
- filename = `https://cdn.jsdelivr.net/npm/${basename}${version}/${basename}.${ext}`
251
- } else {
252
- // なでしこ3プラグイン
253
- filename = `https://n3s.nadesi.com/plain/${basename}.${ext}`
254
- }
255
- } else {
256
- throw new NakoImportError('『取込』の指定エラー。『拡張プラグイン:(ファイル名).(js|nako3)(@ver)』の書式で指定してください。', tokens[i].file, tokens[i].line)
257
- }
258
- }
259
- // push
260
- requireStatements.push({
261
- ...tokens[i],
262
- start: i,
263
- end: i + 3,
264
- value: filename,
265
- firstToken: tokens[i],
266
- lastToken: tokens[i + 2]
267
- })
268
- i += 2
269
- }
270
- return requireStatements
239
+ static listRequireStatements (tokens: Token[]): Token[] {
240
+ return listRequireStatements(tokens)
271
241
  }
272
242
 
273
243
  /**
274
244
  * プログラムが依存するファイルを再帰的に取得する。
275
- * - 依存するファイルがJavaScriptファイルの場合、そのファイルを実行して評価結果をthis.addPluginFileに渡す。
276
- * - 依存するファイルがなでしこ言語の場合、ファイルの中身を取得して変数に保存し、再帰する。
245
+ * (実体は nako_require.mts の NakoRequireLoader.load)
277
246
  *
278
247
  * @param {string} code
279
248
  * @param {string} filename
280
249
  * @param {string} preCode
281
250
  * @param {LoaderTool} tools 実行環境 (ブラウザ or Node.js) によって外部ファイルの取得・実行方法は異なるため、引数でそれらを行う関数を受け取る。
282
- * - resolvePath は指定した名前をもつファイルを検索し、正規化されたファイル名を返す関数。返されたファイル名はreadNako3かreadJsの引数になる。
283
- * - readNako3は指定されたファイルの中身を返す関数。
284
- * - readJsは指定したファイルをJavaScriptのプログラムとして実行し、`export default` でエクスポートされた値を返す関数。
285
251
  * @returns {Promise<unknown> | void}
286
252
  * @protected
287
253
  */
288
- _loadDependencies(code: string, filename: string, preCode: string, tools: LoaderTool) {
289
- const dependencies: Dependencies = {}
290
- const compiler = new NakoCompiler({ useBasicPlugin: true })
291
- /**
292
- * @param {any} item
293
- * @param {any} tasks
294
- */
295
- const loadJS = (item: any, tasks: any) => {
296
- // jsならプラグインとして読み込む。(ESMでは必ず動的に読む)
297
- const obj = tools.readJs(item.filePath, item.firstToken)
298
- tasks.push(obj.task.then((res: any) => {
299
- const pluginFuncs = res()
300
- this.addPluginFromFile(item.filePath, pluginFuncs)
301
- dependencies[item.filePath].funclist = pluginFuncs
302
- dependencies[item.filePath].moduleExport = {}
303
- dependencies[item.filePath].addPluginFile = () => { this.addPluginFromFile(item.filePath, pluginFuncs) }
304
- }))
305
- }
306
- const loadNako3 = (item: any, tasks: any) => {
307
- // nako3ならファイルを読んでdependenciesに保存する。
308
- const content = tools.readNako3(item.filePath, item.firstToken)
309
- const registerFile = (code: string) => {
310
- // シンタックスハイライトの高速化のために、事前にファイルが定義する関数名のリストを取り出しておく。
311
- // preDefineFuncはトークン列に変更を加えるため、事前にクローンしておく。
312
- // 「プラグイン名設定」を行う (#956)
313
- const modName = NakoLexer.filenameToModName(item.filePath)
314
- code = `『${modName}』に名前空間設定;『${modName}』にプラグイン名設定;` + code + ';名前空間ポップ;'
315
- const tokens = this.rawtokenize(code, 0, item.filePath)
316
- dependencies[item.filePath].tokens = tokens
317
- const funclist = new Map()
318
- const moduleexport = new Map()
319
- NakoLexer.preDefineFunc(cloneAsJSON(tokens), this.logger, funclist, moduleexport)
320
- dependencies[item.filePath].funclist = funclist
321
- dependencies[item.filePath].moduleExport = moduleexport
322
- // 再帰
323
- return loadRec(code, item.filePath, '')
324
- }
325
- // 取り込み構文における問題を減らすため、必ず非同期でプログラムを読み込む仕様とした #1219
326
- tasks.push(content.task.then((res) => registerFile(res)))
327
- }
328
- const loadRec = (code: string, filename: string, preCode: string): Promise<unknown>|void => {
329
- const tasks: Promise<unknown>[] = []
330
- // 取り込みが必要な情報一覧を調べる(トークン分割して、取り込みタグを得る)
331
- const tags = NakoCompiler.listRequireStatements(compiler.rawtokenize(code, 0, filename, preCode))
332
- // パスを解決する
333
- const tagsResolvePath = tags.map((v) => ({ ...v, ...tools.resolvePath(v.value, v.firstToken as Token, filename) }))
334
- // 取り込み開始
335
- for (const item of tagsResolvePath) {
336
- // 2回目以降の読み込み
337
- // eslint-disable-next-line no-prototype-builtins
338
- if (dependencies.hasOwnProperty(item.filePath)) {
339
- dependencies[item.filePath].alias.add(item.value)
340
- continue
341
- }
342
-
343
- // 初回の読み込み
344
-
345
- dependencies[item.filePath] = { tokens: [], alias: new Set([item.value]), addPluginFile: ():void => {}, funclist: {}, moduleExport: {} }
346
- if (item.type === 'js' || item.type === 'mjs') {
347
- loadJS(item, tasks)
348
- } else if (item.type === 'nako3') {
349
- loadNako3(item, tasks)
350
- } else {
351
- throw new NakoImportError(`ファイル『${String(item.value)}』を読み込めません。ファイルが存在しないか未対応の拡張子です。`,
352
- (item.firstToken as Token).file, (item.firstToken as Token).line)
353
- }
354
- }
355
- if (tasks.length > 0) {
356
- return Promise.all(tasks)
357
- }
358
- return undefined
359
- }
360
-
361
- try {
362
- const result = loadRec(code, filename, preCode)
363
-
364
- // 非同期な場合のエラーハンドリング
365
- if (result !== undefined) {
366
- result.catch((err) => {
367
- // 読み込みに失敗したら処理を中断する
368
- this.logger.error(err.msg)
369
- this.numFailures++
370
- })
371
- }
372
-
373
- // すべてが終わってからthis.dependenciesに代入する。そうしないと、「実行」ボタンを連打した場合など、
374
- // loadDependencies() が並列実行されるときに正しく動作しない。
375
- this.dependencies = dependencies
376
- return result
377
- } catch (err) {
378
- // 同期処理では素直に例外を投げる
379
- this.logger.error(String(err))
380
- throw err
381
- }
254
+ _loadDependencies (code: string, filename: string, preCode: string, tools: LoaderTool): Promise<unknown>|void {
255
+ return this.requireLoader.load(code, filename, preCode, tools)
382
256
  }
383
257
 
384
258
  /**
385
259
  * コードを単語に分割する
260
+ * (実体は nako_tokenizer.mts の NakoTokenizer.rawtokenize)
386
261
  * @param code なでしこのプログラム
387
262
  * @param line なでしこのプログラムの行番号
388
263
  * @param filename
@@ -390,79 +265,19 @@ export class NakoCompiler {
390
265
  * @returns トークンのリスト
391
266
  */
392
267
  rawtokenize(code: string, line: number, filename: string, preCode = ''): Token[] {
393
- if (!code.startsWith(preCode)) {
394
- throw new Error('codeの先頭にはpreCodeを含める必要があります。')
395
- }
396
- // 名前空間のモジュールリストに自身を追加
397
- const modName = NakoLexer.filenameToModName(filename)
398
- const modList = this.getModList()
399
- if (modList.indexOf(modName) < 0) { modList.unshift(modName) }
400
- // 全角半角の統一処理
401
- const preprocessed = this.prepare.convert(code)
402
- const tokenizationSourceMapping = new SourceMappingOfTokenization(code.length, preprocessed)
403
- const indentationSyntaxSourceMapping = new SourceMappingOfIndentSyntax(code, [], [])
404
- const offsetToLineColumn = new OffsetToLineColumn(code)
405
- // トークン分割
406
- let tokens: Token[]
407
- try {
408
- tokens = this.lexer.tokenize(preprocessed.map((v) => v.text).join(''), line, filename)
409
- } catch (err) {
410
- if (!(err instanceof InternalLexerError)) {
411
- throw err
412
- }
413
- // エラー位置をソースコード上の位置に変換して返す
414
- const dest = indentationSyntaxSourceMapping.map(tokenizationSourceMapping.map(err.preprocessedCodeStartOffset), tokenizationSourceMapping.map(err.preprocessedCodeEndOffset))
415
- const line: number|undefined = dest.startOffset === null ? err.line : offsetToLineColumn.map(dest.startOffset, false).line
416
- const map = subtractSourceMapByPreCodeLength({ ...dest, line }, preCode)
417
- throw new NakoLexerError(err.msg, map.startOffset, map.endOffset, map.line, filename)
418
- }
419
- // DNCL ver2 (core #41)
420
- tokens = convertDNCL2(tokens)
421
- // DNCL ver1 (#1140)
422
- tokens = convertDNCL(tokens)
423
- // インデント構文を変換 #596
424
- tokens = convertIndentSyntax(tokens)
425
- // インラインインデントを変換 #1215
426
- tokens = convertInlineIndent(tokens)
427
-
428
- // ソースコード上の位置に変換
429
- tokens = tokens.map((token) => {
430
- const dest = indentationSyntaxSourceMapping.map(
431
- tokenizationSourceMapping.map(token.preprocessedCodeOffset || 0),
432
- tokenizationSourceMapping.map((token.preprocessedCodeOffset || 0) + (token.preprocessedCodeLength || 0))
433
- )
434
- let line = token.line
435
- let column = 0
436
- if (token.type === 'eol' && dest.endOffset !== null) {
437
- // eolはnako_genで `line = ${eolToken.line};` に変換されるため、
438
- // 行末のeolのlineは次の行の行数を表す必要がある。
439
- const out = offsetToLineColumn.map(dest.endOffset, false)
440
- line = out.line
441
- column = out.column
442
- } else if (dest.startOffset !== null) {
443
- const out = offsetToLineColumn.map(dest.startOffset, false)
444
- line = out.line
445
- column = out.column
446
- }
447
- return {
448
- ...token,
449
- ...subtractSourceMapByPreCodeLength({ line, column, startOffset: dest.startOffset, endOffset: dest.endOffset }, preCode),
450
- rawJosi: token.josi
451
- }
452
- })
453
- return tokens
268
+ return this.tokenizer.rawtokenize(code, line, filename, preCode)
454
269
  }
455
270
 
456
271
  /**
457
272
  * 単語の属性を構文解析に先立ち補正する
273
+ * (実体は nako_tokenizer.mts の NakoTokenizer.converttoken)
458
274
  * @param {Token[]} tokens トークンのリスト
459
275
  * @param {boolean} isFirst 最初の呼び出しかどうか
460
276
  * @param {string} filename
461
277
  * @returns コード (なでしこ)
462
278
  */
463
279
  converttoken(tokens: Token[], isFirst: boolean, filename: string): Token[] {
464
- const tok = this.lexer.replaceTokens(tokens, isFirst, filename)
465
- return tok
280
+ return this.tokenizer.converttoken(tokens, isFirst, filename)
466
281
  }
467
282
 
468
283
  /**
@@ -477,7 +292,7 @@ export class NakoCompiler {
477
292
  // そのため、例外的にオプションを指定すると、プラグインのクリアイベントを呼ばない
478
293
  try {
479
294
  this.clearPlugins()
480
- } catch (_) {
295
+ } catch {
481
296
  // pass
482
297
  }
483
298
  }
@@ -494,14 +309,7 @@ export class NakoCompiler {
494
309
  this.__locals = this.newVaiables()
495
310
 
496
311
  // プラグイン命令以外を削除する。
497
- this.funclist = new Map()
498
- for (const name of this.__v0.keys()) {
499
- const original = this.pluginFunclist[name] // record
500
- if (!original) {
501
- continue
502
- }
503
- this.funclist.set(name, JSON.parse(JSON.stringify(original)))
504
- }
312
+ this.funclist = this.pluginManager.createFuncListFromPlugins(this.__v0)
505
313
 
506
314
  this.lexer.setFuncList(this.funclist)
507
315
 
@@ -513,6 +321,7 @@ export class NakoCompiler {
513
321
 
514
322
  /**
515
323
  * typeがcodeのトークンを単語に分割するための処理
324
+ * (実体は nako_tokenizer.mts の NakoTokenizer.lexCodeToken)
516
325
  * @param {string} code
517
326
  * @param {number} line
518
327
  * @param {string} filename
@@ -521,131 +330,37 @@ export class NakoCompiler {
521
330
  * @private
522
331
  */
523
332
  lexCodeToken(code: string, line: number, filename: string, startOffset: number|null): {commentTokens: Token[], tokens: Token[]} {
524
- // 単語に分割
525
- let tokens = this.rawtokenize(code, line, filename, '')
526
-
527
- // 文字列内位置からファイル内位置へ変換
528
- if (startOffset === null) {
529
- for (const token of tokens) {
530
- token.startOffset = undefined
531
- token.endOffset = undefined
532
- }
533
- } else {
534
- for (const token of tokens) {
535
- if (token.startOffset !== undefined) {
536
- token.startOffset += startOffset
537
- }
538
- if (token.endOffset !== undefined) {
539
- token.endOffset += startOffset
540
- }
541
- }
542
- }
543
-
544
- // convertTokenで消されるコメントのトークンを残す
545
- const commentTokens = tokens.filter((t) => t.type === 'line_comment' || t.type === 'range_comment')
546
- .map((v) => ({ ...v })) // clone
547
-
548
- tokens = this.converttoken(tokens, false, filename)
549
-
550
- return { tokens, commentTokens }
333
+ return this.tokenizer.lexCodeToken(code, line, filename, startOffset)
551
334
  }
552
335
 
553
336
  /**
554
337
  * 再帰的にrequire文を置換する。
555
338
  * .jsであれば削除し、.nako3であればそのファイルのトークン列で置換する。
556
- * @param {TokenWithSourceMap[]} tokens
339
+ * (実体は nako_require.mts の NakoRequireLoader.replaceRequireStatements)
340
+ * @param {Token[]} tokens
557
341
  * @param {Set<string>} [includeGuard]
558
342
  * @returns {Token[]} 削除された取り込み文のトークン
559
343
  */
560
- replaceRequireStatements(tokens: Token[], includeGuard:Set<string> = new Set()): Token[] {
561
- /** @type {TokenWithSourceMap[]} */
562
- const deletedTokens = []
563
- for (const r of NakoCompiler.listRequireStatements(tokens).reverse()) {
564
- // C言語のinclude guardと同じ仕組みで無限ループを防ぐ。
565
- if (includeGuard.has(r.value)) {
566
- deletedTokens.push(...tokens.splice((r.start || 0), (r.end || 0) - (r.start || 0)))
567
- continue
568
- }
569
- const filePath = Object.keys(this.dependencies).find((key) => this.dependencies[key].alias.has(r.value))
570
- if (filePath === undefined) {
571
- if (!r.firstToken) { throw new Error(`ファイル『${String(r.value)}』が読み込まれていません。`) }
572
- throw new NakoLexerError(`ファイル『${String(r.value)}』が読み込まれていません。`,
573
- (r.firstToken).startOffset || 0,
574
- (r.firstToken).endOffset || 0,
575
- (r.firstToken).line, (r.firstToken).file)
576
- }
577
- this.dependencies[filePath].addPluginFile()
578
- const children = cloneAsJSON(this.dependencies[filePath].tokens)
579
- includeGuard.add(r.value)
580
- deletedTokens.push(...this.replaceRequireStatements(children, includeGuard))
581
- deletedTokens.push(...tokens.splice(r.start || 0, (r.end || 0) - (r.start || 0), ...children))
582
- }
583
- return deletedTokens
344
+ replaceRequireStatements (tokens: Token[], includeGuard: Set<string> = new Set()): Token[] {
345
+ return this.requireLoader.replaceRequireStatements(tokens, includeGuard)
584
346
  }
585
347
 
586
348
  /**
587
349
  * replaceRequireStatementsのシンタックスハイライト用の実装。
588
- * @param {TokenWithSourceMap[]} tokens
589
- * @returns {TokenWithSourceMap[]} 削除された取り込み文のトークン
350
+ * (実体は nako_require.mts の NakoRequireLoader.removeRequireStatements)
351
+ * @param {Token[]} tokens
352
+ * @returns {Token[]} 削除された取り込み文のトークン
590
353
  */
591
- removeRequireStatements(tokens: Token[]): Token[] {
592
- /** @type {TokenWithSourceMap[]} */
593
- const deletedTokens = []
594
- for (const r of NakoCompiler.listRequireStatements(tokens).reverse()) {
595
- // プラグイン命令のシンタックスハイライトのために、addPluginFileを呼んで関数のリストをthis.dependencies[filePath].funclistに保存させる。
596
- const filePath = Object.keys(this.dependencies).find((key) => this.dependencies[key].alias.has(r.value))
597
- if (filePath !== undefined) {
598
- this.dependencies[filePath].addPluginFile()
599
- }
600
-
601
- // 全ての取り込み文を削除する。そうしないとトークン化に時間がかかりすぎる。
602
- deletedTokens.push(...tokens.splice(r.start || 0, (r.end || 0) - (r.start || 0)))
603
- }
604
- return deletedTokens
354
+ removeRequireStatements (tokens: Token[]): Token[] {
355
+ return this.requireLoader.removeRequireStatements(tokens)
605
356
  }
606
357
 
607
- /** 字句解析を行う */
358
+ /**
359
+ * 字句解析を行う
360
+ * (実体は nako_tokenizer.mts の NakoTokenizer.lex)
361
+ */
608
362
  lex(code: string, filename = 'main.nako3', preCode = '', syntaxHighlighting = false): LexResult {
609
- // 単語に分割
610
- let tokens = this.rawtokenize(code, 0, filename, preCode)
611
-
612
- // require文を再帰的に置換する
613
- const requireStatementTokens = syntaxHighlighting ? this.removeRequireStatements(tokens) : this.replaceRequireStatements(tokens, undefined)
614
- for (const t of requireStatementTokens) {
615
- if (t.type === 'word' || t.type === 'not') {
616
- t.type = 'require'
617
- }
618
- }
619
- if (requireStatementTokens.length >= 3) {
620
- // modList を更新
621
- for (let i = 0; i < requireStatementTokens.length; i += 3) {
622
- let modName = requireStatementTokens[i + 1].value
623
- modName = NakoLexer.filenameToModName(modName)
624
- if (this.lexer.modList.indexOf(modName) < 0) {
625
- this.lexer.modList.push(modName)
626
- }
627
- }
628
- }
629
-
630
- // convertTokenで消されるコメントのトークンを残す
631
- const commentTokens: Token[] = tokens.filter((t) => t.type === 'line_comment' || t.type === 'range_comment')
632
- .map((v) => ({ ...v })) // clone
633
-
634
- tokens = this.converttoken(tokens, true, filename)
635
-
636
- // 'string_ex'トークンから変換された'code'トークンを字句解析する
637
- for (let i = 0; i < tokens.length; i++) {
638
- if (tokens[i] && tokens[i].type === 'code') {
639
- const children = this.lexCodeToken(tokens[i].value, tokens[i].line, filename, tokens[i].startOffset || 0)
640
- commentTokens.push(...children.commentTokens)
641
- tokens.splice(i, 1, ...children.tokens)
642
- i--
643
- }
644
- }
645
-
646
- this.logger.trace('--- lex ---\n' + JSON.stringify(tokens, null, 2))
647
-
648
- return { commentTokens, tokens, requireTokens: requireStatementTokens }
363
+ return this.tokenizer.lex(code, filename, preCode, syntaxHighlighting)
649
364
  }
650
365
 
651
366
  /**
@@ -698,7 +413,7 @@ export class NakoCompiler {
698
413
 
699
414
  deleteUnNakoFuncs(): Set<string> {
700
415
  for (const func of this.usedFuncs) {
701
- if (!this.commandlist.has(func)) {
416
+ if (!this.pluginManager.hasCommand(func)) {
702
417
  this.usedFuncs.delete(func)
703
418
  }
704
419
  }
@@ -728,16 +443,16 @@ export class NakoCompiler {
728
443
  if (options.resetEnv) { this.reset() }
729
444
  if (options.resetAll) { this.clearPlugins() }
730
445
  // onBeforeParse
731
- this.eventList.filter(o => o.eventName === 'beforeParse').map(e => e.callback(code))
446
+ this.events.fire('beforeParse', code)
732
447
  // parse
733
448
  const ast = this.parse(code, filename, options.preCode)
734
449
  // onBeforeGenerate
735
- this.eventList.filter(o => o.eventName === 'beforeGenerate').map(e => e.callback(ast))
450
+ this.events.fire('beforeGenerate', ast)
736
451
  // generate
737
452
  const genOptions = new NakoGenOptions(options.testOnly)
738
453
  const outCode = this.generateCode(ast, genOptions)
739
454
  // onAfterGenerate
740
- this.eventList.filter(o => o.eventName === 'afterGenerate').map(e => e.callback(outCode))
455
+ this.events.fire('afterGenerate', outCode)
741
456
  return outCode
742
457
  } catch (e: any) {
743
458
  this.logger.error(e)
@@ -782,55 +497,32 @@ export class NakoCompiler {
782
497
  * @param [preCode]
783
498
  * @deprecated 代わりにrunAsyncメソッドを使ってください。(core #52)
784
499
  */
785
-
500
+
786
501
  async _run(code: string, fname: string, isReset: boolean, isTest: boolean, preCode = ''): Promise<NakoGlobal> {
787
- const opts: CompilerOptions = newCompilerOptions({
788
- resetEnv: isReset,
789
- resetAll: isReset,
790
- testOnly: isTest,
791
- preCode
792
- })
793
- return this._runEx(code, fname, opts)
502
+ return this.runner.run(code, fname, isReset, isTest, preCode)
794
503
  }
795
504
 
796
- /** 各プラグインをリセットする */
505
+ /**
506
+ * 各プラグインをリセットする
507
+ * (実体は nako_runner.mts の NakoRunner.clearPlugins)
508
+ */
797
509
  clearPlugins() {
798
- // 他に実行している「なでしこ」があればクリアする
799
- this.__globals.forEach((sys: NakoGlobal) => {
800
- if (!sys) { return }
801
- // core #56
802
- sys.__setSysVar('__forceClose', true)
803
- sys.reset()
804
- })
805
- this.__globals = [] // clear
510
+ this.runner.clearPlugins()
806
511
  }
807
512
 
808
513
  /**
809
514
  * 環境を指定してJavaScriptのコードを実行する
515
+ * (実体は nako_runner.mts の NakoRunner.evalJS)
810
516
  * @param code JavaScriptのコード
811
517
  * @param nakoGlobal 実行環境
812
518
  */
813
519
  private evalJS(code: string, nakoGlobal: NakoGlobal): void {
814
- this.__globalObj = nakoGlobal // 現在のnakoGlobalを記録
815
- this.__globalObj.lastJSCode = code
816
- // 実行前に環境を初期化するイベントを実行(beforeRun)
817
- this.eventList.filter(o => o.eventName === 'beforeRun').map(e => e.callback(nakoGlobal))
818
- try {
819
-
820
- const f = new Function(nakoGlobal.lastJSCode)
821
- f.apply(nakoGlobal)
822
- } catch (err: any) {
823
- // なでしこコードのエラーは抑止してログにのみ記録
824
- nakoGlobal.numFailures++
825
- this.getLogger().error(err)
826
- throw err
827
- }
828
- // 実行後に終了イベントを実行(finish)
829
- this.eventList.filter(o => o.eventName === 'finish').map(e => e.callback(nakoGlobal))
520
+ this.runner.evalJS(code, nakoGlobal)
830
521
  }
831
522
 
832
523
  /**
833
524
  * (非推奨) 同期的になでしこのプログラムcodeを実行する
525
+ * (実体は nako_runner.mts の NakoRunner.runSync)
834
526
  * @param code なでしこのプログラム
835
527
  * @param filename ファイル名
836
528
  * @param options オプション
@@ -838,50 +530,24 @@ export class NakoCompiler {
838
530
  * @deprecated 代わりにrunAsyncメソッドを使ってください。(core #52)
839
531
  */
840
532
  public runSync(code: string, filename: string, options: CompilerOptions|undefined = undefined): NakoGlobal {
841
- // コンパイル
842
- options = newCompilerOptions(options)
843
- const out = this.compileFromCode(code, filename, options)
844
- // 実行前に環境を生成
845
- const nakoGlobal = this.getNakoGlobal(options, out.gen, filename)
846
- // 実行
847
- this.evalJS(out.runtimeEnv, nakoGlobal)
848
- return nakoGlobal
533
+ return this.runner.runSync(code, filename, options)
849
534
  }
850
535
 
851
536
  /**
852
537
  * 非同期になでしこのプログラムcodeを実行する
538
+ * (実体は nako_runner.mts の NakoRunner.runAsync)
853
539
  * @param code なでしこのプログラム
854
540
  * @param filename ファイル名
855
541
  * @param options オプション
856
542
  * @returns 実行に利用したグローバルオブジェクト
857
543
  */
858
-
544
+
859
545
  public async runAsync(code: string, filename: string, options: CompilerOptions|undefined = undefined): Promise<NakoGlobal> {
860
- // コンパイル
861
- options = newCompilerOptions(options)
862
- const compiledCode = this.compileFromCode(code, filename, options)
863
- // 実行前に環境を生成
864
- const nakoGlobal = this.getNakoGlobal(options, compiledCode.gen, filename)
865
- // 実行
866
- this.evalJS(compiledCode.runtimeEnv, nakoGlobal)
867
- return nakoGlobal
546
+ return this.runner.runAsync(code, filename, options)
868
547
  }
869
548
 
870
549
  private getNakoGlobal(options: CompilerOptions, gen: NakoGen, filename: string): NakoGlobal {
871
- // オプションを参照
872
- let g: NakoGlobal|null = options.nakoGlobal
873
- if (!g) {
874
- // 空ならば前回の値を参照(リセットするなら新規で作成する)
875
- if (this.__globals.length > 0 && options.resetAll === false && options.resetEnv === false) {
876
- g = this.__globals[this.__globals.length - 1]
877
- } else {
878
- g = new NakoGlobal(this, gen, (this.__globals.length + 1))
879
- }
880
- // 名前空間を設定
881
- g.__varslist[0].set('名前空間', NakoLexer.filenameToModName(filename))
882
- }
883
- if (this.__globals.indexOf(g) < 0) { this.__globals.push(g) }
884
- return g
550
+ return this.runner.getNakoGlobal(options, gen, filename)
885
551
  }
886
552
 
887
553
  /**
@@ -890,7 +556,7 @@ export class NakoCompiler {
890
556
  * @param callback コールバック関数
891
557
  */
892
558
  addListener(eventName: NakoComEventName, callback: (event:any) => void) {
893
- this.eventList.push({ eventName, callback })
559
+ this.events.on(eventName, callback)
894
560
  }
895
561
 
896
562
  /**
@@ -901,10 +567,7 @@ export class NakoCompiler {
901
567
  * @param testOnly
902
568
  */
903
569
  test(code: string, fname: string, preCode = '', testOnly = false) {
904
- const options = newCompilerOptions()
905
- options.preCode = preCode
906
- options.testOnly = testOnly
907
- return this.runSync(code, fname, options)
570
+ return this.runner.test(code, fname, preCode, testOnly)
908
571
  }
909
572
 
910
573
  /**
@@ -934,102 +597,13 @@ export class NakoCompiler {
934
597
 
935
598
  /**
936
599
  * プラグイン・オブジェクトを追加
600
+ * (実体は nako_plugin_manager.mts の NakoPluginManager.addPlugin)
937
601
  * @param po プラグイン・オブジェクト
938
602
  * @param persistent falseのとき、次以降の実行では使えない
939
603
  * @param fpath ファイルパス
940
604
  */
941
- addPlugin(po: {[key: string]: any}, persistent = true, fpath = ''): void {
942
- // __v0を取得
943
- const __v0 = this.__varslist[0]
944
- // プラグインのメタ情報をチェック (#1034) (#1647)
945
- let __pluginInfo = __v0.get('__pluginInfo')
946
- if (!__pluginInfo) {
947
- __pluginInfo = {}
948
- __v0.set('__pluginInfo', __pluginInfo)
949
- }
950
- // バージョンチェック
951
- let intVersion = 0
952
- let pluginName = 'unknown'
953
- let metaValue = { pluginName: 'unknown', nakoVersionResult: true, nakoVersion: '0.0.0', path: '' }
954
- if (po.meta) {
955
- if (po.meta.value && typeof (po.meta) === 'object') {
956
- const meta = po.meta
957
- metaValue = meta.value || { pluginName: 'unknown', nakoVersion: '0.0.0' }
958
- pluginName = metaValue.pluginName || 'unknown'
959
- // version check
960
- const nakoVersion = (metaValue.nakoVersion || '0.0.0') + '.0.0'
961
- const versions = nakoVersion.split('.').map((v) => parseInt(v))
962
- intVersion = versions[1] * 100 + versions[2]
963
- // fpath
964
- metaValue.path = fpath
965
- }
966
- }
967
- // unknown の場合は、関数名からプラグイン名を自動生成する
968
- if (pluginName === 'unknown') {
969
- pluginName = Object.keys(po).join('-')
970
- }
971
- // プラグイン名の重複を確認
972
- if (__pluginInfo[pluginName] !== undefined) {
973
- // プラグイン名が重複した場合はプラグインとして登録しない
974
- return
975
- }
976
- // Windowsのパスやファイル名に使えない文字列があると、JSファイル書き出しでエラーになるので置換
977
- const removeInvalidFilenameChars = (str: string): string => {
978
- return str.replace(/[^a-zA-z0-9\-_\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FAF\u3400-\u4DBF\uF900-\uFAFF]/g, '_')
979
- }
980
- pluginName = removeInvalidFilenameChars(pluginName)
981
- // プラグイン情報を記録
982
- __pluginInfo[pluginName] = metaValue
983
- // バージョンチェック
984
- if (PLUGIN_MIN_VERSION_INT > intVersion) {
985
- const keyStr: string = Object.keys(po).join(',')
986
- if (pluginName === 'unknown') {
987
- pluginName = keyStr.substring(0, 30) + '...'
988
- }
989
- if (pluginName !== '') {
990
- const errMsg = `なでしこプラグイン『${pluginName}』は古い形式なので正しく動作しない可能性があります。` +
991
- `(ランタイムの要求: ${PLUGIN_MIN_VERSION_INT}/プラグイン: ${intVersion})`
992
- console.warn(errMsg, 'see', 'https://github.com/kujirahand/nadesiko3/issues/1647')
993
- this.logger.warn(errMsg)
994
- metaValue.nakoVersionResult = false
995
- }
996
- }
997
- // 初期化とクリアを変換する
998
- this.__module[pluginName] = po
999
- this.pluginfiles[pluginName] = '*'
1000
- // `初期化`と`クリア`をチェック
1001
- if (typeof (po['初期化']) === 'object') {
1002
- const def = po['初期化']
1003
- delete po['初期化']
1004
- const initKey = `!${pluginName}:初期化`
1005
- po[initKey] = def
1006
- }
1007
- // プラグインの値を、なでしこシステム変数(Map)にコピー
1008
- for (const key in po) {
1009
- const v = po[key]
1010
- this.funclist.set(key, v)
1011
- if (persistent) {
1012
- this.pluginFunclist[key] = JSON.parse(JSON.stringify(v))
1013
- }
1014
- if (v.type === 'func') {
1015
- __v0.set(key, v.fn)
1016
- if (v.asyncFn) { // asyncFn を正しく実行するために pure に変更する (core#142)
1017
- v.pure = true
1018
- }
1019
- } else if (v.type === 'const' || v.type === 'var') {
1020
- // メタ情報としての const | var は現在利用していない
1021
- // meta[key] = { readonly: v.type === 'const' }
1022
- __v0.set(key, v.value)
1023
- } else {
1024
- console.error('[プラグイン追加エラー]', v)
1025
- throw new Error('プラグインの追加でエラー。')
1026
- }
1027
- // コマンドを登録するか?
1028
- if (key === '初期化' || key.substring(0, 1) === '!') { // 登録しない関数名
1029
- continue
1030
- }
1031
- this.commandlist.add(key)
1032
- }
605
+ addPlugin (po: {[key: string]: any}, persistent = true, fpath = ''): void {
606
+ this.pluginManager.addPlugin(po, persistent, fpath)
1033
607
  }
1034
608
 
1035
609
  /**
@@ -1038,12 +612,8 @@ export class NakoCompiler {
1038
612
  * @param po 関数リスト
1039
613
  * @param persistent falseのとき、次以降の実行では使えない
1040
614
  */
1041
- addPluginObject(objName: string, po: {[key: string]: any}, persistent = true): void {
1042
- // metaプロパティがなければ互換性のため適当に追加
1043
- if (po.meta === undefined) {
1044
- po.meta = { type: 'const', value: { pluginName: objName, nakoVersion: '0.0.0' } }
1045
- }
1046
- this.addPlugin(po, persistent)
615
+ addPluginObject (objName: string, po: {[key: string]: any}, persistent = true): void {
616
+ this.pluginManager.addPluginObject(objName, po, persistent)
1047
617
  }
1048
618
 
1049
619
  /**
@@ -1054,18 +624,18 @@ export class NakoCompiler {
1054
624
  * @param persistent falseのとき、次以降の実行では使えない
1055
625
  * @deprecated 利用は非推奨
1056
626
  */
1057
- addPluginFile(_objName: string, fpath: string, po: {[key: string]: any}, persistent = true): void {
627
+ addPluginFile (_objName: string, fpath: string, po: {[key: string]: any}, persistent = true): void {
1058
628
  this.addPluginFromFile(fpath, po, persistent)
1059
629
  }
1060
630
 
1061
631
  /**
1062
- * プラグイン・ファイルを追加(Node.js向け)
1063
- * @param fpath ファイルパス
1064
- * @param po 登録するオブジェクト
1065
- * @param persistent falseのとき、次以降の実行では使えない
1066
- */
1067
- addPluginFromFile(fpath: string, po: { [key: string]: any }, persistent = true): void {
1068
- this.addPlugin(po, persistent, fpath)
632
+ * プラグイン・ファイルを追加(Node.js向け)
633
+ * @param fpath ファイルパス
634
+ * @param po 登録するオブジェクト
635
+ * @param persistent falseのとき、次以降の実行では使えない
636
+ */
637
+ addPluginFromFile (fpath: string, po: { [key: string]: any }, persistent = true): void {
638
+ this.pluginManager.addPluginFromFile(fpath, po, persistent)
1069
639
  }
1070
640
 
1071
641
  /**
@@ -1076,17 +646,14 @@ export class NakoCompiler {
1076
646
  * @param {boolean} returnNone 値を返す関数の場合はfalseを指定
1077
647
  * @param {boolean} asyncFn Promiseを返す関数かを指定
1078
648
  */
1079
- addFunc(key: string, josi: FuncArgs, fn: any, returnNone = true, asyncFn = false): void {
1080
- const funcObj: FuncListItem = { josi, fn, type: 'func', return_none: returnNone, asyncFn, pure: true }
1081
- this.funclist.set(key, funcObj)
1082
- this.pluginFunclist[key] = cloneAsJSON(funcObj)
1083
- this.__varslist[0].set(key, fn)
649
+ addFunc (key: string, josi: FuncArgs, fn: any, returnNone = true, asyncFn = false): void {
650
+ this.pluginManager.addFunc(key, josi, fn, returnNone, asyncFn)
1084
651
  }
1085
652
 
1086
653
  /** (非推奨) 互換性のため ... 関数を追加する
1087
654
  * @deprecated 代わりにaddFuncを使ってください
1088
655
  */
1089
- public setFunc(key: string, josi: FuncArgs, fn: any, returnNone = true, asyncFn = false): void {
656
+ public setFunc (key: string, josi: FuncArgs, fn: any, returnNone = true, asyncFn = false): void {
1090
657
  this.addFunc(key, josi, fn, returnNone, asyncFn)
1091
658
  }
1092
659
 
@@ -1095,18 +662,16 @@ export class NakoCompiler {
1095
662
  * @param key プラグイン関数の関数名
1096
663
  * @returns プラグイン・オブジェクト
1097
664
  */
1098
- getFunc(key: string): FuncListItem|undefined {
1099
- return this.funclist.get(key)
665
+ getFunc (key: string): FuncListItem|undefined {
666
+ return this.pluginManager.getFunc(key)
1100
667
  }
1101
668
 
1102
669
  /** 同期的になでしこのプログラムcodeを実行する
670
+ * (実体は nako_runner.mts の NakoRunner.runEx)
1103
671
  * @deprecated 代わりにrunAsyncメソッドを使ってください。(core #52)
1104
672
  */
1105
673
  private _runEx(code: string, filename: string, opts: CompilerOptions, preCode = '', nakoGlobal: NakoGlobal|undefined = undefined): NakoGlobal {
1106
- // コンパイル
1107
- opts.preCode = preCode
1108
- if (nakoGlobal) { opts.nakoGlobal = nakoGlobal }
1109
- return this.runSync(code, filename, opts)
674
+ return this.runner.runEx(code, filename, opts, preCode, nakoGlobal)
1110
675
  }
1111
676
 
1112
677
  /** (非推奨) 同期的になでしこのプログラムcodeを実行する
@@ -1127,8 +692,7 @@ export class NakoCompiler {
1127
692
  * @param [preCode]
1128
693
  */
1129
694
  async runReset(code: string, fname = 'main.nako3', preCode = ''): Promise<NakoGlobal> {
1130
- const opts = newCompilerOptions({ resetAll: true, resetEnv: true, preCode })
1131
- return this.runAsync(code, fname, opts)
695
+ return this.runner.runReset(code, fname, preCode)
1132
696
  }
1133
697
 
1134
698
  /**