@eagleoutice/flowr 2.12.2 → 2.13.0

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 (319) hide show
  1. package/README.md +38 -91
  2. package/abstract-interpretation/data-frame/dataframe-domain.d.ts +3 -3
  3. package/abstract-interpretation/data-frame/dataframe-domain.js +14 -6
  4. package/abstract-interpretation/data-frame/semantics.js +12 -16
  5. package/abstract-interpretation/domains/abstract-domain.d.ts +46 -44
  6. package/abstract-interpretation/domains/abstract-domain.js +146 -6
  7. package/abstract-interpretation/domains/bounded-set-domain.d.ts +16 -25
  8. package/abstract-interpretation/domains/bounded-set-domain.js +22 -69
  9. package/abstract-interpretation/domains/interval-domain.d.ts +27 -36
  10. package/abstract-interpretation/domains/interval-domain.js +111 -146
  11. package/abstract-interpretation/domains/lattice.d.ts +3 -3
  12. package/abstract-interpretation/domains/multi-value-state-domain.js +3 -3
  13. package/abstract-interpretation/domains/partial-product-domain.d.ts +12 -19
  14. package/abstract-interpretation/domains/partial-product-domain.js +21 -54
  15. package/abstract-interpretation/domains/positive-interval-domain.d.ts +8 -12
  16. package/abstract-interpretation/domains/positive-interval-domain.js +21 -50
  17. package/abstract-interpretation/domains/product-domain.d.ts +1 -1
  18. package/abstract-interpretation/domains/product-domain.js +4 -4
  19. package/abstract-interpretation/domains/set-range-domain.d.ts +60 -56
  20. package/abstract-interpretation/domains/set-range-domain.js +141 -200
  21. package/abstract-interpretation/domains/set-upper-bound-domain.d.ts +17 -23
  22. package/abstract-interpretation/domains/set-upper-bound-domain.js +59 -103
  23. package/abstract-interpretation/domains/singleton-domain.d.ts +15 -18
  24. package/abstract-interpretation/domains/singleton-domain.js +33 -72
  25. package/abstract-interpretation/domains/state-abstract-domain.d.ts +12 -16
  26. package/abstract-interpretation/domains/state-abstract-domain.js +36 -126
  27. package/abstract-interpretation/domains/state-domain-like.d.ts +2 -2
  28. package/abstract-interpretation/domains/value-abstract-domain.d.ts +120 -0
  29. package/abstract-interpretation/domains/{satisfiable-domain.js → value-abstract-domain.js} +14 -2
  30. package/benchmark/slicer.d.ts +2 -2
  31. package/benchmark/slicer.js +6 -5
  32. package/cli/common/options.d.ts +10 -0
  33. package/cli/common/options.js +2 -0
  34. package/cli/common/scripts-info.d.ts +10 -0
  35. package/cli/flowr-main-options.d.ts +4 -0
  36. package/cli/flowr-main-options.js +5 -0
  37. package/cli/flowr.d.ts +5 -0
  38. package/cli/flowr.js +15 -7
  39. package/cli/repl/commands/repl-query.js +42 -20
  40. package/cli/repl/commands/repl-signature.js +2 -2
  41. package/cli/repl/core.d.ts +14 -5
  42. package/cli/repl/core.js +32 -17
  43. package/cli/repl/parser/slice-query-parser.d.ts +69 -8
  44. package/cli/repl/parser/slice-query-parser.js +82 -13
  45. package/cli/repl/path-input.d.ts +6 -0
  46. package/cli/repl/path-input.js +41 -0
  47. package/cli/repl/print-version.js +3 -5
  48. package/cli/slicer-app.d.ts +2 -0
  49. package/cli/slicer-app.js +2 -1
  50. package/config.d.ts +54 -6
  51. package/config.js +133 -12
  52. package/control-flow/control-flow-graph.d.ts +3 -2
  53. package/control-flow/control-flow-graph.js +34 -14
  54. package/control-flow/semantic-cfg-guided-visitor.d.ts +3 -0
  55. package/control-flow/semantic-cfg-guided-visitor.js +3 -0
  56. package/core/steps/all/static-slicing/10-reconstruct.d.ts +6 -0
  57. package/core/steps/all/static-slicing/10-reconstruct.js +3 -1
  58. package/data/r-base-packages.generated.d.ts +1 -1
  59. package/data/r-base-packages.generated.js +3 -3
  60. package/data/sigdb/sigdb.remote.json +53 -53
  61. package/dataflow/environments/built-in-proc-name.d.ts +2 -0
  62. package/dataflow/environments/built-in-proc-name.js +2 -0
  63. package/dataflow/environments/built-in.d.ts +2 -0
  64. package/dataflow/environments/built-in.js +2 -0
  65. package/dataflow/environments/default-builtin-config.d.ts +3 -5
  66. package/dataflow/environments/default-builtin-config.js +2 -2
  67. package/dataflow/environments/environment.d.ts +9 -0
  68. package/dataflow/environments/environment.js +28 -7
  69. package/dataflow/environments/identifier.d.ts +1 -2
  70. package/dataflow/environments/identifier.js +1 -5
  71. package/dataflow/extractor.js +1 -2
  72. package/dataflow/graph/dataflowgraph-builder.js +42 -3
  73. package/dataflow/graph/df-helper.d.ts +15 -0
  74. package/dataflow/graph/df-helper.js +20 -0
  75. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +4 -4
  76. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +7 -0
  77. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +13 -0
  78. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +4 -0
  79. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +57 -11
  80. package/dataflow/internal/process/functions/call/built-in/built-in-load.d.ts +12 -0
  81. package/dataflow/internal/process/functions/call/built-in/built-in-load.js +233 -0
  82. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +2 -1
  83. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +5 -3
  84. package/documentation/data/faq/faqs.js +12 -1
  85. package/documentation/doc-readme.js +1 -1
  86. package/documentation/doc-util/doc-files.d.ts +2 -2
  87. package/documentation/doc-util/doc-files.js +4 -7
  88. package/documentation/doc-util/doc-query.d.ts +12 -9
  89. package/documentation/doc-util/doc-query.js +63 -28
  90. package/documentation/wiki-absint.js +1 -4
  91. package/documentation/wiki-analyzer.js +8 -3
  92. package/documentation/wiki-cfg.js +3 -2
  93. package/documentation/wiki-dataflow-graph.js +14 -4
  94. package/documentation/wiki-interface.js +29 -16
  95. package/documentation/wiki-mk/doc-maker.js +1 -1
  96. package/documentation/wiki-query.js +189 -30
  97. package/documentation/wiki-signature-database.d.ts +1 -1
  98. package/documentation/wiki-signature-database.js +53 -27
  99. package/linter/linter-output.d.ts +24 -0
  100. package/linter/linter-output.js +117 -0
  101. package/linter/linter-rules.d.ts +2 -4
  102. package/linter/rules/dataframe-access-validation.js +4 -4
  103. package/linter/rules/deprecated-functions.d.ts +2 -4
  104. package/linter/rules/deprecated-functions.js +58 -3
  105. package/linter/rules/undefined-symbol.js +18 -10
  106. package/linter/rules/unused-definition.js +24 -0
  107. package/package.json +5 -2
  108. package/project/context/flowr-analyzer-context.d.ts +59 -1
  109. package/project/context/flowr-analyzer-context.js +118 -3
  110. package/project/context/flowr-analyzer-dependencies-context.d.ts +32 -7
  111. package/project/context/flowr-analyzer-dependencies-context.js +33 -3
  112. package/project/context/flowr-analyzer-files-context.d.ts +32 -0
  113. package/project/context/flowr-analyzer-files-context.js +132 -14
  114. package/project/context/flowr-analyzer-loading-order-context.d.ts +6 -0
  115. package/project/context/flowr-analyzer-loading-order-context.js +20 -0
  116. package/project/context/flowr-analyzer-meta-context.d.ts +92 -10
  117. package/project/context/flowr-analyzer-meta-context.js +64 -23
  118. package/project/context/flowr-file.d.ts +7 -0
  119. package/project/context/flowr-file.js +7 -0
  120. package/project/context/project-kind.d.ts +22 -0
  121. package/project/context/project-kind.js +27 -0
  122. package/project/dependency-version-space.d.ts +166 -0
  123. package/project/dependency-version-space.js +564 -0
  124. package/project/flowr-analyzer-builder.js +1 -1
  125. package/project/flowr-analyzer.d.ts +4 -0
  126. package/project/flowr-analyzer.js +5 -0
  127. package/project/plugins/file-plugins/files/flowr-description-file.d.ts +4 -0
  128. package/project/plugins/file-plugins/files/flowr-description-file.js +7 -0
  129. package/project/plugins/file-plugins/files/flowr-namespace-file.js +5 -1
  130. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +739 -0
  131. package/project/plugins/file-plugins/files/flowr-rda-file.js +2407 -0
  132. package/project/plugins/file-plugins/files/flowr-rproject-file.d.ts +31 -0
  133. package/project/plugins/file-plugins/files/flowr-rproject-file.js +66 -0
  134. package/project/plugins/file-plugins/files/r-fun-tab.d.ts +828 -0
  135. package/project/plugins/file-plugins/files/r-fun-tab.js +1039 -0
  136. package/project/plugins/file-plugins/flowr-analyzer-description-file-plugin.d.ts +1 -1
  137. package/project/plugins/file-plugins/flowr-analyzer-description-file-plugin.js +1 -1
  138. package/project/plugins/file-plugins/flowr-analyzer-file-plugin.js +1 -1
  139. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.d.ts +1 -1
  140. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.js +1 -1
  141. package/project/plugins/file-plugins/flowr-analyzer-license-file-plugin.d.ts +1 -1
  142. package/project/plugins/file-plugins/flowr-analyzer-license-file-plugin.js +1 -1
  143. package/project/plugins/file-plugins/flowr-analyzer-namespace-files-plugin.d.ts +1 -1
  144. package/project/plugins/file-plugins/flowr-analyzer-namespace-files-plugin.js +1 -1
  145. package/project/plugins/file-plugins/flowr-analyzer-news-file-plugin.d.ts +1 -1
  146. package/project/plugins/file-plugins/flowr-analyzer-news-file-plugin.js +1 -1
  147. package/project/plugins/file-plugins/flowr-analyzer-rda-file-plugin.d.ts +26 -0
  148. package/project/plugins/file-plugins/flowr-analyzer-rda-file-plugin.js +38 -0
  149. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.d.ts +17 -0
  150. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.js +30 -0
  151. package/project/plugins/file-plugins/flowr-analyzer-rproject-file-plugin.d.ts +22 -0
  152. package/project/plugins/file-plugins/flowr-analyzer-rproject-file-plugin.js +36 -0
  153. package/project/plugins/file-plugins/flowr-analyzer-test-file-plugin.d.ts +1 -1
  154. package/project/plugins/file-plugins/flowr-analyzer-test-file-plugin.js +1 -1
  155. package/project/plugins/file-plugins/flowr-analyzer-vignette-file-plugin.d.ts +1 -1
  156. package/project/plugins/file-plugins/flowr-analyzer-vignette-file-plugin.js +1 -1
  157. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.d.ts +3 -4
  158. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.js +5 -6
  159. package/project/plugins/flowr-analyzer-plugin.js +5 -0
  160. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-description-file-plugin.d.ts +1 -1
  161. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-description-file-plugin.js +1 -1
  162. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-implicit-sources-plugin.d.ts +14 -0
  163. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-implicit-sources-plugin.js +53 -0
  164. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-plugin.js +1 -1
  165. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-rprofile-plugin.d.ts +15 -0
  166. package/project/plugins/loading-order-plugins/flowr-analyzer-loading-order-rprofile-plugin.js +33 -0
  167. package/project/plugins/package-version-plugins/flowr-analyzer-meta-description-file-plugin.d.ts +1 -1
  168. package/project/plugins/package-version-plugins/flowr-analyzer-meta-description-file-plugin.js +18 -13
  169. package/project/plugins/package-version-plugins/flowr-analyzer-meta-rproject-file-plugin.d.ts +13 -0
  170. package/project/plugins/package-version-plugins/flowr-analyzer-meta-rproject-file-plugin.js +32 -0
  171. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-description-file-plugin.d.ts +1 -1
  172. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-description-file-plugin.js +1 -1
  173. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.d.ts +8 -1
  174. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.js +70 -7
  175. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-namespace-file-plugin.d.ts +1 -1
  176. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-namespace-file-plugin.js +1 -1
  177. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.js +1 -1
  178. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-session-info-plugin.d.ts +18 -0
  179. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-session-info-plugin.js +62 -0
  180. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +4 -1
  181. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +5 -13
  182. package/project/plugins/package-version-plugins/package.d.ts +4 -1
  183. package/project/plugins/package-version-plugins/package.js +8 -5
  184. package/project/plugins/plugin-registry.d.ts +11 -3
  185. package/project/plugins/plugin-registry.js +24 -5
  186. package/project/plugins/project-discovery/flowr-analyzer-ignore-file-project-discovery-plugin.d.ts +51 -0
  187. package/project/plugins/project-discovery/flowr-analyzer-ignore-file-project-discovery-plugin.js +101 -0
  188. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +10 -5
  189. package/project/sigdb/build.js +12 -2
  190. package/project/sigdb/decode.d.ts +7 -0
  191. package/project/sigdb/decode.js +35 -4
  192. package/project/sigdb/decompress.d.ts +2 -0
  193. package/project/sigdb/decompress.js +5 -0
  194. package/project/sigdb/manifest.d.ts +5 -0
  195. package/project/sigdb/manifest.js +37 -6
  196. package/project/sigdb/reader.d.ts +82 -2
  197. package/project/sigdb/reader.js +226 -14
  198. package/project/sigdb/schema.d.ts +31 -5
  199. package/project/sigdb/schema.js +7 -3
  200. package/project/sigdb/{version.d.ts → sigdb-version.d.ts} +21 -1
  201. package/project/sigdb/sigdb-version.js +119 -0
  202. package/queries/catalog/absint-query/absint-query-format.d.ts +2 -0
  203. package/queries/catalog/absint-query/absint-query-format.js +2 -0
  204. package/queries/catalog/call-context-query/call-context-query-executor.js +30 -3
  205. package/queries/catalog/call-context-query/call-context-query-format.d.ts +1 -0
  206. package/queries/catalog/call-context-query/call-context-query-format.js +1 -0
  207. package/queries/catalog/call-graph-query/call-graph-query-executor.js +3 -1
  208. package/queries/catalog/call-graph-query/call-graph-query-format.d.ts +6 -0
  209. package/queries/catalog/call-graph-query/call-graph-query-format.js +2 -0
  210. package/queries/catalog/call-graph-query/expand-library-internals.d.ts +19 -0
  211. package/queries/catalog/call-graph-query/expand-library-internals.js +59 -0
  212. package/queries/catalog/cluster-query/cluster-query-format.d.ts +1 -0
  213. package/queries/catalog/cluster-query/cluster-query-format.js +1 -0
  214. package/queries/catalog/config-query/config-query-executor.js +15 -6
  215. package/queries/catalog/config-query/config-query-format.d.ts +18 -4
  216. package/queries/catalog/config-query/config-query-format.js +246 -96
  217. package/queries/catalog/control-flow-query/control-flow-query-format.d.ts +1 -0
  218. package/queries/catalog/control-flow-query/control-flow-query-format.js +1 -0
  219. package/queries/catalog/dataflow-lens-query/dataflow-lens-query-format.d.ts +1 -0
  220. package/queries/catalog/dataflow-lens-query/dataflow-lens-query-format.js +1 -0
  221. package/queries/catalog/dataflow-query/dataflow-query-format.d.ts +1 -0
  222. package/queries/catalog/dataflow-query/dataflow-query-format.js +1 -0
  223. package/queries/catalog/dependencies-query/dependencies-query-executor.js +2 -7
  224. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +13 -1
  225. package/queries/catalog/dependencies-query/dependencies-query-format.js +117 -17
  226. package/queries/catalog/dice-query/dice-query-executor.js +6 -9
  227. package/queries/catalog/dice-query/dice-query-format.d.ts +4 -5
  228. package/queries/catalog/dice-query/dice-query-format.js +10 -6
  229. package/queries/catalog/does-call-query/does-call-query-executor.js +15 -2
  230. package/queries/catalog/does-call-query/does-call-query-format.d.ts +8 -0
  231. package/queries/catalog/does-call-query/does-call-query-format.js +4 -1
  232. package/queries/catalog/files-query/files-query-format.d.ts +2 -0
  233. package/queries/catalog/files-query/files-query-format.js +2 -0
  234. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-executor.d.ts +6 -0
  235. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-executor.js +277 -0
  236. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.d.ts +119 -0
  237. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +331 -0
  238. package/queries/catalog/happens-before-query/happens-before-query-format.d.ts +1 -0
  239. package/queries/catalog/happens-before-query/happens-before-query-format.js +1 -0
  240. package/queries/catalog/id-map-query/id-map-query-format.d.ts +1 -0
  241. package/queries/catalog/id-map-query/id-map-query-format.js +1 -0
  242. package/queries/catalog/input-sources-query/input-sources-query-format.d.ts +2 -0
  243. package/queries/catalog/input-sources-query/input-sources-query-format.js +2 -0
  244. package/queries/catalog/inspect-exceptions-query/inspect-exception-query-format.d.ts +2 -0
  245. package/queries/catalog/inspect-exceptions-query/inspect-exception-query-format.js +2 -0
  246. package/queries/catalog/inspect-higher-order-query/inspect-higher-order-query-format.d.ts +2 -0
  247. package/queries/catalog/inspect-higher-order-query/inspect-higher-order-query-format.js +2 -0
  248. package/queries/catalog/inspect-recursion-query/inspect-recursion-query-format.d.ts +2 -0
  249. package/queries/catalog/inspect-recursion-query/inspect-recursion-query-format.js +2 -0
  250. package/queries/catalog/linter-query/linter-query-executor.js +11 -2
  251. package/queries/catalog/linter-query/linter-query-format.d.ts +9 -4
  252. package/queries/catalog/linter-query/linter-query-format.js +44 -21
  253. package/queries/catalog/location-map-query/location-map-query-format.d.ts +2 -0
  254. package/queries/catalog/location-map-query/location-map-query-format.js +2 -0
  255. package/queries/catalog/normalized-ast-query/normalized-ast-query-format.d.ts +1 -0
  256. package/queries/catalog/normalized-ast-query/normalized-ast-query-format.js +1 -0
  257. package/queries/catalog/origin-query/origin-query-format.d.ts +2 -0
  258. package/queries/catalog/origin-query/origin-query-format.js +2 -0
  259. package/queries/catalog/project-query/project-query-executor.d.ts +0 -15
  260. package/queries/catalog/project-query/project-query-executor.js +19 -62
  261. package/queries/catalog/project-query/project-query-format.d.ts +7 -18
  262. package/queries/catalog/project-query/project-query-format.js +3 -18
  263. package/queries/catalog/provenance-query/provenance-query-format.d.ts +2 -0
  264. package/queries/catalog/provenance-query/provenance-query-format.js +2 -0
  265. package/queries/catalog/resolve-value-query/resolve-value-query-format.d.ts +2 -0
  266. package/queries/catalog/resolve-value-query/resolve-value-query-format.js +2 -0
  267. package/queries/catalog/search-query/search-query-format.d.ts +1 -0
  268. package/queries/catalog/search-query/search-query-format.js +1 -0
  269. package/queries/catalog/signature-query/signature-query-executor.d.ts +5 -0
  270. package/queries/catalog/signature-query/signature-query-executor.js +267 -57
  271. package/queries/catalog/signature-query/signature-query-format.d.ts +37 -6
  272. package/queries/catalog/signature-query/signature-query-format.js +41 -5
  273. package/queries/catalog/signature-query/signature-query-render.js +48 -6
  274. package/queries/catalog/slice-query-options.d.ts +49 -0
  275. package/queries/catalog/slice-query-options.js +50 -0
  276. package/queries/catalog/static-slice-query/static-slice-query-executor.js +4 -12
  277. package/queries/catalog/static-slice-query/static-slice-query-format.d.ts +4 -15
  278. package/queries/catalog/static-slice-query/static-slice-query-format.js +9 -10
  279. package/queries/query-print.js +3 -1
  280. package/queries/query.d.ts +63 -3
  281. package/queries/query.js +9 -2
  282. package/r-bridge/data/data.d.ts +16 -0
  283. package/r-bridge/data/data.js +20 -0
  284. package/r-bridge/lang-4.x/ast/model/model.d.ts +1 -0
  285. package/r-bridge/lang-4.x/ast/model/processing/decorate.js +2 -1
  286. package/r-bridge/lang-4.x/ast/parser/main/internal/normalize-access.js +2 -1
  287. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize.js +19 -16
  288. package/reconstruct/reconstruct.d.ts +18 -1
  289. package/reconstruct/reconstruct.js +42 -19
  290. package/slicing/criterion/parse.d.ts +4 -0
  291. package/slicing/criterion/parse.js +4 -0
  292. package/slicing/static/slice-call.js +17 -9
  293. package/slicing/static/static-slicer.d.ts +1 -1
  294. package/slicing/static/static-slicer.js +5 -4
  295. package/util/files.d.ts +19 -1
  296. package/util/files.js +45 -3
  297. package/util/glob.d.ts +19 -0
  298. package/util/glob.js +67 -0
  299. package/util/log.d.ts +12 -0
  300. package/util/log.js +17 -1
  301. package/util/logic.d.ts +6 -0
  302. package/util/logic.js +31 -1
  303. package/util/mermaid/dfg.js +17 -12
  304. package/util/mermaid/mermaid.js +2 -2
  305. package/util/objects.d.ts +5 -0
  306. package/util/objects.js +8 -0
  307. package/util/r-version.d.ts +9 -1
  308. package/util/r-version.js +27 -2
  309. package/util/schema.d.ts +16 -0
  310. package/util/schema.js +89 -4
  311. package/util/text/ansi.d.ts +4 -0
  312. package/util/text/ansi.js +27 -3
  313. package/util/text/strings.d.ts +9 -0
  314. package/util/text/strings.js +29 -0
  315. package/util/version.js +79 -6
  316. package/abstract-interpretation/domains/satisfiable-domain.d.ts +0 -29
  317. package/project/plugins/project-discovery/flowr-analyzer-gitignore-project-discovery-plugin.d.ts +0 -22
  318. package/project/plugins/project-discovery/flowr-analyzer-gitignore-project-discovery-plugin.js +0 -52
  319. package/project/sigdb/version.js +0 -55
