diff --git a/kclvm/Cargo.lock b/kclvm/Cargo.lock
index 2fda15ad3..fb93d48aa 100644
--- a/kclvm/Cargo.lock
+++ b/kclvm/Cargo.lock
@@ -868,9 +868,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
-version = "0.4.8"
+version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "259d404d09818dec19332e31d94558aeb442fea04c817006456c24b5460bbd4b"
+checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3"
dependencies = [
"serde",
"serde_core",
@@ -884,7 +884,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1260,15 +1260,6 @@ dependencies = [
"digest 0.10.7",
]
-[[package]]
-name = "home"
-version = "0.5.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5"
-dependencies = [
- "windows-sys 0.52.0",
-]
-
[[package]]
name = "hostname"
version = "0.4.1"
@@ -1684,7 +1675,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1910,7 +1901,6 @@ dependencies = [
"prost-types",
"prost-wkt",
"prost-wkt-build",
- "prost-wkt-types",
"protoc-bin-vendored",
"serde",
"serde_json",
@@ -2408,12 +2398,6 @@ dependencies = [
"serde",
]
-[[package]]
-name = "linux-raw-sys"
-version = "0.4.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
-
[[package]]
name = "linux-raw-sys"
version = "0.11.0"
@@ -3028,12 +3012,12 @@ dependencies = [
[[package]]
name = "prettyplease"
-version = "0.1.25"
+version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
- "syn 1.0.109",
+ "syn 2.0.108",
]
[[package]]
@@ -3062,9 +3046,9 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.11.9"
+version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd"
+checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d"
dependencies = [
"bytes",
"prost-derive",
@@ -3072,51 +3056,51 @@ dependencies = [
[[package]]
name = "prost-build"
-version = "0.11.9"
+version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "119533552c9a7ffacc21e099c24a0ac8bb19c2a2a3f363de84cd9b844feab270"
+checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1"
dependencies = [
- "bytes",
"heck 0.4.1",
"itertools",
- "lazy_static",
"log",
"multimap",
+ "once_cell",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
- "syn 1.0.109",
+ "syn 2.0.108",
"tempfile",
- "which",
]
[[package]]
name = "prost-derive"
-version = "0.11.9"
+version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
+checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425"
dependencies = [
"anyhow",
"itertools",
"proc-macro2",
"quote",
- "syn 1.0.109",
+ "syn 2.0.108",
]
[[package]]
name = "prost-types"
-version = "0.11.9"
+version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13"
+checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72"
dependencies = [
"prost",
]
[[package]]
name = "prost-wkt"
-version = "0.4.1"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "655944d0ce015e71b3ec21279437e6a09e58433e50c7b0677901f3d5235e74f5"
dependencies = [
"chrono",
"inventory",
@@ -3129,7 +3113,9 @@ dependencies = [
[[package]]
name = "prost-wkt-build"
-version = "0.4.1"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f869f1443fee474b785e935d92e1007f57443e485f51668ed41943fc01a321a2"
dependencies = [
"heck 0.4.1",
"prost",
@@ -3138,30 +3124,15 @@ dependencies = [
"quote",
]
-[[package]]
-name = "prost-wkt-types"
-version = "0.4.1"
-dependencies = [
- "chrono",
- "prost",
- "prost-build",
- "prost-types",
- "prost-wkt",
- "prost-wkt-build",
- "protoc-bin-vendored",
- "regex",
- "serde",
- "serde_derive",
- "serde_json",
-]
-
[[package]]
name = "protoc-bin-vendored"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa"
dependencies = [
"protoc-bin-vendored-linux-aarch_64",
"protoc-bin-vendored-linux-ppcle_64",
+ "protoc-bin-vendored-linux-s390_64",
"protoc-bin-vendored-linux-x86_32",
"protoc-bin-vendored-linux-x86_64",
"protoc-bin-vendored-macos-aarch_64",
@@ -3172,37 +3143,50 @@ dependencies = [
[[package]]
name = "protoc-bin-vendored-linux-aarch_64"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c"
[[package]]
name = "protoc-bin-vendored-linux-ppcle_64"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c"
+
+[[package]]
+name = "protoc-bin-vendored-linux-s390_64"
+version = "3.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0"
[[package]]
name = "protoc-bin-vendored-linux-x86_32"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5"
[[package]]
name = "protoc-bin-vendored-linux-x86_64"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78"
[[package]]
name = "protoc-bin-vendored-macos-aarch_64"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092"
[[package]]
name = "protoc-bin-vendored-macos-x86_64"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756"
[[package]]
name = "protoc-bin-vendored-win32"
version = "3.2.0"
-source = "git+https://github.com/kcl-lang/rust-protoc-bin-vendored#53c1f87ffc3027642ea6b822025b1dc699a3135b"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
[[package]]
name = "quinn"
@@ -3686,19 +3670,6 @@ dependencies = [
"semver 1.0.27",
]
-[[package]]
-name = "rustix"
-version = "0.38.44"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
-dependencies = [
- "bitflags 2.10.0",
- "errno",
- "libc",
- "linux-raw-sys 0.4.15",
- "windows-sys 0.59.0",
-]
-
[[package]]
name = "rustix"
version = "1.1.2"
@@ -3708,8 +3679,8 @@ dependencies = [
"bitflags 2.10.0",
"errno",
"libc",
- "linux-raw-sys 0.11.0",
- "windows-sys 0.52.0",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -4228,8 +4199,8 @@ dependencies = [
"fastrand",
"getrandom 0.3.4",
"once_cell",
- "rustix 1.1.2",
- "windows-sys 0.52.0",
+ "rustix",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -5032,18 +5003,6 @@ dependencies = [
"rustls-pki-types",
]
-[[package]]
-name = "which"
-version = "4.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
-dependencies = [
- "either",
- "home",
- "once_cell",
- "rustix 0.38.44",
-]
-
[[package]]
name = "winapi"
version = "0.3.9"
@@ -5066,7 +5025,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.48.0",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -5471,7 +5430,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
- "rustix 1.1.2",
+ "rustix",
]
[[package]]
diff --git a/kclvm/Cargo.toml b/kclvm/Cargo.toml
index 679b3163d..5aae89d5b 100644
--- a/kclvm/Cargo.toml
+++ b/kclvm/Cargo.toml
@@ -37,9 +37,6 @@ lto = true
[workspace]
members = [
- "third-party/prost-wkt",
- "third-party/prost-wkt/wkt-build",
- "third-party/prost-wkt/wkt-types",
"primitives",
"api",
"cmd",
diff --git a/kclvm/api/Cargo.toml b/kclvm/api/Cargo.toml
index 32f606a72..b64dfbdcd 100644
--- a/kclvm/api/Cargo.toml
+++ b/kclvm/api/Cargo.toml
@@ -7,16 +7,16 @@ edition = "2021"
futures = "0.3.28"
tempfile = "3.5.0"
maplit = "1.0.2"
-prost = "0.11.8"
-prost-types = "0.11.8"
+
serde_json = "1.0"
serde_yaml_ng = "0.10.0"
anyhow = "1.0.70"
serde = { version = "1", features = ["derive"] }
once_cell = "1.5.2"
-prost-wkt = { path = "../third-party/prost-wkt", version = "0.4.1" }
-prost-wkt-types = { path = "../third-party/prost-wkt/wkt-types", version = "0.4.1" }
+prost = "0.14.1"
+prost-wkt = "0.7.0"
+prost-types = "0.14.1"
kclvm-runner = { path = "../runner" }
kclvm-config = { path = "../config" }
@@ -43,9 +43,9 @@ tokio = { version = "1.37.0", features = ["full"] }
criterion = "0.5"
[build-dependencies]
-protoc-bin-vendored = { git = "https://github.com/kcl-lang/rust-protoc-bin-vendored", version = "3.2.0" }
-prost-build = "0.11.8"
-prost-wkt-build = { path = "../third-party/prost-wkt/wkt-build", version = "0.4.1" }
+protoc-bin-vendored = "3.2.0"
+prost-build = "0.14.1"
+prost-wkt-build = "0.7.0"
[features]
llvm = ["kclvm-runner/llvm"]
diff --git a/kclvm/api/src/capi_test.rs b/kclvm/api/src/capi_test.rs
index 004e434aa..d3a05d1e0 100644
--- a/kclvm/api/src/capi_test.rs
+++ b/kclvm/api/src/capi_test.rs
@@ -273,7 +273,7 @@ fn test_c_api_testing() {
fn test_c_api_without_wrapper(svc_name: &str, input: &str, output: &str)
where
A: Message + DeserializeOwned,
- R: Message + Default + PartialEq + DeserializeOwned + serde::Serialize,
+ R: Message + Default + std::fmt::Debug + PartialEq + DeserializeOwned + serde::Serialize,
{
test_c_api::(svc_name, input, output, |_| {})
}
@@ -281,7 +281,13 @@ where
fn test_c_api(svc_name: &str, input: &str, output: &str, wrapper: F)
where
A: Message + DeserializeOwned,
- R: Message + Default + PartialEq + DeserializeOwned + serde::Serialize + ?Sized,
+ R: Message
+ + Default
+ + std::fmt::Debug
+ + PartialEq
+ + DeserializeOwned
+ + serde::Serialize
+ + ?Sized,
F: Fn(&mut R),
{
let _test_lock = TEST_MUTEX.lock().unwrap();
diff --git a/kclvm/runner/src/linker.rs b/kclvm/runner/src/linker.rs
index 81d1b661b..e6aefa782 100644
--- a/kclvm/runner/src/linker.rs
+++ b/kclvm/runner/src/linker.rs
@@ -54,7 +54,6 @@ impl Command {
.cargo_metadata(false)
.no_default_flags(false)
.pic(true)
- .shared_flag(true)
.opt_level(0)
.target(&target)
.host(&target)
diff --git a/kclvm/runner/src/runner.rs b/kclvm/runner/src/runner.rs
index 82d71e049..cfa1449c7 100644
--- a/kclvm/runner/src/runner.rs
+++ b/kclvm/runner/src/runner.rs
@@ -467,7 +467,7 @@ thread_local! {
#[cfg(target_arch = "wasm32")]
static ONCE_PANIC_HOOK: Lazy<()> = Lazy::new(|| {
- std::panic::set_hook(Box::new(|info: &std::panic::PanicInfo| {
+ std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| {
KCL_RUNTIME_PANIC_RECORD.with(|record| {
let mut record = record.borrow_mut();
record.kcl_panic_info = true;
diff --git a/kclvm/runtime/src/net/mod.rs b/kclvm/runtime/src/net/mod.rs
index e87a5a812..f53b7dd84 100644
--- a/kclvm/runtime/src/net/mod.rs
+++ b/kclvm/runtime/src/net/mod.rs
@@ -238,7 +238,7 @@ pub extern "C-unwind" fn kclvm_net_to_IP6(
let s = format!("{addr}");
return ValueRef::str(s.as_ref()).into_raw(ctx);
}
- Err(e) => {
+ Err(_) => {
match Ipv4Addr::from_str(ip.as_ref()) {
Ok(addr) => {
// Convert IPv4 to IPv6-mapped address (::ffff:0:0/96)
diff --git a/kclvm/src/capi.rs b/kclvm/src/capi.rs
index 65e39378a..31cf412bb 100644
--- a/kclvm/src/capi.rs
+++ b/kclvm/src/capi.rs
@@ -198,7 +198,7 @@ pub unsafe extern "C-unwind" fn kcl_run(
match intern_run(filename, src) {
Ok(result) => CString::new(result.yaml_result).unwrap().into_raw(),
- Err(err) => CString::new(format!("ERROR:{}", err)).unwrap().into_raw(),
+ Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(),
}
}
@@ -218,7 +218,7 @@ pub unsafe extern "C-unwind" fn kcl_run_with_log_message(
Ok(result) => CString::new(result.log_message + &result.yaml_result)
.unwrap()
.into_raw(),
- Err(err) => CString::new(format!("ERROR:{}", err)).unwrap().into_raw(),
+ Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(),
}
}
@@ -232,7 +232,7 @@ pub unsafe extern "C-unwind" fn kcl_fmt(src_ptr: *const c_char) -> *const c_char
match intern_fmt(src) {
Ok(result) => CString::new(result).unwrap().into_raw(),
- Err(err) => CString::new(format!("ERROR:{}", err)).unwrap().into_raw(),
+ Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(),
}
}
diff --git a/kclvm/third-party/prost-wkt/.gitignore b/kclvm/third-party/prost-wkt/.gitignore
deleted file mode 100644
index 96ef6c0b9..000000000
--- a/kclvm/third-party/prost-wkt/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/target
-Cargo.lock
diff --git a/kclvm/third-party/prost-wkt/Cargo.toml b/kclvm/third-party/prost-wkt/Cargo.toml
deleted file mode 100644
index c25fbf9d0..000000000
--- a/kclvm/third-party/prost-wkt/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-[package]
-name = "prost-wkt"
-version = "0.4.1"
-authors = ["fdeantoni "]
-license = "Apache-2.0"
-repository = "https://github.com/fdeantoni/prost-wkt"
-description = "Helper crate for prost to allow JSON serialization and deserialization of Well Known Types."
-readme = "README.md"
-documentation = "https://docs.rs/prost-wkt-derive"
-edition = "2021"
-
-[dependencies]
-prost = "0.11.6"
-inventory = "0.3.0"
-serde = "1.0"
-serde_json = "1.0"
-serde_derive = "1.0"
-chrono = { version = "0.4", default-features = false, features = ["serde"] }
-typetag = "0.2"
diff --git a/kclvm/third-party/prost-wkt/LICENSE b/kclvm/third-party/prost-wkt/LICENSE
deleted file mode 100644
index 16fe87b06..000000000
--- a/kclvm/third-party/prost-wkt/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
-Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/kclvm/third-party/prost-wkt/README.md b/kclvm/third-party/prost-wkt/README.md
deleted file mode 100644
index d39122a6b..000000000
--- a/kclvm/third-party/prost-wkt/README.md
+++ /dev/null
@@ -1,303 +0,0 @@
-# *PROST Well Known Types JSON Serialization and Deserialization* #
-[](https://crates.io/crates/prost-wkt-types) [](https://github.com/fdeantoni/prost-wkt/actions/workflows/rust.yml)
-
-[Prost](https://github.com/tokio-rs/prost) is a [Protocol Buffers](https://developers.google.com/protocol-buffers/)
-implementation for the [Rust Language](https://www.rust-lang.org/) that generates simple, idiomatic Rust code from
-`proto2` and `proto3` files.
-
-It includes `prost-types` which gives basic support for protobuf Well-Known-Types (WKT), but support is basic. For
-example, it does not include packing or unpacking of messages in the `Any` type, nor much support in the way of JSON
-serialization and deserialization of that type.
-
-This crate can help you if you need:
- - helper methods for packing and unpacking messages to/from an [Any](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Any),
- - helper methods for converting [chrono](https://github.com/chronotope/chrono) types to [Timestamp](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp) and back again,
- - helper methods for converting common rust types to [Value](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value) and back again,
- - serde support for the types above.
-
-To use it, include this crate along with prost:
-
-```toml
-[dependencies]
-prost = "0.11"
-prost-wkt = "0.4"
-prost-wkt-types = "0.4"
-serde = { version = "1.0", features = ["derive"] }
-
-[build-dependencies]
-prost-build = "0.11"
-prost-wkt-build = "0.4"
-```
-
-In your `build.rs`, make sure to add the following options:
-```rust
-use std::{env, path::PathBuf};
-use prost_wkt_build::*;
-
-fn main() {
- let out = PathBuf::from(env::var("OUT_DIR").unwrap());
- let descriptor_file = out.join("descriptors.bin");
- let mut prost_build = prost_build::Config::new();
- prost_build
- .type_attribute(
- ".",
- "#[derive(serde::Serialize,serde::Deserialize)]"
- )
- .extern_path(
- ".google.protobuf.Any",
- "::prost_wkt_types::Any"
- )
- .extern_path(
- ".google.protobuf.Timestamp",
- "::prost_wkt_types::Timestamp"
- )
- .extern_path(
- ".google.protobuf.Value",
- "::prost_wkt_types::Value"
- )
- .file_descriptor_set_path(&descriptor_file)
- .compile_protos(
- &[
- "proto/messages.proto"
- ],
- &["proto/"],
- )
- .unwrap();
-
- let descriptor_bytes =
- std::fs::read(descriptor_file)
- .unwrap();
-
- let descriptor =
- FileDescriptorSet::decode(&descriptor_bytes[..])
- .unwrap();
-
- prost_wkt_build::add_serde(out, descriptor);
-}
-```
-
-The above configuration will include `Serialize`, and `Deserialize` on each generated struct. This will allow you to
-use `serde` fully. Moreover, it ensures that the `Any` type is deserialized properly as JSON. For example, assume we
-have the following messages defined in our proto file:
-
-```proto
-syntax = "proto3";
-
-import "google/protobuf/any.proto";
-import "google/protobuf/timestamp.proto";
-
-package my.pkg;
-
-message Request {
- string requestId = 1;
- google.protobuf.Any payload = 2;
-}
-
-message Foo {
- string data = 1;
- google.protobuf.Timestamp timestamp = 2;
-}
-```
-
-After generating the rust structs for the above using `prost-build` with the above configuration, you will then be able
-to do the following:
-
-```rust
-use serde::{Deserialize, Serialize};
-use chrono::prelude::*;
-
-use prost_wkt_types::*;
-
-include!(concat!(env!("OUT_DIR"), "/my.pkg.rs"));
-
-fn main() -> Result<(), AnyError> {
- let foo_msg: Foo = Foo {
- data: "Hello World".to_string(),
- timestamp: Some(Utc::now().into()),
- };
-
- let mut request: Request = Request::default();
- let any = Any::try_pack(foo_msg)?;
- request.request_id = "test1".to_string();
- request.payload = Some(any);
-
- let json = serde_json::to_string_pretty(&request).expect("Failed to serialize request");
-
- println!("JSON:\n{}", json);
-
- let back: Request = serde_json::from_str(&json).expect("Failed to deserialize request");
-
- if let Some(payload) = back.payload {
- let unpacked: Box< dyn MessageSerde> = payload.try_unpack()?;
-
- let unpacked_foo: &Foo = unpacked
- .downcast_ref::()
- .expect("Failed to downcast payload to Foo");
-
- println!("Unpacked: {:?}", unpacked_foo);
- }
-}
-```
-
-The above will generate the following stdout:
-
-```
-JSON:
-{
- "requestId": "test1",
- "payload": {
- "@type": "type.googleapis.com/my.pkg.Foo",
- "data": "Hello World",
- "timestamp": "2020-05-25T12:19:57.755998Z"
- }
-}
-Unpacked: Foo { data: "Hello World", timestamp: Some(Timestamp { seconds: 1590409197, nanos: 755998000 }) }
-```
-
-Notice that the request message is properly serialized to JSON as per the [protobuf specification](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Any),
-and that it can be deserialized as well.
-
-See the `example` sub-project for a fully functioning example.
-
-## Known Problems ##
-
-### oneOf types ###
-
-The way `prost-build` generates the `oneOf` type is to place it in a sub module, for example:
-
-```proto
-message SomeOne {
- oneof body {
- string some_string = 1;
- bool some_bool = 2;
- float some_float = 3;
- }
-}
-```
-
-is converted to rust as follows:
-```rust
-#[derive(Serialize, Deserialize)]
-#[derive(Clone, PartialEq, ::prost::Message)]
-#[prost(package="my.pkg")]
-pub struct SomeOne {
- #[prost(oneof="some_one::Body", tags="1, 2, 3")]
- pub body: ::core::option::Option,
-}
-/// Nested message and enum types in `SomeOne`.
-pub mod some_one {
- #[derive(Serialize, Deserialize)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
- pub enum Body {
- #[prost(string, tag="1")]
- SomeString(::prost::alloc::string::String),
- #[prost(bool, tag="2")]
- SomeBool(bool),
- #[prost(float, tag="3")]
- SomeFloat(f32),
- }
-}
-```
-
-However, rust requires the importation of macros in each module, so each should have the following added:
-```rust
-use serde::{Serialize, Deserialize};
-```
-
-In the generated code snippet, the above statement is missing in the `some_one` module, and the rust compiler will
-complain about it. To fix it, we would have to add the appropriate use statement in the `some_one` module like so:
-```rust
-#[derive(Serialize, Deserialize)]
-#[derive(Clone, PartialEq, ::prost::Message)]
-#[prost(package="my.pkg")]
-pub struct SomeOne {
- #[prost(oneof="some_one::Body", tags="1, 2, 3")]
- pub body: ::core::option::Option,
-}
-/// Nested message and enum types in `SomeOne`.
-pub mod some_one {
- use serde::{Serialize, Deserialize};
- #[derive(Serialize, Deserialize)]
- #[derive(Clone, PartialEq, ::prost::Oneof)]
- pub enum Body {
- #[prost(string, tag="1")]
- SomeString(::prost::alloc::string::String),
- #[prost(bool, tag="2")]
- SomeBool(bool),
- #[prost(float, tag="3")]
- SomeFloat(f32),
- }
-}
-```
-
-Luckily, you can achieve the above by tweaking the `build.rs`. The configuration below, for example, will add the
-required serde import to the `some_one` module as needed:
-```rust
-fn main() {
- let out = PathBuf::from(env::var("OUT_DIR").unwrap());
- let descriptor_file = out.join("descriptors.bin");
- let mut prost_build = prost_build::Config::new();
- prost_build
- .type_attribute(
- ".my.pkg.MyEnum",
- "#[derive(serde::Serialize,serde::Deserialize)]"
- )
- .type_attribute(
- ".my.pkg.MyMessage",
- "#[derive(serde::Serialize,serde::Deserialize)] #[serde(default)]"
- )
- .type_attribute(
- ".my.pkg.SomeOne.body",
- "#[derive(serde::Serialize,serde::Deserialize)]"
- )
- .extern_path(
- ".google.protobuf.Any",
- "::prost_wkt_types::Any"
- )
- .extern_path(
- ".google.protobuf.Timestamp",
- "::prost_wkt_types::Timestamp"
- )
- .extern_path(
- ".google.protobuf.Value",
- "::prost_wkt_types::Value"
- )
- .file_descriptor_set_path(&descriptor_file)
- .compile_protos(
- &[
- "proto/messages.proto"
- ],
- &["proto/"],
- )
- .unwrap();
-
- let descriptor_bytes =
- std::fs::read(descriptor_file).unwrap();
-
- let descriptor =
- FileDescriptorSet::decode(&descriptor_bytes[..]).unwrap();
-
- prost_wkt_build::add_serde(out, descriptor);
-}
-```
-
-## Development ##
-
-Contributions are welcome!
-
-### Upgrading Prost ###
-
-When upgrading Prost to the latest version, make sure to also run `wkt-types/resources/update.sh` script. This will
-grab the latest source files from `prost-types` and merge them into `prost-wkt-types` at build time. After the script
-has run, be sure to validate that the selected line numbers in functions `process_prost_types_lib` and
-`process_prost_types_datetime` in the `wkt-types/build.rs` are still correct!
-
-Please see `wkt-types/README.md` for more info.
-
-## License ##
-
-`prost-wkt` is distributed under the terms of the Apache License (Version 2.0).
-
-See [LICENSE](LICENSE) for details.
-
-Copyright 2023 Ferdinand de Antoni
diff --git a/kclvm/third-party/prost-wkt/src/lib.rs b/kclvm/third-party/prost-wkt/src/lib.rs
deleted file mode 100644
index 0186a6e1f..000000000
--- a/kclvm/third-party/prost-wkt/src/lib.rs
+++ /dev/null
@@ -1,95 +0,0 @@
-pub use inventory;
-
-pub use typetag;
-
-/// Trait to support serialization and deserialization of `prost` messages.
-#[typetag::serde(tag = "@type")]
-pub trait MessageSerde: prost::Message + std::any::Any {
- /// message name as in proto file
- fn message_name(&self) -> &'static str;
- /// package name as in proto file
- fn package_name(&self) -> &'static str;
- /// the message proto type url e.g. type.googleapis.com/my.package.MyMessage
- fn type_url(&self) -> &'static str;
- /// Creates a new instance of this message using the protobuf encoded data
- fn new_instance(&self, data: Vec) -> Result, prost::DecodeError>;
- /// Returns the encoded protobuf message as bytes
- fn try_encoded(&self) -> Result, prost::EncodeError>;
-}
-
-/// The implementation here is a direct copy of the `impl dyn` of [`std::any::Any`]!
-impl dyn MessageSerde {
- /// Returns `true` if the inner type is the same as `T`.
- #[inline]
- pub fn is(&self) -> bool {
- // Get `TypeId` of the type this function is instantiated with.
- let t = std::any::TypeId::of::();
-
- // Get `TypeId` of the type in the trait object (`self`).
- let concrete = self.type_id();
-
- // Compare both `TypeId`s on equality.
- t == concrete
- }
-
- /// Returns some reference to the inner value if it is of type `T`, or
- /// `None` if it isn't.
- #[inline]
- pub fn downcast_ref(&self) -> Option<&T> {
- if self.is::() {
- // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
- // that check for memory safety because we have implemented Any for all types; no other
- // impls can exist as they would conflict with our impl.
- unsafe { Some(self.downcast_ref_unchecked()) }
- } else {
- Option::None
- }
- }
-
- /// Returns some mutable reference to the boxed value if it is of type `T`,
- /// or `None` if it isn't.
- #[inline]
- pub fn downcast_mut(&mut self) -> Option<&mut T> {
- if self.is::() {
- // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
- // that check for memory safety because we have implemented Any for all types; no other
- // impls can exist as they would conflict with our impl.
- unsafe { Some(self.downcast_mut_unchecked()) }
- } else {
- Option::None
- }
- }
-
- /// Returns a reference to the inner value as type `dyn T`.
- ///
- /// # Safety
- ///
- /// The contained value must be of type `T`. Calling this method
- /// with the incorrect type is *undefined behavior*.
- #[inline]
- pub unsafe fn downcast_ref_unchecked(&self) -> &T {
- debug_assert!(self.is::());
- // SAFETY: caller guarantees that T is the correct type
- unsafe { &*(self as *const dyn MessageSerde as *const T) }
- }
-
- /// Returns a mutable reference to the inner value as type `dyn T`.
- ///
- /// # Safety
- ///
- /// The contained value must be of type `T`. Calling this method
- /// with the incorrect type is *undefined behavior*.
- #[inline]
- pub unsafe fn downcast_mut_unchecked(&mut self) -> &mut T {
- &mut *(self as *mut Self as *mut T)
- }
-}
-
-type MessageSerdeDecoderFn = fn(&[u8]) -> Result, ::prost::DecodeError>;
-
-pub struct MessageSerdeDecoderEntry {
- pub type_url: &'static str,
- pub decoder: MessageSerdeDecoderFn,
-}
-
-inventory::collect!(MessageSerdeDecoderEntry);
diff --git a/kclvm/third-party/prost-wkt/wkt-build/Cargo.toml b/kclvm/third-party/prost-wkt/wkt-build/Cargo.toml
deleted file mode 100644
index 690baf2de..000000000
--- a/kclvm/third-party/prost-wkt/wkt-build/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "prost-wkt-build"
-version = "0.4.1"
-authors = ["fdeantoni "]
-license = "Apache-2.0"
-repository = "https://github.com/fdeantoni/prost-wkt"
-description = "Helper crate for prost to allow JSON serialization and deserialization of Well Known Types."
-readme = "../README.md"
-documentation = "https://docs.rs/prost-wkt-build"
-edition = "2021"
-
-[dependencies]
-prost = "0.11.6"
-prost-types = "0.11.5"
-prost-build = "0.11.5"
-quote = "1.0"
-heck = "0.4"
diff --git a/kclvm/third-party/prost-wkt/wkt-build/src/lib.rs b/kclvm/third-party/prost-wkt/wkt-build/src/lib.rs
deleted file mode 100644
index c576f0a7e..000000000
--- a/kclvm/third-party/prost-wkt/wkt-build/src/lib.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-use heck::{ToShoutySnakeCase, ToUpperCamelCase};
-use quote::{format_ident, quote};
-use std::fs::{File, OpenOptions};
-use std::io::Write;
-use std::path::PathBuf;
-
-pub use prost::Message;
-pub use prost_types::FileDescriptorSet;
-
-use prost_build::Module;
-
-pub fn add_serde(out: PathBuf, descriptor: FileDescriptorSet) {
- for fd in &descriptor.file {
- let package_name = match fd.package {
- Some(ref pkg) => pkg,
- None => continue,
- };
-
- let rust_path = out
- .join(Module::from_protobuf_package_name(package_name).to_file_name_or(package_name));
-
- // In some cases the generated file would be in empty. These files are no longer created by Prost, so
- // we'll create here. Otherwise we append.
- let mut rust_file = OpenOptions::new()
- .create(true)
- .append(true)
- .open(rust_path)
- .unwrap();
-
- for msg in &fd.message_type {
- let message_name = match msg.name {
- Some(ref name) => name,
- None => continue,
- };
-
- let type_url = format!("type.googleapis.com/{package_name}.{message_name}");
-
- gen_trait_impl(&mut rust_file, package_name, message_name, &type_url);
- }
- }
-}
-
-// This method uses the `heck` crate (the same that prost uses) to properly format the message name
-// to UpperCamelCase as the prost_build::ident::{to_snake, to_upper_camel} methods
-// in the `ident` module of prost_build is private.
-fn gen_trait_impl(rust_file: &mut File, package_name: &str, message_name: &str, type_url: &str) {
- let type_name = message_name.to_upper_camel_case();
- let type_name = format_ident!("{}", type_name);
-
- let dummy_const = format_ident!(
- "IMPL_MESSAGE_SERDE_FOR_{}",
- message_name.to_shouty_snake_case()
- );
-
- let tokens = quote! {
- #[allow(dead_code)]
- const #dummy_const: () = {
- use ::prost_wkt::typetag;
- #[typetag::serde(name=#type_url)]
- impl ::prost_wkt::MessageSerde for #type_name {
- fn package_name(&self) -> &'static str {
- #package_name
- }
- fn message_name(&self) -> &'static str {
- #message_name
- }
- fn type_url(&self) -> &'static str {
- #type_url
- }
- fn new_instance(&self, data: Vec) -> Result, ::prost::DecodeError> {
- let mut target = Self::default();
- ::prost::Message::merge(&mut target, data.as_slice())?;
- let erased: Box = Box::new(target);
- Ok(erased)
- }
- fn try_encoded(&self) -> Result, ::prost::EncodeError> {
- let mut buf = Vec::new();
- buf.reserve(::prost::Message::encoded_len(self));
- ::prost::Message::encode(self, &mut buf)?;
- Ok(buf)
- }
- }
-
- ::prost_wkt::inventory::submit!{
- ::prost_wkt::MessageSerdeDecoderEntry {
- type_url: #type_url,
- decoder: |buf: &[u8]| {
- let msg: #type_name = ::prost::Message::decode(buf)?;
- Ok(Box::new(msg))
- }
- }
- }
- };
- };
-
- writeln!(rust_file).unwrap();
- writeln!(rust_file, "{}", &tokens).unwrap();
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/Cargo.toml b/kclvm/third-party/prost-wkt/wkt-types/Cargo.toml
deleted file mode 100644
index cd3ffdfac..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/Cargo.toml
+++ /dev/null
@@ -1,35 +0,0 @@
-[package]
-name = "prost-wkt-types"
-version = "0.4.1"
-authors = ["fdeantoni "]
-license = "Apache-2.0"
-repository = "https://github.com/fdeantoni/prost-wkt"
-description = "Helper crate for prost to allow JSON serialization and deserialization of Well Known Types."
-readme = "../README.md"
-documentation = "https://docs.rs/prost-wkt"
-keywords = ["protobuf", "serde", "json"]
-categories = ["encoding"]
-edition = "2021"
-
-[lib]
-doctest = false
-
-[features]
-default = ["std"]
-std = []
-
-[dependencies]
-prost-wkt = { version = "0.4.1", path = ".." }
-prost = "0.11.6"
-serde = "1.0"
-serde_json = "1.0"
-serde_derive = "1.0"
-chrono = { version = "0.4", default-features = false, features = ["serde"] }
-
-[build-dependencies]
-protoc-bin-vendored = { git = "https://github.com/kcl-lang/rust-protoc-bin-vendored", version = "3.2.0" }
-prost = "0.11.6"
-prost-types = "0.11.5"
-prost-build = "0.11.5"
-prost-wkt-build = { version = "0.4.1", path = "../wkt-build" }
-regex = "1"
diff --git a/kclvm/third-party/prost-wkt/wkt-types/build.rs b/kclvm/third-party/prost-wkt/wkt-types/build.rs
deleted file mode 100644
index 620c759ae..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/build.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-//6 April 2023 - Modified by NeverRaR
-use std::env;
-use std::fs::create_dir_all;
-use std::path::{Path, PathBuf};
-
-use std::fs::File;
-use std::io::Write;
-
-use prost::Message;
-use prost_types::FileDescriptorSet;
-
-use regex::Regex;
-
-fn main() {
- //hack: set protoc_bin_vendored::protoc_bin_path() to PROTOC
- if env::var("PROTOC").is_err() {
- env::set_var(
- "PROTOC",
- protoc_bin_vendored::protoc_bin_path().unwrap().as_os_str(),
- );
- }
- let dir = PathBuf::from(env::var("OUT_DIR").unwrap());
- process_prost_pbtime(&dir);
-
- build(&dir, "pbtime");
- build(&dir, "pbstruct");
- build(&dir, "pbany");
- build(&dir, "pbempty");
-}
-
-fn build(dir: &Path, proto: &str) {
- let out = dir.join(proto);
- create_dir_all(&out).unwrap();
- let source = format!("proto/{proto}.proto");
- let descriptor_file = out.join("descriptors.bin");
- let mut prost_build = prost_build::Config::new();
- prost_build
- .compile_well_known_types()
- .type_attribute(
- "google.protobuf.Duration",
- "#[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(default)]",
- )
- .type_attribute(
- "google.protobuf.Empty",
- "#[derive(serde_derive::Serialize, serde_derive::Deserialize)]",
- )
- .file_descriptor_set_path(&descriptor_file)
- .out_dir(&out)
- .compile_protos(&[source], &["proto/".to_string()])
- .unwrap();
-
- let descriptor_bytes = std::fs::read(descriptor_file).unwrap();
- let descriptor = FileDescriptorSet::decode(&descriptor_bytes[..]).unwrap();
-
- prost_wkt_build::add_serde(out, descriptor);
-}
-
-fn process_prost_pbtime(dir: &Path) {
- process_prost_types_lib(dir);
- process_prost_types_datetime(dir);
-}
-
-fn process_prost_types_lib(dir: &Path) {
- let source: String = std::fs::read_to_string("./resources/lib.rs").unwrap();
- let lines: Vec<&str> = source.split('\n').collect();
- let selection = &lines[25..402];
- let mut string = String::new();
- for line in selection {
- string.push_str(line);
- string.push('\n');
- }
-
- let file = dir.join("prost_snippet.rs");
- File::create(file)
- .unwrap()
- .write_all(string.as_bytes())
- .unwrap();
-}
-
-fn process_prost_types_datetime(dir: &Path) {
- let source: String = std::fs::read_to_string("./resources/datetime.rs").unwrap();
- let lines: Vec<&str> = source.split('\n').collect();
- let selection = &lines[0..585];
- let mut string = String::new();
- for line in selection {
- string.push_str(line);
- string.push('\n');
- }
-
- let re = Regex::new(r"crate").unwrap();
- let result = re.replace_all(&string, "super").to_string();
- let file = dir.join("datetime.rs");
- File::create(file)
- .unwrap()
- .write_all(result.as_bytes())
- .unwrap();
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/proto/pbany.proto b/kclvm/third-party/prost-wkt/wkt-types/proto/pbany.proto
deleted file mode 100644
index c096a1a85..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/proto/pbany.proto
+++ /dev/null
@@ -1,5 +0,0 @@
-syntax = "proto3";
-
-import "google/protobuf/any.proto";
-
-package pbany;
\ No newline at end of file
diff --git a/kclvm/third-party/prost-wkt/wkt-types/proto/pbempty.proto b/kclvm/third-party/prost-wkt/wkt-types/proto/pbempty.proto
deleted file mode 100644
index 3f217ae7b..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/proto/pbempty.proto
+++ /dev/null
@@ -1,5 +0,0 @@
-syntax = "proto3";
-
-import "google/protobuf/empty.proto";
-
-package empty;
diff --git a/kclvm/third-party/prost-wkt/wkt-types/proto/pbstruct.proto b/kclvm/third-party/prost-wkt/wkt-types/proto/pbstruct.proto
deleted file mode 100644
index cf64d69a9..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/proto/pbstruct.proto
+++ /dev/null
@@ -1,5 +0,0 @@
-syntax = "proto3";
-
-import "google/protobuf/struct.proto";
-
-package pbstruct;
\ No newline at end of file
diff --git a/kclvm/third-party/prost-wkt/wkt-types/proto/pbtime.proto b/kclvm/third-party/prost-wkt/wkt-types/proto/pbtime.proto
deleted file mode 100644
index 4e892062c..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/proto/pbtime.proto
+++ /dev/null
@@ -1,6 +0,0 @@
-syntax = "proto3";
-
-import "google/protobuf/duration.proto";
-import "google/protobuf/timestamp.proto";
-
-package pbtime;
diff --git a/kclvm/third-party/prost-wkt/wkt-types/resources/README.md b/kclvm/third-party/prost-wkt/wkt-types/resources/README.md
deleted file mode 100644
index ce60da696..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/resources/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-The files contained in this directory is from [prost-types](https://raw.githubusercontent.com/tokio-rs/prost/v0.10.0/prost-types/src/). It is used by `build.rs` to create the appropriate `prost_snippet.rs` in `./src/pbtime.rs`.
-
-When updating the Prost dependencies in this project you should run the `update.sh` script in this directory. This script
-will update the above mentioned files. If the files are updated, do validate whether the line numbers selected in the
-`../build.rs` are still correct.
diff --git a/kclvm/third-party/prost-wkt/wkt-types/resources/datetime.rs b/kclvm/third-party/prost-wkt/wkt-types/resources/datetime.rs
deleted file mode 100644
index f6c3cca1c..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/resources/datetime.rs
+++ /dev/null
@@ -1,869 +0,0 @@
-//! A date/time type which exists primarily to convert [`Timestamp`]s into an RFC 3339 formatted
-//! string.
-
-use core::fmt;
-
-use crate::Duration;
-use crate::Timestamp;
-
-/// A point in time, represented as a date and time in the UTC timezone.
-#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
-pub(crate) struct DateTime {
- /// The year.
- pub(crate) year: i64,
- /// The month of the year, from 1 to 12, inclusive.
- pub(crate) month: u8,
- /// The day of the month, from 1 to 31, inclusive.
- pub(crate) day: u8,
- /// The hour of the day, from 0 to 23, inclusive.
- pub(crate) hour: u8,
- /// The minute of the hour, from 0 to 59, inclusive.
- pub(crate) minute: u8,
- /// The second of the minute, from 0 to 59, inclusive.
- pub(crate) second: u8,
- /// The nanoseconds, from 0 to 999_999_999, inclusive.
- pub(crate) nanos: u32,
-}
-
-impl DateTime {
- /// The minimum representable [`Timestamp`] as a `DateTime`.
- pub(crate) const MIN: DateTime = DateTime {
- year: -292_277_022_657,
- month: 1,
- day: 27,
- hour: 8,
- minute: 29,
- second: 52,
- nanos: 0,
- };
-
- /// The maximum representable [`Timestamp`] as a `DateTime`.
- pub(crate) const MAX: DateTime = DateTime {
- year: 292_277_026_596,
- month: 12,
- day: 4,
- hour: 15,
- minute: 30,
- second: 7,
- nanos: 999_999_999,
- };
-
- /// Returns `true` if the `DateTime` is a valid calendar date.
- pub(crate) fn is_valid(&self) -> bool {
- self >= &DateTime::MIN
- && self <= &DateTime::MAX
- && self.month > 0
- && self.month <= 12
- && self.day > 0
- && self.day <= days_in_month(self.year, self.month)
- && self.hour < 24
- && self.minute < 60
- && self.second < 60
- && self.nanos < 1_000_000_000
- }
-}
-
-impl fmt::Display for DateTime {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- // Pad years to at least 4 digits.
- if self.year > 9999 {
- write!(f, "+{}", self.year)?;
- } else if self.year < 0 {
- write!(f, "{:05}", self.year)?;
- } else {
- write!(f, "{:04}", self.year)?;
- };
-
- write!(
- f,
- "-{:02}-{:02}T{:02}:{:02}:{:02}",
- self.month, self.day, self.hour, self.minute, self.second,
- )?;
-
- // Format subseconds to either nothing, millis, micros, or nanos.
- let nanos = self.nanos;
- if nanos == 0 {
- write!(f, "Z")
- } else if nanos % 1_000_000 == 0 {
- write!(f, ".{:03}Z", nanos / 1_000_000)
- } else if nanos % 1_000 == 0 {
- write!(f, ".{:06}Z", nanos / 1_000)
- } else {
- write!(f, ".{:09}Z", nanos)
- }
- }
-}
-
-impl From for DateTime {
- /// musl's [`__secs_to_tm`][1] converted to Rust via [c2rust][2] and then cleaned up by hand.
- ///
- /// All existing `strftime`-like APIs in Rust are unable to handle the full range of timestamps
- /// representable by `Timestamp`, including `strftime` itself, since tm.tm_year is an int.
- ///
- /// [1]: http://git.musl-libc.org/cgit/musl/tree/src/time/__secs_to_tm.c
- /// [2]: https://c2rust.com/
- fn from(mut timestamp: Timestamp) -> DateTime {
- timestamp.normalize();
-
- let t = timestamp.seconds;
- let nanos = timestamp.nanos;
-
- // 2000-03-01 (mod 400 year, immediately after feb29
- const LEAPOCH: i64 = 946_684_800 + 86400 * (31 + 29);
- const DAYS_PER_400Y: i32 = 365 * 400 + 97;
- const DAYS_PER_100Y: i32 = 365 * 100 + 24;
- const DAYS_PER_4Y: i32 = 365 * 4 + 1;
- const DAYS_IN_MONTH: [u8; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
-
- // Note(dcb): this bit is rearranged slightly to avoid integer overflow.
- let mut days: i64 = (t / 86_400) - (LEAPOCH / 86_400);
- let mut remsecs: i32 = (t % 86_400) as i32;
- if remsecs < 0i32 {
- remsecs += 86_400;
- days -= 1
- }
-
- let mut qc_cycles: i32 = (days / i64::from(DAYS_PER_400Y)) as i32;
- let mut remdays: i32 = (days % i64::from(DAYS_PER_400Y)) as i32;
- if remdays < 0 {
- remdays += DAYS_PER_400Y;
- qc_cycles -= 1;
- }
-
- let mut c_cycles: i32 = remdays / DAYS_PER_100Y;
- if c_cycles == 4 {
- c_cycles -= 1;
- }
- remdays -= c_cycles * DAYS_PER_100Y;
-
- let mut q_cycles: i32 = remdays / DAYS_PER_4Y;
- if q_cycles == 25 {
- q_cycles -= 1;
- }
- remdays -= q_cycles * DAYS_PER_4Y;
-
- let mut remyears: i32 = remdays / 365;
- if remyears == 4 {
- remyears -= 1;
- }
- remdays -= remyears * 365;
-
- let mut years: i64 = i64::from(remyears)
- + 4 * i64::from(q_cycles)
- + 100 * i64::from(c_cycles)
- + 400 * i64::from(qc_cycles);
-
- let mut months: i32 = 0;
- while i32::from(DAYS_IN_MONTH[months as usize]) <= remdays {
- remdays -= i32::from(DAYS_IN_MONTH[months as usize]);
- months += 1
- }
-
- if months >= 10 {
- months -= 12;
- years += 1;
- }
-
- let date_time = DateTime {
- year: years + 2000,
- month: (months + 3) as u8,
- day: (remdays + 1) as u8,
- hour: (remsecs / 3600) as u8,
- minute: (remsecs / 60 % 60) as u8,
- second: (remsecs % 60) as u8,
- nanos: nanos as u32,
- };
- debug_assert!(date_time.is_valid());
- date_time
- }
-}
-
-/// Returns the number of days in the month.
-fn days_in_month(year: i64, month: u8) -> u8 {
- const DAYS_IN_MONTH: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
- let (_, is_leap) = year_to_seconds(year);
- DAYS_IN_MONTH[usize::from(month - 1)] + u8::from(is_leap && month == 2)
-}
-
-macro_rules! ensure {
- ($expr:expr) => {{
- if !$expr {
- return None;
- }
- }};
-}
-
-/// Parses a date in RFC 3339 format from ASCII string `b`, returning the year, month, day, and
-/// remaining input.
-///
-/// The date is not validated according to a calendar.
-fn parse_date(s: &str) -> Option<(i64, u8, u8, &str)> {
- debug_assert!(s.is_ascii());
-
- // Smallest valid date is YYYY-MM-DD.
- ensure!(s.len() >= 10);
-
- // Parse the year in one of three formats:
- // * +YYYY[Y]+
- // * -[Y]+
- // * YYYY
- let (year, s) = match s.as_bytes()[0] {
- b'+' => {
- let (digits, s) = parse_digits(&s[1..]);
- ensure!(digits.len() >= 5);
- let date: i64 = digits.parse().ok()?;
- (date, s)
- }
- b'-' => {
- let (digits, s) = parse_digits(&s[1..]);
- ensure!(digits.len() >= 4);
- let date: i64 = digits.parse().ok()?;
- (-date, s)
- }
- _ => {
- // Parse a 4 digit numeric.
- let (n1, s) = parse_two_digit_numeric(s)?;
- let (n2, s) = parse_two_digit_numeric(s)?;
- (i64::from(n1) * 100 + i64::from(n2), s)
- }
- };
-
- let s = parse_char(s, b'-')?;
- let (month, s) = parse_two_digit_numeric(s)?;
- let s = parse_char(s, b'-')?;
- let (day, s) = parse_two_digit_numeric(s)?;
- Some((year, month, day, s))
-}
-
-/// Parses a time in RFC 3339 format from ASCII string `s`, returning the hour, minute, second, and
-/// nanos.
-///
-/// The date is not validated according to a calendar.
-fn parse_time(s: &str) -> Option<(u8, u8, u8, u32, &str)> {
- debug_assert!(s.is_ascii());
-
- let (hour, s) = parse_two_digit_numeric(s)?;
- let s = parse_char(s, b':')?;
- let (minute, s) = parse_two_digit_numeric(s)?;
- let s = parse_char(s, b':')?;
- let (second, s) = parse_two_digit_numeric(s)?;
-
- let (nanos, s) = parse_nanos(s)?;
-
- Some((hour, minute, second, nanos, s))
-}
-
-/// Parses an optional nanosecond time from ASCII string `s`, returning the nanos and remaining
-/// string.
-fn parse_nanos(s: &str) -> Option<(u32, &str)> {
- debug_assert!(s.is_ascii());
-
- // Parse the nanoseconds, if present.
- let (nanos, s) = if let Some(s) = parse_char(s, b'.') {
- let (digits, s) = parse_digits(s);
- ensure!(digits.len() <= 9);
- let nanos = 10u32.pow(9 - digits.len() as u32) * digits.parse::().ok()?;
- (nanos, s)
- } else {
- (0, s)
- };
-
- Some((nanos, s))
-}
-
-/// Parses a timezone offset in RFC 3339 format from ASCII string `s`, returning the offset hour,
-/// offset minute, and remaining input.
-fn parse_offset(s: &str) -> Option<(i8, i8, &str)> {
- debug_assert!(s.is_ascii());
-
- if s.is_empty() {
- // If no timezone specified, assume UTC.
- return Some((0, 0, s));
- }
-
- // Snowflake's timestamp format contains a space separator before the offset.
- let s = parse_char(s, b' ').unwrap_or(s);
-
- if let Some(s) = parse_char_ignore_case(s, b'Z') {
- Some((0, 0, s))
- } else {
- let (is_positive, s) = if let Some(s) = parse_char(s, b'+') {
- (true, s)
- } else if let Some(s) = parse_char(s, b'-') {
- (false, s)
- } else {
- return None;
- };
-
- let (hour, s) = parse_two_digit_numeric(s)?;
-
- let (minute, s) = if s.is_empty() {
- // No offset minutes are sepcified, e.g. +00 or +07.
- (0, s)
- } else {
- // Optional colon separator between the hour and minute digits.
- let s = parse_char(s, b':').unwrap_or(s);
- let (minute, s) = parse_two_digit_numeric(s)?;
- (minute, s)
- };
-
- // '-00:00' indicates an unknown local offset.
- ensure!(is_positive || hour > 0 || minute > 0);
-
- ensure!(hour < 24 && minute < 60);
-
- let hour = hour as i8;
- let minute = minute as i8;
-
- if is_positive {
- Some((hour, minute, s))
- } else {
- Some((-hour, -minute, s))
- }
- }
-}
-
-/// Parses a two-digit base-10 number from ASCII string `s`, returning the number and the remaining
-/// string.
-fn parse_two_digit_numeric(s: &str) -> Option<(u8, &str)> {
- debug_assert!(s.is_ascii());
-
- let (digits, s) = s.split_at(2);
- Some((digits.parse().ok()?, s))
-}
-
-/// Splits ASCII string `s` at the first occurrence of a non-digit character.
-fn parse_digits(s: &str) -> (&str, &str) {
- debug_assert!(s.is_ascii());
-
- let idx = s
- .as_bytes()
- .iter()
- .position(|c| !c.is_ascii_digit())
- .unwrap_or(s.len());
- s.split_at(idx)
-}
-
-/// Attempts to parse ASCII character `c` from ASCII string `s`, returning the remaining string. If
-/// the character can not be parsed, returns `None`.
-fn parse_char(s: &str, c: u8) -> Option<&str> {
- debug_assert!(s.is_ascii());
-
- ensure!(*s.as_bytes().first()? == c);
- Some(&s[1..])
-}
-
-/// Attempts to parse ASCII character `c` from ASCII string `s`, ignoring ASCII case, returning the
-/// remaining string. If the character can not be parsed, returns `None`.
-fn parse_char_ignore_case(s: &str, c: u8) -> Option<&str> {
- debug_assert!(s.is_ascii());
-
- ensure!(s.as_bytes().first()?.eq_ignore_ascii_case(&c));
- Some(&s[1..])
-}
-
-/// Returns the offset in seconds from the Unix epoch of the date time.
-///
-/// This is musl's [`__tm_to_secs`][1] converted to Rust via [c2rust[2] and then cleaned up by
-/// hand.
-///
-/// [1]: https://git.musl-libc.org/cgit/musl/tree/src/time/__tm_to_secs.c
-/// [2]: https://c2rust.com/
-fn date_time_to_seconds(tm: &DateTime) -> i64 {
- let (start_of_year, is_leap) = year_to_seconds(tm.year);
-
- let seconds_within_year = month_to_seconds(tm.month, is_leap)
- + 86400 * u32::from(tm.day - 1)
- + 3600 * u32::from(tm.hour)
- + 60 * u32::from(tm.minute)
- + u32::from(tm.second);
-
- (start_of_year + i128::from(seconds_within_year)) as i64
-}
-
-/// Returns the number of seconds in the year prior to the start of the provided month.
-///
-/// This is musl's [`__month_to_secs`][1] converted to Rust via c2rust and then cleaned up by hand.
-///
-/// [1]: https://git.musl-libc.org/cgit/musl/tree/src/time/__month_to_secs.c
-fn month_to_seconds(month: u8, is_leap: bool) -> u32 {
- const SECS_THROUGH_MONTH: [u32; 12] = [
- 0,
- 31 * 86400,
- 59 * 86400,
- 90 * 86400,
- 120 * 86400,
- 151 * 86400,
- 181 * 86400,
- 212 * 86400,
- 243 * 86400,
- 273 * 86400,
- 304 * 86400,
- 334 * 86400,
- ];
- let t = SECS_THROUGH_MONTH[usize::from(month - 1)];
- if is_leap && month > 2 {
- t + 86400
- } else {
- t
- }
-}
-
-/// Returns the offset in seconds from the Unix epoch of the start of a year.
-///
-/// musl's [`__year_to_secs`][1] converted to Rust via c2rust and then cleaned up by hand.
-///
-/// Returns an i128 because the start of the earliest supported year underflows i64.
-///
-/// [1]: https://git.musl-libc.org/cgit/musl/tree/src/time/__year_to_secs.c
-pub(crate) fn year_to_seconds(year: i64) -> (i128, bool) {
- let is_leap;
- let year = year - 1900;
-
- // Fast path for years 1900 - 2038.
- if year as u64 <= 138 {
- let mut leaps: i64 = (year - 68) >> 2;
- if (year - 68).trailing_zeros() >= 2 {
- leaps -= 1;
- is_leap = true;
- } else {
- is_leap = false;
- }
- return (
- i128::from(31_536_000 * (year - 70) + 86400 * leaps),
- is_leap,
- );
- }
-
- let centuries: i64;
- let mut leaps: i64;
-
- let mut cycles: i64 = (year - 100) / 400;
- let mut rem: i64 = (year - 100) % 400;
-
- if rem < 0 {
- cycles -= 1;
- rem += 400
- }
- if rem == 0 {
- is_leap = true;
- centuries = 0;
- leaps = 0;
- } else {
- if rem >= 200 {
- if rem >= 300 {
- centuries = 3;
- rem -= 300;
- } else {
- centuries = 2;
- rem -= 200;
- }
- } else if rem >= 100 {
- centuries = 1;
- rem -= 100;
- } else {
- centuries = 0;
- }
- if rem == 0 {
- is_leap = false;
- leaps = 0;
- } else {
- leaps = rem / 4;
- rem %= 4;
- is_leap = rem == 0;
- }
- }
- leaps += 97 * cycles + 24 * centuries - i64::from(is_leap);
-
- (
- i128::from((year - 100) * 31_536_000) + i128::from(leaps * 86400 + 946_684_800 + 86400),
- is_leap,
- )
-}
-
-/// Parses a timestamp in RFC 3339 format from `s`.
-pub(crate) fn parse_timestamp(s: &str) -> Option {
- // Check that the string is ASCII, since subsequent parsing steps use byte-level indexing.
- ensure!(s.is_ascii());
-
- let (year, month, day, s) = parse_date(s)?;
-
- if s.is_empty() {
- // The string only contained a date.
- let date_time = DateTime {
- year,
- month,
- day,
- ..DateTime::default()
- };
-
- ensure!(date_time.is_valid());
-
- return Some(Timestamp::from(date_time));
- }
-
- // Accept either 'T' or ' ' as delimiter between date and time.
- let s = parse_char_ignore_case(s, b'T').or_else(|| parse_char(s, b' '))?;
- let (hour, minute, mut second, nanos, s) = parse_time(s)?;
- let (offset_hour, offset_minute, s) = parse_offset(s)?;
-
- ensure!(s.is_empty());
-
- // Detect whether the timestamp falls in a leap second. If this is the case, roll it back
- // to the previous second. To be maximally conservative, this should be checking that the
- // timestamp is the last second in the UTC day (23:59:60), and even potentially checking
- // that it's the final day of the UTC month, however these checks are non-trivial because
- // at this point we have, in effect, a local date time, since the offset has not been
- // applied.
- if second == 60 {
- second = 59;
- }
-
- let date_time = DateTime {
- year,
- month,
- day,
- hour,
- minute,
- second,
- nanos,
- };
-
- ensure!(date_time.is_valid());
-
- let Timestamp { seconds, nanos } = Timestamp::from(date_time);
-
- let seconds =
- seconds.checked_sub(i64::from(offset_hour) * 3600 + i64::from(offset_minute) * 60)?;
-
- Some(Timestamp { seconds, nanos })
-}
-
-/// Parse a duration in the [Protobuf JSON encoding spec format][1].
-///
-/// [1]: https://developers.google.com/protocol-buffers/docs/proto3#json
-pub(crate) fn parse_duration(s: &str) -> Option {
- // Check that the string is ASCII, since subsequent parsing steps use byte-level indexing.
- ensure!(s.is_ascii());
-
- let (is_negative, s) = match parse_char(s, b'-') {
- Some(s) => (true, s),
- None => (false, s),
- };
-
- let (digits, s) = parse_digits(s);
- let seconds = digits.parse::().ok()?;
-
- let (nanos, s) = parse_nanos(s)?;
-
- let s = parse_char(s, b's')?;
- ensure!(s.is_empty());
- ensure!(nanos < crate::NANOS_PER_SECOND as u32);
-
- // If the duration is negative, also flip the nanos sign.
- let (seconds, nanos) = if is_negative {
- (-seconds, -(nanos as i32))
- } else {
- (seconds, nanos as i32)
- };
-
- Some(Duration {
- seconds,
- nanos: nanos as i32,
- })
-}
-
-impl From for Timestamp {
- fn from(date_time: DateTime) -> Timestamp {
- let seconds = date_time_to_seconds(&date_time);
- let nanos = date_time.nanos;
- Timestamp {
- seconds,
- nanos: nanos as i32,
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
-
- use std::convert::TryFrom;
-
- use proptest::prelude::*;
-
- use super::*;
-
- #[test]
- fn test_min_max() {
- assert_eq!(
- DateTime::MIN,
- DateTime::from(Timestamp {
- seconds: i64::MIN,
- nanos: 0
- }),
- );
- assert_eq!(
- DateTime::MAX,
- DateTime::from(Timestamp {
- seconds: i64::MAX,
- nanos: 999_999_999
- }),
- );
- }
-
- #[test]
- fn test_datetime_from_timestamp() {
- let case = |expected: &str, secs: i64, nanos: i32| {
- let timestamp = Timestamp {
- seconds: secs,
- nanos,
- };
- assert_eq!(
- expected,
- format!("{}", DateTime::from(timestamp.clone())),
- "timestamp: {:?}",
- timestamp
- );
- };
-
- // Mostly generated with:
- // - date -jur +"%Y-%m-%dT%H:%M:%S.000000000Z"
- // - http://unixtimestamp.50x.eu/
-
- case("1970-01-01T00:00:00Z", 0, 0);
-
- case("1970-01-01T00:00:00.000000001Z", 0, 1);
- case("1970-01-01T00:00:00.123450Z", 0, 123_450_000);
- case("1970-01-01T00:00:00.050Z", 0, 50_000_000);
- case("1970-01-01T00:00:01.000000001Z", 1, 1);
- case("1970-01-01T00:01:01.000000001Z", 60 + 1, 1);
- case("1970-01-01T01:01:01.000000001Z", 60 * 60 + 60 + 1, 1);
- case(
- "1970-01-02T01:01:01.000000001Z",
- 24 * 60 * 60 + 60 * 60 + 60 + 1,
- 1,
- );
-
- case("1969-12-31T23:59:59Z", -1, 0);
- case("1969-12-31T23:59:59.000001Z", -1, 1_000);
- case("1969-12-31T23:59:59.500Z", -1, 500_000_000);
- case("1969-12-31T23:58:59.000001Z", -60 - 1, 1_000);
- case("1969-12-31T22:58:59.000001Z", -60 * 60 - 60 - 1, 1_000);
- case(
- "1969-12-30T22:58:59.000000001Z",
- -24 * 60 * 60 - 60 * 60 - 60 - 1,
- 1,
- );
-
- case("2038-01-19T03:14:07Z", i32::MAX as i64, 0);
- case("2038-01-19T03:14:08Z", i32::MAX as i64 + 1, 0);
- case("1901-12-13T20:45:52Z", i32::MIN as i64, 0);
- case("1901-12-13T20:45:51Z", i32::MIN as i64 - 1, 0);
-
- // Skipping these tests on windows as std::time::SysteTime range is low
- // on Windows compared with that of Unix which can cause the following
- // high date value tests to panic
- #[cfg(not(target_os = "windows"))]
- {
- case("+292277026596-12-04T15:30:07Z", i64::MAX, 0);
- case("+292277026596-12-04T15:30:06Z", i64::MAX - 1, 0);
- case("-292277022657-01-27T08:29:53Z", i64::MIN + 1, 0);
- }
-
- case("1900-01-01T00:00:00Z", -2_208_988_800, 0);
- case("1899-12-31T23:59:59Z", -2_208_988_801, 0);
- case("0000-01-01T00:00:00Z", -62_167_219_200, 0);
- case("-0001-12-31T23:59:59Z", -62_167_219_201, 0);
-
- case("1234-05-06T07:08:09Z", -23_215_049_511, 0);
- case("-1234-05-06T07:08:09Z", -101_097_651_111, 0);
- case("2345-06-07T08:09:01Z", 11_847_456_541, 0);
- case("-2345-06-07T08:09:01Z", -136_154_620_259, 0);
- }
-
- #[test]
- fn test_parse_timestamp() {
- // RFC 3339 Section 5.8 Examples
- assert_eq!(
- "1985-04-12T23:20:50.52Z".parse::(),
- Timestamp::date_time_nanos(1985, 4, 12, 23, 20, 50, 520_000_000),
- );
- assert_eq!(
- "1996-12-19T16:39:57-08:00".parse::(),
- Timestamp::date_time(1996, 12, 20, 0, 39, 57),
- );
- assert_eq!(
- "1996-12-19T16:39:57-08:00".parse::(),
- Timestamp::date_time(1996, 12, 20, 0, 39, 57),
- );
- assert_eq!(
- "1990-12-31T23:59:60Z".parse::(),
- Timestamp::date_time(1990, 12, 31, 23, 59, 59),
- );
- assert_eq!(
- "1990-12-31T15:59:60-08:00".parse::(),
- Timestamp::date_time(1990, 12, 31, 23, 59, 59),
- );
- assert_eq!(
- "1937-01-01T12:00:27.87+00:20".parse::(),
- Timestamp::date_time_nanos(1937, 1, 1, 11, 40, 27, 870_000_000),
- );
-
- // Date
- assert_eq!(
- "1937-01-01".parse::(),
- Timestamp::date(1937, 1, 1),
- );
-
- // Negative year
- assert_eq!(
- "-0008-01-01".parse::(),
- Timestamp::date(-8, 1, 1),
- );
-
- // Plus year
- assert_eq!(
- "+19370-01-01".parse::(),
- Timestamp::date(19370, 1, 1),
- );
-
- // Full nanos
- assert_eq!(
- "2020-02-03T01:02:03.123456789Z".parse::(),
- Timestamp::date_time_nanos(2020, 2, 3, 1, 2, 3, 123_456_789),
- );
-
- // Leap day
- assert_eq!(
- "2020-02-29T01:02:03.00Z".parse::().unwrap(),
- Timestamp::from(DateTime {
- year: 2020,
- month: 2,
- day: 29,
- hour: 1,
- minute: 2,
- second: 3,
- nanos: 0,
- }),
- );
-
- // Test extensions to RFC 3339.
- // ' ' instead of 'T' as date/time separator.
- assert_eq!(
- "1985-04-12 23:20:50.52Z".parse::(),
- Timestamp::date_time_nanos(1985, 4, 12, 23, 20, 50, 520_000_000),
- );
-
- // No time zone specified.
- assert_eq!(
- "1985-04-12T23:20:50.52".parse::(),
- Timestamp::date_time_nanos(1985, 4, 12, 23, 20, 50, 520_000_000),
- );
-
- // Offset without minutes specified.
- assert_eq!(
- "1996-12-19T16:39:57-08".parse::(),
- Timestamp::date_time(1996, 12, 20, 0, 39, 57),
- );
-
- // Snowflake stage style.
- assert_eq!(
- "2015-09-12 00:47:19.591 Z".parse::(),
- Timestamp::date_time_nanos(2015, 9, 12, 0, 47, 19, 591_000_000),
- );
- assert_eq!(
- "2020-06-15 00:01:02.123 +0800".parse::(),
- Timestamp::date_time_nanos(2020, 6, 14, 16, 1, 2, 123_000_000),
- );
- }
-
- #[test]
- fn test_parse_duration() {
- let case = |s: &str, seconds: i64, nanos: i32| {
- assert_eq!(
- s.parse::().unwrap(),
- Duration { seconds, nanos },
- "duration: {}",
- s
- );
- };
-
- case("0s", 0, 0);
- case("0.0s", 0, 0);
- case("0.000s", 0, 0);
-
- case("-0s", 0, 0);
- case("-0.0s", 0, 0);
- case("-0.000s", 0, 0);
-
- case("-0s", 0, 0);
- case("-0.0s", 0, 0);
- case("-0.000s", 0, 0);
-
- case("0.05s", 0, 50_000_000);
- case("0.050s", 0, 50_000_000);
-
- case("-0.05s", 0, -50_000_000);
- case("-0.050s", 0, -50_000_000);
-
- case("1s", 1, 0);
- case("1.0s", 1, 0);
- case("1.000s", 1, 0);
-
- case("-1s", -1, 0);
- case("-1.0s", -1, 0);
- case("-1.000s", -1, 0);
-
- case("15s", 15, 0);
- case("15.1s", 15, 100_000_000);
- case("15.100s", 15, 100_000_000);
-
- case("-15s", -15, 0);
- case("-15.1s", -15, -100_000_000);
- case("-15.100s", -15, -100_000_000);
-
- case("100.000000009s", 100, 9);
- case("-100.000000009s", -100, -9);
- }
-
- #[test]
- fn test_parse_non_ascii() {
- assert!("2021️⃣-06-15 00:01:02.123 +0800"
- .parse::()
- .is_err());
-
- assert!("1️⃣s".parse::().is_err());
- }
-
- proptest! {
- #[cfg(feature = "std")]
- #[test]
- fn check_timestamp_parse_to_string_roundtrip(
- system_time in std::time::SystemTime::arbitrary(),
- ) {
-
- let ts = Timestamp::from(system_time);
-
- assert_eq!(
- ts,
- ts.to_string().parse::().unwrap(),
- )
- }
-
- #[test]
- fn check_duration_parse_to_string_roundtrip(
- duration in core::time::Duration::arbitrary(),
- ) {
- let duration = match Duration::try_from(duration) {
- Ok(duration) => duration,
- Err(_) => return Err(TestCaseError::reject("duration out of range")),
- };
-
- prop_assert_eq!(
- &duration,
- &duration.to_string().parse::().unwrap(),
- "{}", duration.to_string()
- );
- }
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/resources/lib.rs b/kclvm/third-party/prost-wkt/wkt-types/resources/lib.rs
deleted file mode 100644
index b51e7fdfb..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/resources/lib.rs
+++ /dev/null
@@ -1,679 +0,0 @@
-#![doc(html_root_url = "https://docs.rs/prost-types/0.11.5")]
-
-//! Protocol Buffers well-known types.
-//!
-//! Note that the documentation for the types defined in this crate are generated from the Protobuf
-//! definitions, so code examples are not in Rust.
-//!
-//! See the [Protobuf reference][1] for more information about well-known types.
-//!
-//! [1]: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf
-
-#![cfg_attr(not(feature = "std"), no_std)]
-
-use core::convert::TryFrom;
-use core::fmt;
-use core::i32;
-use core::i64;
-use core::str::FromStr;
-use core::time;
-
-include!("protobuf.rs");
-pub mod compiler {
- include!("compiler.rs");
-}
-
-mod datetime;
-
-// The Protobuf `Duration` and `Timestamp` types can't delegate to the standard library equivalents
-// because the Protobuf versions are signed. To make them easier to work with, `From` conversions
-// are defined in both directions.
-
-const NANOS_PER_SECOND: i32 = 1_000_000_000;
-const NANOS_MAX: i32 = NANOS_PER_SECOND - 1;
-
-impl Duration {
- /// Normalizes the duration to a canonical format.
- ///
- /// Based on [`google::protobuf::util::CreateNormalized`][1].
- ///
- /// [1]: https://github.com/google/protobuf/blob/v3.3.2/src/google/protobuf/util/time_util.cc#L79-L100
- pub fn normalize(&mut self) {
- // Make sure nanos is in the range.
- if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
- if let Some(seconds) = self
- .seconds
- .checked_add((self.nanos / NANOS_PER_SECOND) as i64)
- {
- self.seconds = seconds;
- self.nanos %= NANOS_PER_SECOND;
- } else if self.nanos < 0 {
- // Negative overflow! Set to the least normal value.
- self.seconds = i64::MIN;
- self.nanos = -NANOS_MAX;
- } else {
- // Positive overflow! Set to the greatest normal value.
- self.seconds = i64::MAX;
- self.nanos = NANOS_MAX;
- }
- }
-
- // nanos should have the same sign as seconds.
- if self.seconds < 0 && self.nanos > 0 {
- if let Some(seconds) = self.seconds.checked_add(1) {
- self.seconds = seconds;
- self.nanos -= NANOS_PER_SECOND;
- } else {
- // Positive overflow! Set to the greatest normal value.
- debug_assert_eq!(self.seconds, i64::MAX);
- self.nanos = NANOS_MAX;
- }
- } else if self.seconds > 0 && self.nanos < 0 {
- if let Some(seconds) = self.seconds.checked_sub(1) {
- self.seconds = seconds;
- self.nanos += NANOS_PER_SECOND;
- } else {
- // Negative overflow! Set to the least normal value.
- debug_assert_eq!(self.seconds, i64::MIN);
- self.nanos = -NANOS_MAX;
- }
- }
- // TODO: should this be checked?
- // debug_assert!(self.seconds >= -315_576_000_000 && self.seconds <= 315_576_000_000,
- // "invalid duration: {:?}", self);
- }
-}
-
-impl TryFrom for Duration {
- type Error = DurationError;
-
- /// Converts a `std::time::Duration` to a `Duration`, failing if the duration is too large.
- fn try_from(duration: time::Duration) -> Result {
- let seconds = i64::try_from(duration.as_secs()).map_err(|_| DurationError::OutOfRange)?;
- let nanos = duration.subsec_nanos() as i32;
-
- let mut duration = Duration { seconds, nanos };
- duration.normalize();
- Ok(duration)
- }
-}
-
-impl TryFrom for time::Duration {
- type Error = DurationError;
-
- /// Converts a `Duration` to a `std::time::Duration`, failing if the duration is negative.
- fn try_from(mut duration: Duration) -> Result {
- duration.normalize();
- if duration.seconds >= 0 {
- Ok(time::Duration::new(
- duration.seconds as u64,
- duration.nanos as u32,
- ))
- } else {
- Err(DurationError::NegativeDuration(time::Duration::new(
- (-duration.seconds) as u64,
- (-duration.nanos) as u32,
- )))
- }
- }
-}
-
-impl fmt::Display for Duration {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let mut d = self.clone();
- d.normalize();
- if self.seconds < 0 && self.nanos < 0 {
- write!(f, "-")?;
- }
- write!(f, "{}", d.seconds.abs())?;
-
- // Format subseconds to either nothing, millis, micros, or nanos.
- let nanos = d.nanos.abs();
- if nanos == 0 {
- write!(f, "s")
- } else if nanos % 1_000_000 == 0 {
- write!(f, ".{:03}s", nanos / 1_000_000)
- } else if nanos % 1_000 == 0 {
- write!(f, ".{:06}s", nanos / 1_000)
- } else {
- write!(f, ".{:09}s", nanos)
- }
- }
-}
-
-/// A duration handling error.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Debug, PartialEq)]
-#[non_exhaustive]
-pub enum DurationError {
- /// Indicates failure to parse a [`Duration`] from a string.
- ///
- /// The [`Duration`] string format is specified in the [Protobuf JSON mapping specification][1].
- ///
- /// [1]: https://developers.google.com/protocol-buffers/docs/proto3#json
- ParseFailure,
-
- /// Indicates failure to convert a `prost_types::Duration` to a `std::time::Duration` because
- /// the duration is negative. The included `std::time::Duration` matches the magnitude of the
- /// original negative `prost_types::Duration`.
- NegativeDuration(time::Duration),
-
- /// Indicates failure to convert a `std::time::Duration` to a `prost_types::Duration`.
- ///
- /// Converting a `std::time::Duration` to a `prost_types::Duration` fails if the magnitude
- /// exceeds that representable by `prost_types::Duration`.
- OutOfRange,
-}
-
-impl fmt::Display for DurationError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- DurationError::ParseFailure => write!(f, "failed to parse duration"),
- DurationError::NegativeDuration(duration) => {
- write!(f, "failed to convert negative duration: {:?}", duration)
- }
- DurationError::OutOfRange => {
- write!(f, "failed to convert duration out of range")
- }
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl std::error::Error for DurationError {}
-
-impl FromStr for Duration {
- type Err = DurationError;
-
- fn from_str(s: &str) -> Result {
- datetime::parse_duration(s).ok_or(DurationError::ParseFailure)
- }
-}
-
-impl Timestamp {
- /// Normalizes the timestamp to a canonical format.
- ///
- /// Based on [`google::protobuf::util::CreateNormalized`][1].
- ///
- /// [1]: https://github.com/google/protobuf/blob/v3.3.2/src/google/protobuf/util/time_util.cc#L59-L77
- pub fn normalize(&mut self) {
- // Make sure nanos is in the range.
- if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
- if let Some(seconds) = self
- .seconds
- .checked_add((self.nanos / NANOS_PER_SECOND) as i64)
- {
- self.seconds = seconds;
- self.nanos %= NANOS_PER_SECOND;
- } else if self.nanos < 0 {
- // Negative overflow! Set to the earliest normal value.
- self.seconds = i64::MIN;
- self.nanos = 0;
- } else {
- // Positive overflow! Set to the latest normal value.
- self.seconds = i64::MAX;
- self.nanos = 999_999_999;
- }
- }
-
- // For Timestamp nanos should be in the range [0, 999999999].
- if self.nanos < 0 {
- if let Some(seconds) = self.seconds.checked_sub(1) {
- self.seconds = seconds;
- self.nanos += NANOS_PER_SECOND;
- } else {
- // Negative overflow! Set to the earliest normal value.
- debug_assert_eq!(self.seconds, i64::MIN);
- self.nanos = 0;
- }
- }
-
- // TODO: should this be checked?
- // debug_assert!(self.seconds >= -62_135_596_800 && self.seconds <= 253_402_300_799,
- // "invalid timestamp: {:?}", self);
- }
-
- /// Creates a new `Timestamp` at the start of the provided UTC date.
- pub fn date(year: i64, month: u8, day: u8) -> Result {
- Timestamp::date_time_nanos(year, month, day, 0, 0, 0, 0)
- }
-
- /// Creates a new `Timestamp` instance with the provided UTC date and time.
- pub fn date_time(
- year: i64,
- month: u8,
- day: u8,
- hour: u8,
- minute: u8,
- second: u8,
- ) -> Result {
- Timestamp::date_time_nanos(year, month, day, hour, minute, second, 0)
- }
-
- /// Creates a new `Timestamp` instance with the provided UTC date and time.
- pub fn date_time_nanos(
- year: i64,
- month: u8,
- day: u8,
- hour: u8,
- minute: u8,
- second: u8,
- nanos: u32,
- ) -> Result {
- let date_time = datetime::DateTime {
- year,
- month,
- day,
- hour,
- minute,
- second,
- nanos,
- };
-
- if date_time.is_valid() {
- Ok(Timestamp::from(date_time))
- } else {
- Err(TimestampError::InvalidDateTime)
- }
- }
-}
-
-/// Implements the unstable/naive version of `Eq`: a basic equality check on the internal fields of the `Timestamp`.
-/// This implies that `normalized_ts != non_normalized_ts` even if `normalized_ts == non_normalized_ts.normalized()`.
-#[cfg(feature = "std")]
-impl Eq for Timestamp {}
-
-#[cfg(feature = "std")]
-#[allow(clippy::derive_hash_xor_eq)] // Derived logic is correct: comparing the 2 fields for equality
-impl std::hash::Hash for Timestamp {
- fn hash(&self, state: &mut H) {
- self.seconds.hash(state);
- self.nanos.hash(state);
- }
-}
-
-#[cfg(feature = "std")]
-impl From for Timestamp {
- fn from(system_time: std::time::SystemTime) -> Timestamp {
- let (seconds, nanos) = match system_time.duration_since(std::time::UNIX_EPOCH) {
- Ok(duration) => {
- let seconds = i64::try_from(duration.as_secs()).unwrap();
- (seconds, duration.subsec_nanos() as i32)
- }
- Err(error) => {
- let duration = error.duration();
- let seconds = i64::try_from(duration.as_secs()).unwrap();
- let nanos = duration.subsec_nanos() as i32;
- if nanos == 0 {
- (-seconds, 0)
- } else {
- (-seconds - 1, 1_000_000_000 - nanos)
- }
- }
- };
- Timestamp { seconds, nanos }
- }
-}
-
-/// A timestamp handling error.
-#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Debug, PartialEq)]
-#[non_exhaustive]
-pub enum TimestampError {
- /// Indicates that a [`Timestamp`] could not be converted to
- /// [`SystemTime`][std::time::SystemTime] because it is out of range.
- ///
- /// The range of times that can be represented by `SystemTime` depends on the platform. All
- /// `Timestamp`s are likely representable on 64-bit Unix-like platforms, but other platforms,
- /// such as Windows and 32-bit Linux, may not be able to represent the full range of
- /// `Timestamp`s.
- OutOfSystemRange(Timestamp),
-
- /// An error indicating failure to parse a timestamp in RFC-3339 format.
- ParseFailure,
-
- /// Indicates an error when constructing a timestamp due to invalid date or time data.
- InvalidDateTime,
-}
-
-impl fmt::Display for TimestampError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- TimestampError::OutOfSystemRange(timestamp) => {
- write!(
- f,
- "{} is not representable as a `SystemTime` because it is out of range",
- timestamp
- )
- }
- TimestampError::ParseFailure => {
- write!(f, "failed to parse RFC-3339 formatted timestamp")
- }
- TimestampError::InvalidDateTime => {
- write!(f, "invalid date or time")
- }
- }
- }
-}
-
-#[cfg(feature = "std")]
-impl std::error::Error for TimestampError {}
-
-#[cfg(feature = "std")]
-impl TryFrom for std::time::SystemTime {
- type Error = TimestampError;
-
- fn try_from(mut timestamp: Timestamp) -> Result {
- let orig_timestamp = timestamp.clone();
- timestamp.normalize();
-
- let system_time = if timestamp.seconds >= 0 {
- std::time::UNIX_EPOCH.checked_add(time::Duration::from_secs(timestamp.seconds as u64))
- } else {
- std::time::UNIX_EPOCH.checked_sub(time::Duration::from_secs(
- timestamp
- .seconds
- .checked_neg()
- .ok_or_else(|| TimestampError::OutOfSystemRange(timestamp.clone()))?
- as u64,
- ))
- };
-
- let system_time = system_time.and_then(|system_time| {
- system_time.checked_add(time::Duration::from_nanos(timestamp.nanos as u64))
- });
-
- system_time.ok_or(TimestampError::OutOfSystemRange(orig_timestamp))
- }
-}
-
-impl FromStr for Timestamp {
- type Err = TimestampError;
-
- fn from_str(s: &str) -> Result {
- datetime::parse_timestamp(s).ok_or(TimestampError::ParseFailure)
- }
-}
-
-impl fmt::Display for Timestamp {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- datetime::DateTime::from(self.clone()).fmt(f)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::time::{self, SystemTime, UNIX_EPOCH};
-
- use proptest::prelude::*;
-
- use super::*;
-
- #[cfg(feature = "std")]
- proptest! {
- #[test]
- fn check_system_time_roundtrip(
- system_time in SystemTime::arbitrary(),
- ) {
- prop_assert_eq!(SystemTime::try_from(Timestamp::from(system_time)).unwrap(), system_time);
- }
-
- #[test]
- fn check_timestamp_roundtrip_via_system_time(
- seconds in i64::arbitrary(),
- nanos in i32::arbitrary(),
- ) {
- let mut timestamp = Timestamp { seconds, nanos };
- timestamp.normalize();
- if let Ok(system_time) = SystemTime::try_from(timestamp.clone()) {
- prop_assert_eq!(Timestamp::from(system_time), timestamp);
- }
- }
-
- #[test]
- fn check_duration_roundtrip(
- std_duration in time::Duration::arbitrary(),
- ) {
- let prost_duration = match Duration::try_from(std_duration) {
- Ok(duration) => duration,
- Err(_) => return Err(TestCaseError::reject("duration out of range")),
- };
- prop_assert_eq!(time::Duration::try_from(prost_duration.clone()).unwrap(), std_duration);
-
- if std_duration != time::Duration::default() {
- let neg_prost_duration = Duration {
- seconds: -prost_duration.seconds,
- nanos: -prost_duration.nanos,
- };
-
- prop_assert!(
- matches!(
- time::Duration::try_from(neg_prost_duration),
- Err(DurationError::NegativeDuration(d)) if d == std_duration,
- )
- )
- }
- }
- }
-
- #[cfg(feature = "std")]
- #[test]
- fn check_timestamp_negative_seconds() {
- // Representative tests for the case of timestamps before the UTC Epoch time:
- // validate the expected behaviour that "negative second values with fractions
- // must still have non-negative nanos values that count forward in time"
- // https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Timestamp
- //
- // To ensure cross-platform compatibility, all nanosecond values in these
- // tests are in minimum 100 ns increments. This does not affect the general
- // character of the behaviour being tested, but ensures that the tests are
- // valid for both POSIX (1 ns precision) and Windows (100 ns precision).
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(1_001, 0)),
- Timestamp {
- seconds: -1_001,
- nanos: 0
- }
- );
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(0, 999_999_900)),
- Timestamp {
- seconds: -1,
- nanos: 100
- }
- );
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(2_001_234, 12_300)),
- Timestamp {
- seconds: -2_001_235,
- nanos: 999_987_700
- }
- );
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(768, 65_432_100)),
- Timestamp {
- seconds: -769,
- nanos: 934_567_900
- }
- );
- }
-
- #[cfg(all(unix, feature = "std"))]
- #[test]
- fn check_timestamp_negative_seconds_1ns() {
- // UNIX-only test cases with 1 ns precision
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(0, 999_999_999)),
- Timestamp {
- seconds: -1,
- nanos: 1
- }
- );
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(1_234_567, 123)),
- Timestamp {
- seconds: -1_234_568,
- nanos: 999_999_877
- }
- );
- assert_eq!(
- Timestamp::from(UNIX_EPOCH - time::Duration::new(890, 987_654_321)),
- Timestamp {
- seconds: -891,
- nanos: 12_345_679
- }
- );
- }
-
- #[test]
- fn check_duration_normalize() {
- #[rustfmt::skip] // Don't mangle the table formatting.
- let cases = [
- // --- Table of test cases ---
- // test seconds test nanos expected seconds expected nanos
- (line!(), 0, 0, 0, 0),
- (line!(), 1, 1, 1, 1),
- (line!(), -1, -1, -1, -1),
- (line!(), 0, 999_999_999, 0, 999_999_999),
- (line!(), 0, -999_999_999, 0, -999_999_999),
- (line!(), 0, 1_000_000_000, 1, 0),
- (line!(), 0, -1_000_000_000, -1, 0),
- (line!(), 0, 1_000_000_001, 1, 1),
- (line!(), 0, -1_000_000_001, -1, -1),
- (line!(), -1, 1, 0, -999_999_999),
- (line!(), 1, -1, 0, 999_999_999),
- (line!(), -1, 1_000_000_000, 0, 0),
- (line!(), 1, -1_000_000_000, 0, 0),
- (line!(), i64::MIN , 0, i64::MIN , 0),
- (line!(), i64::MIN + 1, 0, i64::MIN + 1, 0),
- (line!(), i64::MIN , 1, i64::MIN + 1, -999_999_999),
- (line!(), i64::MIN , 1_000_000_000, i64::MIN + 1, 0),
- (line!(), i64::MIN , -1_000_000_000, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 1, -1_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN + 2, -1_000_000_000, i64::MIN + 1, 0),
- (line!(), i64::MIN , -1_999_999_998, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 1, -1_999_999_998, i64::MIN , -999_999_998),
- (line!(), i64::MIN + 2, -1_999_999_998, i64::MIN + 1, -999_999_998),
- (line!(), i64::MIN , -1_999_999_999, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 1, -1_999_999_999, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 2, -1_999_999_999, i64::MIN + 1, -999_999_999),
- (line!(), i64::MIN , -2_000_000_000, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 1, -2_000_000_000, i64::MIN , -999_999_999),
- (line!(), i64::MIN + 2, -2_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN , -999_999_998, i64::MIN , -999_999_998),
- (line!(), i64::MIN + 1, -999_999_998, i64::MIN + 1, -999_999_998),
- (line!(), i64::MAX , 0, i64::MAX , 0),
- (line!(), i64::MAX - 1, 0, i64::MAX - 1, 0),
- (line!(), i64::MAX , -1, i64::MAX - 1, 999_999_999),
- (line!(), i64::MAX , 1_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_000_000_000, i64::MAX , 0),
- (line!(), i64::MAX - 2, 1_000_000_000, i64::MAX - 1, 0),
- (line!(), i64::MAX , 1_999_999_998, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_999_999_998, i64::MAX , 999_999_998),
- (line!(), i64::MAX - 2, 1_999_999_998, i64::MAX - 1, 999_999_998),
- (line!(), i64::MAX , 1_999_999_999, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_999_999_999, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 2, 1_999_999_999, i64::MAX - 1, 999_999_999),
- (line!(), i64::MAX , 2_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 2_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 2, 2_000_000_000, i64::MAX , 0),
- (line!(), i64::MAX , 999_999_998, i64::MAX , 999_999_998),
- (line!(), i64::MAX - 1, 999_999_998, i64::MAX - 1, 999_999_998),
- ];
-
- for case in cases.iter() {
- let mut test_duration = Duration {
- seconds: case.1,
- nanos: case.2,
- };
- test_duration.normalize();
-
- assert_eq!(
- test_duration,
- Duration {
- seconds: case.3,
- nanos: case.4,
- },
- "test case on line {} doesn't match",
- case.0,
- );
- }
- }
-
- #[cfg(feature = "std")]
- #[test]
- fn check_timestamp_normalize() {
- // Make sure that `Timestamp::normalize` behaves correctly on and near overflow.
- #[rustfmt::skip] // Don't mangle the table formatting.
- let cases = [
- // --- Table of test cases ---
- // test seconds test nanos expected seconds expected nanos
- (line!(), 0, 0, 0, 0),
- (line!(), 1, 1, 1, 1),
- (line!(), -1, -1, -2, 999_999_999),
- (line!(), 0, 999_999_999, 0, 999_999_999),
- (line!(), 0, -999_999_999, -1, 1),
- (line!(), 0, 1_000_000_000, 1, 0),
- (line!(), 0, -1_000_000_000, -1, 0),
- (line!(), 0, 1_000_000_001, 1, 1),
- (line!(), 0, -1_000_000_001, -2, 999_999_999),
- (line!(), -1, 1, -1, 1),
- (line!(), 1, -1, 0, 999_999_999),
- (line!(), -1, 1_000_000_000, 0, 0),
- (line!(), 1, -1_000_000_000, 0, 0),
- (line!(), i64::MIN , 0, i64::MIN , 0),
- (line!(), i64::MIN + 1, 0, i64::MIN + 1, 0),
- (line!(), i64::MIN , 1, i64::MIN , 1),
- (line!(), i64::MIN , 1_000_000_000, i64::MIN + 1, 0),
- (line!(), i64::MIN , -1_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN + 1, -1_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN + 2, -1_000_000_000, i64::MIN + 1, 0),
- (line!(), i64::MIN , -1_999_999_998, i64::MIN , 0),
- (line!(), i64::MIN + 1, -1_999_999_998, i64::MIN , 0),
- (line!(), i64::MIN + 2, -1_999_999_998, i64::MIN , 2),
- (line!(), i64::MIN , -1_999_999_999, i64::MIN , 0),
- (line!(), i64::MIN + 1, -1_999_999_999, i64::MIN , 0),
- (line!(), i64::MIN + 2, -1_999_999_999, i64::MIN , 1),
- (line!(), i64::MIN , -2_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN + 1, -2_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN + 2, -2_000_000_000, i64::MIN , 0),
- (line!(), i64::MIN , -999_999_998, i64::MIN , 0),
- (line!(), i64::MIN + 1, -999_999_998, i64::MIN , 2),
- (line!(), i64::MAX , 0, i64::MAX , 0),
- (line!(), i64::MAX - 1, 0, i64::MAX - 1, 0),
- (line!(), i64::MAX , -1, i64::MAX - 1, 999_999_999),
- (line!(), i64::MAX , 1_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_000_000_000, i64::MAX , 0),
- (line!(), i64::MAX - 2, 1_000_000_000, i64::MAX - 1, 0),
- (line!(), i64::MAX , 1_999_999_998, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_999_999_998, i64::MAX , 999_999_998),
- (line!(), i64::MAX - 2, 1_999_999_998, i64::MAX - 1, 999_999_998),
- (line!(), i64::MAX , 1_999_999_999, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 1_999_999_999, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 2, 1_999_999_999, i64::MAX - 1, 999_999_999),
- (line!(), i64::MAX , 2_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 1, 2_000_000_000, i64::MAX , 999_999_999),
- (line!(), i64::MAX - 2, 2_000_000_000, i64::MAX , 0),
- (line!(), i64::MAX , 999_999_998, i64::MAX , 999_999_998),
- (line!(), i64::MAX - 1, 999_999_998, i64::MAX - 1, 999_999_998),
- ];
-
- for case in cases.iter() {
- let mut test_timestamp = crate::Timestamp {
- seconds: case.1,
- nanos: case.2,
- };
- test_timestamp.normalize();
-
- assert_eq!(
- test_timestamp,
- crate::Timestamp {
- seconds: case.3,
- nanos: case.4,
- },
- "test case on line {} doesn't match",
- case.0,
- );
- }
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/resources/update.sh b/kclvm/third-party/prost-wkt/wkt-types/resources/update.sh
deleted file mode 100755
index 71f68570f..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/resources/update.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-
-WORKSPACE=`cargo metadata --format-version 1 | jq -r '.workspace_root '`
-RESOURCES="${WORKSPACE}/wkt-types/resources"
-VERSION=`cargo metadata --format-version 1 | jq -r '.packages[] | select( .name == "prost" ) | .version '`
-
-REPO="https://raw.githubusercontent.com/tokio-rs/prost/v${VERSION}/prost-types"
-LIB_FILE="${REPO}/src/lib.rs"
-DATETIME_FILE="${REPO}/src/datetime.rs"
-
-curl --silent ${LIB_FILE} > ${RESOURCES}/lib.rs
-curl --silent ${DATETIME_FILE} > ${RESOURCES}/datetime.rs
-
-printf "\n!! Please update ${WORKSPACE}/wkt-types/build.rs to reflect new lib.rs !!\n\n"
diff --git a/kclvm/third-party/prost-wkt/wkt-types/src/lib.rs b/kclvm/third-party/prost-wkt/wkt-types/src/lib.rs
deleted file mode 100644
index 7d4dfcc2d..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/src/lib.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-//! `prost-wkt` adds helper methods to deal with protobuf well known types.
-
-mod pbtime;
-pub use crate::pbtime::*;
-
-mod pbstruct;
-pub use crate::pbstruct::*;
-
-mod pbany;
-pub use crate::pbany::*;
-
-mod pbempty;
-pub use crate::pbempty::*;
-
-pub use prost_wkt::MessageSerde;
diff --git a/kclvm/third-party/prost-wkt/wkt-types/src/pbany.rs b/kclvm/third-party/prost-wkt/wkt-types/src/pbany.rs
deleted file mode 100644
index 4c46183fc..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/src/pbany.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-use prost_wkt::MessageSerde;
-use serde::de::{Deserialize, Deserializer};
-use serde::ser::{Serialize, SerializeStruct, Serializer};
-
-include!(concat!(env!("OUT_DIR"), "/pbany/google.protobuf.rs"));
-
-use prost::{DecodeError, Message};
-
-use std::borrow::Cow;
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct AnyError {
- description: Cow<'static, str>,
-}
-
-impl AnyError {
- pub fn new(description: S) -> Self
- where
- S: Into>,
- {
- AnyError {
- description: description.into(),
- }
- }
-}
-
-impl std::error::Error for AnyError {
- fn description(&self) -> &str {
- &self.description
- }
-}
-
-impl std::fmt::Display for AnyError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str("failed to convert Value: ")?;
- f.write_str(&self.description)
- }
-}
-
-impl From for AnyError {
- fn from(error: DecodeError) -> Self {
- AnyError::new(format!("Error decoding message: {error:?}"))
- }
-}
-
-impl From for AnyError {
- fn from(error: prost::EncodeError) -> Self {
- AnyError::new(format!("Error encoding message: {error:?}"))
- }
-}
-
-impl Any {
- /// Packs a message into an `Any` containing a `type_url` which will take the format
- /// of `type.googleapis.com/package_name.struct_name`, and a value containing the
- /// encoded message.
- #[deprecated(since = "0.3.0", note = "please use `try_pack` instead")]
- pub fn pack(message: T) -> Self
- where
- T: Message + MessageSerde + Default,
- {
- let type_url = MessageSerde::type_url(&message).to_string();
- // Serialize the message into a value
- let mut buf = Vec::new();
- buf.reserve(message.encoded_len());
- message.encode(&mut buf).expect("Failed to encode message");
- Any {
- type_url,
- value: buf,
- }
- }
-
- /// Packs a message into an `Any` containing a `type_url` which will take the format
- /// of `type.googleapis.com/package_name.struct_name`, and a value containing the
- /// encoded message.
- pub fn try_pack(message: T) -> Result
- where
- T: Message + MessageSerde + Default,
- {
- let type_url = MessageSerde::type_url(&message).to_string();
- // Serialize the message into a value
- let mut buf = Vec::new();
- buf.reserve(message.encoded_len());
- message.encode(&mut buf)?;
- let encoded = Any {
- type_url,
- value: buf,
- };
- Ok(encoded)
- }
-
- /// Unpacks the contents of the `Any` into the provided message type. Example usage:
- ///
- /// ```ignore
- /// let back: Foo = any.unpack_as(Foo::default())?;
- /// ```
- pub fn unpack_as(self, mut target: T) -> Result {
- let instance = target.merge(self.value.as_slice()).map(|_| target)?;
- Ok(instance)
- }
-
- #[deprecated(since = "0.3.0", note = "Method renamed to `try_unpack`")]
- pub fn unpack(self) -> Result, AnyError> {
- self.try_unpack()
- }
-
- /// Unpacks the contents of the `Any` into the `MessageSerde` trait object. Example
- /// usage:
- ///
- /// ```ignore
- /// let back: Box = any.try_unpack()?;
- /// ```
- pub fn try_unpack(self) -> Result, AnyError> {
- ::prost_wkt::inventory::iter::<::prost_wkt::MessageSerdeDecoderEntry>
- .into_iter()
- .find(|entry| self.type_url == entry.type_url)
- .ok_or_else(|| format!("Failed to deserialize {}. Make sure prost-wkt-build is executed.", self.type_url))
- .and_then(|entry| {
- (entry.decoder)(&self.value).map_err(|error| {
- format!(
- "Failed to deserialize {}. Make sure it implements prost::Message. Error reported: {}",
- self.type_url,
- error
- )
- })
- })
- .map_err(AnyError::new)
- }
-}
-
-impl Serialize for Any {
- fn serialize(&self, serializer: S) -> Result<::Ok, ::Error>
- where
- S: Serializer,
- {
- match self.clone().try_unpack() {
- Ok(result) => serde::ser::Serialize::serialize(result.as_ref(), serializer),
- Err(_) => {
- let mut state = serializer.serialize_struct("Any", 3)?;
- state.serialize_field("@type", &self.type_url)?;
- state.serialize_field("value", &self.value)?;
- state.end()
- }
- }
- }
-}
-
-impl<'de> Deserialize<'de> for Any {
- fn deserialize(deserializer: D) -> Result
- where
- D: Deserializer<'de>,
- {
- let erased: Box =
- serde::de::Deserialize::deserialize(deserializer)?;
- let type_url = erased.type_url().to_string();
- let value = erased.try_encoded().map_err(|err| {
- serde::de::Error::custom(format!("Failed to encode message: {err:?}"))
- })?;
- Ok(Any { type_url, value })
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::pbany::*;
- use prost::{DecodeError, EncodeError, Message};
- use prost_wkt::*;
- use serde::*;
- use serde_json::json;
-
- #[derive(Clone, Eq, PartialEq, ::prost::Message, Serialize, Deserialize)]
- #[serde(default, rename_all = "camelCase")]
- pub struct Foo {
- #[prost(string, tag = "1")]
- pub string: std::string::String,
- }
-
- #[typetag::serde(name = "type.googleapis.com/any.test.Foo")]
- impl prost_wkt::MessageSerde for Foo {
- fn message_name(&self) -> &'static str {
- "Foo"
- }
-
- fn package_name(&self) -> &'static str {
- "any.test"
- }
-
- fn type_url(&self) -> &'static str {
- "type.googleapis.com/any.test.Foo"
- }
- fn new_instance(&self, data: Vec) -> Result, DecodeError> {
- let mut target = Self::default();
- Message::merge(&mut target, data.as_slice())?;
- let erased: Box = Box::new(target);
- Ok(erased)
- }
-
- fn try_encoded(&self) -> Result, EncodeError> {
- let mut buf = Vec::new();
- buf.reserve(Message::encoded_len(self));
- Message::encode(self, &mut buf)?;
- Ok(buf)
- }
- }
-
- #[test]
- fn pack_unpack_test() {
- let msg = Foo {
- string: "Hello World!".to_string(),
- };
- let any = Any::try_pack(msg.clone()).unwrap();
- println!("{any:?}");
- let unpacked = any.unpack_as(Foo::default()).unwrap();
- println!("{unpacked:?}");
- assert_eq!(unpacked, msg)
- }
-
- #[test]
- fn pack_unpack_with_downcast_test() {
- let msg = Foo {
- string: "Hello World!".to_string(),
- };
- let any = Any::try_pack(msg.clone()).unwrap();
- println!("{any:?}");
- let unpacked: &dyn MessageSerde = &any.unpack_as(Foo::default()).unwrap();
- let downcast = unpacked.downcast_ref::().unwrap();
- assert_eq!(downcast, &msg);
- }
-
- #[test]
- fn deserialize_default_test() {
- let type_url = "type.googleapis.com/any.test.Foo";
- let data = json!({
- "@type": type_url,
- "value": {}
- });
- let erased: Box = serde_json::from_value(data).unwrap();
- let foo: &Foo = erased.downcast_ref::().unwrap();
- println!("Deserialize default: {foo:?}");
- assert_eq!(foo, &Foo::default())
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/src/pbempty.rs b/kclvm/third-party/prost-wkt/wkt-types/src/pbempty.rs
deleted file mode 100644
index 12ab968aa..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/src/pbempty.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-include!(concat!(env!("OUT_DIR"), "/pbempty/google.protobuf.rs"));
-
-const EMPTY: Empty = Empty {};
-
-impl From<()> for Empty {
- fn from(_value: ()) -> Self {
- EMPTY
- }
-}
-
-#[cfg(test)]
-mod tests {
-
- use crate::pbempty::*;
-
- #[test]
- fn serialize_empty() {
- let msg = EMPTY;
- println!(
- "Serialized to string: {}",
- serde_json::to_string_pretty(&msg).unwrap()
- );
- }
-
- #[test]
- fn deserialize_empty() {
- let msg: Empty =
- serde_json::from_str("{}").expect("Could not deserialize `{}` to an Empty struct!");
- assert_eq!(msg, EMPTY);
- }
-
- #[test]
- fn convert_unit() {
- let msg: Empty = ().into();
- assert_eq!(msg, Empty {});
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/src/pbstruct.rs b/kclvm/third-party/prost-wkt/wkt-types/src/pbstruct.rs
deleted file mode 100644
index 26b8e82f9..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/src/pbstruct.rs
+++ /dev/null
@@ -1,430 +0,0 @@
-use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
-use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
-
-use std::borrow::Cow;
-use std::convert::TryFrom;
-use std::fmt;
-
-include!(concat!(env!("OUT_DIR"), "/pbstruct/google.protobuf.rs"));
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct ValueError {
- description: Cow<'static, str>,
-}
-
-impl ValueError {
- pub fn new(description: S) -> Self
- where
- S: Into>,
- {
- ValueError {
- description: description.into(),
- }
- }
-}
-
-impl std::error::Error for ValueError {
- fn description(&self) -> &str {
- &self.description
- }
-}
-
-impl std::fmt::Display for ValueError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str("failed to convert Value: ")?;
- f.write_str(&self.description)
- }
-}
-
-impl Value {
- pub fn null() -> Self {
- let kind = Some(value::Kind::NullValue(0));
- Value { kind }
- }
- pub fn number(num: f64) -> Self {
- Value::from(num)
- }
- pub fn string(s: String) -> Self {
- Value::from(s)
- }
- pub fn bool(b: bool) -> Self {
- Value::from(b)
- }
- pub fn pb_struct(m: std::collections::HashMap) -> Self {
- Value::from(m)
- }
- pub fn pb_list(l: std::vec::Vec) -> Self {
- Value::from(l)
- }
-}
-
-impl From for Value {
- fn from(_: NullValue) -> Self {
- Value::null()
- }
-}
-
-impl From for Value {
- fn from(num: f64) -> Self {
- let kind = Some(value::Kind::NumberValue(num));
- Value { kind }
- }
-}
-
-impl TryFrom for f64 {
- type Error = ValueError;
-
- fn try_from(value: Value) -> Result {
- match value.kind {
- Some(value::Kind::NumberValue(num)) => Ok(num),
- Some(_other) => Err(ValueError::new(
- "Cannot convert to f64 because this is not a ValueNumber.",
- )),
- _ => Err(ValueError::new(
- "Conversion to f64 failed because value is empty!",
- )),
- }
- }
-}
-
-impl From for Value {
- fn from(s: String) -> Self {
- let kind = Some(value::Kind::StringValue(s));
- Value { kind }
- }
-}
-
-impl TryFrom for String {
- type Error = ValueError;
-
- fn try_from(value: Value) -> Result {
- match value.kind {
- Some(value::Kind::StringValue(string)) => Ok(string),
- Some(_other) => Err(ValueError::new(
- "Cannot convert to String because this is not a StringValue.",
- )),
- _ => Err(ValueError::new(
- "Conversion to String failed because value is empty!",
- )),
- }
- }
-}
-
-impl From for Value {
- fn from(b: bool) -> Self {
- let kind = Some(value::Kind::BoolValue(b));
- Value { kind }
- }
-}
-
-impl TryFrom for bool {
- type Error = ValueError;
-
- fn try_from(value: Value) -> Result {
- match value.kind {
- Some(value::Kind::BoolValue(b)) => Ok(b),
- Some(_other) => Err(ValueError::new(
- "Cannot convert to bool because this is not a BoolValue.",
- )),
- _ => Err(ValueError::new(
- "Conversion to bool failed because value is empty!",
- )),
- }
- }
-}
-
-impl From> for Value {
- fn from(fields: std::collections::HashMap) -> Self {
- let s = Struct { fields };
- let kind = Some(value::Kind::StructValue(s));
- Value { kind }
- }
-}
-
-impl TryFrom for std::collections::HashMap {
- type Error = ValueError;
-
- fn try_from(value: Value) -> Result {
- match value.kind {
- Some(value::Kind::StructValue(s)) => Ok(s.fields),
- Some(_other) => Err(ValueError::new(
- "Cannot convert to HashMap because this is not a StructValue.",
- )),
- _ => Err(ValueError::new(
- "Conversion to HashMap failed because value is empty!",
- )),
- }
- }
-}
-
-impl From> for Value {
- fn from(values: Vec) -> Self {
- let v = ListValue { values };
- let kind = Some(value::Kind::ListValue(v));
- Value { kind }
- }
-}
-
-impl TryFrom for std::vec::Vec {
- type Error = ValueError;
-
- fn try_from(value: Value) -> Result {
- match value.kind {
- Some(value::Kind::ListValue(list)) => Ok(list.values),
- Some(_other) => Err(ValueError::new(
- "Cannot convert to Vec because this is not a ListValue.",
- )),
- _ => Err(ValueError::new(
- "Conversion to Vec failed because value is empty!",
- )),
- }
- }
-}
-
-impl Serialize for ListValue {
- fn serialize(&self, serializer: S) -> Result<::Ok, ::Error>
- where
- S: Serializer,
- {
- let mut seq = serializer.serialize_seq(Some(self.values.len()))?;
- for e in &self.values {
- seq.serialize_element(e)?;
- }
- seq.end()
- }
-}
-
-impl Serialize for Struct {
- fn serialize(&self, serializer: S) -> Result<::Ok, ::Error>
- where
- S: Serializer,
- {
- let mut map = serializer.serialize_map(Some(self.fields.len()))?;
- for (k, v) in &self.fields {
- map.serialize_entry(k, v)?;
- }
- map.end()
- }
-}
-
-impl Serialize for Value {
- fn serialize(&self, serializer: S) -> Result<::Ok, ::Error>
- where
- S: Serializer,
- {
- match &self.kind {
- Some(value::Kind::NumberValue(num)) => serializer.serialize_f64(*num),
- Some(value::Kind::StringValue(string)) => serializer.serialize_str(string),
- Some(value::Kind::BoolValue(boolean)) => serializer.serialize_bool(*boolean),
- Some(value::Kind::NullValue(_)) => serializer.serialize_none(),
- Some(value::Kind::ListValue(list)) => list.serialize(serializer),
- Some(value::Kind::StructValue(object)) => object.serialize(serializer),
- _ => serializer.serialize_none(),
- }
- }
-}
-
-struct ListValueVisitor;
-impl<'de> Visitor<'de> for ListValueVisitor {
- type Value = crate::ListValue;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("a prost_wkt_types::ListValue struct")
- }
-
- fn visit_seq(self, mut seq: A) -> Result
- where
- A: SeqAccess<'de>,
- {
- let mut values: Vec = Vec::new();
- while let Some(el) = seq.next_element()? {
- values.push(el)
- }
- Ok(ListValue { values })
- }
-}
-
-impl<'de> Deserialize<'de> for ListValue {
- fn deserialize(deserializer: D) -> Result>::Error>
- where
- D: Deserializer<'de>,
- {
- deserializer.deserialize_seq(ListValueVisitor)
- }
-}
-
-struct StructVisitor;
-impl<'de> Visitor<'de> for StructVisitor {
- type Value = crate::Struct;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("a prost_wkt_types::Struct struct")
- }
-
- fn visit_map(self, mut map: A) -> Result
- where
- A: MapAccess<'de>,
- {
- let mut fields: std::collections::HashMap = std::collections::HashMap::new();
- while let Some((key, value)) = map.next_entry::()? {
- fields.insert(key, value);
- }
- Ok(Struct { fields })
- }
-}
-
-impl<'de> Deserialize<'de> for Struct {
- fn deserialize(deserializer: D) -> Result>::Error>
- where
- D: Deserializer<'de>,
- {
- deserializer.deserialize_map(StructVisitor)
- }
-}
-
-impl<'de> Deserialize<'de> for Value {
- fn deserialize(deserializer: D) -> Result>::Error>
- where
- D: Deserializer<'de>,
- {
- struct ValueVisitor;
-
- impl<'de> Visitor<'de> for ValueVisitor {
- type Value = crate::Value;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("a prost_wkt_types::Value struct")
- }
-
- fn visit_bool(self, value: bool) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(value))
- }
-
- fn visit_i64(self, value: i64) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(value as f64))
- }
-
- fn visit_u64(self, value: u64) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(value as f64))
- }
-
- fn visit_f64(self, value: f64) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(value))
- }
-
- fn visit_str(self, value: &str) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(String::from(value)))
- }
-
- fn visit_string(self, value: String) -> Result
- where
- E: de::Error,
- {
- Ok(Value::from(value))
- }
-
- fn visit_none(self) -> Result
- where
- E: de::Error,
- {
- Ok(Value::null())
- }
-
- fn visit_unit(self) -> Result
- where
- E: de::Error,
- {
- Ok(Value::null())
- }
-
- fn visit_seq(self, seq: A) -> Result
- where
- A: SeqAccess<'de>,
- {
- ListValueVisitor.visit_seq(seq).map(|lv| {
- let kind = Some(value::Kind::ListValue(lv));
- Value { kind }
- })
- }
-
- fn visit_map(self, map: A) -> Result
- where
- A: MapAccess<'de>,
- {
- StructVisitor.visit_map(map).map(|s| {
- let kind = Some(value::Kind::StructValue(s));
- Value { kind }
- })
- }
- }
- deserializer.deserialize_any(ValueVisitor)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::pbstruct::*;
- use std::collections::HashMap;
-
- #[test]
- fn conversion_test() {
- let number: Value = Value::from(10.0);
- println!("Number: {number:?}");
- let null: Value = Value::null();
- println!("Null: {null:?}");
- let string: Value = Value::from(String::from("Hello"));
- println!("String: {string:?}");
- let list = vec![Value::null(), Value::from(100.0)];
- let pb_list: Value = Value::from(list);
- println!("List: {pb_list:?}");
- let mut map: HashMap = HashMap::new();
- map.insert(String::from("some_number"), number);
- map.insert(String::from("a_null_value"), null);
- map.insert(String::from("string"), string);
- map.insert(String::from("list"), pb_list);
- let pb_struct: Value = Value::from(map);
- println!("Struct: {pb_struct:?}");
- }
-
- #[test]
- fn convert_serde_json_test() {
- let data = r#"{
- "string":"hello",
- "timestamp":"1970-01-01T00:01:39.000000042Z",
- "boolean":true,
- "data": {
- "test_number": 1.0,
- "test_bool": true,
- "testString": "hi there",
- "testList": [1.0, 2.0, 3.0, 4.0],
- "testInnerStruct": {
- "one": 1.0,
- "two": 2.0
- }
- },
- "list": []
- }"#;
- let sj: serde_json::Value = serde_json::from_str(data).unwrap();
- println!("serde_json::Value: {sj:#?}");
- let pj: Value = serde_json::from_value(sj.clone()).unwrap();
- let string: String = serde_json::to_string_pretty(&pj).unwrap();
- println!("prost_wkt_types String: {string}");
- let back: serde_json::Value = serde_json::from_str(&string).unwrap();
- assert_eq!(sj, back);
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/src/pbtime.rs b/kclvm/third-party/prost-wkt/wkt-types/src/pbtime.rs
deleted file mode 100644
index 055d17819..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/src/pbtime.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-use core::convert::TryFrom;
-use core::str::FromStr;
-use core::*;
-use std::convert::TryInto;
-
-use chrono::prelude::*;
-
-use serde::de::{self, Deserialize, Deserializer, Visitor};
-use serde::ser::{Serialize, Serializer};
-
-include!(concat!(env!("OUT_DIR"), "/pbtime/google.protobuf.rs"));
-include!(concat!(env!("OUT_DIR"), "/prost_snippet.rs"));
-
-/// Converts chrono's `NaiveDateTime` to `Timestamp`..
-impl From for Timestamp {
- fn from(dt: NaiveDateTime) -> Self {
- Timestamp {
- seconds: dt.and_utc().timestamp(),
- nanos: dt.and_utc().timestamp_subsec_nanos() as i32,
- }
- }
-}
-
-/// Converts chrono's `DateTime` to `Timestamp`
-impl From> for Timestamp {
- fn from(dt: DateTime) -> Self {
- Timestamp {
- seconds: dt.timestamp(),
- nanos: dt.timestamp_subsec_nanos() as i32,
- }
- }
-}
-
-/// Converts proto timestamp to chrono's DateTime
-impl From for DateTime {
- fn from(val: Timestamp) -> Self {
- let mut value = val;
- // A call to `normalize` should capture all out-of-bound sitations hopefully
- // ensuring a panic never happens! Ideally this implementation should be
- // deprecated in favour of TryFrom but unfortunately having `TryFrom` along with
- // `From` causes a conflict.
- value.normalize();
- DateTime::from_timestamp(value.seconds, value.nanos as u32)
- .expect("invalid or out-of-range datetime")
- }
-}
-
-impl Serialize for Timestamp {
- fn serialize(&self, serializer: S) -> Result<::Ok, ::Error>
- where
- S: Serializer,
- {
- let mut ts = Timestamp {
- seconds: self.seconds,
- nanos: self.nanos,
- };
- ts.normalize();
- let dt: DateTime = ts.try_into().map_err(serde::ser::Error::custom)?;
- serializer.serialize_str(format!("{dt:?}").as_str())
- }
-}
-
-impl<'de> Deserialize<'de> for Timestamp {
- fn deserialize(deserializer: D) -> Result>::Error>
- where
- D: Deserializer<'de>,
- {
- struct TimestampVisitor;
-
- impl<'de> Visitor<'de> for TimestampVisitor {
- type Value = Timestamp;
-
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_str("Timestamp in RFC3339 format")
- }
-
- fn visit_str(self, value: &str) -> Result
- where
- E: de::Error,
- {
- let utc: DateTime = chrono::DateTime::from_str(value).map_err(|err| {
- serde::de::Error::custom(format!(
- "Failed to parse {value} as datetime: {err:?}"
- ))
- })?;
- let ts = Timestamp::from(utc);
- Ok(ts)
- }
- }
- deserializer.deserialize_str(TimestampVisitor)
- }
-}
-
-#[cfg(test)]
-mod tests {
-
- use crate::pbtime::*;
- use chrono::{DateTime, Utc};
-
- #[test]
- fn serialize_duration() {
- let duration = Duration {
- seconds: 10,
- nanos: 100,
- };
- let json = serde_json::to_string_pretty(&duration).expect("json");
- println!("{json}");
- let back: Duration = serde_json::from_str(&json).expect("duration");
- assert_eq!(duration, back);
- }
-
- #[test]
- fn invalid_timestamp_test() {
- let ts = Timestamp {
- seconds: 10,
- nanos: 2000000000,
- };
- let datetime_utc: DateTime = ts.into();
-
- println!("{datetime_utc:?}");
- }
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/tests/pbany_test.rs b/kclvm/third-party/prost-wkt/wkt-types/tests/pbany_test.rs
deleted file mode 100644
index 815c14e09..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/tests/pbany_test.rs
+++ /dev/null
@@ -1,179 +0,0 @@
-use prost::{DecodeError, EncodeError, Message};
-use prost_wkt::*;
-use prost_wkt_types::*;
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-
-#[derive(Clone, PartialEq, ::prost::Message, Serialize, Deserialize)]
-#[prost(package = "any.test")]
-#[serde(rename_all = "camelCase")]
-pub struct Foo {
- #[prost(string, tag = "1")]
- pub string: std::string::String,
- #[prost(message, optional, tag = "2")]
- pub timestamp: ::std::option::Option<::prost_wkt_types::Timestamp>,
- #[prost(bool, tag = "3")]
- pub boolean: bool,
- #[prost(message, optional, tag = "4")]
- pub value_data: ::std::option::Option<::prost_wkt_types::Value>,
- #[prost(string, repeated, tag = "5")]
- pub list: ::std::vec::Vec,
- #[prost(message, optional, tag = "6")]
- pub payload: ::std::option::Option<::prost_wkt_types::Any>,
-}
-
-#[typetag::serde(name = "type.googleapis.com/any.test.Foo")]
-impl prost_wkt::MessageSerde for Foo {
- fn message_name(&self) -> &'static str {
- "Foo"
- }
-
- fn package_name(&self) -> &'static str {
- "any.test"
- }
-
- fn type_url(&self) -> &'static str {
- "type.googleapis.com/any.test.Foo"
- }
-
- fn new_instance(&self, data: Vec) -> Result, DecodeError> {
- let mut target = Self::default();
- Message::merge(&mut target, data.as_slice())?;
- let erased: Box = Box::new(target);
- Ok(erased)
- }
-
- fn try_encoded(&self) -> Result, EncodeError> {
- let mut buf = Vec::new();
- buf.reserve(Message::encoded_len(self));
- Message::encode(self, &mut buf)?;
- Ok(buf)
- }
-}
-
-::prost_wkt::inventory::submit! {
- ::prost_wkt::MessageSerdeDecoderEntry {
- type_url: "type.googleapis.com/any.test.Foo",
- decoder: |buf: &[u8]| {
- let msg: Foo = ::prost::Message::decode(buf)?;
- Ok(Box::new(msg))
- }
- }
-}
-
-fn create_struct() -> Value {
- let number: Value = Value::from(10.0);
- let null: Value = Value::null();
- let string: Value = Value::from(String::from("Hello"));
- let list = vec![Value::null(), Value::from(100.0)];
- let pb_list: Value = Value::from(list);
- let mut map: HashMap = HashMap::new();
- map.insert(String::from("number"), number);
- map.insert(String::from("null"), null);
- map.insert(String::from("string"), string);
- map.insert(String::from("list"), pb_list);
- Value::from(map)
-}
-
-#[test]
-fn test_any_serialization() {
- let inner = Foo {
- string: String::from("inner"),
- timestamp: None,
- boolean: false,
- value_data: Some(create_struct()),
- list: vec!["een".to_string(), "twee".to_string()],
- payload: None,
- };
-
- let msg = Foo {
- string: String::from("hello"),
- timestamp: Some(prost_wkt_types::Timestamp {
- seconds: 99,
- nanos: 42,
- }),
- boolean: true,
- value_data: Some(prost_wkt_types::Value::from("world".to_string())),
- list: vec!["one".to_string(), "two".to_string()],
- payload: prost_wkt_types::Any::try_pack(inner).ok(),
- };
- println!(
- "Serialized to string: {}",
- serde_json::to_string_pretty(&msg).unwrap()
- );
- let erased = &msg as &dyn MessageSerde;
- let json = serde_json::to_string(erased).unwrap();
- println!("Erased json: {json}");
-}
-
-#[test]
-fn test_any_deserialize_string() {
- let data = r#"{
- "string":"hello",
- "timestamp":"1970-01-01T00:01:39.000000042Z",
- "boolean":true,
- "valueData": {
- "test_number": 1,
- "test_bool": true,
- "test_string": "hi there",
- "test_list": [1, 2, 3, 4],
- "test_inner_struct": {
- "one": 1,
- "two": 2
- }
- },
- "list": []
- }"#;
- let msg: Foo = serde_json::from_str(data).unwrap();
- println!("Deserialized from string: {msg:?}");
- let serialized = serde_json::to_string_pretty(&msg).expect("serialized Foo");
- println!("{serialized}")
-}
-
-#[test]
-fn test_any_serialize_deserialize() {
- let inner = Foo {
- string: String::from("inner"),
- timestamp: None,
- boolean: false,
- value_data: None,
- list: vec!["een".to_string(), "twee".to_string()],
- payload: None,
- };
-
- let original = Foo {
- string: String::from("original"),
- timestamp: Some(prost_wkt_types::Timestamp {
- seconds: 99,
- nanos: 42,
- }),
- boolean: true,
- value_data: Some(prost_wkt_types::Value::from("world".to_string())),
- list: vec!["one".to_string(), "two".to_string()],
- payload: prost_wkt_types::Any::try_pack(inner).ok(),
- };
-
- let json = serde_json::to_string(&original).unwrap();
- println!("Serialized Foo: {json}");
- let back: Foo = serde_json::from_str(&json).unwrap();
- println!("Deserialized Foo: {:?}", &back);
- assert_eq!(back, original)
-}
-
-#[test]
-#[allow(clippy::disallowed_names)]
-fn test_any_unpack() {
- let payload = Foo {
- string: String::from("hello payload"),
- timestamp: None,
- boolean: false,
- value_data: None,
- list: vec!["een".to_string(), "twee".to_string()],
- payload: None,
- };
- let any = prost_wkt_types::Any::try_pack(payload).unwrap();
- let unpacked = any.try_unpack().unwrap();
- let foo = unpacked.downcast_ref::().unwrap();
- println!("Unpacked: {foo:?}");
- assert_eq!(foo.string, "hello payload");
-}
diff --git a/kclvm/third-party/prost-wkt/wkt-types/tests/pbstruct_test.rs b/kclvm/third-party/prost-wkt/wkt-types/tests/pbstruct_test.rs
deleted file mode 100644
index add9ef65e..000000000
--- a/kclvm/third-party/prost-wkt/wkt-types/tests/pbstruct_test.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-use prost_wkt_types::*;
-use std::collections::HashMap;
-
-fn create_struct() -> Value {
- let number: Value = Value::from(10.0);
- let null: Value = Value::null();
- let string: Value = Value::from(String::from("Hello"));
- let list = vec![Value::null(), Value::from(100.0)];
- let pb_list: Value = Value::from(list);
- let mut map: HashMap = HashMap::new();
- map.insert(String::from("number"), number);
- map.insert(String::from("null"), null);
- map.insert(String::from("some_string"), string);
- map.insert(String::from("list"), pb_list);
- Value::from(map)
-}
-
-#[test]
-fn test_serde() {
- let value = create_struct();
- let string = serde_json::to_string_pretty(&value).expect("Json string");
- println!("{string}");
- let back: Value = serde_json::from_str(&string).expect("Value");
- println!("{back:?}");
- assert_eq!(value, back);
-}
-
-#[test]
-fn test_flatten_struct() {
- let mut fields: HashMap = HashMap::new();
- fields.insert("test".to_string(), create_struct());
- let strct = Struct {
- fields: fields.clone(),
- };
- let string_strct = serde_json::to_string_pretty(&strct).expect("Serialized struct");
- println!("{string_strct}");
-
- let value = Value::from(fields);
- let string = serde_json::to_string_pretty(&value).expect("A Value serialized to string");
- println!("{string}");
-
- assert_eq!(string_strct, string);
-}
-
-#[test]
-fn test_flatten_list() {
- let values: Vec = vec![Value::null(), Value::from(20.0), Value::from(true)];
- let list: ListValue = ListValue {
- values: values.clone(),
- };
- let string_list = serde_json::to_string_pretty(&list).expect("Serialized list");
- println!("{string_list}");
-
- let value = Value::from(values);
- let string = serde_json::to_string_pretty(&value).expect("A Value serialized to string");
- println!("{string}");
-
- assert_eq!(string_list, string);
-}