feat(stdlib): add datetime and project-mode clock APIs
This commit is contained in:
1 parent
cffb6790be
commit
ae69391bc0
15 files changed
+527
-11
No files matched your search
@@ -127,8 +127,10 @@ fn every_public_stdlib_module_has_a_product_test() {
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
"clock.mq.md",
|
||||
"console.mq.md",
|
||||
"csv.mq.md",
|
||||
"datetime.mq.md",
|
||||
"demo.mq.md",
|
||||
"format.mq.md",
|
||||
"fs.mq.md",
|
||||
@@ -276,6 +278,38 @@ fn regex_test_matches_anchors_classes_and_search() {
|
||||
assert_eq!(items[11]["value"], "regex.unsupported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_test_formats_and_parses_utc_instants() {
|
||||
let report = run_product_test(
|
||||
product_tests()
|
||||
.iter()
|
||||
.find(|file| file.name == "datetime.mq.md")
|
||||
.expect("datetime test"),
|
||||
);
|
||||
let items = report["value"]["items"].as_array().expect("list");
|
||||
assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z");
|
||||
assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z");
|
||||
assert_eq!(items[2]["decimal"], "0");
|
||||
assert_eq!(items[3]["decimal"], "1795248000123");
|
||||
assert_eq!(items[4]["value"], false);
|
||||
assert_eq!(items[5]["value"], false);
|
||||
assert_eq!(items[6]["value"], "1969-12-31T23:59:59.999Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_test_reports_project_mode_unix_millis() {
|
||||
let report = run_product_test(
|
||||
product_tests()
|
||||
.iter()
|
||||
.find(|file| file.name == "clock.mq.md")
|
||||
.expect("clock test"),
|
||||
);
|
||||
let items = report["value"]["items"].as_array().expect("list");
|
||||
assert_eq!(items[0]["value"], true);
|
||||
assert_eq!(items[1]["value"], "Int");
|
||||
assert_eq!(items[2]["value"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_test_pins_value_semantics_and_handle_observation() {
|
||||
let report = run_product_test(
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use marqdo_plugin_abi::{
|
||||
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
|
||||
@@ -1127,6 +1127,41 @@ impl Host for StdHost {
|
||||
"resource operations accept only Text path arguments",
|
||||
));
|
||||
}
|
||||
if operation == "clock.now" {
|
||||
if !args.is_empty() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Arity,
|
||||
ctx.span,
|
||||
format!(
|
||||
"resource operation `clock.now` expects 0 arguments, got {}",
|
||||
args.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
ctx.span,
|
||||
format!("system clock is before the Unix epoch: {error}"),
|
||||
)
|
||||
})?
|
||||
.as_millis()
|
||||
.min(i64::MAX as u128) as i64;
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::int(millis));
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=clock.now"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "clock.now");
|
||||
return Ok(Value::Map(map));
|
||||
}
|
||||
let Some(name) = operation.strip_prefix("fs.") else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
|
||||
@@ -614,3 +614,30 @@ fn fs_requests_reject_traversal_before_touching_the_filesystem() {
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_now_is_project_only_and_returns_unix_millis() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ctx = context();
|
||||
let mut pure = StdHost::new(SandboxMode::Pure, Capabilities::pure(), dir.path());
|
||||
let error = pure
|
||||
.resource_request("clock.now", Vec::new(), &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::PermissionDenied);
|
||||
|
||||
let mut project = StdHost::new(SandboxMode::Project, Capabilities::project(), dir.path());
|
||||
let value = project
|
||||
.resource_request("clock.now", Vec::new(), &ctx)
|
||||
.unwrap();
|
||||
assert_eq!(field(&value, "ok"), &Value::Bool(true));
|
||||
let Value::Int(millis) = field(&value, "value") else {
|
||||
panic!("clock.now did not return an Int");
|
||||
};
|
||||
let millis = millis.to_string().parse::<i64>().expect("i64 millis");
|
||||
assert!(millis > 1_600_000_000_000);
|
||||
|
||||
let error = project
|
||||
.resource_request("clock.now", vec![Value::text("x")], &ctx)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.category, ErrorCategory::Arity);
|
||||
}
|
||||
+7
-6
@@ -58,7 +58,7 @@ byte-identical).
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace --locked PASS
|
||||
471 passed, 0 failed, 2 ignored; includes 7/7 Linux security tests
|
||||
474 passed, 0 failed, 2 ignored; includes 7/7 Linux security tests
|
||||
```
|
||||
|
||||
The documentation and test migration is local work; re-run this block after it
|
||||
@@ -202,11 +202,12 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
over the existing `resource.*` ABI plus `存在`/`元数据`/`列出目录`/`创建目录`/
|
||||
`删除`/`重命名` over `resource.request` (ADR-0041); `data/json`/`data/csv`
|
||||
provide recursive JSON and quoted single-row CSV product parsers; `path` and a
|
||||
`regex` subset are pure `.mq.md`. Append/seek/watch, recursive walk, streaming
|
||||
JSON/CSV, a JSON depth bound, regex groups/alternation and `datetime`/`env`/
|
||||
`process` remain open.
|
||||
`regex` subset are pure `.mq.md`; `datetime` is pure UTC ISO-8601 and
|
||||
`clock.现在` reads `clock.now` in project mode (ADR-0042). Append/seek/watch,
|
||||
recursive walk, streaming JSON/CSV, a JSON depth bound, regex groups/
|
||||
alternation and `env`/`process` remain open.
|
||||
- Bundled standard library (CM-A10, ADR-0028): `stdlib/` ships
|
||||
`format`/`text`/`io`/`fs`/`data`/`path`/`regex`; explicit `std:` imports resolve only inside the bundle;
|
||||
`format`/`text`/`io`/`fs`/`data`/`path`/`regex`/`datetime`/`clock`; explicit `std:` imports resolve only inside the bundle;
|
||||
a SHA-256 digest over `*.mq.md` is verified before loading; Analysis records
|
||||
`project.stdlib`; a frozen-binary test asserts the CLI hash is unchanged after
|
||||
running a `std:io` project and that tampering is rejected. `打印/print` is
|
||||
@@ -232,7 +233,7 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
|
||||
status/index links and SHA-pinned evidence; `crates/cli/tests/architecture_boundaries.rs`
|
||||
pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib
|
||||
digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
|
||||
runs every public stdlib module (`console/csv/demo/format/fs/http/io/json/path/regex/stream/table/text/utf8`)
|
||||
runs every public stdlib module (`clock/console/csv/datetime/demo/format/fs/http/io/json/path/regex/stream/table/text/utf8`)
|
||||
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
|
||||
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
|
||||
`0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# ADR-0042: `clock.now` resource operation
|
||||
|
||||
Status: **Accepted**
|
||||
Date: 2026-11-21
|
||||
Relates to: ADR-0041
|
||||
Specs: `spec/evaluation.md`
|
||||
Evidence: `docs/evidence/2026-11-21-datetime-clock-product.md`
|
||||
|
||||
## Context
|
||||
|
||||
The bundled standard library needs a product clock API. Reading the OS clock
|
||||
inside a Rust builtin would add a second side-effect path beside
|
||||
`resource.request`, and making time available in every mode would break the
|
||||
pure/strict fail-closed contract without an explicit capability decision.
|
||||
|
||||
## Decision
|
||||
|
||||
Extend `resource.request` with one non-filesystem operation:
|
||||
|
||||
```text
|
||||
resource.request("clock.now", []) -> {ok:true, value:UnixMillis}
|
||||
```
|
||||
|
||||
* Zero arguments; any argument is a fatal `call.arity` error.
|
||||
* Project mode only. `pure` and `strict` return `permission.denied`, like
|
||||
`fs.*`.
|
||||
* The value is UTC Unix milliseconds, clamped to `i64`. A clock before the
|
||||
Unix epoch is a fatal `host.error`.
|
||||
* The call records the same `resource.request` semantic/effect events with
|
||||
`op=clock.now`.
|
||||
* `stdlib/clock.mq.md` is a thin `.mq.md` facade; `stdlib/datetime.mq.md` is a
|
||||
pure UTC formatter/parser over Unix milliseconds and has no host dependency.
|
||||
|
||||
## Consequences
|
||||
|
||||
* The clock remains a capability-gated host operation, not a language keyword.
|
||||
* No new CLI flag is introduced; project mode already implies the existing
|
||||
host boundary. A future per-call clock grant can replace this default.
|
||||
* Monotonic time, time zones and locale formatting are not part of this
|
||||
decision.
|
||||
@@ -18,7 +18,7 @@ platform".
|
||||
| Dimension | Current state | Source |
|
||||
|---|---|---|
|
||||
| Implemented | Rust workspace `0.1.0`: Markdown/frontend/IR, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, bundled stdlib, CLI composition root | `Cargo.toml`, `crates/`, `stdlib/` |
|
||||
| Tested locally | `cargo test --workspace --locked`: **471 passed, 0 failed, 2 ignored** on Linux x86_64 at the baseline | `docs/STATUS.md` §3 |
|
||||
| Tested locally | `cargo test --workspace --locked`: **474 passed, 0 failed, 2 ignored** on Linux x86_64 at the baseline | `docs/STATUS.md` §3 |
|
||||
| Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` |
|
||||
| Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 |
|
||||
|
||||
@@ -92,6 +92,8 @@ review RFC, not a new crate per provider.
|
||||
| `std:data/csv` | `csv.解析行(文本)` -> Result with List<Text>; `csv.格式化行(列表)` -> Text | implemented (single row, quoted) | `stdlib_product` |
|
||||
| `std:path` | `path.连接/文件名/目录名/扩展名/规范/是否绝对`; lexical only | implemented (no I/O) | `stdlib_product` |
|
||||
| `std:regex` | `regex.匹配/搜索` with `^ $ . * + ? [...]` escapes | implemented subset; no groups/alternation | `stdlib_product` |
|
||||
| `std:datetime` | `datetime.格式化(毫秒)` / `datetime.解析(文本)`; UTC ISO-8601, pre-1970 supported | implemented (pure) | `stdlib_product` |
|
||||
| `std:clock` | `clock.现在()` -> `resource.request("clock.now", [])` | implemented (project mode; pure/strict denied) | `resource_streams`, `stdlib_product` |
|
||||
| file metadata / directory / rename / remove / mkdir | not part of the current Resource contract | **not implemented**; needs a separate Resource Operation ADR | — |
|
||||
| TCP | `resource.open("tcp", ip:port, ["read","write"])`; exact IP grant, 5 s timeout | implemented; no DNS/TLS/server socket/UDP | `tcp_endpoint`, `http_over_tcp` |
|
||||
| HTTP/1.1 | `stdlib/net/http.mq.md`: status/header/chunked-byte parse, request build | implemented over an already-authorized TCP stream; not a DNS/TLS client | `stdlib_http`, `http_over_tcp`, `stdlib_product` |
|
||||
@@ -123,7 +125,7 @@ that a phase is complete.
|
||||
| P1 | `crates/cli/src/commands.rs` and `crates/marqdo-host/src/host.rs` still mix multiple responsibilities | open refactor, behavior-preserving |
|
||||
| P2 | HTTP parsing is Unicode-codepoint oriented; a general byte body is not the only path | open; convert before a general network release |
|
||||
| P2 | No DNS, TLS, listener or UDP provider | open |
|
||||
| P2 | `std:path` and a regex subset are implemented; no `std:datetime`, `std:env`, `std:process`, secure random or compression | open |
|
||||
| P2 | `std:path`, a regex subset, `std:datetime` and `std:clock` are implemented; no `std:env`, `std:process`, secure random or compression | open |
|
||||
| P2 | Memory limits: 16 MiB per region, 64 MiB per run | current budget, not a product limit |
|
||||
| P3 | No concurrency tasks, atomics or cancellable long-running scheduling | open; separate ADR |
|
||||
| P3 | No native optimizer/JIT or columnar numeric backend | open; benchmark-first |
|
||||
@@ -154,5 +156,6 @@ that a phase is complete.
|
||||
- [Language/frontmatter blueprint](../DEVELOPMENT_BLUEPRINT.md) — design baseline; not current status.
|
||||
- [Stable-release implementation plan](../STABLE_RELEASE_IMPLEMENTATION.md) — next-phase plan; not implemented behavior.
|
||||
- [ADR-0041: non-streaming resource operations](../adr/0041-resource-operation-fs.md) — accepted `resource.request` `fs.*` contract.
|
||||
- [ADR-0042: `clock.now` resource operation](../adr/0042-clock-resource-operation.md) — accepted project-mode Unix-millis clock.
|
||||
- [Compute-machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) and [core/stdlib RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) — design input.
|
||||
- [Architecture audit and refactor RFC](Marqdo_CLI_Latest_Architecture_Audit_and_Refactor_RFC.md) — review input for this migration.
|
||||
@@ -46,6 +46,7 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
|
||||
| Stdlib extraction deferral | [0039](../adr/0039-stdlib-extraction-intent.md) | Accepted (in-repo for now) |
|
||||
| Stdio stdin/stderr plus stdlib stream/console APIs | [0040](../adr/0040-stdio-stdin-stderr-and-stdlib-streams.md) | Accepted (stdin read, separate stdout/stderr, product stdlib) |
|
||||
| Non-streaming `resource.request` `fs.*` operations | [0041](../adr/0041-resource-operation-fs.md) | Accepted (project mode, grant-checked, recoverable fs Result) |
|
||||
| `clock.now` resource operation | [0042](../adr/0042-clock-resource-operation.md) | Accepted (project mode, Unix millis) |
|
||||
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
|
||||
|
||||
## Evidence and status
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Evidence: `std:datetime` and `std:clock`
|
||||
|
||||
Date: 2026-11-21 (Asia/Shanghai)
|
||||
Source baseline: `cffb6790bee49966226f5abc3be026e6c4e0f8f3`
|
||||
Repository: `marqdo-cli`
|
||||
Decision record: [ADR-0042](../adr/0042-clock-resource-operation.md)
|
||||
RFC item: P2 datetime/clock product APIs
|
||||
|
||||
## Implemented
|
||||
|
||||
`stdlib/datetime.mq.md` is pure `.mq.md`: `格式化(毫秒)` emits UTC ISO-8601
|
||||
(`YYYY-MM-DDTHH:MM:SS[.mmm]Z`) using the civil-from-days algorithm;
|
||||
`解析(文本)` validates separators, digit components, ranges, leap years and
|
||||
returns recoverable `datetime.invalid`. Pre-1970 negatives are supported.
|
||||
|
||||
`stdlib/clock.mq.md` is a thin facade: `现在()` ->
|
||||
`resource.request("clock.now", [])`. The host adds `clock.now` to the
|
||||
ADR-0041 operation channel: zero arguments, project mode only, UTC Unix
|
||||
milliseconds, one `resource.request` trace/effect event. `pure`/`strict`
|
||||
return `permission.denied`.
|
||||
|
||||
No new Rust builtin, `HostOp` or parser node was added.
|
||||
|
||||
## Tests
|
||||
|
||||
`stdlib/tests/datetime.mq.md` and `stdlib/tests/clock.mq.md` run through
|
||||
`std:datetime`/`std:clock` and are pinned by
|
||||
`crates/cli/tests/stdlib_product.rs` (12 product tests total).
|
||||
`crates/marqdo-host/tests/resource_streams.rs` pins project-only access,
|
||||
Unix-millis shape and zero-argument arity (21 host tests).
|
||||
|
||||
```text
|
||||
cargo fmt --all -- --check PASS
|
||||
cargo clippy --workspace --all-targets -- -D warnings PASS
|
||||
cargo test --workspace 474 passed, 0 failed, 2 ignored
|
||||
cargo test -p marqdo-host --test resource_streams 21 passed
|
||||
cargo test -p marqdo-cli --test stdlib_product 12 passed
|
||||
python3 tools/pack-stdlib.py PASS
|
||||
```
|
||||
|
||||
## Not covered
|
||||
|
||||
No time zones, locale formatting, duration type, monotonic clock or
|
||||
calendar arithmetic beyond UTC instants. No network time source.
|
||||
+5
-1
@@ -205,6 +205,7 @@ resource.request("fs.list", [path]) -> {ok:true, value:List<Text>}
|
||||
resource.request("fs.mkdir", [path]) -> {ok:true, value:None}
|
||||
resource.request("fs.remove", [path]) -> {ok:true, value:None}
|
||||
resource.request("fs.rename", [from, to]) -> {ok:true, value:None}
|
||||
resource.request("clock.now", []) -> {ok:true, value:UnixMillis}
|
||||
```
|
||||
|
||||
* Arguments are `Text` paths only. `Memory`/`Resource` values are rejected.
|
||||
@@ -223,6 +224,9 @@ resource.request("fs.rename", [from, to]) -> {ok:true, value:None}
|
||||
* `remove` never recurses; `rename` never overwrites; `mkdir` is single-level.
|
||||
* The operation never moves file bytes. Content still uses
|
||||
`resource.open/read/write/close`.
|
||||
* `clock.now` takes no arguments and returns UTC Unix milliseconds. It is
|
||||
project-mode only like `fs.*`; a clock before the epoch is fatal host error
|
||||
(ADR-0042).
|
||||
|
||||
## 4. Errors
|
||||
|
||||
@@ -318,7 +322,7 @@ host boundary. Names are stable; adding one requires a spec update.
|
||||
| `resource.read` | `(handle, memory: Memory, offset: Int, max_bytes: Int) -> Result` | bounded chunk read into Memory; `{count,eof}` |
|
||||
| `resource.write` | `(handle, memory: Memory, offset: Int, length: Int) -> Result` | bounded byte write; `{count}` |
|
||||
| `resource.close` | `(handle) -> Result` | releases the host slot |
|
||||
| `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations; project-mode and grant-checked (ADR-0041) |
|
||||
| `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations (ADR-0041) and `clock.now` (ADR-0042); project-mode and grant-checked |
|
||||
| `math.parse/eval/substitute` | see `spec/math.md` | P5; `math.simplify`/`math.differentiate` are declared but return `math.unsupported` in this build |
|
||||
| `foreign.run/call` | see `spec/foreign.md` | P5, capability-gated |
|
||||
| `fs.read/write` | see `spec/security.md` | capability-gated |
|
||||
|
||||
@@ -15,6 +15,8 @@ module; a mismatch is a hard error.
|
||||
- `data/json.mq.md` — recursive JSON parser and formatter (recoverable Result)
|
||||
- `data/csv.mq.md` — quoted single-row CSV parser and formatter
|
||||
- `data/table.mq.md` — value-returning table select/filter/sort/append/set/join/group/GFM
|
||||
- `datetime.mq.md` — UTC ISO-8601 format/parse over Unix milliseconds (pure)
|
||||
- `clock.mq.md` — project-mode `clock.now` over `resource.request`
|
||||
- `path.mq.md` — lexical join/basename/dirname/extension/normalize (no I/O)
|
||||
- `regex.mq.md` — `^ $ . * + ? [...]` matcher and search (no groups)
|
||||
- `net/http.mq.md` — HTTP/1.1 response parsing (headers/chunked) and request builder
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
## 现在
|
||||
|
||||
`()`
|
||||
|
||||
返回项目模式下的 UTC Unix 毫秒。`pure`/`strict` 返回
|
||||
`permission.denied`,与 `resource.request` 的其他操作一致。
|
||||
|
||||
*resource.request("clock.now", [])*
|
||||
@@ -0,0 +1,299 @@
|
||||
## 失败
|
||||
|
||||
`(消息)`
|
||||
|
||||
*{ok: false, code: "datetime.invalid", message: 消息}*
|
||||
|
||||
## 闰年
|
||||
|
||||
`(年)`
|
||||
|
||||
*年 % 4 == 0 and (年 % 100 != 0 or 年 % 400 == 0)*
|
||||
|
||||
## 每月天数
|
||||
|
||||
`(年, 月)`
|
||||
|
||||
1. `月 == 2`
|
||||
|
||||
1. `闰年(年)`
|
||||
|
||||
*29*
|
||||
|
||||
*28*
|
||||
|
||||
2. `月 == 4 or 月 == 6 or 月 == 9 or 月 == 11`
|
||||
|
||||
*30*
|
||||
|
||||
*31*
|
||||
|
||||
## 补零2
|
||||
|
||||
`(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
|
||||
*文本(值)*
|
||||
|
||||
## 补零3
|
||||
|
||||
`(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
|
||||
*"00" + 文本(值)*
|
||||
|
||||
2. `值 < 100`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
|
||||
*文本(值)*
|
||||
|
||||
## 补零4
|
||||
|
||||
`(值)`
|
||||
|
||||
1. `值 < 10`
|
||||
|
||||
*"000" + 文本(值)*
|
||||
|
||||
2. `值 < 100`
|
||||
|
||||
*"00" + 文本(值)*
|
||||
|
||||
3. `值 < 1000`
|
||||
|
||||
*"0" + 文本(值)*
|
||||
|
||||
*文本(值)*
|
||||
|
||||
## 月份
|
||||
|
||||
`(mp)`
|
||||
|
||||
1. `mp < 10`
|
||||
|
||||
*mp + 3*
|
||||
|
||||
*mp - 9*
|
||||
|
||||
## 年份
|
||||
|
||||
`(年, 月)`
|
||||
|
||||
1. `月 <= 2`
|
||||
|
||||
*年 + 1*
|
||||
|
||||
*年*
|
||||
|
||||
## 日期部件
|
||||
|
||||
`(天)`
|
||||
|
||||
Howard Hinnant 的 civil-from-days 算法,输入为 1970-01-01 起的天数。
|
||||
|
||||
**z = 天 + 719468**
|
||||
|
||||
**era = z // 146097**
|
||||
|
||||
**doe = z - era * 146097**
|
||||
|
||||
**yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365**
|
||||
|
||||
**年 = yoe + era * 400**
|
||||
|
||||
**doy = doe - (365 * yoe + yoe // 4 - yoe // 100)**
|
||||
|
||||
**mp = (5 * doy + 2) // 153**
|
||||
|
||||
**日 = doy - (153 * mp + 2) // 5 + 1**
|
||||
|
||||
**月 = 月份(mp)**
|
||||
|
||||
*{年: 年份(年, 月), 月: 月, 日: 日}*
|
||||
|
||||
## 日期序号
|
||||
|
||||
`(年, 月, 日)`
|
||||
|
||||
**y = 年**
|
||||
|
||||
1. `月 <= 2`
|
||||
|
||||
**y = y - 1**
|
||||
|
||||
2. `true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
**era = y // 400**
|
||||
|
||||
**yoe = y - era * 400**
|
||||
|
||||
**m = 月**
|
||||
|
||||
1. `月 > 2`
|
||||
|
||||
**m = 月 - 3**
|
||||
|
||||
2. `true`
|
||||
|
||||
**m = 月 + 9**
|
||||
|
||||
**doy = (153 * m + 2) // 5 + 日 - 1**
|
||||
|
||||
**doe = yoe * 365 + yoe // 4 - yoe // 100 + doy**
|
||||
|
||||
*era * 146097 + doe - 719468*
|
||||
|
||||
## 是数字串
|
||||
|
||||
`(文本)`
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
**结果 = 长度(点) > 0**
|
||||
|
||||
**下标 = 0**
|
||||
|
||||
- `下标 < 长度(点) and 结果`
|
||||
|
||||
1. `点[下标] < 48 or 点[下标] > 57`
|
||||
|
||||
**结果 = false**
|
||||
|
||||
2. `true`
|
||||
|
||||
**忽略 = 0**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
|
||||
## 片段
|
||||
|
||||
`(点, 起点, 终点)`
|
||||
|
||||
**结果 = ""**
|
||||
|
||||
**下标 = 起点**
|
||||
|
||||
- `下标 < 终点`
|
||||
|
||||
**结果 = 结果 + text.from_codepoint(点[下标])**
|
||||
|
||||
**下标 = 下标 + 1**
|
||||
|
||||
*结果*
|
||||
|
||||
## 格式化
|
||||
|
||||
`(毫秒)`
|
||||
|
||||
输出 UTC ISO-8601:`YYYY-MM-DDTHH:MM:SSZ`;毫秒非零时追加
|
||||
`.mmm`。负数毫秒按 1970 前的 UTC 时间处理。
|
||||
|
||||
**秒 = 毫秒 // 1000**
|
||||
|
||||
**毫 = 毫秒 % 1000**
|
||||
|
||||
**天 = 秒 // 86400**
|
||||
|
||||
**日内 = 秒 % 86400**
|
||||
|
||||
**时 = 日内 // 3600**
|
||||
|
||||
**分 = 日内 % 3600 // 60**
|
||||
|
||||
**秒数 = 日内 % 60**
|
||||
|
||||
**日期 = 日期部件(天)**
|
||||
|
||||
**基 = 补零4(日期.年) + "-" + 补零2(日期.月) + "-" + 补零2(日期.日) + "T" + 补零2(时) + ":" + 补零2(分) + ":" + 补零2(秒数)**
|
||||
|
||||
1. `毫 == 0`
|
||||
|
||||
*基 + "Z"*
|
||||
|
||||
*基 + "." + 补零3(毫) + "Z"*
|
||||
|
||||
## 解析
|
||||
|
||||
`(文本)`
|
||||
|
||||
解析 `YYYY-MM-DDTHH:MM:SSZ` 或带 `.mmm` 的 UTC 文本,返回 Unix 毫秒。
|
||||
范围、闰年和格式错误都是可恢复 `datetime.invalid`。
|
||||
|
||||
**点 = text.codepoints(文本)**
|
||||
|
||||
1. `长度(点) < 20 or 长度(点) > 24`
|
||||
|
||||
*失败("长度不是 20–24 个码点")*
|
||||
|
||||
1. `点[4] != 45 or 点[7] != 45 or 点[10] != 84 or 点[13] != 58 or 点[16] != 58`
|
||||
|
||||
*失败("分隔符不符合 YYYY-MM-DDTHH:MM:SS")*
|
||||
|
||||
**年文本 = 片段(点, 0, 4)**
|
||||
|
||||
**月文本 = 片段(点, 5, 7)**
|
||||
|
||||
**日文本 = 片段(点, 8, 10)**
|
||||
|
||||
**时文本 = 片段(点, 11, 13)**
|
||||
|
||||
**分文本 = 片段(点, 14, 16)**
|
||||
|
||||
**秒文本 = 片段(点, 17, 19)**
|
||||
|
||||
1. `not 是数字串(年文本) or not 是数字串(月文本) or not 是数字串(日文本) or not 是数字串(时文本) or not 是数字串(分文本) or not 是数字串(秒文本)`
|
||||
|
||||
*失败("日期时间分量必须是数字")*
|
||||
|
||||
**年 = 整数(年文本)**
|
||||
|
||||
**月 = 整数(月文本)**
|
||||
|
||||
**日 = 整数(日文本)**
|
||||
|
||||
**时 = 整数(时文本)**
|
||||
|
||||
**分 = 整数(分文本)**
|
||||
|
||||
**秒 = 整数(秒文本)**
|
||||
|
||||
**毫文本 = "0"**
|
||||
|
||||
**结束 = 20**
|
||||
|
||||
1. `长度(点) >= 24 and 点[19] == 46 and 点[23] == 90`
|
||||
|
||||
**毫文本 = 片段(点, 20, 23)**
|
||||
|
||||
**结束 = 24**
|
||||
|
||||
1. `长度(点) != 结束 or 点[结束 - 1] != 90`
|
||||
|
||||
*失败("必须以 Z 结尾")*
|
||||
|
||||
1. `not 是数字串(毫文本)`
|
||||
|
||||
*失败("毫秒必须是数字")*
|
||||
|
||||
**毫 = 整数(毫文本)**
|
||||
|
||||
1. `年 < 1970 or 月 < 1 or 月 > 12 or 日 < 1 or 日 > 每月天数(年, 月)`
|
||||
|
||||
*失败("日期超出范围")*
|
||||
|
||||
1. `时 < 0 or 时 > 23 or 分 < 0 or 分 > 59 or 秒 < 0 or 秒 > 59`
|
||||
|
||||
*失败("时间超出范围")*
|
||||
|
||||
**毫秒 = 日期序号(年, 月, 日) * 86400000 + 时 * 3600000 + 分 * 60000 + 秒 * 1000 + 毫**
|
||||
|
||||
*{ok: true, value: 毫秒}*
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.1.0",
|
||||
"digest": "sha256:b692e264f046098b83c8046ae9c19ba03c116a078eaac3bdcf207d121e794ffb"
|
||||
"digest": "sha256:030562dbce90a671f86fdef984620699925b39a302e2b68639ca752a94adde9c"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
import:
|
||||
clock: "std:clock"
|
||||
---
|
||||
|
||||
## main
|
||||
|
||||
**现在 = clock.现在()**
|
||||
|
||||
*[现在.ok, 类型(现在.value), 现在.value > 1600000000000]*
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
import:
|
||||
datetime: "std:datetime"
|
||||
---
|
||||
|
||||
## main
|
||||
|
||||
*[datetime.格式化(0), datetime.格式化(1700000000123), datetime.解析("1970-01-01T00:00:00Z").value, datetime.解析("2026-11-21T08:00:00.123Z").value, datetime.解析("2026-13-01T00:00:00Z").ok, datetime.解析("2026-02-29T00:00:00Z").ok, datetime.格式化(-1)]*
|
||||
Reference in new issue
Block a user