@@ -0,0 +1,2407 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RDAParser = exports.SerializationFormat = exports.SexpType = exports.SerializationTypeTag = exports.CompressionType = exports.FlowrRDAFile = void 0;
7
+ const flowr_file_1 = require("../../../context/flowr-file");
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const r_fun_tab_1 = require("./r-fun-tab");
10
+ const shell_executor_1 = require("../../../../r-bridge/shell-executor");
11
+ /**
12
+ * This decorates a text file and provides access to its content in the format of an {@link RObjectData}.
13
+ */
14
+ class FlowrRDAFile extends flowr_file_1.FlowrFile {
15
+ wrapped;
16
+ shortcut;
17
+ /**
18
+ * Prefer the static {@link FlowrRDAFile.from} method to create instances of this class as it will not re-create if already a description file
19
+ * and handle role assignments.
20
+ * @param file - The underlying file provider whose path points to an RDA file.
21
+ * @param shortcut - When `true`, only top-level object names and types are
22
+ * collected during parsing. Payload data is skipped.
23
+ */
24
+ constructor(file, shortcut = true) {
25
+ super(file.path(), file.roles);
26
+ this.wrapped = file;
27
+ this.shortcut = shortcut ?? false;
28
+ }
29
+ /**
30
+ * Loads and parses the content of the wrapped file as an RDA structure.
31
+ * @see {@link parse} for details on the parsing logic.
32
+ * @returns An array of top-level {@link RObjectData}s or `[{}]` when the
33
+ * file contains no R objects.
34
+ */
35
+ loadContent() {
36
+ return new RDAParser(this.wrapped, this.shortcut).parse() ?? [{}];
37
+ }
38
+ /**
39
+ * RDA file lifter, this does not re-create if already an RDA file.
40
+ * @param file - A raw {@link FlowrFileProvider} or an existing {@link FlowrRDAFile}.
41
+ * @param role - Optional {@link FileRole} to assign before returning.
42
+ * @returns The (possibly newly created) {@link FlowrRDAFile}.
43
+ */
44
+ static from(file, role) {
45
+ if (role) {
46
+ file.assignRole(role);
47
+ }
48
+ return file instanceof FlowrRDAFile ? file : new FlowrRDAFile(file);
49
+ }
50
+ }
51
+ exports.FlowrRDAFile = FlowrRDAFile;
52
+ /**
53
+ * Compression algorithm wrapping an RDA file.
54
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/connections.c#L2673 | R source: comp_type}
55
+ */
56
+ var CompressionType;
57
+ (function (CompressionType) {
58
+ CompressionType["CompGz"] = "COMP_GZ";
59
+ CompressionType["CompBz"] = "COMP_BZ";
60
+ CompressionType["CompXz"] = "COMP_XZ";
61
+ CompressionType["CompLzma"] = "COMP_LZMA";
62
+ CompressionType["CompZstd"] = "COMP_ZSTD";
63
+ CompressionType["CompUnknownOrNo"] = "COMP_UNKNOWN_OR_NO";
64
+ })(CompressionType || (exports.CompressionType = CompressionType = {}));
65
+ /**
66
+ * RDA file serialization format and version.
67
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/saveload.c#L61-L72 | R source: saveload.c}
68
+ */
69
+ var SerializationTypeTag;
70
+ (function (SerializationTypeTag) {
71
+ SerializationTypeTag["MagicEmpty"] = "R_MAGIC_EMPTY";
72
+ SerializationTypeTag["MagicCorrupt"] = "R_MAGIC_CORRUPT";
73
+ SerializationTypeTag["MagicAsciiV1"] = "R_MAGIC_ASCII_V1";
74
+ SerializationTypeTag["MagicBinaryV1"] = "R_MAGIC_BINARY_V1";
75
+ SerializationTypeTag["MagicXdrV1"] = "R_MAGIC_XDR_V1";
76
+ SerializationTypeTag["MagicAsciiV2"] = "R_MAGIC_ASCII_V2";
77
+ SerializationTypeTag["MagicBinaryV2"] = "R_MAGIC_BINARY_V2";
78
+ SerializationTypeTag["MagicXdrV2"] = "R_MAGIC_XDR_V2";
79
+ SerializationTypeTag["MagicAsciiV3"] = "R_MAGIC_ASCII_V3";
80
+ SerializationTypeTag["MagicBinaryV3"] = "R_MAGIC_BINARY_V3";
81
+ SerializationTypeTag["MagicXdrV3"] = "R_MAGIC_XDR_V3";
82
+ SerializationTypeTag["MagicMaybeTooNew"] = "R_MAGIC_MAYBE_TOONEW";
83
+ })(SerializationTypeTag || (exports.SerializationTypeTag = SerializationTypeTag = {}));
84
+ /**
85
+ * Numeric identifiers for R SEXP types.
86
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/include/Rinternals.h#L111-L144 | R source: SEXP}
87
+ * @see {@link http://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L681-L711 | R source: SEXP}
88
+ */
89
+ var SexpType;
90
+ (function (SexpType) {
91
+ SexpType[SexpType["NilSxp"] = 0] = "NilSxp";
92
+ SexpType[SexpType["SymSxp"] = 1] = "SymSxp";
93
+ SexpType[SexpType["ListSxp"] = 2] = "ListSxp";
94
+ SexpType[SexpType["CloSxp"] = 3] = "CloSxp";
95
+ SexpType[SexpType["EnvSxp"] = 4] = "EnvSxp";
96
+ SexpType[SexpType["PromSxp"] = 5] = "PromSxp";
97
+ SexpType[SexpType["LangSxp"] = 6] = "LangSxp";
98
+ SexpType[SexpType["SpecialSxp"] = 7] = "SpecialSxp";
99
+ SexpType[SexpType["BuiltInSxp"] = 8] = "BuiltInSxp";
100
+ SexpType[SexpType["CharSxp"] = 9] = "CharSxp";
101
+ SexpType[SexpType["LglSxp"] = 10] = "LglSxp";
102
+ SexpType[SexpType["IntSxp"] = 13] = "IntSxp";
103
+ SexpType[SexpType["RealSxp"] = 14] = "RealSxp";
104
+ SexpType[SexpType["CplxSxp"] = 15] = "CplxSxp";
105
+ SexpType[SexpType["StrSxp"] = 16] = "StrSxp";
106
+ SexpType[SexpType["DotSxp"] = 17] = "DotSxp";
107
+ SexpType[SexpType["AnySxp"] = 18] = "AnySxp";
108
+ SexpType[SexpType["VecSxp"] = 19] = "VecSxp";
109
+ SexpType[SexpType["ExprSxp"] = 20] = "ExprSxp";
110
+ SexpType[SexpType["BcodesSxp"] = 21] = "BcodesSxp";
111
+ SexpType[SexpType["ExtPtrSxp"] = 22] = "ExtPtrSxp";
112
+ SexpType[SexpType["WeakRefSxp"] = 23] = "WeakRefSxp";
113
+ SexpType[SexpType["RawSxp"] = 24] = "RawSxp";
114
+ SexpType[SexpType["ObjSxp"] = 25] = "ObjSxp";
115
+ SexpType[SexpType["NewSxp"] = 30] = "NewSxp";
116
+ SexpType[SexpType["FreeSxp"] = 31] = "FreeSxp";
117
+ SexpType[SexpType["FunSxp"] = 99] = "FunSxp";
118
+ SexpType[SexpType["RefSxp"] = 255] = "RefSxp";
119
+ SexpType[SexpType["NilValueSxp"] = 254] = "NilValueSxp";
120
+ SexpType[SexpType["GlobalEnvSxp"] = 253] = "GlobalEnvSxp";
121
+ SexpType[SexpType["UnboundValueSxp"] = 252] = "UnboundValueSxp";
122
+ SexpType[SexpType["MissingArgSxp"] = 251] = "MissingArgSxp";
123
+ SexpType[SexpType["BaseNamespaceSxp"] = 250] = "BaseNamespaceSxp";
124
+ SexpType[SexpType["NamespaceSxp"] = 249] = "NamespaceSxp";
125
+ SexpType[SexpType["PackageSxp"] = 248] = "PackageSxp";
126
+ SexpType[SexpType["PersistSxp"] = 247] = "PersistSxp";
127
+ SexpType[SexpType["ClassRefSxp"] = 246] = "ClassRefSxp";
128
+ SexpType[SexpType["GenericRefSxp"] = 245] = "GenericRefSxp";
129
+ SexpType[SexpType["BcRepDef"] = 244] = "BcRepDef";
130
+ SexpType[SexpType["BcRepRef"] = 243] = "BcRepRef";
131
+ SexpType[SexpType["EmptyEnvSxp"] = 242] = "EmptyEnvSxp";
132
+ SexpType[SexpType["BaseEnvSxp"] = 241] = "BaseEnvSxp";
133
+ SexpType[SexpType["AltLangSxp"] = 240] = "AltLangSxp";
134
+ SexpType[SexpType["AttrListSxp"] = 239] = "AttrListSxp";
135
+ SexpType[SexpType["AltRepSxp"] = 238] = "AltRepSxp";
136
+ })(SexpType || (exports.SexpType = SexpType = {}));
137
+ /**
138
+ * Special values used internally by R serialization.
139
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/include/Rinternals.h#L401-L471 | R source: RValues}
140
+ */
141
+ var RValues;
142
+ (function (RValues) {
143
+ RValues["NilValue"] = "NIL";
144
+ RValues["EmptyEnv"] = "EMPTY_ENV";
145
+ RValues["BaseEnv"] = "BASE_ENV";
146
+ RValues["GlobalEnv"] = "GLOBAL_ENV";
147
+ RValues["UnboundValue"] = "UNBOUND_VALUE";
148
+ RValues["MissingArg"] = "MISSING_ARG";
149
+ RValues["BaseNamespace"] = "BASE_NAMESPACE";
150
+ RValues["ClassSymbol"] = "CLASS";
151
+ RValues["NaString"] = "NA_character_";
152
+ RValues["NaInteger"] = "NA_integer_";
153
+ RValues["NaReal"] = "NA_real_";
154
+ RValues["NaComplex"] = "NA_complex_";
155
+ RValues["NaN"] = "NaN";
156
+ RValues["PosInf"] = "Pos_Inf";
157
+ RValues["NegInf"] = "Neg_inf";
158
+ })(RValues || (RValues = {}));
159
+ var SerializationFormat;
160
+ (function (SerializationFormat) {
161
+ SerializationFormat["Xdr"] = "XDR";
162
+ SerializationFormat["Ascii"] = "ASCII";
163
+ SerializationFormat["Binary"] = "BINARY";
164
+ })(SerializationFormat || (exports.SerializationFormat = SerializationFormat = {}));
165
+ /**
166
+ * Parser for RDA files.
167
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c | R source: serialize.c}
168
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/saveload.c | R source: saveload.c}
169
+ */
170
+ class RDAParser {
171
+ file;
172
+ shortcut;
173
+ buffer;
174
+ currentDepth = 0;
175
+ static INITIAL_DEPTH = 1;
176
+ lastName = undefined;
177
+ setLastName = false;
178
+ offset = 0;
179
+ static R_CODE_SET_MAX = 2 ** 6 - 1;
180
+ RWeakRefs = null;
181
+ static CHUNK_SIZE = 8906;
182
+ static SIZE_OF_DOUBLE = 2 ** 3;
183
+ static WORD_SIZE = 2 ** 7;
184
+ static MAX_VECTOR_LENGTH = 2 ** 16;
185
+ format;
186
+ refTable = [];
187
+ Registry = null;
188
+ opinfo = {
189
+ addr: null,
190
+ argc: null,
191
+ instName: null
192
+ };
193
+ constructor(file, shortcut = true) {
194
+ this.file = file;
195
+ this.shortcut = shortcut ?? true;
196
+ }
197
+ /**
198
+ * Parses an RDA file.
199
+ *
200
+ * The file is decompressed, deserialized and converted into a flattened
201
+ * object representation.
202
+ * @param file - RDA file provider.
203
+ * @param shortcut - When `true`, only names and types are collected.
204
+ * @returns List of found {@link RObjectData} or `null` if the file is empty.
205
+ */
206
+ parse() {
207
+ const fileContent = node_fs_1.default.readFileSync(this.file.path());
208
+ const compressionType = this.detectCompression(fileContent);
209
+ this.buffer = this.decompress(fileContent, compressionType);
210
+ const result = this.deserialize2();
211
+ if (result === RValues.NilValue) {
212
+ return null;
213
+ }
214
+ else {
215
+ return this.flattenRObject(result, this.shortcut);
216
+ }
217
+ }
218
+ /**
219
+ * Detects the compression algorithm used for an RDA file.
220
+ * @param buf - Raw file buffer.
221
+ * @param with_zlib - Whether zlib headers should also be considered.
222
+ * @returns Detected {@link CompressionType}.
223
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/connections.c#L2675-L2710 | R source: comp_type_from_memory}
224
+ */
225
+ detectCompression(buf, with_zlib = false) {
226
+ if (buf.length >= 2 && buf[0] == 0x1f && buf[1] == 0x8b) {
227
+ return CompressionType.CompGz;
228
+ }
229
+ if (with_zlib && buf.length >= 2 && buf[0] == 0x78 && buf[1] == 0x9c) {
230
+ return CompressionType.CompGz;
231
+ }
232
+ if (buf.length >= 10 && buf[0] === 0x42 && buf[1] === 0x5a && buf[2] === 0x68) {
233
+ if (buf[3] >= 0x31 && buf[3] <= 0x39) {
234
+ const magic1 = [0x31, 0x41, 0x59, 0x26, 0x53, 0x59];
235
+ const magic2 = [0x17, 0x72, 0x45, 0x38, 0x50, 0x90];
236
+ const isMagic1 = magic1.every((v, i) => buf[4 + i] === v);
237
+ const isMagic2 = magic2.every((v, i) => buf[4 + i] === v);
238
+ if (isMagic1 || isMagic2) {
239
+ return CompressionType.CompBz;
240
+ }
241
+ }
242
+ }
243
+ if (buf.length >= 4) {
244
+ if (buf.length >= 4 && buf[0] == 0x89 && buf[1] === 0x4c && buf[2] === 0x5a && buf[3] === 0x4f) {
245
+ throw new Error('this is a lzop-compressed file which this build of R does not support');
246
+ }
247
+ else if (buf.length >= 4 && buf[0] === 0x28 && buf[1] === 0xB5 && buf[2] === 0x2F && buf[3] === 0xFD) {
248
+ return CompressionType.CompZstd;
249
+ }
250
+ }
251
+ if (buf.length >= 5) {
252
+ if (buf[0] === 0xFD && buf[1] === 0x37 && buf[2] === 0x7a && buf[3] === 0x58 && buf[4] === 0x5a) {
253
+ return CompressionType.CompXz;
254
+ }
255
+ else if (buf[0] === 0xFF && buf[1] === 0x4C && buf[2] === 0x5A && buf[3] === 0x4D && buf[4] === 0x41) {
256
+ return CompressionType.CompLzma;
257
+ }
258
+ else if (buf[0] === 0x5D && buf[1] === 0x00 && buf[2] === 0x00 && buf[3] === 0x80 && buf[4] === 0x00) {
259
+ return CompressionType.CompLzma;
260
+ }
261
+ }
262
+ return CompressionType.CompUnknownOrNo;
263
+ }
264
+ /**
265
+ * Decompresses the given RDA file buffer.
266
+ * @param fileContent - Raw compressed file buffer.
267
+ * @param compressionType - {@link CompressionType} as returned by {@link detectCompression}.
268
+ * @returns Decompressed buffer.
269
+ * @throws Error for unsupported compression types.
270
+ */
271
+ decompress(fileContent, compressionType) {
272
+ let buffer;
273
+ switch (compressionType) {
274
+ case CompressionType.CompGz: {
275
+ // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment
276
+ const zlib = require('node:zlib');
277
+ try {
278
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
279
+ buffer = zlib.gunzipSync(fileContent);
280
+ }
281
+ catch {
282
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
283
+ buffer = zlib.inflateSync(fileContent);
284
+ }
285
+ break;
286
+ }
287
+ case CompressionType.CompBz: {
288
+ // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-unsafe-assignment
289
+ const bzip2 = require('bzip2');
290
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
291
+ const decompressed = bzip2.simple(bzip2.array(fileContent));
292
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
293
+ buffer = Buffer.from(decompressed);
294
+ break;
295
+ }
296
+ case CompressionType.CompXz:
297
+ case CompressionType.CompLzma:
298
+ case CompressionType.CompZstd: {
299
+ throw new Error(compressionType + 'not supported yet.');
300
+ }
301
+ case CompressionType.CompUnknownOrNo:
302
+ buffer = fileContent;
303
+ break;
304
+ default:
305
+ throw new Error('Unknown or unsupported compression type.');
306
+ }
307
+ return buffer;
308
+ }
309
+ /**
310
+ * Detects the serialization type used for the RDA-file.
311
+ * @param buf - Buffer with decompressed RDA-file content
312
+ * @returns The identified {@link SerializationTypes} of decompressed RDA-file
313
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/saveload.c#L1808-L1858 | R source: R_ReadMagic}
314
+ */
315
+ determineSerializationType(buf) {
316
+ if (buf.length < 5) {
317
+ if (buf.length === 0) {
318
+ return SerializationTypeTag.MagicEmpty;
319
+ }
320
+ else {
321
+ return SerializationTypeTag.MagicCorrupt;
322
+ }
323
+ }
324
+ const magic = buf.toString('ascii', 0, 5);
325
+ switch (magic) {
326
+ case 'RDA1\n':
327
+ return SerializationTypeTag.MagicAsciiV1;
328
+ case 'RDB1\n':
329
+ return SerializationTypeTag.MagicBinaryV1;
330
+ case 'RDX1\n':
331
+ return SerializationTypeTag.MagicXdrV1;
332
+ case 'RDA2\n':
333
+ return SerializationTypeTag.MagicAsciiV2;
334
+ case 'RDB2\n':
335
+ return SerializationTypeTag.MagicBinaryV2;
336
+ case 'RDX2\n':
337
+ return SerializationTypeTag.MagicXdrV2;
338
+ case 'RDA3\n':
339
+ return SerializationTypeTag.MagicAsciiV3;
340
+ case 'RDB3\n':
341
+ return SerializationTypeTag.MagicBinaryV3;
342
+ case 'RDX3\n':
343
+ return SerializationTypeTag.MagicXdrV3;
344
+ }
345
+ if (magic.startsWith('RD')) {
346
+ return SerializationTypeTag.MagicMaybeTooNew;
347
+ }
348
+ return Number(buf.toString('ascii', 0, 4));
349
+ }
350
+ /**
351
+ * Deserializes a decompressed RDA-file.
352
+ * @returns Deserialized RDA-file as {@link RObject} or {@link RValues.NilValue}, if the deserialization fails
353
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/saveload.c#L1923-L1972 | R source: R_LoadFromFile}
354
+ */
355
+ deserialize2() {
356
+ this.offset = 0;
357
+ const serializationType = this.determineSerializationType(this.buffer);
358
+ this.offset += 5;
359
+ if (serializationType === undefined ||
360
+ serializationType === 'R_MAGIC_CORRUPT' ||
361
+ serializationType === 'R_MAGIC_EMPTY' ||
362
+ serializationType === 'R_MAGIC_MAYBE_TOONEW') {
363
+ throw new Error('Could not determine serialization type');
364
+ }
365
+ if (serializationType === 'R_MAGIC_ASCII_V2' ||
366
+ serializationType === 'R_MAGIC_ASCII_V3' ||
367
+ serializationType === 'R_MAGIC_XDR_V2' ||
368
+ serializationType === 'R_MAGIC_XDR_V3' ||
369
+ serializationType === 'R_MAGIC_BINARY_V2' ||
370
+ serializationType === 'R_MAGIC_BINARY_V3') {
371
+ const result = this.deserialize();
372
+ this.currentDepth--;
373
+ return result;
374
+ }
375
+ if (serializationType === 'R_MAGIC_ASCII_V1' ||
376
+ serializationType === 'R_MAGIC_XDR_V1' ||
377
+ serializationType === 'R_MAGIC_BINARY_V1') {
378
+ // https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/saveload.c#L2157-L2196
379
+ console.warn('Version one rda files are not supported yet');
380
+ }
381
+ return RValues.NilValue;
382
+ }
383
+ /**
384
+ * Deserializes a decompressed RDA-file.
385
+ * @returns Deserialized RDA-file as {@link RObject}
386
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2237-L2292 | R source: R_Unserialize}
387
+ */
388
+ deserialize() {
389
+ switch (String.fromCodePoint(this.buffer[this.offset])) {
390
+ case 'A':
391
+ this.format = SerializationFormat.Ascii;
392
+ break;
393
+ case 'B':
394
+ this.format = SerializationFormat.Binary;
395
+ break;
396
+ case 'X':
397
+ this.format = SerializationFormat.Xdr;
398
+ break;
399
+ case '\n':
400
+ if (String.fromCodePoint(this.buffer[this.offset + 1]) === 'A') {
401
+ this.format = SerializationFormat.Ascii;
402
+ this.offset += 1;
403
+ }
404
+ break;
405
+ default:
406
+ throw new Error('unknown input format');
407
+ }
408
+ this.offset += 2;
409
+ const version = this.assertInteger(this.inInteger());
410
+ const writerVersion = this.assertInteger(this.inInteger());
411
+ const minReaderVersion = this.assertInteger(this.inInteger());
412
+ switch (version) {
413
+ case 2: break;
414
+ case 3:
415
+ {
416
+ const neLen = this.assertInteger(this.inInteger());
417
+ if (neLen > RDAParser.R_CODE_SET_MAX || neLen < 0) {
418
+ throw new Error('invalid length of encoding name');
419
+ }
420
+ const _nativeEncoding = this.inString(neLen);
421
+ break;
422
+ }
423
+ default:
424
+ {
425
+ const [vw, pw, sw] = this.decodeVersion(writerVersion);
426
+ if (minReaderVersion < 0) {
427
+ throw new Error(`cannot read unreleased workspace version ${version} written by experimental R ${vw}.${pw}.${sw}`);
428
+ }
429
+ else {
430
+ const [vm, pm, sm] = this.decodeVersion(minReaderVersion);
431
+ throw new Error(`cannot read unreleased workspace version ${version} written by experimental R ${vw}.${pw}.${sw}; need R ${vm}.${pm}.${sm} or newer`);
432
+ }
433
+ }
434
+ }
435
+ return this.readItem();
436
+ }
437
+ /**
438
+ * Reads a serialized integer value from the current buffer position.
439
+ * @returns Parsed integer value or {@link RValues.NaInteger}.
440
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L396-L420 | R source: inInteger}
441
+ */
442
+ inInteger() {
443
+ switch (this.format) {
444
+ case SerializationFormat.Ascii: {
445
+ const word = this.inWord(128);
446
+ if (word === 'NA') {
447
+ return RValues.NaInteger;
448
+ }
449
+ const i = Number.parseInt(word, 10);
450
+ if (Number.isNaN(i)) {
451
+ throw new TypeError(`${word} (or ${i}) is not a number`);
452
+ }
453
+ return i;
454
+ }
455
+ case SerializationFormat.Binary: {
456
+ const i = this.buffer.readInt32LE(this.offset);
457
+ this.offset += 4;
458
+ return i;
459
+ }
460
+ case SerializationFormat.Xdr: {
461
+ const i = this.buffer.readInt32BE(this.offset);
462
+ this.offset += 4;
463
+ return i;
464
+ }
465
+ default:
466
+ return RValues.NaInteger;
467
+ }
468
+ }
469
+ /**
470
+ * Advances the buffer offset past a serialized integer value.
471
+ *
472
+ * Mirrors {@link inInteger}.
473
+ */
474
+ skipInteger() {
475
+ if (this.format === SerializationFormat.Ascii) {
476
+ this.skipWord();
477
+ }
478
+ else if (this.format === SerializationFormat.Binary || this.format === SerializationFormat.Xdr) {
479
+ this.offset += 4;
480
+ }
481
+ else {
482
+ return;
483
+ }
484
+ }
485
+ /**
486
+ * Ensures that the given value is not {@link RValues.NaInteger}.
487
+ * @param value - Integer value to be tested.
488
+ * @returns The validated integer value.
489
+ * @throws Error if the value equals `RValues.NaInteger`.
490
+ */
491
+ assertInteger(value) {
492
+ if (value === RValues.NaInteger) {
493
+ throw new Error('Unexpected NA integer');
494
+ }
495
+ return value;
496
+ }
497
+ /**
498
+ * Ensures that the given object is not {@link RValues.NilValue}.
499
+ * @param obj - R object to validate.
500
+ * @returns The validated {@link RObjectData}.
501
+ * @throws Error if the object equals {@link RValues.NilValue}.
502
+ */
503
+ assertRObjectData(obj) {
504
+ if (obj === RValues.NilValue) {
505
+ throw new Error('Unexpected NilValue');
506
+ }
507
+ return obj;
508
+ }
509
+ /**
510
+ * Reads an ASCII word from the input buffer.
511
+ * @param size - Maximum allowed word size.
512
+ * @returns The parsed word.
513
+ * @throws Error if EOF is reached or the word exceeds the allowed size.
514
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L378-L394 | R source: inWord}
515
+ */
516
+ inWord(size) {
517
+ let i = 0;
518
+ let c;
519
+ const word = new Array(size);
520
+ do {
521
+ c = this.inChar();
522
+ if (c === -1) {
523
+ throw new Error('Read character is -1.');
524
+ }
525
+ } while (this.isSpace(c));
526
+ while (!this.isSpace(c) && i < size) {
527
+ word[i++] = String.fromCodePoint(c);
528
+ c = this.inChar();
529
+ }
530
+ if (i >= size) {
531
+ throw new Error(`$\{i} >= ${size} when reading word.`);
532
+ }
533
+ return word.join('');
534
+ }
535
+ /**
536
+ * Skips an ASCII word in the input buffer.
537
+ *
538
+ * Mirrors {@link inWord}
539
+ * @returns An empty string.
540
+ * @throws Error if EOF is reached or the word exceeds {@link RDAParser.WORD_SIZE}.
541
+ */
542
+ skipWord() {
543
+ let c;
544
+ let i = 0;
545
+ do {
546
+ c = this.inChar();
547
+ if (c === -1) {
548
+ throw new Error('Read character is -1.');
549
+ }
550
+ } while (this.isSpace(c));
551
+ while (!this.isSpace(c) && i < RDAParser.WORD_SIZE) {
552
+ i++;
553
+ c = this.inChar();
554
+ }
555
+ if (i >= RDAParser.WORD_SIZE) {
556
+ throw new Error(`$\{i} >= ${RDAParser.WORD_SIZE} when reading word.`);
557
+ }
558
+ return '';
559
+ }
560
+ /**
561
+ * Reads the next character from the input buffer.
562
+ * @returns The next character or `-1` on EOF.
563
+ */
564
+ inChar() {
565
+ if (this.offset >= this.buffer.length) {
566
+ return -1;
567
+ }
568
+ const char = this.buffer[this.offset];
569
+ this.offset++;
570
+ return char;
571
+ }
572
+ /**
573
+ * Checks whether the given byte represents a whitespace character.
574
+ * @param c - Character code to check.
575
+ * @returns `true` if the character is whitespace.
576
+ */
577
+ isSpace(c) {
578
+ return c >= 9 && c <= 13 || c === 32;
579
+ }
580
+ /**
581
+ * Reads a serialized string from the buffer.
582
+ * @param len - Length of the serialized string.
583
+ * @returns Decoded string.
584
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L505-L550 | R source: inString}
585
+ */
586
+ inString(len) {
587
+ if (this.format === SerializationFormat.Ascii) {
588
+ if (len > 0) {
589
+ const result = [];
590
+ while (this.offset < this.buffer.length) {
591
+ const c = this.buffer[this.offset++];
592
+ if (!this.isSpace(c)) {
593
+ break;
594
+ }
595
+ }
596
+ this.offset--;
597
+ for (let i = 0; i < len; i++) {
598
+ let c = String.fromCodePoint(this.buffer[this.offset++]);
599
+ if (c === '\\') {
600
+ c = String.fromCodePoint(this.buffer[this.offset++]);
601
+ switch (c) {
602
+ case 'n':
603
+ result.push('\n');
604
+ break;
605
+ case 't':
606
+ result.push('\t');
607
+ break;
608
+ case 'v':
609
+ result.push('\v');
610
+ break;
611
+ case 'b':
612
+ result.push('\b');
613
+ break;
614
+ case 'r':
615
+ result.push('\r');
616
+ break;
617
+ case 'f':
618
+ result.push('\f');
619
+ break;
620
+ case 'a':
621
+ result.push('\x07');
622
+ break; // \a
623
+ case '\\':
624
+ result.push('\\');
625
+ break;
626
+ case '?':
627
+ result.push('?');
628
+ break;
629
+ case '\'':
630
+ result.push('\'');
631
+ break;
632
+ case '"':
633
+ result.push('"');
634
+ break;
635
+ case '0':
636
+ case '1':
637
+ case '2':
638
+ case '3':
639
+ case '4':
640
+ case '5':
641
+ case '6':
642
+ case '7': {
643
+ let d = 0;
644
+ let j = 0;
645
+ while ('0' <= c && c < '8' && j < 3) {
646
+ d = d * 8 + (Number.parseInt(c));
647
+ c = String.fromCodePoint(this.buffer[this.offset++]);
648
+ j++;
649
+ }
650
+ result.push(String.fromCodePoint(d));
651
+ this.offset--;
652
+ break;
653
+ }
654
+ default:
655
+ result.push(c);
656
+ }
657
+ }
658
+ else {
659
+ result.push(c);
660
+ }
661
+ }
662
+ return result.join('');
663
+ }
664
+ return '';
665
+ }
666
+ else {
667
+ const bytes = this.buffer.subarray(this.offset, this.offset + len);
668
+ this.offset += len;
669
+ return bytes.toString('latin1');
670
+ }
671
+ }
672
+ /**
673
+ * Skips a serialized string depending on the current serialization format.
674
+ *
675
+ * Mirrors {@link inString}
676
+ * @param len - Length of the serialized string.
677
+ */
678
+ skipString(len) {
679
+ if (this.format === SerializationFormat.Ascii) {
680
+ if (len > 0) {
681
+ while (this.offset < this.buffer.length) {
682
+ const c = this.buffer[this.offset++];
683
+ if (!this.isSpace(c)) {
684
+ break;
685
+ }
686
+ }
687
+ this.offset--;
688
+ for (let i = 0; i < len; i++) {
689
+ let c = String.fromCodePoint(this.buffer[this.offset++]);
690
+ if (c === '\\') {
691
+ c = String.fromCodePoint(this.buffer[this.offset++]);
692
+ switch (c) {
693
+ case '0':
694
+ case '1':
695
+ case '2':
696
+ case '3':
697
+ case '4':
698
+ case '5':
699
+ case '6':
700
+ case '7': {
701
+ let j = 0;
702
+ while ('0' <= c && c < '8' && j < 3) {
703
+ c = String.fromCodePoint(this.buffer[this.offset++]);
704
+ j++;
705
+ }
706
+ this.offset--;
707
+ break;
708
+ }
709
+ }
710
+ }
711
+ }
712
+ }
713
+ }
714
+ else {
715
+ this.offset += len;
716
+ }
717
+ }
718
+ /**
719
+ * Decodes an R writer version integer into v, p, and s.
720
+ * @param writerVersion - Encoded writer version.
721
+ * @returns Tuple containing version components `[v,p,s]`.
722
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2230-L2235 | R source: decodeVersion}
723
+ */
724
+ decodeVersion(writerVersion) {
725
+ const v = writerVersion / RDAParser.MAX_VECTOR_LENGTH;
726
+ writerVersion = writerVersion % RDAParser.MAX_VECTOR_LENGTH;
727
+ const p = writerVersion / 2 ** 8;
728
+ writerVersion = writerVersion % 2 ** 8;
729
+ const s = writerVersion;
730
+ return [v, p, s];
731
+ }
732
+ /**
733
+ * Reads the next flags and dispatches to {@link readItemRecursive}.
734
+ * This is the main recursive entry point called for every R object encountered
735
+ * during deserialization.
736
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2117-L2121 | R source: ReadItem}
737
+ */
738
+ readItem() {
739
+ const flags = this.assertInteger(this.inInteger());
740
+ return this.readItemRecursive(flags);
741
+ }
742
+ /**
743
+ * Resolves a namespace reference by name using `getNamespace()` in R.
744
+ * Simpler variant of {@link R_FindNamespace1}.
745
+ * @param info - The {@link RObjectData} holding the namespace/package info.
746
+ * @returns An {@link RObjectData} of type {@link SexpType.EnvSxp} whose
747
+ * `value` is set to the resolved environment. Currently only
748
+ * `R_GlobalEnv` is handled; other results are logged as warnings.
749
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3795-L3804 | R source: R_FindNamespace}
750
+ */
751
+ R_FindNamespace(info) {
752
+ const namespaceName = info.value.name;
753
+ const code = `getNamespace("${namespaceName}")`;
754
+ const shell = new shell_executor_1.RShellExecutor();
755
+ const result = shell.run(code);
756
+ shell.close();
757
+ const val = {};
758
+ val.type = SexpType.EnvSxp;
759
+ if (result === '<environment: R_GlobalEnv>') {
760
+ val.value = RValues.GlobalEnv;
761
+ }
762
+ return val;
763
+ }
764
+ /**
765
+ * Resolves a serialized namespace reference by executing R at runtime.
766
+ * @param info - The {@link RObjectData} holding the namespace/package info.
767
+ * @returns An {@link RObjectData} of type {@link SexpType.EnvSxp} whose
768
+ * `value` is set to the resolved environment. Currently only
769
+ * `R_GlobalEnv` is handled; other results are logged as warnings.
770
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1785-L1796 | R source: R_FindNamespace1}
771
+ */
772
+ R_FindNamespace1(info) {
773
+ const where = {};
774
+ where.type = SexpType.CharSxp;
775
+ where.value = this.lastName;
776
+ const code = `..getNamespace("${info.value[0].name}", "${where.value}")`;
777
+ const shell = new shell_executor_1.RShellExecutor();
778
+ const result = shell.run(code);
779
+ shell.close();
780
+ const val = {};
781
+ val.type = SexpType.EnvSxp;
782
+ if (result == '<environment: R_GlobalEnv>') {
783
+ val.value = RValues.GlobalEnv;
784
+ }
785
+ return val;
786
+ }
787
+ /**
788
+ * Deserializes a single SEXP node recursively.
789
+ *
790
+ * The method dispatches to the corresponding deserialization logic
791
+ * depending on the encoded {@link SexpType}.
792
+ * @param flags - Serialized SEXP flags word.
793
+ * @returns Deserialized {@link RObjectData}.
794
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1871-L2115 | R source: ReadItem_Recursive}
795
+ */
796
+ readItemRecursive(flags) {
797
+ const [type, levels, object, hasAttribute, _hasTag] = this.unpackFlags(flags);
798
+ let s = {};
799
+ switch (type) {
800
+ case SexpType.NilValueSxp:
801
+ s.value = RValues.NilValue;
802
+ s.type = SexpType.NilSxp;
803
+ return s;
804
+ case SexpType.EmptyEnvSxp:
805
+ s.value = RValues.EmptyEnv;
806
+ s.type = SexpType.EnvSxp;
807
+ return s;
808
+ case SexpType.BaseEnvSxp:
809
+ s.value = RValues.BaseEnv;
810
+ s.type = SexpType.EnvSxp;
811
+ return s;
812
+ case SexpType.GlobalEnvSxp:
813
+ s.value = RValues.GlobalEnv;
814
+ s.type = SexpType.EnvSxp;
815
+ return s;
816
+ case SexpType.UnboundValueSxp:
817
+ s.value = RValues.UnboundValue;
818
+ s.type = SexpType.EnvSxp;
819
+ return s;
820
+ case SexpType.MissingArgSxp:
821
+ s.value = RValues.MissingArg;
822
+ s.type = SexpType.EnvSxp;
823
+ return s;
824
+ case SexpType.BaseNamespaceSxp:
825
+ s.value = RValues.BaseNamespace;
826
+ s.type = SexpType.EnvSxp;
827
+ return s;
828
+ case SexpType.RefSxp: return this.getReadRef(this.inRefIndex(flags));
829
+ case SexpType.PersistSxp: {
830
+ s = this.inStringVec();
831
+ this.addReadRef(s);
832
+ return s;
833
+ }
834
+ case SexpType.AltRepSxp:
835
+ {
836
+ this.currentDepth++;
837
+ console.warn('AltReps are not supported yet!');
838
+ const info = this.readItem();
839
+ const state = this.readItem();
840
+ const attr = this.readItem();
841
+ s.type = info.cdr.cdr.car.type;
842
+ s = this.AltRepUnserializeEx(info, state, attr, object, levels);
843
+ this.currentDepth--;
844
+ return s;
845
+ }
846
+ case SexpType.SymSxp: {
847
+ this.currentDepth++;
848
+ s = this.assertRObjectData(this.readItem());
849
+ this.currentDepth--;
850
+ s.type = SexpType.SymSxp;
851
+ this.addReadRef(s);
852
+ return s;
853
+ }
854
+ case SexpType.PackageSxp:
855
+ {
856
+ s = this.inStringVec();
857
+ s = this.rFindPackageEnv(s);
858
+ this.addReadRef(s);
859
+ return s;
860
+ }
861
+ case SexpType.NamespaceSxp:
862
+ s = this.inStringVec();
863
+ s = this.R_FindNamespace1(s);
864
+ this.addReadRef(s);
865
+ return s;
866
+ case SexpType.EnvSxp:
867
+ {
868
+ const locked = this.inInteger();
869
+ s.type = SexpType.EnvSxp;
870
+ this.addReadRef(s);
871
+ this.currentDepth++;
872
+ this.SetEnClos(s, this.assertRObjectData(this.readItem()));
873
+ s.frame = this.readItem();
874
+ s.hashTab = this.readItem();
875
+ s.attributes = this.assertRObjectData(this.readItem()).attributes;
876
+ this.currentDepth--;
877
+ if (s.attributes?.some(e => e.name === RValues.ClassSymbol)) {
878
+ s._isObject = true;
879
+ }
880
+ // R_RestoreHashCount(s);
881
+ if (locked) {
882
+ s._isLocked = false;
883
+ }
884
+ if (!s.enClos || s.enClos === RValues.NilValue) {
885
+ this.SetEnClos(s, {
886
+ value: RValues.BaseEnv,
887
+ type: SexpType.EnvSxp,
888
+ enClos: RValues.NilValue
889
+ });
890
+ }
891
+ return s;
892
+ }
893
+ case SexpType.ListSxp:
894
+ case SexpType.LangSxp:
895
+ case SexpType.CloSxp:
896
+ case SexpType.PromSxp:
897
+ case SexpType.DotSxp:
898
+ return this.readItemIterative(flags);
899
+ default:
900
+ switch (type) {
901
+ case SexpType.ExtPtrSxp: {
902
+ s.type = type;
903
+ this.addReadRef(s);
904
+ s.address = null;
905
+ this.currentDepth++;
906
+ s.protected = this.readItem();
907
+ s.tag = this.readItem();
908
+ this.currentDepth--;
909
+ break;
910
+ }
911
+ case SexpType.WeakRefSxp:
912
+ s.value = this.R_MakeWeakRef({ type: SexpType.NilSxp, value: RValues.NilValue }, RValues.NilValue, { type: SexpType.NilSxp, value: RValues.NilValue }, false);
913
+ this.addReadRef(s);
914
+ break;
915
+ case SexpType.SpecialSxp:
916
+ case SexpType.BuiltInSxp:
917
+ {
918
+ const len = this.assertInteger(this.inInteger());
919
+ if (len < 0) {
920
+ throw new Error('invalid length');
921
+ }
922
+ const name = this.inString(len);
923
+ const index = r_fun_tab_1.RFunTabOffsets[name];
924
+ if (name in r_fun_tab_1.RFunTabOffsets) {
925
+ s = this.mkPrimSxp(index, type === SexpType.BuiltInSxp ? 1 : 0);
926
+ }
927
+ else {
928
+ s.value = RValues.NilValue;
929
+ throw new Error(`unrecognized internal function name "${name}"`);
930
+ }
931
+ }
932
+ break;
933
+ case SexpType.CharSxp: {
934
+ const len = this.assertInteger(this.inInteger());
935
+ if (len < -1) {
936
+ throw new Error(`Invalid length ${len} of string.`);
937
+ }
938
+ else if (len == -1) {
939
+ s.name = RValues.NaString;
940
+ }
941
+ else if (len < 1000) {
942
+ s.name = this.readChar(len, levels);
943
+ }
944
+ else {
945
+ s.name = this.readChar(len, levels);
946
+ }
947
+ break;
948
+ }
949
+ case SexpType.LglSxp:
950
+ case SexpType.IntSxp:
951
+ {
952
+ const len = this.readLength();
953
+ s.type = type;
954
+ s.value = this.inIntegerVec(len);
955
+ break;
956
+ }
957
+ case SexpType.RealSxp:
958
+ {
959
+ const len = this.readLength();
960
+ s.type = type;
961
+ s.value = this.inRealVec(len);
962
+ break;
963
+ }
964
+ case SexpType.CplxSxp: {
965
+ const len = this.readLength();
966
+ s.type = type;
967
+ s.value = this.inComplexVec(len);
968
+ break;
969
+ }
970
+ case SexpType.StrSxp: {
971
+ const len = this.readLength();
972
+ s.type = type;
973
+ s.value = new Array(len);
974
+ this.currentDepth++;
975
+ for (let count = 0; count < len; ++count) {
976
+ this.SET_STRING_ELT(s, count, this.assertRObjectData(this.readItem()));
977
+ }
978
+ this.currentDepth--;
979
+ break;
980
+ }
981
+ case SexpType.VecSxp:
982
+ case SexpType.ExprSxp: {
983
+ const len = this.readLength();
984
+ s.type = type;
985
+ s.value = new Array(len);
986
+ this.currentDepth++;
987
+ for (let count = 0; count < len; ++count) {
988
+ this.SET_VECTOR_ELT(s, count, this.readItem());
989
+ }
990
+ this.currentDepth--;
991
+ break;
992
+ }
993
+ case SexpType.BcodesSxp:
994
+ s = this.readBC();
995
+ break;
996
+ case SexpType.ClassRefSxp:
997
+ throw new Error('this version of R cannot read class references');
998
+ case SexpType.GenericRefSxp:
999
+ throw new Error('this version of R cannot read generic function references');
1000
+ case SexpType.RawSxp: {
1001
+ const len = this.readLength();
1002
+ s.type = type;
1003
+ s.value = this.inRaw(len);
1004
+ break;
1005
+ }
1006
+ case SexpType.ObjSxp:
1007
+ s.type = SexpType.ObjSxp;
1008
+ break;
1009
+ default:
1010
+ throw new Error(`ReadItem: unknown type ${type}, perhaps written by later version of R`);
1011
+ }
1012
+ if (type !== SexpType.CharSxp) {
1013
+ s.levels = levels;
1014
+ }
1015
+ s.object = object;
1016
+ if (s.type === SexpType.CharSxp) {
1017
+ this.currentDepth++;
1018
+ if (hasAttribute) {
1019
+ this.readItem();
1020
+ }
1021
+ this.currentDepth--;
1022
+ }
1023
+ else {
1024
+ this.currentDepth++;
1025
+ s.attributes = hasAttribute ? [this.readItem()] : undefined;
1026
+ this.currentDepth--;
1027
+ }
1028
+ if (s.type === SexpType.BcodesSxp && !this.R_BCVersionOK(s)) {
1029
+ return this.R_BytecodeExpr(s);
1030
+ }
1031
+ return s;
1032
+ }
1033
+ }
1034
+ /**
1035
+ * Skips a serialized SEXP node, only filling in its type and calling other skip methods to
1036
+ * advance the buffer position.
1037
+ *
1038
+ * Mirrors the structure of {@link readItemRecursive} but skips payload data.
1039
+ * @returns A minimal {@link RObjectData} with little to no payload.
1040
+ */
1041
+ skipItem() {
1042
+ const flags = this.assertInteger(this.inInteger());
1043
+ const [type, levels, _object, hasAttribute, _hasTag] = this.unpackFlags(flags);
1044
+ let s = {};
1045
+ switch (type) {
1046
+ case SexpType.NilValueSxp:
1047
+ case SexpType.EmptyEnvSxp:
1048
+ case SexpType.BaseEnvSxp:
1049
+ case SexpType.GlobalEnvSxp:
1050
+ case SexpType.UnboundValueSxp:
1051
+ case SexpType.MissingArgSxp:
1052
+ case SexpType.BaseNamespaceSxp:
1053
+ s.type = SexpType.EnvSxp;
1054
+ return s;
1055
+ case SexpType.RefSxp:
1056
+ return this.getReadRef(this.inRefIndex(flags));
1057
+ case SexpType.NamespaceSxp:
1058
+ this.skipStringVec();
1059
+ s.type = SexpType.EnvSxp;
1060
+ this.addReadRef(s);
1061
+ return s;
1062
+ case SexpType.PackageSxp:
1063
+ case SexpType.PersistSxp: {
1064
+ this.skipStringVec();
1065
+ s.type = SexpType.CharSxp;
1066
+ return s;
1067
+ }
1068
+ case SexpType.AltRepSxp:
1069
+ {
1070
+ this.currentDepth++;
1071
+ const info = this.skipItem();
1072
+ const _state = this.skipItem();
1073
+ const _attr = this.skipItem();
1074
+ s.type = info.cdr.cdr.car.type;
1075
+ this.currentDepth--;
1076
+ return s;
1077
+ }
1078
+ case SexpType.SymSxp: {
1079
+ this.currentDepth++;
1080
+ s = this.skipItem();
1081
+ this.currentDepth--;
1082
+ s.type = SexpType.SymSxp;
1083
+ this.addReadRef(s);
1084
+ return s;
1085
+ }
1086
+ case SexpType.EnvSxp:
1087
+ {
1088
+ this.skipInteger();
1089
+ s.type = SexpType.EnvSxp;
1090
+ this.addReadRef(s);
1091
+ this.currentDepth++;
1092
+ this.SetEnClos(s, this.assertRObjectData(this.skipItem()));
1093
+ s.frame = this.skipItem();
1094
+ s.hashTab = this.skipItem();
1095
+ s.attributes = this.assertRObjectData(this.skipItem()).attributes;
1096
+ this.currentDepth--;
1097
+ if (!s.enClos || s.enClos === RValues.NilValue) {
1098
+ this.SetEnClos(s, {
1099
+ value: RValues.BaseEnv,
1100
+ type: SexpType.EnvSxp,
1101
+ enClos: RValues.NilValue
1102
+ });
1103
+ }
1104
+ return s;
1105
+ }
1106
+ case SexpType.ListSxp:
1107
+ case SexpType.LangSxp:
1108
+ case SexpType.CloSxp:
1109
+ case SexpType.PromSxp:
1110
+ case SexpType.DotSxp:
1111
+ return this.readItemIterative(flags);
1112
+ default:
1113
+ switch (type) {
1114
+ case SexpType.ExtPtrSxp: {
1115
+ s.type = type;
1116
+ this.addReadRef(s);
1117
+ this.currentDepth++;
1118
+ s.protected = this.skipItem();
1119
+ s.tag = this.skipItem();
1120
+ this.currentDepth--;
1121
+ break;
1122
+ }
1123
+ case SexpType.WeakRefSxp:
1124
+ s.value = this.R_MakeWeakRef({ type: SexpType.NilSxp, value: RValues.NilValue }, RValues.NilValue, { type: SexpType.NilSxp, value: RValues.NilValue }, false);
1125
+ this.addReadRef(s);
1126
+ break;
1127
+ case SexpType.SpecialSxp:
1128
+ case SexpType.BuiltInSxp:
1129
+ {
1130
+ s.type = type;
1131
+ const len = this.assertInteger(this.inInteger());
1132
+ if (len < 0) {
1133
+ throw new Error('invalid length');
1134
+ }
1135
+ this.skipString(len);
1136
+ }
1137
+ break;
1138
+ case SexpType.CharSxp: {
1139
+ const len = this.assertInteger(this.inInteger());
1140
+ if (len < -1) {
1141
+ throw new Error(`Invalid length ${len} of string.`);
1142
+ }
1143
+ else if (len == -1) {
1144
+ s.name = RValues.NaString;
1145
+ }
1146
+ else if (len < 1000) {
1147
+ s.name = this.readChar(len, levels);
1148
+ }
1149
+ else {
1150
+ s.name = this.readChar(len, levels);
1151
+ }
1152
+ break;
1153
+ }
1154
+ case SexpType.LglSxp:
1155
+ case SexpType.IntSxp:
1156
+ {
1157
+ const len = this.readLength();
1158
+ s.type = type;
1159
+ s.value = this.skipIntegerVec(len);
1160
+ break;
1161
+ }
1162
+ case SexpType.RealSxp:
1163
+ {
1164
+ const len = this.readLength();
1165
+ s.type = type;
1166
+ s.value = this.skipRealVec(len);
1167
+ break;
1168
+ }
1169
+ case SexpType.CplxSxp: {
1170
+ const len = this.readLength();
1171
+ s.type = type;
1172
+ this.skipComplexVec(len);
1173
+ break;
1174
+ }
1175
+ case SexpType.StrSxp:
1176
+ case SexpType.VecSxp:
1177
+ case SexpType.ExprSxp: {
1178
+ const len = this.readLength();
1179
+ s.type = type;
1180
+ this.currentDepth++;
1181
+ for (let count = 0; count < len; ++count) {
1182
+ this.skipItem();
1183
+ }
1184
+ this.currentDepth--;
1185
+ break;
1186
+ }
1187
+ case SexpType.BcodesSxp:
1188
+ this.skipBC();
1189
+ s.type = SexpType.VecSxp;
1190
+ break;
1191
+ case SexpType.ClassRefSxp:
1192
+ throw new Error('this version of R cannot read class references');
1193
+ case SexpType.GenericRefSxp:
1194
+ throw new Error('this version of R cannot read generic function references');
1195
+ case SexpType.RawSxp: {
1196
+ const len = this.readLength();
1197
+ s.type = type;
1198
+ this.skipRaw(len);
1199
+ break;
1200
+ }
1201
+ case SexpType.ObjSxp:
1202
+ s.type = SexpType.ObjSxp;
1203
+ break;
1204
+ default:
1205
+ throw new Error(`ReadItem: unknown type ${type}, perhaps written by later version of R`);
1206
+ }
1207
+ if (s.type === SexpType.CharSxp) {
1208
+ this.currentDepth++;
1209
+ if (hasAttribute) {
1210
+ this.skipItem();
1211
+ }
1212
+ this.currentDepth--;
1213
+ }
1214
+ else {
1215
+ this.currentDepth++;
1216
+ s.attributes = hasAttribute ? [this.skipItem()] : undefined;
1217
+ this.currentDepth--;
1218
+ }
1219
+ return s;
1220
+ }
1221
+ }
1222
+ /**
1223
+ * Reads `len` raw bytes from the buffer into a number array.
1224
+ * @param len - Number of raw bytes to read.
1225
+ * @returns Array of unsigned byte values.
1226
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2062-L2084 | R source: ReadItem_Recursive}
1227
+ */
1228
+ inRaw(len) {
1229
+ const result = [];
1230
+ switch (this.format) {
1231
+ case SerializationFormat.Ascii:
1232
+ for (let ix = 0; ix < len; ix++) {
1233
+ const word = this.inWord(128);
1234
+ result[ix] = Number.parseInt(word, 16);
1235
+ }
1236
+ break;
1237
+ default: {
1238
+ let t = 0;
1239
+ for (let done = 0; done < len; done += t) {
1240
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1241
+ for (let i = 0; i < t; i++) {
1242
+ result[done + i] = this.buffer[this.offset];
1243
+ this.offset += 1;
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+ return result;
1249
+ }
1250
+ /**
1251
+ * Advances the buffer offset past `len` raw bytes without reading values.
1252
+ *
1253
+ * Mirrors {@link inRaw}.
1254
+ * @param len - Number of raw bytes to skip.
1255
+ */
1256
+ skipRaw(len) {
1257
+ if (this.format === SerializationFormat.Ascii) {
1258
+ for (let ix = 0; ix < len; ix++) {
1259
+ this.skipWord();
1260
+ }
1261
+ }
1262
+ else {
1263
+ let t = 0;
1264
+ for (let done = 0; done < len; done += t) {
1265
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1266
+ for (let i = 0; i < t; i++) {
1267
+ this.offset += 1;
1268
+ }
1269
+ }
1270
+ }
1271
+ }
1272
+ /**
1273
+ * Resolves package environments.
1274
+ * @param s - String-vec {@link RObject} identifying the package.
1275
+ *
1276
+ * Not implemented yet!
1277
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3732-L3741 | R source: R_FindPackageEnv}
1278
+ */
1279
+ rFindPackageEnv(s) {
1280
+ console.warn('Resolving package environments was triggered, but is not implemented yet!');
1281
+ return s;
1282
+ }
1283
+ /**
1284
+ * Decodes the SEXP flags.
1285
+ * @param flags - Raw 32-bit flags word.
1286
+ * @returns `[type, levels, isObject, hasAttribute, hasTag]`.
1287
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L748-L756 | R source: UnpackFlags}
1288
+ */
1289
+ unpackFlags(flags) {
1290
+ const pType = flags & 255;
1291
+ const pLevels = flags >> 12;
1292
+ const pIsObj = (flags & (1 << 8)) !== 0;
1293
+ const pHasAttr = (flags & (1 << 9)) !== 0;
1294
+ const pHasTag = (flags & (1 << 10)) !== 0;
1295
+ return [pType, pLevels, pIsObj, pHasAttr, pHasTag];
1296
+ }
1297
+ /**
1298
+ * Retrieves an object from the reference table.
1299
+ * @param index - 1-based reference index.
1300
+ * @returns A registered {@link RObjectData}.
1301
+ * @throws Error if the index is out of range.
1302
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1461-L1469 | R source: GetReadRef}
1303
+ */
1304
+ getReadRef(index) {
1305
+ const i = index - 1;
1306
+ if (i < 0 || i >= this.refTable.length) {
1307
+ throw new Error('reference index out of range');
1308
+ }
1309
+ return this.refTable[i];
1310
+ }
1311
+ /**
1312
+ * Extracts the reference index from the given flags.
1313
+ *
1314
+ * When bits 8–31 are non-zero they encode the index directly;
1315
+ * otherwise the index is read as the next integer from the stream.
1316
+ * @param flags - Raw 32-bit flags word.
1317
+ * @returns A 1-based reference index.
1318
+ * @see {@link http://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L782-L789 | R source: InRefIndex}
1319
+ */
1320
+ inRefIndex(flags) {
1321
+ const i = flags >> 8;
1322
+ if (i === 0) {
1323
+ return this.assertInteger(this.inInteger());
1324
+ }
1325
+ else {
1326
+ return i;
1327
+ }
1328
+ }
1329
+ /**
1330
+ * Appends an object to the reference table so it can be resolved later by {@link getReadRef}.
1331
+ * @param value - The {@link RObject} to register.
1332
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1471-L1490 | R source: AddReadRef}
1333
+ */
1334
+ addReadRef(value) {
1335
+ this.refTable.push(value);
1336
+ }
1337
+ /**
1338
+ * Reads a persistent string vector from the stream.
1339
+ * @returns An {@link RObjectData} of type `CharSxp` whose `value` array holds the deserialized string items.
1340
+ * @throws Error if the names flag is non-zero.
1341
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1492-L1504 | R source: InStringVec}
1342
+ */
1343
+ inStringVec() {
1344
+ if (this.inInteger() !== 0) {
1345
+ throw new Error('names in persistent strings are not supported yet');
1346
+ }
1347
+ const len = this.assertInteger(this.inInteger());
1348
+ const s = {};
1349
+ s.type = SexpType.CharSxp;
1350
+ s.value = new Array(len);
1351
+ this.currentDepth++;
1352
+ for (let i = 0; i < len; i++) {
1353
+ (s.value)[i] = this.readItem();
1354
+ }
1355
+ this.currentDepth--;
1356
+ return s;
1357
+ }
1358
+ /**
1359
+ * Advances the buffer past a persistent string vector without reading values.
1360
+ *
1361
+ * Mirrors {@link inStringVec}.
1362
+ * @throws Error if the names flag is non-zero.
1363
+ */
1364
+ skipStringVec() {
1365
+ if (this.inInteger() !== 0) {
1366
+ throw new Error('names in persistent strings are not supported yet');
1367
+ }
1368
+ const len = this.assertInteger(this.inInteger());
1369
+ this.currentDepth++;
1370
+ for (let i = 0; i < len; i++) {
1371
+ this.skipItem();
1372
+ }
1373
+ this.currentDepth--;
1374
+ }
1375
+ /**
1376
+ * Sets the enclosing environment of an environment object.
1377
+ * @param x - Environment whose enclosure should be set.
1378
+ * @param v - Parent environment.
1379
+ * @throws Error if the parent is invalid or would introduce a cycle.
1380
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L4677-L4690 | R source: SET_ENCLOS}
1381
+ */
1382
+ SetEnClos(x, v) {
1383
+ if (v.value === undefined || v.value === RValues.NilValue) {
1384
+ v.value = RValues.EmptyEnv;
1385
+ }
1386
+ if (v.type !== SexpType.EnvSxp) {
1387
+ throw new Error("'parent' is not an environment");
1388
+ }
1389
+ for (let e = v; e !== RValues.NilValue; e = e.enClos ?? RValues.NilValue) {
1390
+ if (e === x) {
1391
+ throw new Error('cycles in parent chains are not allowed');
1392
+ }
1393
+ }
1394
+ x.enClos = v;
1395
+ }
1396
+ /**
1397
+ * Iteratively deserializes linked-list based SEXP structures.
1398
+ * @param flags - Initial flags.
1399
+ * @returns Head node of the reconstructed pairlist chain as {@link RObjectData}.
1400
+ * @throws Error if the initial type is not a valid pairlist type.
1401
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1800-L1868 | R source: ReadItem_Iterative}
1402
+ */
1403
+ readItemIterative(flags) {
1404
+ let sFirst = null;
1405
+ let sLast = {};
1406
+ let type = flags & 255;
1407
+ const validIterativeTypes = new Set([
1408
+ SexpType.ListSxp, // 2
1409
+ SexpType.LangSxp, // 6
1410
+ SexpType.CloSxp, // 3
1411
+ SexpType.PromSxp, // 5
1412
+ SexpType.DotSxp // 17
1413
+ ]);
1414
+ if (!validIterativeTypes.has(type)) {
1415
+ throw new Error('Wrong type.');
1416
+ }
1417
+ while (validIterativeTypes.has(type)) {
1418
+ const unpackedFlags = this.unpackFlags(flags);
1419
+ type = unpackedFlags[0];
1420
+ const levels = unpackedFlags[1];
1421
+ const isObject = unpackedFlags[2];
1422
+ const hasAttr = unpackedFlags[3];
1423
+ const hasTag = unpackedFlags[4];
1424
+ const s = {};
1425
+ s.type = type;
1426
+ s.levels = levels;
1427
+ s.object = isObject;
1428
+ this.currentDepth++;
1429
+ s.attributes = hasAttr ? [this.shortcut ? this.skipItem() : this.assertRObjectData(this.readItem())] : undefined;
1430
+ s.tag = hasTag ? this.readItem() : RValues.NilValue;
1431
+ if (hasTag && this.currentDepth == RDAParser.INITIAL_DEPTH && typeof s.tag === 'object') {
1432
+ this.lastName = s.tag.name;
1433
+ this.setLastName = true;
1434
+ }
1435
+ s.car = this.shortcut ? this.skipItem() : this.readItem();
1436
+ this.currentDepth--;
1437
+ if (sFirst === null) {
1438
+ sFirst = s;
1439
+ }
1440
+ else {
1441
+ sLast.cdr = s;
1442
+ }
1443
+ sLast = s;
1444
+ if (type === SexpType.CloSxp && (!s.enClos || s.cloEnv === RValues.NilValue)) {
1445
+ s.cloEnv = RValues.EmptyEnv;
1446
+ }
1447
+ else if (type === SexpType.PromSxp && (!s.prEnv || s.prEnv === RValues.NilValue)) {
1448
+ s.prEnv = RValues.BaseEnv;
1449
+ }
1450
+ flags = this.assertInteger(this.inInteger());
1451
+ type = flags & 255;
1452
+ }
1453
+ this.currentDepth++;
1454
+ const s = this.readItemRecursive(flags);
1455
+ this.currentDepth--;
1456
+ sLast.cdr = s;
1457
+ return sFirst;
1458
+ }
1459
+ /**
1460
+ * Creates a weak reference object.
1461
+ * @param key - Weak reference key object.
1462
+ * @param val - Referenced value.
1463
+ * @param fin - Finalizer function or NULL.
1464
+ * @param onexit - Whether the finalizer should run on exit.
1465
+ * @returns The created weak reference object as {@link RObject}.
1466
+ * @throws Error if the finalizer type is invalid.
1467
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L1424-L1435 | R source: R_MakeWeakRef}
1468
+ */
1469
+ R_MakeWeakRef(key, val, fin, onexit) {
1470
+ switch (fin.type) {
1471
+ case SexpType.NilSxp:
1472
+ case SexpType.CloSxp:
1473
+ case SexpType.BuiltInSxp:
1474
+ case SexpType.SpecialSxp:
1475
+ break;
1476
+ default:
1477
+ throw new Error('finalizer must be a function or NULL');
1478
+ }
1479
+ return this.newWeakRef(key, val, fin, onexit);
1480
+ }
1481
+ /**
1482
+ * Allocates and initializes a weak reference object.
1483
+ * @param key - Weak reference key object.
1484
+ * @param val - Referenced value.
1485
+ * @param fin - Finalizer function.
1486
+ * @param onexit - Whether the finalizer should run on exit.
1487
+ * @returns The initialized weak reference object as {@link RObject}.
1488
+ * @throws Error if the key type is invalid.
1489
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L1388-L1422 | R source: NewWeakRef}
1490
+ */
1491
+ newWeakRef(key, val, fin, onexit) {
1492
+ switch (key.type) {
1493
+ case SexpType.NilSxp:
1494
+ case SexpType.EnvSxp:
1495
+ case SexpType.ExtPtrSxp:
1496
+ case SexpType.BcodesSxp:
1497
+ break;
1498
+ default:
1499
+ throw new Error('can only weakly reference/finalize reference objects');
1500
+ }
1501
+ // PROTECT(val = MAYBE_REFERENCED(val) ? duplicate(val) : val);
1502
+ // w = allocVector(VECSXP, WEAKREF_SIZE);
1503
+ // SET_TYPEOF(w, WEAKREFSXP);
1504
+ const w = {};
1505
+ w.type = SexpType.WeakRefSxp;
1506
+ if (key.value !== RValues.NilValue) {
1507
+ w.key = key;
1508
+ w.value = val;
1509
+ w.finalizer = fin;
1510
+ w.next = this.RWeakRefs;
1511
+ // CLEAR_READY_TO_FINALIZE(w);
1512
+ if (w.gp) {
1513
+ w.gp &= ~1;
1514
+ }
1515
+ if (onexit) {
1516
+ if (w.gp) {
1517
+ w.gp |= 2;
1518
+ }
1519
+ }
1520
+ else {
1521
+ if (w.gp) {
1522
+ w.gp &= ~2;
1523
+ }
1524
+ }
1525
+ this.RWeakRefs = w;
1526
+ }
1527
+ return w;
1528
+ }
1529
+ /**
1530
+ * Creates or retrieves a cached primitive function object.
1531
+ * @param index - Primitive function table index.
1532
+ * @param evaluation - Non-zero for {@link SexpType.BuiltInSxp}, zero for {@link SexpType.SpecialSxp}.
1533
+ * @returns of type {@link SexpType.BuiltInSxp} or {@link SexpType.SpecialSxp}.
1534
+ * @throws Error if the index is out of range or the cached type mismatches.
1535
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/dstruct.c#L37-L68 | R source: mkPRIMSXP}
1536
+ */
1537
+ mkPrimSxp(index, evaluation) {
1538
+ const type = evaluation ? SexpType.BuiltInSxp : SexpType.SpecialSxp;
1539
+ let primCache = RValues.NilValue;
1540
+ let funTabSize = 0;
1541
+ if (!primCache || primCache === RValues.NilValue) {
1542
+ funTabSize = Object.keys(r_fun_tab_1.RFunTabOffsets).length;
1543
+ primCache = {};
1544
+ primCache.type = SexpType.VecSxp;
1545
+ primCache.value = new Array(funTabSize);
1546
+ }
1547
+ if (index < 0 || index >= funTabSize) {
1548
+ throw new Error('offset is out of R_FunTab range');
1549
+ }
1550
+ let result = this.VECTOR_ELT(primCache, index);
1551
+ if (!result || result === RValues.NilValue) {
1552
+ result = {};
1553
+ result.type = type;
1554
+ result.offset = index;
1555
+ // SET_VECTOR_ELT(primCache, index, result);
1556
+ }
1557
+ else if (result.type !== type) {
1558
+ throw new Error('requested primitive type is not consistent with cached value');
1559
+ }
1560
+ return result;
1561
+ }
1562
+ /**
1563
+ * Reads `len` bytes as a character string and applies encoding from the GP bits.
1564
+ *
1565
+ * Encoding flags: bit 3 = UTF-8, bit 2 = Latin-1, bit 6 = bytes (returned as-is).
1566
+ * @param len - Number of bytes to read.
1567
+ * @param levels - GP levels bits from the `CharSxp` flags word.
1568
+ * @returns The decoded string, or `''` when the encoding is not yet handled.
1569
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1689-L1759 | R source: ReadChar}
1570
+ */
1571
+ readChar(len, levels) {
1572
+ const cBuf = this.inString(len);
1573
+ const bytes = Buffer.from(cBuf, 'latin1');
1574
+ if (levels & (1 << 3)) {
1575
+ return new TextDecoder('utf-8').decode(bytes);
1576
+ }
1577
+ if (levels & (1 << 2)) {
1578
+ return new TextDecoder('iso-8859-1').decode(bytes);
1579
+ }
1580
+ if (levels & (1 << 6)) {
1581
+ return bytes.toString('latin1');
1582
+ }
1583
+ console.warn('Native encoding detected! Native encoding not supported yet! Value will be empty');
1584
+ return '';
1585
+ }
1586
+ /**
1587
+ * Reads a vector length from the stream.
1588
+ * @returns The vector length.
1589
+ * @throws Error for negative lengths or an invalid high-word value.
1590
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1761-L1782 | R source: ReadLENGTH}
1591
+ */
1592
+ readLength() {
1593
+ const len = this.assertInteger(this.inInteger());
1594
+ if (len < -1) {
1595
+ throw new Error('negative serialized length for vector');
1596
+ }
1597
+ if (len == -1) {
1598
+ const len1 = this.assertInteger(this.inInteger());
1599
+ const len2 = this.assertInteger(this.inInteger());
1600
+ const xLen = len1;
1601
+ /* sanity check for now */
1602
+ if (len1 > RDAParser.MAX_VECTOR_LENGTH) {
1603
+ throw new Error('invalid upper part of serialized vector length');
1604
+ }
1605
+ return (xLen << 32) + len2;
1606
+ }
1607
+ else {
1608
+ return len;
1609
+ }
1610
+ }
1611
+ /**
1612
+ * Reads `len` integers from the buffer.
1613
+ * @param len - Number of integers to read.
1614
+ * @returns Array of integer values or {@link RValues.NaInteger}.
1615
+ * @throws Error for BINARY format or XDR buffer overrun.
1616
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1507-L1541 | R source: InIntegerVec}
1617
+ */
1618
+ inIntegerVec(len) {
1619
+ switch (this.format) {
1620
+ case SerializationFormat.Xdr:
1621
+ {
1622
+ let t = 0;
1623
+ const result = [];
1624
+ for (let done = 0; done < len; done += t) {
1625
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1626
+ for (let cnt = 0; cnt < t; cnt++) {
1627
+ if (this.offset + 4 > this.buffer.length) {
1628
+ throw new Error('XDR read failed');
1629
+ }
1630
+ result[done + cnt] = this.buffer.readInt32BE(this.offset);
1631
+ this.offset += 4;
1632
+ }
1633
+ }
1634
+ return result;
1635
+ }
1636
+ case SerializationFormat.Binary:
1637
+ {
1638
+ throw new Error('No binary support yet.');
1639
+ }
1640
+ default: {
1641
+ const result = [];
1642
+ for (let cnt = 0; cnt < len; cnt++) {
1643
+ result[cnt] = this.inInteger();
1644
+ }
1645
+ return result;
1646
+ }
1647
+ }
1648
+ }
1649
+ /**
1650
+ * Advances the buffer past `len` serialized integers without reading values.
1651
+ *
1652
+ * Mirrors {@link inIntegerVec}.
1653
+ * @param len - Number of integers to skip.
1654
+ * @returns An empty array.
1655
+ * @throws Error for BINARY format or XDR buffer overrun.
1656
+ */
1657
+ skipIntegerVec(len) {
1658
+ switch (this.format) {
1659
+ case SerializationFormat.Xdr:
1660
+ {
1661
+ let t = 0;
1662
+ for (let done = 0; done < len; done += t) {
1663
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1664
+ for (let cnt = 0; cnt < t; cnt++) {
1665
+ if (this.offset + 4 > this.buffer.length) {
1666
+ throw new Error('XDR read failed');
1667
+ }
1668
+ this.offset += 4;
1669
+ }
1670
+ }
1671
+ break;
1672
+ }
1673
+ case SerializationFormat.Binary:
1674
+ {
1675
+ throw new Error('No binary support yet.');
1676
+ }
1677
+ default: {
1678
+ for (let cnt = 0; cnt < len; cnt++) {
1679
+ this.skipInteger();
1680
+ }
1681
+ }
1682
+ }
1683
+ return [];
1684
+ }
1685
+ /**
1686
+ * Reads `len` doubles from the buffer.
1687
+ * @param len - Number of doubles to read.
1688
+ * @returns Array of numbers or {@link RValues}.
1689
+ * @throws Error for BINARY format.
1690
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1543-L1577 | R source: InRealVec}
1691
+ */
1692
+ inRealVec(len) {
1693
+ switch (this.format) {
1694
+ case SerializationFormat.Xdr: {
1695
+ const result = [];
1696
+ let t = 0;
1697
+ for (let done = 0; done < len; done += t) {
1698
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1699
+ const chunkBytes = t * RDAParser.SIZE_OF_DOUBLE;
1700
+ const chunk = this.buffer.subarray(this.offset, this.offset + chunkBytes);
1701
+ this.offset += chunkBytes;
1702
+ for (let i = 0; i < t; i++) {
1703
+ const value = chunk.readDoubleBE(i * RDAParser.SIZE_OF_DOUBLE);
1704
+ result.push(value);
1705
+ }
1706
+ }
1707
+ return result;
1708
+ }
1709
+ case SerializationFormat.Binary:
1710
+ {
1711
+ throw new Error('No binary support yet.');
1712
+ }
1713
+ default: {
1714
+ const result = [];
1715
+ for (let cnt = 0; cnt < len; cnt++) {
1716
+ result[cnt] = this.inReal();
1717
+ }
1718
+ return result;
1719
+ }
1720
+ }
1721
+ }
1722
+ /**
1723
+ * Advances the buffer past `len` serialized doubles without reading values.
1724
+ *
1725
+ * Mirrors {@link inRealVec}.
1726
+ * @param len - Number of doubles to skip.
1727
+ * @returns An empty array.
1728
+ * @throws Error for BINARY format.
1729
+ */
1730
+ skipRealVec(len) {
1731
+ switch (this.format) {
1732
+ case SerializationFormat.Xdr: {
1733
+ let t = 0;
1734
+ for (let done = 0; done < len; done += t) {
1735
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1736
+ const chunkBytes = t * RDAParser.SIZE_OF_DOUBLE;
1737
+ this.offset += chunkBytes;
1738
+ }
1739
+ break;
1740
+ }
1741
+ case SerializationFormat.Binary:
1742
+ {
1743
+ throw new Error('No binary support yet.');
1744
+ }
1745
+ default: {
1746
+ for (let cnt = 0; cnt < len; cnt++) {
1747
+ this.skipReal();
1748
+ }
1749
+ }
1750
+ }
1751
+ return [];
1752
+ }
1753
+ /**
1754
+ * Reads the next double from the buffer.
1755
+ * @returns A number or an {@link RValues}.
1756
+ * @throws TypeError if the ASCII token is not a valid float.
1757
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L427-L463 | R source: InReal}
1758
+ */
1759
+ inReal() {
1760
+ switch (this.format) {
1761
+ case SerializationFormat.Ascii: {
1762
+ const word = this.inWord(128);
1763
+ if (word === 'NA') {
1764
+ return RValues.NaReal;
1765
+ }
1766
+ else if (word === 'NaN') {
1767
+ return RValues.NaN;
1768
+ }
1769
+ else if (word === 'Inf') {
1770
+ return RValues.PosInf;
1771
+ }
1772
+ else if (word === '-Inf') {
1773
+ return RValues.NegInf;
1774
+ }
1775
+ else {
1776
+ const d = Number.parseFloat(word);
1777
+ if (Number.isNaN(d)) {
1778
+ throw new TypeError('Read error: Invalid numeric ASCII format');
1779
+ }
1780
+ return d;
1781
+ }
1782
+ }
1783
+ case SerializationFormat.Binary: {
1784
+ const d = this.buffer.readDoubleLE(this.offset);
1785
+ this.offset += 8;
1786
+ return d;
1787
+ }
1788
+ case SerializationFormat.Xdr: {
1789
+ const d = this.buffer.readDoubleBE(this.offset);
1790
+ this.offset += 8;
1791
+ return d;
1792
+ }
1793
+ default:
1794
+ return RValues.NilValue;
1795
+ }
1796
+ }
1797
+ /**
1798
+ * Advances the buffer past the next serialized double without reading it.
1799
+ *
1800
+ * Mirrors {@link inReal}.
1801
+ */
1802
+ skipReal() {
1803
+ if (this.format === SerializationFormat.Ascii) {
1804
+ this.skipWord();
1805
+ return;
1806
+ }
1807
+ else if (this.format === SerializationFormat.Binary || this.format === SerializationFormat.Xdr) {
1808
+ this.offset += 8;
1809
+ return;
1810
+ }
1811
+ }
1812
+ /**
1813
+ * Reads `len` complex numbers from the buffer.
1814
+ *
1815
+ * Each value is read as two consecutive doubles via {@link inComplex}.
1816
+ * @param len - Number of complex values to read.
1817
+ * @returns Array of {@link Complex} objects.
1818
+ * @throws Error for BINARY format.
1819
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L1579-L1616 | R source: InComplexVec}
1820
+ */
1821
+ inComplexVec(len) {
1822
+ switch (this.format) {
1823
+ case SerializationFormat.Xdr: {
1824
+ const result = [];
1825
+ let t = 0;
1826
+ for (let done = 0; done < len; done += t) {
1827
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1828
+ for (let cnt = 0; cnt < t; cnt++) {
1829
+ result[done] = this.inComplex();
1830
+ }
1831
+ }
1832
+ return result;
1833
+ }
1834
+ case SerializationFormat.Binary: {
1835
+ throw new Error('No binary support yet.');
1836
+ }
1837
+ default: {
1838
+ const result = [];
1839
+ for (let cnt = 0; cnt < len; cnt++) {
1840
+ result[cnt] = this.inComplex();
1841
+ }
1842
+ return result;
1843
+ }
1844
+ }
1845
+ }
1846
+ /**
1847
+ * Advances the buffer past `len` serialized complex numbers.
1848
+ *
1849
+ * Mirrors {@link inComplexVec}.
1850
+ * @param len - Number of complex values to skip.
1851
+ * @throws Error for BINARY format.
1852
+ */
1853
+ skipComplexVec(len) {
1854
+ switch (this.format) {
1855
+ case SerializationFormat.Xdr: {
1856
+ let t = 0;
1857
+ for (let done = 0; done < len; done += t) {
1858
+ t = Math.min(RDAParser.CHUNK_SIZE, len - done);
1859
+ for (let cnt = 0; cnt < t; cnt++) {
1860
+ this.skipComplex();
1861
+ }
1862
+ }
1863
+ break;
1864
+ }
1865
+ case SerializationFormat.Binary: {
1866
+ throw new Error('No binary support yet.');
1867
+ }
1868
+ default: {
1869
+ for (let cnt = 0; cnt < len; cnt++) {
1870
+ this.skipComplex();
1871
+ }
1872
+ }
1873
+ }
1874
+ }
1875
+ /**
1876
+ * Reads a single complex number as two consecutive real values.
1877
+ * @returns A {@link Complex} object with `r` (real) and `i` (imaginary) parts.
1878
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L465-L471 | R source: InComplex}
1879
+ */
1880
+ inComplex() {
1881
+ return { r: this.inReal(), i: this.inReal() };
1882
+ }
1883
+ /**
1884
+ * Advances the buffer past a single serialized complex number (two doubles).
1885
+ *
1886
+ * Mirrors {@link inComplex}.
1887
+ */
1888
+ skipComplex() {
1889
+ this.skipReal();
1890
+ this.skipReal();
1891
+ }
1892
+ /**
1893
+ * Sets the `i`-th element of a character vector.
1894
+ * @param x - The character vector with type {@link SexpType.StrSxp} to modify.
1895
+ * @param i - index to set.
1896
+ * @param v - The {@link SexpType.CharSxp} {@link RObjectData} whose `name` is stored.
1897
+ * @throws Error if `x` is not a {@link SexpType.StrSxp} or `i` is out of bounds.
1898
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L4283-L4301 | R source: SET_STRING_ELT}
1899
+ */
1900
+ SET_STRING_ELT(x, i, _v) {
1901
+ if (x.type !== SexpType.StrSxp) {
1902
+ throw new Error(`SET_STRING_ELT() can only be applied to a 'character vector', not a '${x.type}'`);
1903
+ }
1904
+ // if(v.type !== SexpType.CharSxp) {
1905
+ // throw new Error(`Value of SET_STRING_ELT() must be a 'CHARSXP' not a '${v.type}'`);
1906
+ // }
1907
+ const arr = x.value;
1908
+ if (i < 0 || i >= arr.length) {
1909
+ throw new Error(`attempt to set index ${i}/${arr.length} in SET_STRING_ELT`);
1910
+ }
1911
+ // if(x.altRep){
1912
+ // this.ALTSTRING_SET_ELT(x, i, v);
1913
+ // }
1914
+ // arr[i] = v.name;
1915
+ }
1916
+ /**
1917
+ * Sets the `i`-th element of a generic list or vector.
1918
+ *
1919
+ * Mirrors R's `SET_VECTOR_ELT` macro.
1920
+ * @param x - The list or vector to modify.
1921
+ * @param i - index to set.
1922
+ * @param v - The {@link RObject} to store at position `i`.
1923
+ * @throws Error if `x` is not a list type or `i` is out of bounds.
1924
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L4303-L4322 | R source: SET_VECTOR_ELT}
1925
+ */
1926
+ SET_VECTOR_ELT(x, i, v) {
1927
+ if (x.type !== SexpType.VecSxp &&
1928
+ x.type !== SexpType.ExprSxp &&
1929
+ x.type !== SexpType.WeakRefSxp) {
1930
+ throw new Error(`SET_VECTOR_ELT() can only be applied to a 'list', not a '${x.type}'`);
1931
+ }
1932
+ if (i < 0 || i >= x.value.length) {
1933
+ throw new Error(`attempt to set index ${i}/${x.value.length} in SET_VECTOR_ELT`);
1934
+ }
1935
+ x.value[i] = v;
1936
+ }
1937
+ /**
1938
+ * Deserializes an R bytecode object.
1939
+ * @returns A {@link SexpType.BcodesSxp} {@link RObject}.
1940
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2221-L2228 | R source: ReadBC}
1941
+ */
1942
+ readBC() {
1943
+ const reps = {};
1944
+ reps.type = SexpType.VecSxp;
1945
+ reps.value = new Array(this.assertInteger(this.inInteger()));
1946
+ return this.readBC1(reps);
1947
+ }
1948
+ /**
1949
+ * Advances the buffer past a bytecode object without reading it.
1950
+ *
1951
+ * Mirrors {@link readBC}.
1952
+ */
1953
+ skipBC() {
1954
+ this.skipInteger();
1955
+ this.skipBC1();
1956
+ }
1957
+ /**
1958
+ * Advances past a single bytecode.
1959
+ *
1960
+ * Mirrors {@link readBC1}.
1961
+ */
1962
+ skipBC1() {
1963
+ this.currentDepth++;
1964
+ this.skipItem();
1965
+ this.currentDepth--;
1966
+ this.skipBCConsts();
1967
+ }
1968
+ /**
1969
+ * Advances past all bytecode constants.
1970
+ *
1971
+ * Mirrors {@link ReadBCConsts}.
1972
+ */
1973
+ skipBCConsts() {
1974
+ const n = this.assertInteger(this.inInteger());
1975
+ for (let i = 0; i < n; i++) {
1976
+ const type = this.inInteger();
1977
+ switch (type) {
1978
+ case SexpType.BcodesSxp: {
1979
+ this.skipBC1();
1980
+ break;
1981
+ }
1982
+ case SexpType.LangSxp:
1983
+ case SexpType.ListSxp:
1984
+ case SexpType.BcRepDef:
1985
+ case SexpType.BcRepRef:
1986
+ case SexpType.AltLangSxp:
1987
+ case SexpType.AttrListSxp: {
1988
+ this.skipBCLang(type);
1989
+ break;
1990
+ }
1991
+ default:
1992
+ this.currentDepth++;
1993
+ this.skipItem();
1994
+ this.currentDepth--;
1995
+ }
1996
+ }
1997
+ }
1998
+ /**
1999
+ * Registers a bytecode object after encoding.
2000
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L8820-L8885 | R source: R_registerBC}
2001
+ */
2002
+ R_registerBC(_bytes, _s) {
2003
+ throw new Error('BC not implemented yet');
2004
+ }
2005
+ /**
2006
+ * Deserializes a single bytecode object.
2007
+ * @param reps - Pre-allocated repetition table shared across all constants.
2008
+ * @returns A {@link SexpType.BcodesSxp} {@link RObjectData}.
2009
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2205-L2219 | R source: ReadBC1}
2010
+ */
2011
+ readBC1(reps) {
2012
+ const s = {};
2013
+ s.type = SexpType.BcodesSxp;
2014
+ this.currentDepth++;
2015
+ s.car = this.readItem();
2016
+ this.currentDepth--;
2017
+ const _bytes = s.car;
2018
+ // s.car = R_bcEncode(bytes);
2019
+ s.cdr = this.ReadBCConsts(reps);
2020
+ s.tag = RValues.NilValue;
2021
+ // R_registerBC(bytes, s);
2022
+ return s;
2023
+ }
2024
+ /**
2025
+ * Encodes bytecode instructions.
2026
+ * @param _bytes - integer array
2027
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L8723-L8771 | R source: R_bcEncode}
2028
+ */
2029
+ _R_bcEncode(_bytes) {
2030
+ throw new Error('Not implemented');
2031
+ }
2032
+ /**
2033
+ * Reads the constants of a bytecode object.
2034
+ * @param reps - Shared repetition table for `BcRepDef`/`BcRepRef` resolution.
2035
+ * @returns A `VecSxp` {@link RObjectData} holding all `n` constants.
2036
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2173-L2203 | R source: ReadBCConsts}
2037
+ */
2038
+ ReadBCConsts(reps) {
2039
+ const n = this.assertInteger(this.inInteger());
2040
+ const ans = {};
2041
+ ans.type = SexpType.VecSxp;
2042
+ ans.value = new Array(n);
2043
+ for (let i = 0; i < n; i++) {
2044
+ const type = this.inInteger();
2045
+ switch (type) {
2046
+ case SexpType.BcodesSxp: {
2047
+ const c = this.readBC1(reps);
2048
+ this.SET_VECTOR_ELT(ans, i, c);
2049
+ break;
2050
+ }
2051
+ case SexpType.LangSxp:
2052
+ case SexpType.ListSxp:
2053
+ case SexpType.BcRepDef:
2054
+ case SexpType.BcRepRef:
2055
+ case SexpType.AltLangSxp:
2056
+ case SexpType.AttrListSxp: {
2057
+ const c = this.ReadBCLang(type, reps);
2058
+ this.SET_VECTOR_ELT(ans, i, c);
2059
+ break;
2060
+ }
2061
+ default:
2062
+ this.currentDepth++;
2063
+ this.SET_VECTOR_ELT(ans, i, this.readItem());
2064
+ this.currentDepth--;
2065
+ }
2066
+ }
2067
+ return ans;
2068
+ }
2069
+ /**
2070
+ * Reads a single language object from bytecode constants.
2071
+ * @param type - {@link SexpType} read from the constants.
2072
+ * @param reps - Shared repetition table.
2073
+ * @returns The deserialized language {@link RObjectData}.
2074
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/serialize.c#L2125-L2171 | R source: ReadBCLang}
2075
+ */
2076
+ ReadBCLang(type, reps) {
2077
+ switch (type) {
2078
+ case SexpType.BcRepRef:
2079
+ return this.VECTOR_ELT(reps, this.assertInteger(this.inInteger()));
2080
+ case SexpType.BcRepDef:
2081
+ case SexpType.LangSxp:
2082
+ case SexpType.ListSxp:
2083
+ case SexpType.AltLangSxp:
2084
+ case SexpType.AttrListSxp:
2085
+ {
2086
+ let pos = -1;
2087
+ let hasAttr = false;
2088
+ if (type == SexpType.BcRepDef) {
2089
+ pos = this.assertInteger(this.inInteger());
2090
+ type = this.assertInteger(this.inInteger());
2091
+ }
2092
+ switch (type) {
2093
+ case SexpType.AltLangSxp:
2094
+ type = SexpType.LangSxp;
2095
+ hasAttr = true;
2096
+ break;
2097
+ case SexpType.AttrListSxp:
2098
+ type = SexpType.ListSxp;
2099
+ hasAttr = true;
2100
+ break;
2101
+ }
2102
+ const ans = {};
2103
+ ans.type = type;
2104
+ if (pos >= 0) {
2105
+ this.SET_VECTOR_ELT(reps, pos, ans);
2106
+ }
2107
+ this.currentDepth++;
2108
+ if (hasAttr) {
2109
+ ans.attributes ??= [];
2110
+ ans.attributes.push(this.assertRObjectData(this.readItem()));
2111
+ }
2112
+ ans.tag = this.readItem();
2113
+ this.currentDepth--;
2114
+ ans.car = this.ReadBCLang(this.assertInteger(this.inInteger()), reps);
2115
+ ans.cdr = this.ReadBCLang(this.assertInteger(this.inInteger()), reps);
2116
+ return ans;
2117
+ }
2118
+ default:
2119
+ {
2120
+ this.currentDepth++;
2121
+ const res = this.readItem();
2122
+ this.currentDepth--;
2123
+ return res;
2124
+ }
2125
+ }
2126
+ }
2127
+ /**
2128
+ * Advances the buffer past a single language object.
2129
+ *
2130
+ * Mirrors {@link ReadBCLang}.
2131
+ * @param type - read {@link SexpType}.
2132
+ */
2133
+ skipBCLang(type) {
2134
+ switch (type) {
2135
+ case SexpType.BcRepRef:
2136
+ this.skipInteger();
2137
+ break;
2138
+ case SexpType.BcRepDef:
2139
+ case SexpType.LangSxp:
2140
+ case SexpType.ListSxp:
2141
+ case SexpType.AltLangSxp:
2142
+ case SexpType.AttrListSxp:
2143
+ {
2144
+ let hasAttr = false;
2145
+ if (type == SexpType.BcRepDef) {
2146
+ this.skipInteger();
2147
+ type = this.assertInteger(this.inInteger());
2148
+ }
2149
+ switch (type) {
2150
+ case SexpType.AltLangSxp:
2151
+ type = SexpType.LangSxp;
2152
+ hasAttr = true;
2153
+ break;
2154
+ case SexpType.AttrListSxp:
2155
+ type = SexpType.ListSxp;
2156
+ hasAttr = true;
2157
+ break;
2158
+ }
2159
+ this.currentDepth++;
2160
+ if (hasAttr) {
2161
+ this.skipItem();
2162
+ }
2163
+ this.readItem();
2164
+ this.skipItem();
2165
+ this.currentDepth--;
2166
+ this.skipBCLang(this.assertInteger(this.inInteger()));
2167
+ this.skipBCLang(this.assertInteger(this.inInteger()));
2168
+ break;
2169
+ }
2170
+ default:
2171
+ {
2172
+ this.currentDepth++;
2173
+ this.skipItem();
2174
+ this.currentDepth--;
2175
+ }
2176
+ }
2177
+ }
2178
+ /**
2179
+ * Retrieves the `i`-th element of a generic list or vector.
2180
+ * @param x - The list / expression / weak-ref vector.
2181
+ * @param i - The index to retrieve.
2182
+ * @returns The {@link RObject} at position `i`.
2183
+ * @throws Error if `x` is not a list type or `i` is out of bounds.
2184
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/memory.c#L4122-L4142 | R source: VECTOR_ELT}
2185
+ */
2186
+ VECTOR_ELT(x, i) {
2187
+ if (x.type !== SexpType.VecSxp &&
2188
+ x.type !== SexpType.ExprSxp &&
2189
+ x.type !== SexpType.WeakRefSxp) {
2190
+ throw new Error(`VECTOR_ELT() can only be applied to a 'list', not a '${x.type}'`);
2191
+ }
2192
+ // "VECTOR_ELT", "list", R_typeToChar(x));
2193
+ if (i < 0 || i >= x.value?.length) {
2194
+ throw new Error('attempt access index %lld/%lld in VECTOR_ELT');
2195
+ }
2196
+ // (long long)i, (long long)XLENGTH(x));
2197
+ if (x.altRep) {
2198
+ const ans = x.value[i];
2199
+ /* the element is marked as not mutable since complex
2200
+ assignment can't see reference counts on any intermediate
2201
+ containers in an ALTREP */
2202
+ // MARK_NOT_MUTABLE(ans);
2203
+ return ans;
2204
+ }
2205
+ else {
2206
+ return x.value[i];
2207
+ }
2208
+ }
2209
+ /**
2210
+ * Checks whether a bytecode object's version is within the supported range.
2211
+ * @param s - The {@link SexpType.BcodesSxp} {@link RObjectData} to check.
2212
+ * @returns `true` if the version is supported.
2213
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L7166-L7175 | R source: R_BCVersionOK}
2214
+ */
2215
+ R_BCVersionOK(s) {
2216
+ if (s.type !== SexpType.BcodesSxp) {
2217
+ return false;
2218
+ }
2219
+ // const pc = s.code;
2220
+ const pc = 0;
2221
+ const version = pc;
2222
+ return (version >= 9 && version <= 12);
2223
+ }
2224
+ /**
2225
+ * Returns the source-language expression for an unsupported bytecode object.
2226
+ * @param s - The {@link SexpType.BcodesSxp} {@link RObjectData}.
2227
+ * @returns First constant pool entry if available, otherwise {@link RValues.NilValue}.
2228
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/eval.c#L5566-L5574 | R source: bytecodeExpr}
2229
+ */
2230
+ R_BytecodeExpr(s) {
2231
+ if (s.type === SexpType.BcodesSxp) {
2232
+ if (s.cdr.value?.length > 0) {
2233
+ return this.VECTOR_ELT(s.cdr, 0);
2234
+ }
2235
+ else {
2236
+ return RValues.NilValue;
2237
+ }
2238
+ }
2239
+ else {
2240
+ return s;
2241
+ }
2242
+ }
2243
+ /**
2244
+ * Attempts to unserialize an ALTREP object.
2245
+ * @param info - The info to be unserialized.
2246
+ * @param _state - Serialized state.
2247
+ * @param _attr - Serialized attributes.
2248
+ * @param _objf - IS_OBJECT flag.
2249
+ * @param _levs - GP levels bits.
2250
+ * @returns The {@link RObjectData} or .
2251
+ * @throws Error if the base type is not a supported vector type.
2252
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/altrep.c#L298-L338 | R source: ALTREP_UNSERIALIZE_EX}
2253
+ */
2254
+ AltRepUnserializeEx(info, _state, _attr, _objf, _levs) {
2255
+ const cSym = info.car;
2256
+ const pSym = info.cdr.car;
2257
+ const type = info.cdr.cdr.car.type;
2258
+ const clss = this.ALTREP_UNSERIALIZE_CLASS(info);
2259
+ if (clss == undefined) {
2260
+ switch (type) {
2261
+ case SexpType.LglSxp:
2262
+ case SexpType.IntSxp:
2263
+ case SexpType.RealSxp:
2264
+ case SexpType.CplxSxp:
2265
+ case SexpType.StrSxp:
2266
+ case SexpType.RawSxp:
2267
+ case SexpType.VecSxp:
2268
+ case SexpType.ExprSxp:
2269
+ console.warn(`cannot unserialize ALTVEC object of class '${cSym.name}'
2270
+ from package '${pSym.name}' returning length zero vector`);
2271
+ info.type = type;
2272
+ info.value = [];
2273
+ return info;
2274
+ default:
2275
+ throw new Error('cannot unserialize this ALTREP object');
2276
+ }
2277
+ }
2278
+ return {};
2279
+ }
2280
+ /**
2281
+ * Looks up the ALTREP class for the given class/package symbol pair.
2282
+ * @param info - The info to be looked up.
2283
+ * @returns The class {@link RObjectData} when found, `undefined` if unregistered, or `null` if `info` is not a `ListSxp`.
2284
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/altrep.c#L279-L296 | R source: ALTREP_UNSERIALIZE_CLASS}
2285
+ */
2286
+ ALTREP_UNSERIALIZE_CLASS(info) {
2287
+ if (info.type == SexpType.ListSxp) {
2288
+ const cSym = info.car;
2289
+ const pSym = info.cdr.car;
2290
+ let clss = this.LookupClass(cSym, pSym);
2291
+ if (clss === undefined) {
2292
+ const pName = this.ScalarString(pSym.name);
2293
+ try {
2294
+ this.R_FindNamespace(pName);
2295
+ }
2296
+ catch (e) {
2297
+ console.log(`${pName.value} ${e}`);
2298
+ }
2299
+ clss = this.LookupClass(cSym, pSym);
2300
+ }
2301
+ return clss;
2302
+ }
2303
+ return null;
2304
+ }
2305
+ /**
2306
+ * Looks up an ALTREP class entry by class and package symbol.
2307
+ * @param cSym - Class symbol.
2308
+ * @param pSym - Package symbol.
2309
+ * @returns The {@link RObjectData} or `undefined` if not registered.
2310
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/altrep.c#L90-L94 | R source: LookupClass}
2311
+ */
2312
+ LookupClass(cSym, pSym) {
2313
+ const entry = this.LookupClassEntry(cSym, pSym);
2314
+ return entry === undefined || entry === null ? undefined : entry.car;
2315
+ }
2316
+ /**
2317
+ * Searches the ALTREP class registry for an entry matching the given symbols.
2318
+ * @param cSym - Class symbol to match.
2319
+ * @param pSym - Package symbol to match.
2320
+ * @returns The matching registry node or `null` if not found.
2321
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/altrep.c#L53-L59 | R source: LookupClassEntry}
2322
+ */
2323
+ LookupClassEntry(cSym, pSym) {
2324
+ if (!this.Registry) {
2325
+ return null;
2326
+ }
2327
+ for (let chain = (this.Registry).cdr || null; chain; chain = chain.cdr) {
2328
+ if (chain.car.tag == cSym && chain.car.cdr.car === pSym) {
2329
+ return chain.car;
2330
+ }
2331
+ }
2332
+ return null;
2333
+ }
2334
+ /**
2335
+ * Creates a length-1 character vector wrapping the given string.
2336
+ * @param x - The string value to wrap.
2337
+ * @returns A {@link SexpType.StrSxp} {@link RObjectData} with one element.
2338
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/include/Rinlinedfuns.h#L1044-L1052 | R source: ScalarString}
2339
+ */
2340
+ ScalarString(x) {
2341
+ const ans = {};
2342
+ ans.type = SexpType.StrSxp;
2343
+ ans.value = new Array(1);
2344
+ this.SET_STRING_ELT(ans, 0, { name: x });
2345
+ return ans;
2346
+ }
2347
+ /**
2348
+ * Recomputes and restores the cached hash-table priority count for an environment.
2349
+ * @param s - The {@link RObjectData} whose hash table is to be repaired.
2350
+ * @see {@link https://github.com/wch/r-source/blob/2196e6982a8f49082ee5c3d3521f6dd6596ea72c/src/main/envir.c#L3685-L3698 | R source: R_RestoreHashCount}
2351
+ */
2352
+ restoreHashCount(s) {
2353
+ if (s.hashTab !== RValues.NilValue) {
2354
+ const table = s.hashTab;
2355
+ const size = table.value.length;
2356
+ let _count = 0;
2357
+ for (let i = 0; i < size; i++) {
2358
+ if (this.VECTOR_ELT(table, i) !== RValues.NilValue) {
2359
+ _count++;
2360
+ }
2361
+ }
2362
+ // SET_HASHPRI(table, count);
2363
+ }
2364
+ }
2365
+ /**
2366
+ * Converts a linked-list based R object tree into a flat array representation.
2367
+ * @param node - Root node of the deserialized object tree.
2368
+ * @param shortcut - Whether payload values should be omitted.
2369
+ * @returns Flattened array of top-level objects.
2370
+ */
2371
+ flattenRObject(node, shortcut) {
2372
+ const result = [];
2373
+ function walk(n, shortcut) {
2374
+ if (!n || n === RValues.NilValue) {
2375
+ return;
2376
+ }
2377
+ const name = n.tag?.name;
2378
+ if (name !== undefined) {
2379
+ let copy = {};
2380
+ if (shortcut) {
2381
+ copy = {
2382
+ name: n.tag.name,
2383
+ type: n.car.type,
2384
+ };
2385
+ }
2386
+ else {
2387
+ copy = {
2388
+ name: n.tag.name,
2389
+ value: n.car.value,
2390
+ hasAttribute: !!n.hasAttribute,
2391
+ attributes: n.attributes,
2392
+ type: n.car.type,
2393
+ tag: RValues.NilValue
2394
+ };
2395
+ }
2396
+ result.push(copy);
2397
+ }
2398
+ if (n.cdr && n.cdr !== RValues.NilValue) {
2399
+ walk(n.cdr, shortcut);
2400
+ }
2401
+ }
2402
+ walk(node, shortcut);
2403
+ return result;
2404
+ }
2405
+ }
2406
+ exports.RDAParser = RDAParser;
2407
+ //# sourceMappingURL=flowr-rda-file.js.map