base_commit stringlengths 40 40 | patch stringlengths 274 280k | instance_id stringlengths 15 36 | pull_number int64 31 15.2k | hints_text stringlengths 0 33.6k | issue_numbers listlengths 1 3 | version stringlengths 3 5 | repo stringclasses 52 values | created_at stringlengths 20 20 | test_patch stringlengths 377 210k | problem_statement stringlengths 34 44.3k | environment_setup_commit stringlengths 40 40 | FAIL_TO_PASS listlengths 1 172 | PASS_TO_PASS listlengths 0 1.78k | FAIL_TO_FAIL listlengths 0 231 | PASS_TO_FAIL listlengths 0 6 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4cb762ec8f24f8ef3e12fcd716326a1207a88018 | diff --git a/docs.md b/docs.md
--- a/docs.md
+++ b/docs.md
@@ -589,6 +589,13 @@ swift_name_macro = "CF_SWIFT_NAME"
# default: "None"
rename_args = "PascalCase"
+# This rule specifies if the order of functions will be sorted in some way.
+#
+# "Name": sort by the name of the function
+# "None": keep order in which the functions have been parsed
+#
+# default: "Name"
+sort_by = "None"
[struct]
# A rule to use to rename struct field names. The renaming assumes the input is
diff --git a/src/bindgen/config.rs b/src/bindgen/config.rs
--- a/src/bindgen/config.rs
+++ b/src/bindgen/config.rs
@@ -201,6 +201,28 @@ impl FromStr for ItemType {
deserialize_enum_str!(ItemType);
+/// Type which specifies the sort order of functions
+#[derive(Debug, Clone, PartialEq)]
+pub enum SortKey {
+ Name,
+ None,
+}
+
+impl FromStr for SortKey {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ use self::SortKey::*;
+ Ok(match &*s.to_lowercase() {
+ "name" => Name,
+ "none" => None,
+ _ => return Err(format!("Unrecognized sort option: '{}'.", s)),
+ })
+ }
+}
+
+deserialize_enum_str!(SortKey);
+
/// Settings to apply when exporting items.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
diff --git a/src/bindgen/config.rs b/src/bindgen/config.rs
--- a/src/bindgen/config.rs
+++ b/src/bindgen/config.rs
@@ -293,6 +315,8 @@ pub struct FunctionConfig {
pub rename_args: Option<RenameRule>,
/// An optional macro to use when generating Swift function name attributes
pub swift_name_macro: Option<String>,
+ /// Sort key for function names
+ pub sort_by: SortKey,
}
impl Default for FunctionConfig {
diff --git a/src/bindgen/config.rs b/src/bindgen/config.rs
--- a/src/bindgen/config.rs
+++ b/src/bindgen/config.rs
@@ -304,6 +328,7 @@ impl Default for FunctionConfig {
args: Layout::Auto,
rename_args: None,
swift_name_macro: None,
+ sort_by: SortKey::Name,
}
}
}
diff --git a/src/bindgen/library.rs b/src/bindgen/library.rs
--- a/src/bindgen/library.rs
+++ b/src/bindgen/library.rs
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::mem;
use crate::bindgen::bindings::Bindings;
-use crate::bindgen::config::{Config, Language};
+use crate::bindgen::config::{Config, Language, SortKey};
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
use crate::bindgen::error::Error;
diff --git a/src/bindgen/library.rs b/src/bindgen/library.rs
--- a/src/bindgen/library.rs
+++ b/src/bindgen/library.rs
@@ -55,10 +55,16 @@ impl Library {
pub fn generate(mut self) -> Result<Bindings, Error> {
self.remove_excluded();
- self.functions.sort_by(|x, y| x.path.cmp(&y.path));
self.transfer_annotations();
self.simplify_standard_types();
+ match self.config.function.sort_by {
+ SortKey::Name => {
+ self.functions.sort_by(|x, y| x.path.cmp(&y.path));
+ }
+ SortKey::None => { /* keep input order */ }
+ }
+
if self.config.language == Language::C {
self.instantiate_monomorphs();
self.resolve_declaration_types();
diff --git a/template.toml b/template.toml
--- a/template.toml
+++ b/template.toml
@@ -74,6 +74,7 @@ rename_args = "None"
# prefix = "START_FUNC"
# postfix = "END_FUNC"
args = "auto"
+sort_by = "Name"
| mozilla__cbindgen-466 | 466 | That is:
https://github.com/eqrion/cbindgen/blob/eb9cce693438d2cc6fe3d74eb5a56aa50094f68f/src/bindgen/library.rs#L58
So there's no way to workaround it at the moment. But it would be reasonable to add a config switch to avoid this. If you want to send a PR for that I'd be happy to review it :) | [
"461"
] | 0.12 | mozilla/cbindgen | 2020-01-26T12:45:53Z | diff --git /dev/null b/tests/expectations/both/function_sort_name.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/function_sort_name.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
diff --git /dev/null b/tests/expectations/both/function_sort_name.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/function_sort_name.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/both/function_sort_none.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/function_sort_none.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
diff --git /dev/null b/tests/expectations/both/function_sort_none.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/function_sort_none.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/function_sort_name.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_name.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
diff --git /dev/null b/tests/expectations/function_sort_name.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_name.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/function_sort_name.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_name.cpp
@@ -0,0 +1,16 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+extern "C" {
+
+void A();
+
+void B();
+
+void C();
+
+void D();
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/function_sort_none.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_none.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
diff --git /dev/null b/tests/expectations/function_sort_none.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_none.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/function_sort_none.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/function_sort_none.cpp
@@ -0,0 +1,16 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+extern "C" {
+
+void C();
+
+void B();
+
+void D();
+
+void A();
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/tag/function_sort_name.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/function_sort_name.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
diff --git /dev/null b/tests/expectations/tag/function_sort_name.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/function_sort_name.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void A(void);
+
+void B(void);
+
+void C(void);
+
+void D(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/tag/function_sort_none.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/function_sort_none.c
@@ -0,0 +1,12 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
diff --git /dev/null b/tests/expectations/tag/function_sort_none.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/function_sort_none.compat.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void C(void);
+
+void B(void);
+
+void D(void);
+
+void A(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/function_sort_name.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/function_sort_name.rs
@@ -0,0 +1,15 @@
+#[no_mangle]
+pub extern "C" fn C()
+{ }
+
+#[no_mangle]
+pub extern "C" fn B()
+{ }
+
+#[no_mangle]
+pub extern "C" fn D()
+{ }
+
+#[no_mangle]
+pub extern "C" fn A()
+{ }
diff --git /dev/null b/tests/rust/function_sort_none.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/function_sort_none.rs
@@ -0,0 +1,15 @@
+#[no_mangle]
+pub extern "C" fn C()
+{ }
+
+#[no_mangle]
+pub extern "C" fn B()
+{ }
+
+#[no_mangle]
+pub extern "C" fn D()
+{ }
+
+#[no_mangle]
+pub extern "C" fn A()
+{ }
diff --git /dev/null b/tests/rust/function_sort_none.toml
new file mode 100644
--- /dev/null
+++ b/tests/rust/function_sort_none.toml
@@ -0,0 +1,2 @@
+[fn]
+sort_by = "None"
| Keep order of exported functions
Hi,
In my project all `extern "C" pub fn`'s are declared in a single file / module.
Is it possible to ensure that the order of the generated exported functions in the header keeps same as in the module?
To me it seems that the functions are ordered by the functions name. Am I correct about this? Is there a way of changing / workaround this?
| 4cb762ec8f24f8ef3e12fcd716326a1207a88018 | [
"test_function_sort_none"
] | [
"bindgen::mangle::generics",
"test_alias",
"test_asserted_cast",
"test_body",
"test_annotation",
"test_assoc_constant",
"test_docstyle_c99",
"test_cfg_2",
"test_documentation",
"test_const_conflict",
"test_cfg",
"test_char",
"test_cdecl",
"test_extern",
"test_const_transparent",
"test_... | [
"test_expand_default_features",
"test_expand",
"test_expand_dep",
"test_expand_dep_v2",
"test_expand_features",
"test_expand_no_default_features"
] | [] |
ff8e5d591dc8bf91a7309c54f0deb67899eeea87 | diff --git a/src/bindgen/utilities.rs b/src/bindgen/utilities.rs
--- a/src/bindgen/utilities.rs
+++ b/src/bindgen/utilities.rs
@@ -272,8 +272,7 @@ impl SynAttributeHelpers for [syn::Attribute] {
})) = attr.parse_meta()
{
if path.is_ident("doc") {
- let text = content.value().trim_end().to_owned();
- comment.push(text);
+ comment.extend(split_doc_attr(&content.value()));
}
}
}
diff --git a/src/bindgen/utilities.rs b/src/bindgen/utilities.rs
--- a/src/bindgen/utilities.rs
+++ b/src/bindgen/utilities.rs
@@ -282,3 +281,15 @@ impl SynAttributeHelpers for [syn::Attribute] {
comment
}
}
+
+fn split_doc_attr(input: &str) -> Vec<String> {
+ input
+ // Convert two newline (indicate "new paragraph") into two line break.
+ .replace("\n\n", " \n \n")
+ // Convert newline after two spaces (indicate "line break") into line break.
+ .split(" \n")
+ // Convert single newline (indicate hard-wrapped) into space.
+ .map(|s| s.replace('\n', " "))
+ .map(|s| s.trim_end().to_string())
+ .collect()
+}
| mozilla__cbindgen-454 | 454 | Yeah, it'd be great to get this fixed :)
After some researching I got some questions. Should I implement this translation by myself or using other crate?
One thing that bother me is that the spec of markdown line break is a bit vague. The algorithm isn't obvious to me. It might works for most cases but I'm afraid there would be missing one :(
Using crate might be overkill, on the other hand.
Any suggestions?
Can you clarify? I (maybe naively) was thinking that just unescaping `\n` would do.
Why isn't this just a matter of splitting/un-escaping `\n` characters in the `#[doc]` attribute? I don't think we need to generate perfect markdown, just not generate broken code.
> Can you clarify? I (maybe naively) was thinking that just unescaping \n would do.
I found that line end with **two space** is the other case markdown would cause line break.
Maybe my concern here is that should we expect the Rust source file used for generating **good** C/C++ header, also generating **good** Rust document using `rustdoc`? I think this might depends on use case.
(good means correct line break) | [
"442"
] | 0.12 | mozilla/cbindgen | 2020-01-14T11:20:17Z | diff --git /dev/null b/tests/expectations/both/documentation_attr.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/documentation_attr.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
diff --git /dev/null b/tests/expectations/both/documentation_attr.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/documentation_attr.compat.c
@@ -0,0 +1,28 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/documentation_attr.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/documentation_attr.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
diff --git /dev/null b/tests/expectations/documentation_attr.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/documentation_attr.compat.c
@@ -0,0 +1,28 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/documentation_attr.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/documentation_attr.cpp
@@ -0,0 +1,22 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+extern "C" {
+
+///With doc attr, each attr contribute to one line of document
+///like this one with a new line character at its end
+///and this one as well. So they are in the same paragraph
+///
+///Line ends with one new line should not break
+///
+///Line ends with two spaces and a new line
+///should break to next line
+///
+///Line ends with two new lines
+///
+///Should break to next paragraph
+void root();
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/tag/documentation_attr.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/documentation_attr.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
diff --git /dev/null b/tests/expectations/tag/documentation_attr.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/documentation_attr.compat.c
@@ -0,0 +1,28 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ *With doc attr, each attr contribute to one line of document
+ *like this one with a new line character at its end
+ *and this one as well. So they are in the same paragraph
+ *
+ *Line ends with one new line should not break
+ *
+ *Line ends with two spaces and a new line
+ *should break to next line
+ *
+ *Line ends with two new lines
+ *
+ *Should break to next paragraph
+ */
+void root(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/documentation_attr.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/documentation_attr.rs
@@ -0,0 +1,12 @@
+#[doc="With doc attr, each attr contribute to one line of document"]
+#[doc="like this one with a new line character at its end"]
+#[doc="and this one as well. So they are in the same paragraph"]
+#[doc=""]
+#[doc="Line ends with one new line\nshould not break"]
+#[doc=""]
+#[doc="Line ends with two spaces and a new line \nshould break to next line"]
+#[doc=""]
+#[doc="Line ends with two new lines\n\nShould break to next paragraph"]
+#[no_mangle]
+pub extern "C" fn root() {
+}
| `doc` attribute doesn't behave like rustc does
Inputs
---
```rust
#[no_mangle]
#[doc = "a \n b"]
pub extern "C" fn example_a() {}
```
and
```rust
#[no_mangle]
#[doc = "a \n\n b"]
pub extern "C" fn example_b() {}
```
Rendered rustdoc
---
[rustdoc/the doc attribute](https://doc.rust-lang.org/rustdoc/the-doc-attribute.html)


Actual generated header
---
```cpp
///a
b
void example_a();
```
```cpp
///a
b
void example_b();
```
Expected generated header
---
```cpp
///a b
void example_a();
```
```cpp
///a
///
///b
void example_b();
```
This happens when I'm trying to generate multi-line comments with macro. Looks like ([code](https://github.com/eqrion/cbindgen/blob/16fe3ec142653277d5405d9a6d25914d925c9c3c/src/bindgen/utilities.rs#L252)) we simply use value in single `doc` attribute directly without any modification (like rustdoc does).
BTW, I'm happy to help this out :)
| 4cb762ec8f24f8ef3e12fcd716326a1207a88018 | [
"test_documentation_attr"
] | [
"bindgen::mangle::generics",
"test_custom_header",
"test_alias",
"test_display_list",
"test_dep_v2",
"test_derive_eq",
"test_cfg_field",
"test_docstyle_doxy",
"test_docstyle_c99",
"test_asserted_cast",
"test_associated_in_body",
"test_constant",
"test_body",
"test_cfg",
"test_char",
"t... | [
"test_expand",
"test_expand_default_features",
"test_expand_dep",
"test_expand_dep_v2",
"test_expand_features",
"test_expand_no_default_features"
] | [] |
5b4cda0d95690f00a1088f6b43726a197d03dad0 | diff --git a/src/bindgen/bindings.rs b/src/bindgen/bindings.rs
--- a/src/bindgen/bindings.rs
+++ b/src/bindgen/bindings.rs
@@ -2,10 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+use std::cell::RefCell;
+use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::{Read, Write};
use std::path;
+use std::rc::Rc;
use bindgen::config::{Config, Language};
use bindgen::ir::{
diff --git a/src/bindgen/bindings.rs b/src/bindgen/bindings.rs
--- a/src/bindgen/bindings.rs
+++ b/src/bindgen/bindings.rs
@@ -19,6 +22,7 @@ pub struct Bindings {
/// The map from path to struct, used to lookup whether a given type is a
/// transparent struct. This is needed to generate code for constants.
struct_map: ItemMap<Struct>,
+ struct_fileds_memo: RefCell<HashMap<BindgenPath, Rc<Vec<String>>>>,
globals: Vec<Static>,
constants: Vec<Constant>,
items: Vec<ItemContainer>,
diff --git a/src/bindgen/bindings.rs b/src/bindgen/bindings.rs
--- a/src/bindgen/bindings.rs
+++ b/src/bindgen/bindings.rs
@@ -37,6 +41,7 @@ impl Bindings {
Bindings {
config,
struct_map,
+ struct_fileds_memo: Default::default(),
globals,
constants,
items,
diff --git a/src/bindgen/bindings.rs b/src/bindgen/bindings.rs
--- a/src/bindgen/bindings.rs
+++ b/src/bindgen/bindings.rs
@@ -57,6 +62,30 @@ impl Bindings {
any
}
+ pub fn struct_field_names(&self, path: &BindgenPath) -> Rc<Vec<String>> {
+ let mut memos = self.struct_fileds_memo.borrow_mut();
+ if let Some(memo) = memos.get(path) {
+ return memo.clone();
+ }
+
+ let mut fields = Vec::<String>::new();
+ self.struct_map.for_items(path, |st| {
+ let mut pos: usize = 0;
+ for field in &st.fields {
+ if let Some(found_pos) = fields.iter().position(|v| *v == field.0) {
+ pos = found_pos + 1;
+ } else {
+ fields.insert(pos, field.0.clone());
+ pos += 1;
+ }
+ }
+ });
+
+ let fields = Rc::new(fields);
+ memos.insert(path.clone(), fields.clone());
+ fields
+ }
+
pub fn write_to_file<P: AsRef<path::Path>>(&self, path: P) -> bool {
// Don't compare files if we've never written this file before
if !path.as_ref().is_file() {
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::borrow::Cow;
-use std::fmt;
+use std::collections::HashMap;
use std::io::Write;
use syn;
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -23,6 +23,10 @@ use syn::UnOp;
#[derive(Debug, Clone)]
pub enum Literal {
Expr(String),
+ PostfixUnaryOp {
+ op: &'static str,
+ value: Box<Literal>,
+ },
BinOp {
left: Box<Literal>,
op: &'static str,
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -31,14 +35,14 @@ pub enum Literal {
Struct {
path: Path,
export_name: String,
- fields: Vec<(String, Literal)>,
+ fields: HashMap<String, Literal>,
},
}
impl Literal {
fn replace_self_with(&mut self, self_ty: &Path) {
match *self {
- Literal::BinOp { .. } | Literal::Expr(..) => {}
+ Literal::PostfixUnaryOp { .. } | Literal::BinOp { .. } | Literal::Expr(..) => {}
Literal::Struct {
ref mut path,
ref mut export_name,
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -47,7 +51,7 @@ impl Literal {
if path.replace_self_with(self_ty) {
*export_name = self_ty.name().to_owned();
}
- for &mut (ref _name, ref mut expr) in fields {
+ for (ref _name, ref mut expr) in fields {
expr.replace_self_with(self_ty);
}
}
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -57,6 +61,7 @@ impl Literal {
fn is_valid(&self, bindings: &Bindings) -> bool {
match *self {
Literal::Expr(..) => true,
+ Literal::PostfixUnaryOp { ref value, .. } => value.is_valid(bindings),
Literal::BinOp {
ref left,
ref right,
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -67,33 +72,6 @@ impl Literal {
}
}
-impl fmt::Display for Literal {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Literal::Expr(v) => write!(f, "{}", v),
- Literal::BinOp {
- ref left,
- op,
- ref right,
- } => write!(f, "{} {} {}", left, op, right),
- Literal::Struct {
- export_name,
- fields,
- ..
- } => write!(
- f,
- "({}){{ {} }}",
- export_name,
- fields
- .iter()
- .map(|(key, lit)| format!(".{} = {}", key, lit))
- .collect::<Vec<String>>()
- .join(", "),
- ),
- }
- }
-}
-
impl Literal {
pub fn rename_for_config(&mut self, config: &Config) {
match self {
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -107,6 +85,9 @@ impl Literal {
lit.rename_for_config(config);
}
}
+ Literal::PostfixUnaryOp { ref mut value, .. } => {
+ value.rename_for_config(config);
+ }
Literal::BinOp {
ref mut left,
ref mut right,
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -174,7 +155,7 @@ impl Literal {
..
}) => {
let struct_name = path.segments[0].ident.to_string();
- let mut field_pairs: Vec<(String, Literal)> = Vec::new();
+ let mut field_map = HashMap::<String, Literal>::default();
for field in fields {
let ident = match field.member {
syn::Member::Named(ref name) => name.to_string(),
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -182,12 +163,12 @@ impl Literal {
};
let key = ident.to_string();
let value = Literal::load(&field.expr)?;
- field_pairs.push((key, value));
+ field_map.insert(key, value);
}
Ok(Literal::Struct {
path: Path::new(struct_name.clone()),
export_name: struct_name,
- fields: field_pairs,
+ fields: field_map,
})
}
syn::Expr::Unary(syn::ExprUnary {
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -195,13 +176,67 @@ impl Literal {
}) => match *op {
UnOp::Neg(_) => {
let val = Self::load(expr)?;
- Ok(Literal::Expr(format!("-{}", val)))
+ Ok(Literal::PostfixUnaryOp {
+ op: "-",
+ value: Box::new(val),
+ })
}
_ => Err(format!("Unsupported Unary expression. {:?}", *op)),
},
_ => Err(format!("Unsupported literal expression. {:?}", *expr)),
}
}
+
+ fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
+ match self {
+ Literal::Expr(v) => write!(out, "{}", v),
+ Literal::PostfixUnaryOp { op, ref value } => {
+ write!(out, "{}", op);
+ value.write(config, out);
+ }
+ Literal::BinOp {
+ ref left,
+ op,
+ ref right,
+ } => {
+ left.write(config, out);
+ write!(out, " {} ", op);
+ right.write(config, out);
+ }
+ Literal::Struct {
+ export_name,
+ fields,
+ path,
+ } => {
+ if config.language == Language::C {
+ write!(out, "({})", export_name);
+ } else {
+ write!(out, "{}", export_name);
+ }
+
+ write!(out, "{{ ");
+ let mut is_first_field = true;
+ // In C++, same order as defined is required.
+ let ordered_fields = out.bindings().struct_field_names(path);
+ for ordered_key in ordered_fields.iter() {
+ if let Some(ref lit) = fields.get(ordered_key) {
+ if !is_first_field {
+ write!(out, ", ");
+ } else {
+ is_first_field = false;
+ }
+ if config.language == Language::Cxx {
+ write!(out, "/* .{} = */ ", ordered_key);
+ } else {
+ write!(out, ".{} = ", ordered_key);
+ }
+ lit.write(config, out);
+ }
+ }
+ write!(out, " }}");
+ }
+ }
+ }
}
#[derive(Debug, Clone)]
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -405,7 +440,7 @@ impl Constant {
ref fields,
ref path,
..
- } if out.bindings().struct_is_transparent(path) => &fields[0].1,
+ } if out.bindings().struct_is_transparent(path) => &fields.iter().next().unwrap().1,
_ => &self.value,
};
diff --git a/src/bindgen/ir/constant.rs b/src/bindgen/ir/constant.rs
--- a/src/bindgen/ir/constant.rs
+++ b/src/bindgen/ir/constant.rs
@@ -417,9 +452,12 @@ impl Constant {
out.write("const ");
}
self.ty.write(config, out);
- write!(out, " {} = {};", name, value)
+ write!(out, " {} = ", name);
+ value.write(config, out);
+ write!(out, ";");
} else {
- write!(out, "#define {} {}", name, value)
+ write!(out, "#define {} ", name);
+ value.write(config, out);
}
condition.write_after(config, out);
}
| mozilla__cbindgen-401 | 401 | [
"397"
] | 0.9 | mozilla/cbindgen | 2019-10-12T13:18:55Z | diff --git a/tests/expectations/associated_in_body.cpp b/tests/expectations/associated_in_body.cpp
--- a/tests/expectations/associated_in_body.cpp
+++ b/tests/expectations/associated_in_body.cpp
@@ -32,11 +32,11 @@ struct StyleAlignFlags {
static const StyleAlignFlags END;
static const StyleAlignFlags FLEX_START;
};
-inline const StyleAlignFlags StyleAlignFlags::AUTO = (StyleAlignFlags){ .bits = 0 };
-inline const StyleAlignFlags StyleAlignFlags::NORMAL = (StyleAlignFlags){ .bits = 1 };
-inline const StyleAlignFlags StyleAlignFlags::START = (StyleAlignFlags){ .bits = 1 << 1 };
-inline const StyleAlignFlags StyleAlignFlags::END = (StyleAlignFlags){ .bits = 1 << 2 };
-inline const StyleAlignFlags StyleAlignFlags::FLEX_START = (StyleAlignFlags){ .bits = 1 << 3 };
+inline const StyleAlignFlags StyleAlignFlags::AUTO = StyleAlignFlags{ /* .bits = */ 0 };
+inline const StyleAlignFlags StyleAlignFlags::NORMAL = StyleAlignFlags{ /* .bits = */ 1 };
+inline const StyleAlignFlags StyleAlignFlags::START = StyleAlignFlags{ /* .bits = */ 1 << 1 };
+inline const StyleAlignFlags StyleAlignFlags::END = StyleAlignFlags{ /* .bits = */ 1 << 2 };
+inline const StyleAlignFlags StyleAlignFlags::FLEX_START = StyleAlignFlags{ /* .bits = */ 1 << 3 };
extern "C" {
diff --git a/tests/expectations/bitflags.cpp b/tests/expectations/bitflags.cpp
--- a/tests/expectations/bitflags.cpp
+++ b/tests/expectations/bitflags.cpp
@@ -27,11 +27,11 @@ struct AlignFlags {
return *this;
}
};
-static const AlignFlags AlignFlags_AUTO = (AlignFlags){ .bits = 0 };
-static const AlignFlags AlignFlags_NORMAL = (AlignFlags){ .bits = 1 };
-static const AlignFlags AlignFlags_START = (AlignFlags){ .bits = 1 << 1 };
-static const AlignFlags AlignFlags_END = (AlignFlags){ .bits = 1 << 2 };
-static const AlignFlags AlignFlags_FLEX_START = (AlignFlags){ .bits = 1 << 3 };
+static const AlignFlags AlignFlags_AUTO = AlignFlags{ /* .bits = */ 0 };
+static const AlignFlags AlignFlags_NORMAL = AlignFlags{ /* .bits = */ 1 };
+static const AlignFlags AlignFlags_START = AlignFlags{ /* .bits = */ 1 << 1 };
+static const AlignFlags AlignFlags_END = AlignFlags{ /* .bits = */ 1 << 2 };
+static const AlignFlags AlignFlags_FLEX_START = AlignFlags{ /* .bits = */ 1 << 3 };
extern "C" {
diff --git /dev/null b/tests/expectations/both/struct_literal_order.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/struct_literal_order.c
@@ -0,0 +1,24 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct ABC {
+ float a;
+ uint32_t b;
+ uint32_t c;
+} ABC;
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+typedef struct BAC {
+ uint32_t b;
+ float a;
+ int32_t c;
+} BAC;
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+void root(ABC a1, BAC a2);
diff --git /dev/null b/tests/expectations/both/struct_literal_order.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/struct_literal_order.compat.c
@@ -0,0 +1,32 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct ABC {
+ float a;
+ uint32_t b;
+ uint32_t c;
+} ABC;
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+typedef struct BAC {
+ uint32_t b;
+ float a;
+ int32_t c;
+} BAC;
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(ABC a1, BAC a2);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git a/tests/expectations/prefixed_struct_literal.cpp b/tests/expectations/prefixed_struct_literal.cpp
--- a/tests/expectations/prefixed_struct_literal.cpp
+++ b/tests/expectations/prefixed_struct_literal.cpp
@@ -7,9 +7,9 @@ struct PREFIXFoo {
int32_t a;
uint32_t b;
};
-static const PREFIXFoo PREFIXFoo_FOO = (PREFIXFoo){ .a = 42, .b = 47 };
+static const PREFIXFoo PREFIXFoo_FOO = PREFIXFoo{ /* .a = */ 42, /* .b = */ 47 };
-static const PREFIXFoo PREFIXBAR = (PREFIXFoo){ .a = 42, .b = 1337 };
+static const PREFIXFoo PREFIXBAR = PREFIXFoo{ /* .a = */ 42, /* .b = */ 1337 };
extern "C" {
diff --git a/tests/expectations/prefixed_struct_literal_deep.cpp b/tests/expectations/prefixed_struct_literal_deep.cpp
--- a/tests/expectations/prefixed_struct_literal_deep.cpp
+++ b/tests/expectations/prefixed_struct_literal_deep.cpp
@@ -13,7 +13,7 @@ struct PREFIXFoo {
PREFIXBar bar;
};
-static const PREFIXFoo PREFIXVAL = (PREFIXFoo){ .a = 42, .b = 1337, .bar = (PREFIXBar){ .a = 323 } };
+static const PREFIXFoo PREFIXVAL = PREFIXFoo{ /* .a = */ 42, /* .b = */ 1337, /* .bar = */ PREFIXBar{ /* .a = */ 323 } };
extern "C" {
diff --git a/tests/expectations/struct_literal.cpp b/tests/expectations/struct_literal.cpp
--- a/tests/expectations/struct_literal.cpp
+++ b/tests/expectations/struct_literal.cpp
@@ -9,12 +9,12 @@ struct Foo {
int32_t a;
uint32_t b;
};
-static const Foo Foo_FOO = (Foo){ .a = 42, .b = 47 };
-static const Foo Foo_FOO2 = (Foo){ .a = 42, .b = 47 };
-static const Foo Foo_FOO3 = (Foo){ .a = 42, .b = 47 };
+static const Foo Foo_FOO = Foo{ /* .a = */ 42, /* .b = */ 47 };
+static const Foo Foo_FOO2 = Foo{ /* .a = */ 42, /* .b = */ 47 };
+static const Foo Foo_FOO3 = Foo{ /* .a = */ 42, /* .b = */ 47 };
-static const Foo BAR = (Foo){ .a = 42, .b = 1337 };
+static const Foo BAR = Foo{ /* .a = */ 42, /* .b = */ 1337 };
diff --git /dev/null b/tests/expectations/struct_literal_order.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/struct_literal_order.c
@@ -0,0 +1,24 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct {
+ float a;
+ uint32_t b;
+ uint32_t c;
+} ABC;
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+typedef struct {
+ uint32_t b;
+ float a;
+ int32_t c;
+} BAC;
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+void root(ABC a1, BAC a2);
diff --git /dev/null b/tests/expectations/struct_literal_order.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/struct_literal_order.compat.c
@@ -0,0 +1,32 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct {
+ float a;
+ uint32_t b;
+ uint32_t c;
+} ABC;
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+typedef struct {
+ uint32_t b;
+ float a;
+ int32_t c;
+} BAC;
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(ABC a1, BAC a2);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/struct_literal_order.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/struct_literal_order.cpp
@@ -0,0 +1,28 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+struct ABC {
+ float a;
+ uint32_t b;
+ uint32_t c;
+};
+static const ABC ABC_abc = ABC{ /* .a = */ 1.0, /* .b = */ 2, /* .c = */ 3 };
+static const ABC ABC_bac = ABC{ /* .a = */ 1.0, /* .b = */ 2, /* .c = */ 3 };
+static const ABC ABC_cba = ABC{ /* .a = */ 1.0, /* .b = */ 2, /* .c = */ 3 };
+
+struct BAC {
+ uint32_t b;
+ float a;
+ int32_t c;
+};
+static const BAC BAC_abc = BAC{ /* .b = */ 1, /* .a = */ 2.0, /* .c = */ 3 };
+static const BAC BAC_bac = BAC{ /* .b = */ 1, /* .a = */ 2.0, /* .c = */ 3 };
+static const BAC BAC_cba = BAC{ /* .b = */ 1, /* .a = */ 2.0, /* .c = */ 3 };
+
+extern "C" {
+
+void root(ABC a1, BAC a2);
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/tag/struct_literal_order.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/struct_literal_order.c
@@ -0,0 +1,24 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct ABC {
+ float a;
+ uint32_t b;
+ uint32_t c;
+};
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+struct BAC {
+ uint32_t b;
+ float a;
+ int32_t c;
+};
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+void root(struct ABC a1, struct BAC a2);
diff --git /dev/null b/tests/expectations/tag/struct_literal_order.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/struct_literal_order.compat.c
@@ -0,0 +1,32 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct ABC {
+ float a;
+ uint32_t b;
+ uint32_t c;
+};
+#define ABC_abc (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_bac (ABC){ .a = 1.0, .b = 2, .c = 3 }
+#define ABC_cba (ABC){ .a = 1.0, .b = 2, .c = 3 }
+
+struct BAC {
+ uint32_t b;
+ float a;
+ int32_t c;
+};
+#define BAC_abc (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_bac (BAC){ .b = 1, .a = 2.0, .c = 3 }
+#define BAC_cba (BAC){ .b = 1, .a = 2.0, .c = 3 }
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(struct ABC a1, struct BAC a2);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/struct_literal_order.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/struct_literal_order.rs
@@ -0,0 +1,28 @@
+#[repr(C)]
+struct ABC {
+ pub a: f32,
+ pub b: u32,
+ pub c: u32,
+}
+
+#[repr(C)]
+struct BAC {
+ pub b: u32,
+ pub a: f32,
+ pub c: i32,
+}
+
+impl ABC {
+ pub const abc: ABC = ABC { a: 1.0, b: 2, c: 3 };
+ pub const bac: ABC = ABC { b: 2, a: 1.0, c: 3 };
+ pub const cba: ABC = ABC { c: 3, b: 2, a: 1.0 };
+}
+
+impl BAC {
+ pub const abc: BAC = BAC { a: 2.0, b: 1, c: 3 };
+ pub const bac: BAC = BAC { b: 1, a: 2.0, c: 3 };
+ pub const cba: BAC = BAC { c: 3, b: 1, a: 2.0 };
+}
+
+#[no_mangle]
+pub extern "C" fn root(a1: ABC, a2: BAC) {}
| Initialize struct literals with list-initializer
On cbindgen 0.9.1, Values of bitflags are converted to static const items with designated initializer.
But designated initializer is not available in C++11. Sadly, It is available in C++20. https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers
For C++11, struct literal should be initialized with the list-initializer.
### rust source
```rust
bitflags! {
#[repr(C)]
pub struct ResultFlags: u8 {
const EMPTY = 0b00000000;
const PROCESSED = 0b00000001;
const TIME_UPDATED = 0b00000010;
}
}
```
### current generated - compile error on C++11
```cpp
struct ResultFlags{
uint8_t bits;
explicit operator bool() const {
return !!bits;
}
ResultFlags operator|(const ResultFlags& other) const {
return {static_cast<decltype(bits)>(this->bits | other.bits)};
}
ResultFlags& operator|=(const ResultFlags& other) {
*this = (*this | other);
return *this;
}
ResultFlags operator&(const ResultFlags& other) const {
return {static_cast<decltype(bits)>(this->bits & other.bits)};
}
ResultFlags& operator&=(const ResultFlags& other) {
*this = (*this & other);
return *this;
}
};
static const ResultFlags ResultFlags_EMPTY = { .bits = 0 };
static const ResultFlags ResultFlags_PROCESSED = { .bits = 1 };
static const ResultFlags ResultFlags_TIME_UPDATED = { .bits = 2 };
```
### suggestion - compatible with C++11
```cpp
struct ResultFlags{
uint8_t bits;
explicit operator bool() const {
return !!bits;
}
ResultFlags operator|(const ResultFlags& other) const {
return {static_cast<decltype(bits)>(this->bits | other.bits)};
}
ResultFlags& operator|=(const ResultFlags& other) {
*this = (*this | other);
return *this;
}
ResultFlags operator&(const ResultFlags& other) const {
return {static_cast<decltype(bits)>(this->bits & other.bits)};
}
ResultFlags& operator&=(const ResultFlags& other) {
*this = (*this & other);
return *this;
}
};
static const ResultFlags ResultFlags_EMPTY = { 0 };
static const ResultFlags ResultFlags_PROCESSED = { 1 };
static const ResultFlags ResultFlags_TIME_UPDATED = { 2 };
```
| 5b4cda0d95690f00a1088f6b43726a197d03dad0 | [
"test_struct_literal_order"
] | [
"bindgen::mangle::generics",
"test_cdecl",
"test_bitflags",
"test_const_conflict",
"test_enum",
"test_annotation",
"test_asserted_cast",
"test_const_transparent",
"test_extern",
"test_assoc_const_conflict",
"test_array",
"test_documentation",
"test_custom_header",
"test_docstyle_doxy",
"... | [
"test_expand_features",
"test_expand_dep",
"test_expand_default_features",
"test_expand",
"test_expand_no_default_features"
] | [] | |
17d7aad7d07dce8aa665aedbc75c39953afe1600 | diff --git a/src/bindgen/parser.rs b/src/bindgen/parser.rs
--- a/src/bindgen/parser.rs
+++ b/src/bindgen/parser.rs
@@ -707,11 +707,22 @@ impl Parse {
return;
}
};
- if ty.is_none() {
- return;
- }
- let impl_path = ty.unwrap().get_root_path().unwrap();
+ let ty = match ty {
+ Some(ty) => ty,
+ None => return,
+ };
+
+ let impl_path = match ty.get_root_path() {
+ Some(p) => p,
+ None => {
+ warn!(
+ "Couldn't find path for {:?}, skipping associated constants",
+ ty
+ );
+ return;
+ }
+ };
for item in items.into_iter() {
if let syn::Visibility::Public(_) = item.vis {
| mozilla__cbindgen-494 | 494 | I can't can't tell whether this is the same thing or not because I can't read it, but I got: https://gist.githubusercontent.com/rainhead/cdc303c498a0d7389671942f6028a215/raw/1266d49996d41dd557987611272a3b97462906f3/cbindgen.txt
It works for me with `0.13.0`... What am I missing?
Looks like it works on master now.
This is the last branch that was failing: https://github.com/RazrFalcon/ttf-parser/tree/b59d608228703be2820c9ec331bbb7ab73c8d2fb
And here is a commit that fixed it: https://github.com/RazrFalcon/ttf-parser/commit/93f4ba5bb72edf2106c991f5bd99a9d962f6c353
Looks like removing some generics helped. | [
"493"
] | 0.13 | mozilla/cbindgen | 2020-03-21T14:08:30Z | diff --git /dev/null b/tests/expectations/associated_constant_panic.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/associated_constant_panic.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/expectations/associated_constant_panic.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/associated_constant_panic.compat.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/expectations/associated_constant_panic.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/associated_constant_panic.cpp
@@ -0,0 +1,4 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
diff --git /dev/null b/tests/expectations/both/associated_constant_panic.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/associated_constant_panic.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/expectations/both/associated_constant_panic.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/associated_constant_panic.compat.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/expectations/tag/associated_constant_panic.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/associated_constant_panic.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/expectations/tag/associated_constant_panic.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/associated_constant_panic.compat.c
@@ -0,0 +1,4 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
diff --git /dev/null b/tests/rust/associated_constant_panic.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/associated_constant_panic.rs
@@ -0,0 +1,7 @@
+pub trait F {
+ const B: u8;
+}
+
+impl F for u16 {
+ const B: u8 = 3;
+}
| Panics with parse_deps=true
When running cbindgen in [this](https://github.com/RazrFalcon/ttf-parser/tree/master/c-api) dir with such config:
```toml
language = "C"
include_guard = "TTFP_H"
braces = "SameLine"
tab_width = 4
documentation_style = "doxy"
[defines]
"feature = logging" = "ENABLE_LOGGING"
[fn]
sort_by = "None"
[parse]
parse_deps = true
```
I'm getting:
`thread 'main' panicked at 'called Option::unwrap() on a None value', /home/razr/.cargo/registry/src/github.com-1ecc6299db9ec823/cbindgen-0.13.1/src/bindgen/parser.rs:687:25`
| 6fd245096dcd5c50c1065b4bd6ce62a09df0b39b | [
"test_associated_constant_panic"
] | [
"bindgen::mangle::generics",
"test_assoc_const_conflict",
"test_cfg_field",
"test_char",
"test_cfg",
"test_cell",
"test_docstyle_doxy",
"test_docstyle_c99",
"test_bitflags",
"test_associated_in_body",
"test_destructor_and_copy_ctor",
"test_annotation",
"test_display_list",
"test_cfg_2",
... | [
"test_expand",
"test_expand_dep",
"test_expand_no_default_features",
"test_expand_default_features",
"test_expand_features",
"test_expand_dep_v2"
] | [] |
6654f99251769e9e037824d471f9f39e8d536b90 | diff --git a/src/bindgen/ir/ty.rs b/src/bindgen/ir/ty.rs
--- a/src/bindgen/ir/ty.rs
+++ b/src/bindgen/ir/ty.rs
@@ -392,6 +392,7 @@ impl Type {
// FIXME(#223): This is not quite correct.
"Option" if generic.is_repr_ptr() => Some(generic),
"NonNull" => Some(Type::Ptr(Box::new(generic))),
+ "Cell" => Some(generic),
_ => None,
}
}
diff --git a/src/bindgen/parser.rs b/src/bindgen/parser.rs
--- a/src/bindgen/parser.rs
+++ b/src/bindgen/parser.rs
@@ -387,6 +387,7 @@ impl Parse {
add_opaque("String", vec![]);
add_opaque("Box", vec!["T"]);
+ add_opaque("RefCell", vec!["T"]);
add_opaque("Rc", vec!["T"]);
add_opaque("Arc", vec!["T"]);
add_opaque("Result", vec!["T", "E"]);
| mozilla__cbindgen-489 | 489 | Here's a reduced test-case:
```rust
pub struct NotReprC<T> { inner: T }
pub type Foo = NotReprC<std::cell::RefCell<i32>>;
#[no_mangle]
pub extern "C" fn root(node: &Foo) {}
```
I think instead we should forward-declare RefCell in this case. Right now cbindgen's output is:
```c++
#include <cstdarg>
#include <cstdint>
#include <cstdlib>
#include <new>
template<typename T>
struct NotReprC;
using Foo = NotReprC<RefCell<int32_t>>;
extern "C" {
void root(const Foo *node);
} // extern "C"
```
With a:
> WARN: Can't find RefCell. This usually means that this type was incompatible or not found.
This is probably a one-line change to make RefCell opaque in the "with-std-types" case. While at it we should probably handle Cell properly, as Cell is repr(transparent). | [
"488"
] | 0.13 | mozilla/cbindgen | 2020-03-09T00:29:19Z | diff --git /dev/null b/tests/expectations/both/cell.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/cell.c
@@ -0,0 +1,14 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct NotReprC_RefCell_i32 NotReprC_RefCell_i32;
+
+typedef NotReprC_RefCell_i32 Foo;
+
+typedef struct MyStruct {
+ int32_t number;
+} MyStruct;
+
+void root(const Foo *a, const MyStruct *with_cell);
diff --git /dev/null b/tests/expectations/both/cell.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/cell.compat.c
@@ -0,0 +1,22 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct NotReprC_RefCell_i32 NotReprC_RefCell_i32;
+
+typedef NotReprC_RefCell_i32 Foo;
+
+typedef struct MyStruct {
+ int32_t number;
+} MyStruct;
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const MyStruct *with_cell);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/cell.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/cell.c
@@ -0,0 +1,14 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct NotReprC_RefCell_i32 NotReprC_RefCell_i32;
+
+typedef NotReprC_RefCell_i32 Foo;
+
+typedef struct {
+ int32_t number;
+} MyStruct;
+
+void root(const Foo *a, const MyStruct *with_cell);
diff --git /dev/null b/tests/expectations/cell.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/cell.compat.c
@@ -0,0 +1,22 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct NotReprC_RefCell_i32 NotReprC_RefCell_i32;
+
+typedef NotReprC_RefCell_i32 Foo;
+
+typedef struct {
+ int32_t number;
+} MyStruct;
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const MyStruct *with_cell);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/cell.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/cell.cpp
@@ -0,0 +1,22 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+template<typename T>
+struct NotReprC;
+
+template<typename T>
+struct RefCell;
+
+using Foo = NotReprC<RefCell<int32_t>>;
+
+struct MyStruct {
+ int32_t number;
+};
+
+extern "C" {
+
+void root(const Foo *a, const MyStruct *with_cell);
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/tag/cell.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/cell.c
@@ -0,0 +1,14 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct NotReprC_RefCell_i32;
+
+typedef struct NotReprC_RefCell_i32 Foo;
+
+struct MyStruct {
+ int32_t number;
+};
+
+void root(const Foo *a, const struct MyStruct *with_cell);
diff --git /dev/null b/tests/expectations/tag/cell.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/cell.compat.c
@@ -0,0 +1,22 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct NotReprC_RefCell_i32;
+
+typedef struct NotReprC_RefCell_i32 Foo;
+
+struct MyStruct {
+ int32_t number;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const struct MyStruct *with_cell);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/cell.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/cell.rs
@@ -0,0 +1,11 @@
+#[repr(C)]
+pub struct MyStruct {
+ number: std::cell::Cell<i32>,
+}
+
+pub struct NotReprC<T> { inner: T }
+
+pub type Foo = NotReprC<std::cell::RefCell<i32>>;
+
+#[no_mangle]
+pub extern "C" fn root(a: &Foo, with_cell: &MyStruct) {}
| Create opaque type for a generic specialization with `RefCell` etc.
I have:
```rust
bundle.rs:
pub type Memoizer = RefCell<IntlLangMemoizer>;
pub type FluentBundle<R> = bundle::FluentBundleBase<R, Memoizer>;
ffi.rs:
type FluentBundleRc = FluentBundle<Rc<FluentResource>>;
#[no_mangle]
pub unsafe extern "C" fn fluent_bundle_new(
locales: &ThinVec<nsCString>,
use_isolating: bool,
pseudo_strategy: &nsACString,
) -> *mut FluentBundleRc;
```
cbindgen generates out of it:
```cpp
using Memoizer = RefCell<IntlLangMemoizer>;
template<typename R>
using FluentBundle = FluentBundleBase<R, Memoizer>;
```
which results in an error:
```
error: no template named 'RefCell'
0:05.42 using Memoizer = RefCell<IntlLangMemoizer>;
```
It would be great to have cbindgen generate an opaque type in this case since all uses in C++ use it as opaque.
| 6fd245096dcd5c50c1065b4bd6ce62a09df0b39b | [
"test_cell"
] | [
"bindgen::mangle::generics",
"test_constant",
"test_associated_in_body",
"test_alias",
"test_display_list",
"test_asserted_cast",
"test_array",
"test_cfg",
"test_assoc_const_conflict",
"test_const_conflict",
"test_annotation",
"test_cfg_2",
"test_docstyle_doxy",
"test_constant_constexpr",
... | [
"test_expand_dep",
"test_expand",
"test_expand_default_features",
"test_expand_dep_v2",
"test_expand_features",
"test_expand_no_default_features"
] | [] |
c3442809b9e0be814918de6281469a955acfe7df | diff --git a/src/bindgen/ir/enumeration.rs b/src/bindgen/ir/enumeration.rs
--- a/src/bindgen/ir/enumeration.rs
+++ b/src/bindgen/ir/enumeration.rs
@@ -17,6 +17,7 @@ use crate::bindgen::library::Library;
use crate::bindgen::mangle;
use crate::bindgen::monomorph::Monomorphs;
use crate::bindgen::rename::{IdentifierType, RenameRule};
+use crate::bindgen::reserved;
use crate::bindgen::utilities::find_first_some;
use crate::bindgen::writer::{ListType, Source, SourceWriter};
diff --git a/src/bindgen/ir/enumeration.rs b/src/bindgen/ir/enumeration.rs
--- a/src/bindgen/ir/enumeration.rs
+++ b/src/bindgen/ir/enumeration.rs
@@ -421,8 +422,11 @@ impl Item for Enum {
}
for variant in &mut self.variants {
- if let Some((_, ref mut body)) = variant.body {
+ reserved::escape(&mut variant.export_name);
+
+ if let Some((ref mut field_name, ref mut body)) = variant.body {
body.rename_for_config(config);
+ reserved::escape(field_name);
}
}
| mozilla__cbindgen-483 | 483 | Minimal rust file would be `#[repr(C, u8)] enum FluentValue { Double(f64), String(*const nsString) }`, or something of that sort.
I'd like to help this one :)
| [
"368"
] | 0.13 | mozilla/cbindgen | 2020-03-05T05:38:30Z | diff --git a/tests/expectations/both/reserved.c b/tests/expectations/both/reserved.c
--- a/tests/expectations/both/reserved.c
+++ b/tests/expectations/both/reserved.c
@@ -30,4 +30,48 @@ typedef struct C {
};
} C;
-void root(A a, B b, C c, int32_t namespace_, float float_);
+enum E_Tag {
+ Double,
+ Float,
+};
+typedef uint8_t E_Tag;
+
+typedef struct Double_Body {
+ double _0;
+} Double_Body;
+
+typedef struct Float_Body {
+ float _0;
+} Float_Body;
+
+typedef struct E {
+ E_Tag tag;
+ union {
+ Double_Body double_;
+ Float_Body float_;
+ };
+} E;
+
+enum F_Tag {
+ double_,
+ float_,
+};
+typedef uint8_t F_Tag;
+
+typedef struct double_Body {
+ double _0;
+} double_Body;
+
+typedef struct float_Body {
+ float _0;
+} float_Body;
+
+typedef struct F {
+ F_Tag tag;
+ union {
+ double_Body double_;
+ float_Body float_;
+ };
+} F;
+
+void root(A a, B b, C c, E e, F f, int32_t namespace_, float float_);
diff --git a/tests/expectations/both/reserved.compat.c b/tests/expectations/both/reserved.compat.c
--- a/tests/expectations/both/reserved.compat.c
+++ b/tests/expectations/both/reserved.compat.c
@@ -36,11 +36,67 @@ typedef struct C {
};
} C;
+enum E_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ Double,
+ Float,
+};
+#ifndef __cplusplus
+typedef uint8_t E_Tag;
+#endif // __cplusplus
+
+typedef struct Double_Body {
+ double _0;
+} Double_Body;
+
+typedef struct Float_Body {
+ float _0;
+} Float_Body;
+
+typedef struct E {
+ E_Tag tag;
+ union {
+ Double_Body double_;
+ Float_Body float_;
+ };
+} E;
+
+enum F_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ double_,
+ float_,
+};
+#ifndef __cplusplus
+typedef uint8_t F_Tag;
+#endif // __cplusplus
+
+typedef struct double_Body {
+ double _0;
+} double_Body;
+
+typedef struct float_Body {
+ float _0;
+} float_Body;
+
+typedef struct F {
+ F_Tag tag;
+ union {
+ double_Body double_;
+ float_Body float_;
+ };
+} F;
+
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(A a, B b, C c, int32_t namespace_, float float_);
+void root(A a, B b, C c, E e, F f, int32_t namespace_, float float_);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/expectations/reserved.c b/tests/expectations/reserved.c
--- a/tests/expectations/reserved.c
+++ b/tests/expectations/reserved.c
@@ -30,4 +30,48 @@ typedef struct {
};
} C;
-void root(A a, B b, C c, int32_t namespace_, float float_);
+enum E_Tag {
+ Double,
+ Float,
+};
+typedef uint8_t E_Tag;
+
+typedef struct {
+ double _0;
+} Double_Body;
+
+typedef struct {
+ float _0;
+} Float_Body;
+
+typedef struct {
+ E_Tag tag;
+ union {
+ Double_Body double_;
+ Float_Body float_;
+ };
+} E;
+
+enum F_Tag {
+ double_,
+ float_,
+};
+typedef uint8_t F_Tag;
+
+typedef struct {
+ double _0;
+} double_Body;
+
+typedef struct {
+ float _0;
+} float_Body;
+
+typedef struct {
+ F_Tag tag;
+ union {
+ double_Body double_;
+ float_Body float_;
+ };
+} F;
+
+void root(A a, B b, C c, E e, F f, int32_t namespace_, float float_);
diff --git a/tests/expectations/reserved.compat.c b/tests/expectations/reserved.compat.c
--- a/tests/expectations/reserved.compat.c
+++ b/tests/expectations/reserved.compat.c
@@ -36,11 +36,67 @@ typedef struct {
};
} C;
+enum E_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ Double,
+ Float,
+};
+#ifndef __cplusplus
+typedef uint8_t E_Tag;
+#endif // __cplusplus
+
+typedef struct {
+ double _0;
+} Double_Body;
+
+typedef struct {
+ float _0;
+} Float_Body;
+
+typedef struct {
+ E_Tag tag;
+ union {
+ Double_Body double_;
+ Float_Body float_;
+ };
+} E;
+
+enum F_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ double_,
+ float_,
+};
+#ifndef __cplusplus
+typedef uint8_t F_Tag;
+#endif // __cplusplus
+
+typedef struct {
+ double _0;
+} double_Body;
+
+typedef struct {
+ float _0;
+} float_Body;
+
+typedef struct {
+ F_Tag tag;
+ union {
+ double_Body double_;
+ float_Body float_;
+ };
+} F;
+
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(A a, B b, C c, int32_t namespace_, float float_);
+void root(A a, B b, C c, E e, F f, int32_t namespace_, float float_);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/expectations/reserved.cpp b/tests/expectations/reserved.cpp
--- a/tests/expectations/reserved.cpp
+++ b/tests/expectations/reserved.cpp
@@ -29,8 +29,50 @@ struct C {
};
};
+struct E {
+ enum class Tag : uint8_t {
+ Double,
+ Float,
+ };
+
+ struct Double_Body {
+ double _0;
+ };
+
+ struct Float_Body {
+ float _0;
+ };
+
+ Tag tag;
+ union {
+ Double_Body double_;
+ Float_Body float_;
+ };
+};
+
+struct F {
+ enum class Tag : uint8_t {
+ double_,
+ float_,
+ };
+
+ struct double_Body {
+ double _0;
+ };
+
+ struct float_Body {
+ float _0;
+ };
+
+ Tag tag;
+ union {
+ double_Body double_;
+ float_Body float_;
+ };
+};
+
extern "C" {
-void root(A a, B b, C c, int32_t namespace_, float float_);
+void root(A a, B b, C c, E e, F f, int32_t namespace_, float float_);
} // extern "C"
diff --git a/tests/expectations/tag/reserved.c b/tests/expectations/tag/reserved.c
--- a/tests/expectations/tag/reserved.c
+++ b/tests/expectations/tag/reserved.c
@@ -30,4 +30,54 @@ struct C {
};
};
-void root(struct A a, struct B b, struct C c, int32_t namespace_, float float_);
+enum E_Tag {
+ Double,
+ Float,
+};
+typedef uint8_t E_Tag;
+
+struct Double_Body {
+ double _0;
+};
+
+struct Float_Body {
+ float _0;
+};
+
+struct E {
+ E_Tag tag;
+ union {
+ struct Double_Body double_;
+ struct Float_Body float_;
+ };
+};
+
+enum F_Tag {
+ double_,
+ float_,
+};
+typedef uint8_t F_Tag;
+
+struct double_Body {
+ double _0;
+};
+
+struct float_Body {
+ float _0;
+};
+
+struct F {
+ F_Tag tag;
+ union {
+ struct double_Body double_;
+ struct float_Body float_;
+ };
+};
+
+void root(struct A a,
+ struct B b,
+ struct C c,
+ struct E e,
+ struct F f,
+ int32_t namespace_,
+ float float_);
diff --git a/tests/expectations/tag/reserved.compat.c b/tests/expectations/tag/reserved.compat.c
--- a/tests/expectations/tag/reserved.compat.c
+++ b/tests/expectations/tag/reserved.compat.c
@@ -36,11 +36,73 @@ struct C {
};
};
+enum E_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ Double,
+ Float,
+};
+#ifndef __cplusplus
+typedef uint8_t E_Tag;
+#endif // __cplusplus
+
+struct Double_Body {
+ double _0;
+};
+
+struct Float_Body {
+ float _0;
+};
+
+struct E {
+ E_Tag tag;
+ union {
+ struct Double_Body double_;
+ struct Float_Body float_;
+ };
+};
+
+enum F_Tag
+#ifdef __cplusplus
+ : uint8_t
+#endif // __cplusplus
+ {
+ double_,
+ float_,
+};
+#ifndef __cplusplus
+typedef uint8_t F_Tag;
+#endif // __cplusplus
+
+struct double_Body {
+ double _0;
+};
+
+struct float_Body {
+ float _0;
+};
+
+struct F {
+ F_Tag tag;
+ union {
+ struct double_Body double_;
+ struct float_Body float_;
+ };
+};
+
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(struct A a, struct B b, struct C c, int32_t namespace_, float float_);
+void root(struct A a,
+ struct B b,
+ struct C c,
+ struct E e,
+ struct F f,
+ int32_t namespace_,
+ float float_);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/rust/reserved.rs b/tests/rust/reserved.rs
--- a/tests/rust/reserved.rs
+++ b/tests/rust/reserved.rs
@@ -13,11 +13,25 @@ enum C {
D { namespace: i32, float: f32 },
}
+#[repr(C, u8)]
+enum E {
+ Double(f64),
+ Float(f32),
+}
+
+#[repr(C, u8)]
+enum F {
+ double(f64),
+ float(f32),
+}
+
#[no_mangle]
pub extern "C" fn root(
a: A,
b: B,
c: C,
+ e: E,
+ f: F,
namespace: i32,
float: f32,
) { }
| Escape `Double`
```irc
> @emilio> gandalf: ah, `double` is a C++ keyword, use `Double_` and file a cbindgen issue to escape that?
```
| 6fd245096dcd5c50c1065b4bd6ce62a09df0b39b | [
"test_reserved"
] | [
"bindgen::mangle::generics",
"test_custom_header",
"test_const_transparent",
"test_documentation",
"test_char",
"test_array",
"test_const_conflict",
"test_associated_in_body",
"test_docstyle_doxy",
"test_asserted_cast",
"test_docstyle_c99",
"test_documentation_attr",
"test_display_list",
"... | [
"test_expand",
"test_expand_default_features",
"test_expand_dep_v2",
"test_expand_dep",
"test_expand_features",
"test_expand_no_default_features"
] | [] |
dfa6e5f9824aac416d267420f8730225011d5c8f | diff --git a/src/bindgen/ir/global.rs b/src/bindgen/ir/global.rs
--- a/src/bindgen/ir/global.rs
+++ b/src/bindgen/ir/global.rs
@@ -6,6 +6,7 @@ use std::io::Write;
use syn;
+use crate::bindgen::cdecl;
use crate::bindgen::config::Config;
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
diff --git a/src/bindgen/ir/global.rs b/src/bindgen/ir/global.rs
--- a/src/bindgen/ir/global.rs
+++ b/src/bindgen/ir/global.rs
@@ -112,7 +113,7 @@ impl Source for Static {
} else if !self.mutable {
out.write("const ");
}
- self.ty.write(config, out);
- write!(out, " {};", self.export_name());
+ cdecl::write_field(out, &self.ty, &self.export_name, config);
+ out.write(";");
}
}
| mozilla__cbindgen-479 | 479 | [
"476"
] | 0.13 | mozilla/cbindgen | 2020-02-25T05:38:43Z | diff --git /dev/null b/tests/expectations/both/global_variable.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/global_variable.c
@@ -0,0 +1,8 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
diff --git /dev/null b/tests/expectations/both/global_variable.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/global_variable.compat.c
@@ -0,0 +1,16 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/global_variable.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/global_variable.c
@@ -0,0 +1,8 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
diff --git /dev/null b/tests/expectations/global_variable.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/global_variable.compat.c
@@ -0,0 +1,16 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/global_variable.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/global_variable.cpp
@@ -0,0 +1,12 @@
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+extern "C" {
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
+
+} // extern "C"
diff --git /dev/null b/tests/expectations/tag/global_variable.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/global_variable.c
@@ -0,0 +1,8 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
diff --git /dev/null b/tests/expectations/tag/global_variable.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/global_variable.compat.c
@@ -0,0 +1,16 @@
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+extern const char CONST_GLOBAL_ARRAY[128];
+
+extern char MUT_GLOBAL_ARRAY[128];
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/global_variable.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/global_variable.rs
@@ -0,0 +1,5 @@
+#[no_mangle]
+pub static mut MUT_GLOBAL_ARRAY: [c_char; 128] = [0; 128];
+
+#[no_mangle]
+pub static CONST_GLOBAL_ARRAY: [c_char; 128] = [0; 128];
| Wrong output for static arrays
```rust
#[no_mangle]
pub static mut MCRT_ERROR_TEXT: [c_char; 128] = [0; 128];
```
outputs this
```c
extern char[128] MCRT_ERROR_TEXT;
```
when it should be this:
```c
extern char MCRT_ERROR_TEXT[128];
```
| 6fd245096dcd5c50c1065b4bd6ce62a09df0b39b | [
"test_global_variable"
] | [
"bindgen::mangle::generics",
"test_cfg",
"test_custom_header",
"test_euclid",
"test_alias",
"test_constant",
"test_documentation",
"test_docstyle_auto",
"test_char",
"test_cdecl",
"test_assoc_constant",
"test_enum",
"test_destructor_and_copy_ctor",
"test_asserted_cast",
"test_const_confl... | [
"test_expand",
"test_expand_default_features",
"test_expand_dep",
"test_expand_dep_v2",
"test_expand_features",
"test_expand_no_default_features"
] | [] | |
6b4181540c146fff75efd500bfb75a2d60403b4c | diff --git a/src/bindgen/ir/generic_path.rs b/src/bindgen/ir/generic_path.rs
--- a/src/bindgen/ir/generic_path.rs
+++ b/src/bindgen/ir/generic_path.rs
@@ -27,18 +27,13 @@ impl GenericParams {
.collect(),
)
}
-}
-
-impl Deref for GenericParams {
- type Target = [Path];
-
- fn deref(&self) -> &[Path] {
- &self.0
- }
-}
-impl Source for GenericParams {
- fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
+ fn write_internal<F: Write>(
+ &self,
+ config: &Config,
+ out: &mut SourceWriter<F>,
+ with_default: bool,
+ ) {
if !self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
diff --git a/src/bindgen/ir/generic_path.rs b/src/bindgen/ir/generic_path.rs
--- a/src/bindgen/ir/generic_path.rs
+++ b/src/bindgen/ir/generic_path.rs
@@ -46,11 +41,32 @@ impl Source for GenericParams {
out.write(", ");
}
write!(out, "typename {}", item);
+ if with_default {
+ write!(out, " = void");
+ }
}
out.write(">");
out.new_line();
}
}
+
+ pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
+ self.write_internal(config, out, true);
+ }
+}
+
+impl Deref for GenericParams {
+ type Target = [Path];
+
+ fn deref(&self) -> &[Path] {
+ &self.0
+ }
+}
+
+impl Source for GenericParams {
+ fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
+ self.write_internal(config, out, false);
+ }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
diff --git a/src/bindgen/ir/opaque.rs b/src/bindgen/ir/opaque.rs
--- a/src/bindgen/ir/opaque.rs
+++ b/src/bindgen/ir/opaque.rs
@@ -105,12 +105,16 @@ impl Item for OpaqueItem {
out: &mut Monomorphs,
) {
assert!(
- self.generic_params.len() > 0,
+ !self.generic_params.is_empty(),
"{} is not generic",
self.path
);
+
+ // We can be instantiated with less generic params because of default
+ // template parameters, or because of empty types that we remove during
+ // parsing (`()`).
assert!(
- self.generic_params.len() == generic_values.len(),
+ self.generic_params.len() >= generic_values.len(),
"{} has {} params but is being instantiated with {} values",
self.path,
self.generic_params.len(),
diff --git a/src/bindgen/ir/opaque.rs b/src/bindgen/ir/opaque.rs
--- a/src/bindgen/ir/opaque.rs
+++ b/src/bindgen/ir/opaque.rs
@@ -137,7 +141,7 @@ impl Source for OpaqueItem {
self.documentation.write(config, out);
- self.generic_params.write(config, out);
+ self.generic_params.write_with_default(config, out);
if config.style.generate_typedef() && config.language == Language::C {
write!(
diff --git a/src/bindgen/parser.rs b/src/bindgen/parser.rs
--- a/src/bindgen/parser.rs
+++ b/src/bindgen/parser.rs
@@ -391,7 +391,7 @@ impl Parse {
add_opaque("Option", vec!["T"]);
add_opaque("NonNull", vec!["T"]);
add_opaque("Vec", vec!["T"]);
- add_opaque("HashMap", vec!["K", "V"]);
+ add_opaque("HashMap", vec!["K", "V", "Hasher"]);
add_opaque("BTreeMap", vec!["K", "V"]);
add_opaque("HashSet", vec!["T"]);
add_opaque("BTreeSet", vec!["T"]);
| mozilla__cbindgen-563 | 563 | Heh, was just about to post a near-identical snippet to 206. CC'ing myself, mostly, but note that it doesn't have to be Result, explicitly. The following also breaks (but *not* without the `()` type parameter):
```
#[repr(C)]
pub struct CResultTempl<O, E> {
pub result_good: bool,
pub result: *const O,
pub err: *const E,
}
#[no_mangle]
pub type CResultNoneAPIError = CResultTempl<(), crate::util::errors::APIError>;
#[no_mangle]
pub static CResultNoneAPIError_free: extern "C" fn(CResultNoneAPIError) = CResultTempl_free::<(), crate::util::errors::APIError>;
```
Yes, this is because cbindgen removes zero-sized types, and in this case gets confused.
Anyone have a workaround for this issue?
Depending on your code you can `cbindgen:ignore` the relevant bits.
I tried that over the offending line and it didn't work:
```rist
// cbindgen:ignore
type NoResult<(), Foo>
```
Needs to be a doc comment, this should work: `/// cbindgen:ignore`
(This is because `syn` ignores the other comments so we can't parse them)
I tried with doc comment too, same result. Here is verbatim what it looks like:
```rust
/// cbindgen:ignore
type NoResult = Result<(), DigestError>;
```
Huh? Running:
```
cbindgen --lang c t.rs
```
With the following file:
```rust
type NoResult = Result<(), DigestError>;
```
panics, though running it on:
```rust
/// cbindgen:ignore
type NoResult = Result<(), DigestError>;
```
doesn't. So there's probably something else going on in that crate. What am I missing?
Thanks for the replies @emilio.
The offending crate is being pulled in via `PaseConfig::include` and for me, the doc comment doesn't avoid the panic. I did see though that after a successful build (remove the `NoResult`) and adding it back that the build succeeded but only because of some kind of dep/dirty issue. If I did a clean build the panic would show up again. Not sure what's going on, it does seem like this should be straight forward.
For now, I've worked around it by removing the nicety `NoResult` type. | [
"527"
] | 0.14 | mozilla/cbindgen | 2020-08-14T20:16:40Z | diff --git /dev/null b/tests/expectations/both/opaque.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/opaque.c
@@ -0,0 +1,28 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+typedef struct Result_Foo Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef Result_Foo Bar;
+
+void root(const Foo *a, const Bar *b);
diff --git /dev/null b/tests/expectations/both/opaque.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/both/opaque.compat.c
@@ -0,0 +1,36 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+typedef struct Result_Foo Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef Result_Foo Bar;
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const Bar *b);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git a/tests/expectations/cell.cpp b/tests/expectations/cell.cpp
--- a/tests/expectations/cell.cpp
+++ b/tests/expectations/cell.cpp
@@ -3,10 +3,10 @@
#include <cstdlib>
#include <new>
-template<typename T>
+template<typename T = void>
struct NotReprC;
-template<typename T>
+template<typename T = void>
struct RefCell;
using Foo = NotReprC<RefCell<int32_t>>;
diff --git a/tests/expectations/monomorph-1.cpp b/tests/expectations/monomorph-1.cpp
--- a/tests/expectations/monomorph-1.cpp
+++ b/tests/expectations/monomorph-1.cpp
@@ -3,7 +3,7 @@
#include <cstdlib>
#include <new>
-template<typename T>
+template<typename T = void>
struct Bar;
template<typename T>
diff --git a/tests/expectations/monomorph-3.cpp b/tests/expectations/monomorph-3.cpp
--- a/tests/expectations/monomorph-3.cpp
+++ b/tests/expectations/monomorph-3.cpp
@@ -3,7 +3,7 @@
#include <cstdlib>
#include <new>
-template<typename T>
+template<typename T = void>
struct Bar;
template<typename T>
diff --git /dev/null b/tests/expectations/opaque.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/opaque.c
@@ -0,0 +1,28 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+typedef struct Result_Foo Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef Result_Foo Bar;
+
+void root(const Foo *a, const Bar *b);
diff --git /dev/null b/tests/expectations/opaque.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/opaque.compat.c
@@ -0,0 +1,36 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+typedef struct Result_Foo Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef Result_Foo Bar;
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const Bar *b);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/expectations/opaque.cpp
new file mode 100644
--- /dev/null
+++ b/tests/expectations/opaque.cpp
@@ -0,0 +1,33 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <cstdarg>
+#include <cstdint>
+#include <cstdlib>
+#include <new>
+
+template<typename K = void, typename V = void, typename Hasher = void>
+struct HashMap;
+
+template<typename T = void, typename E = void>
+struct Result;
+
+/// Fast hash map used internally.
+template<typename K, typename V>
+using FastHashMap = HashMap<K, V, BuildHasherDefault<DefaultHasher>>;
+
+using Foo = FastHashMap<int32_t, int32_t>;
+
+using Bar = Result<Foo>;
+
+extern "C" {
+
+void root(const Foo *a, const Bar *b);
+
+} // extern "C"
diff --git a/tests/expectations/std_lib.cpp b/tests/expectations/std_lib.cpp
--- a/tests/expectations/std_lib.cpp
+++ b/tests/expectations/std_lib.cpp
@@ -3,15 +3,15 @@
#include <cstdlib>
#include <new>
-template<typename T>
+template<typename T = void>
struct Option;
-template<typename T, typename E>
+template<typename T = void, typename E = void>
struct Result;
struct String;
-template<typename T>
+template<typename T = void>
struct Vec;
extern "C" {
diff --git a/tests/expectations/swift_name.cpp b/tests/expectations/swift_name.cpp
--- a/tests/expectations/swift_name.cpp
+++ b/tests/expectations/swift_name.cpp
@@ -5,7 +5,7 @@
#include <cstdlib>
#include <new>
-template<typename T>
+template<typename T = void>
struct Box;
struct Opaque;
diff --git /dev/null b/tests/expectations/tag/opaque.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/opaque.c
@@ -0,0 +1,28 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+struct Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef struct Result_Foo Bar;
+
+void root(const Foo *a, const Bar *b);
diff --git /dev/null b/tests/expectations/tag/opaque.compat.c
new file mode 100644
--- /dev/null
+++ b/tests/expectations/tag/opaque.compat.c
@@ -0,0 +1,36 @@
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+
+
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher;
+
+struct Result_Foo;
+
+/**
+ * Fast hash map used internally.
+ */
+typedef struct HashMap_i32__i32__BuildHasherDefault_DefaultHasher FastHashMap_i32__i32;
+
+typedef FastHashMap_i32__i32 Foo;
+
+typedef struct Result_Foo Bar;
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+void root(const Foo *a, const Bar *b);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
diff --git /dev/null b/tests/rust/opaque.rs
new file mode 100644
--- /dev/null
+++ b/tests/rust/opaque.rs
@@ -0,0 +1,10 @@
+/// Fast hash map used internally.
+type FastHashMap<K, V> =
+ std::collections::HashMap<K, V, std::hash::BuildHasherDefault<std::collections::hash_map::DefaultHasher>>;
+
+pub type Foo = FastHashMap<i32, i32>;
+
+pub type Bar = Result<Foo, ()>;
+
+#[no_mangle]
+pub extern "C" fn root(a: &Foo, b: &Bar) {}
diff --git /dev/null b/tests/rust/opaque.toml
new file mode 100644
--- /dev/null
+++ b/tests/rust/opaque.toml
@@ -0,0 +1,9 @@
+header = """
+#ifdef __cplusplus
+// These could be added as opaque types I guess.
+template <typename T>
+struct BuildHasherDefault;
+
+struct DefaultHasher;
+#endif
+"""
| panic: Result has 2 params but is being instantiated with 1 values
cbdingen version: `v0.14.2`
To reproduce the error, run `cbindgen --lang c --output test.h test.rs`, with the source of `test.rs` being:
```rust
use std::fmt;
// Result<(), T> seems to trip up cbindgen, here T=fmt::Error
// as it was how I ran into it.
type FmtResult = Result<(), fmt::Error>;
fn main() {
println!("cbindgen doesn't like Result<(), T>");
}
```
Should produce the following error+backtrace with `RUST_BACKTRACE=1`:
```
thread 'main' panicked at 'Result has 2 params but is being instantiated with 1 values', /home/sanoj/.local/share/cargo/registry/src/github.com-1ecc6299db9ec823/cbindgen-0.14.2/src/bindgen/ir/opaque.rs:112:9
stack backtrace:
0: backtrace::backtrace::libunwind::trace
at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/libunwind.rs:88
1: backtrace::backtrace::trace_unsynchronized
at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/mod.rs:66
2: std::sys_common::backtrace::_print_fmt
at src/libstd/sys_common/backtrace.rs:84
3: <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt
at src/libstd/sys_common/backtrace.rs:61
4: core::fmt::write
at src/libcore/fmt/mod.rs:1025
5: std::io::Write::write_fmt
at src/libstd/io/mod.rs:1426
6: std::sys_common::backtrace::_print
at src/libstd/sys_common/backtrace.rs:65
7: std::sys_common::backtrace::print
at src/libstd/sys_common/backtrace.rs:50
8: std::panicking::default_hook::{{closure}}
at src/libstd/panicking.rs:193
9: std::panicking::default_hook
at src/libstd/panicking.rs:210
10: std::panicking::rust_panic_with_hook
at src/libstd/panicking.rs:475
11: rust_begin_unwind
at src/libstd/panicking.rs:375
12: std::panicking::begin_panic_fmt
at src/libstd/panicking.rs:326
13: <cbindgen::bindgen::ir::opaque::OpaqueItem as cbindgen::bindgen::ir::item::Item>::instantiate_monomorph
14: cbindgen::bindgen::ir::ty::Type::add_monomorphs
15: cbindgen::bindgen::library::Library::generate
16: cbindgen::bindgen::builder::Builder::generate
17: cbindgen::main
18: std::rt::lang_start::{{closure}}
19: std::rt::lang_start_internal::{{closure}}
at src/libstd/rt.rs:52
20: std::panicking::try::do_call
at src/libstd/panicking.rs:292
21: __rust_maybe_catch_panic
at src/libpanic_unwind/lib.rs:78
22: std::panicking::try
at src/libstd/panicking.rs:270
23: std::panic::catch_unwind
at src/libstd/panic.rs:394
24: std::rt::lang_start_internal
at src/libstd/rt.rs:51
25: main
26: __libc_start_main
27: _start
```
The error does not occur with `--lang c++`.
Also reported here: https://github.com/eqrion/cbindgen/issues/206, but without a snippet to reproduce it.
| 6b4181540c146fff75efd500bfb75a2d60403b4c | [
"test_opaque"
] | [
"bindgen::mangle::generics",
"test_custom_header",
"test_cfg",
"test_constant_constexpr",
"test_cell",
"test_array",
"test_cdecl",
"test_const_transparent",
"test_constant_big",
"test_destructor_and_copy_ctor",
"test_docstyle_auto",
"test_assoc_const_conflict",
"test_docstyle_doxy",
"test_... | [
"test_expand_default_features",
"test_expand",
"test_expand_dep",
"test_expand_features",
"test_expand_dep_v2",
"test_expand_no_default_features"
] | [] |
6ba31b49f445290a4ac1d3141f2a783306b23a88 | diff --git a/src/bindgen/bitflags.rs b/src/bindgen/bitflags.rs
--- a/src/bindgen/bitflags.rs
+++ b/src/bindgen/bitflags.rs
@@ -43,7 +43,7 @@ impl Bitflags {
}
};
- let consts = flags.expand(name);
+ let consts = flags.expand(name, repr);
let impl_ = parse_quote! {
impl #name {
#consts
diff --git a/src/bindgen/bitflags.rs b/src/bindgen/bitflags.rs
--- a/src/bindgen/bitflags.rs
+++ b/src/bindgen/bitflags.rs
@@ -81,7 +81,7 @@ struct Flag {
}
impl Flag {
- fn expand(&self, struct_name: &syn::Ident) -> TokenStream {
+ fn expand(&self, struct_name: &syn::Ident, repr: &syn::Type) -> TokenStream {
let Flag {
ref attrs,
ref name,
diff --git a/src/bindgen/bitflags.rs b/src/bindgen/bitflags.rs
--- a/src/bindgen/bitflags.rs
+++ b/src/bindgen/bitflags.rs
@@ -90,7 +90,7 @@ impl Flag {
} = *self;
quote! {
#(#attrs)*
- pub const #name : #struct_name = #struct_name { bits: #value };
+ pub const #name : #struct_name = #struct_name { bits: (#value) as #repr };
}
}
}
diff --git a/src/bindgen/bitflags.rs b/src/bindgen/bitflags.rs
--- a/src/bindgen/bitflags.rs
+++ b/src/bindgen/bitflags.rs
@@ -124,10 +124,10 @@ impl Parse for Flags {
}
impl Flags {
- fn expand(&self, struct_name: &syn::Ident) -> TokenStream {
+ fn expand(&self, struct_name: &syn::Ident, repr: &syn::Type) -> TokenStream {
let mut ts = quote! {};
for flag in &self.0 {
- ts.extend(flag.expand(struct_name));
+ ts.extend(flag.expand(struct_name, repr));
}
ts
}
| mozilla__cbindgen-556 | 556 | [
"555"
] | 0.14 | mozilla/cbindgen | 2020-07-30T14:25:00Z | diff --git a/tests/expectations/associated_in_body.c b/tests/expectations/associated_in_body.c
--- a/tests/expectations/associated_in_body.c
+++ b/tests/expectations/associated_in_body.c
@@ -14,22 +14,22 @@ typedef struct {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
void root(StyleAlignFlags flags);
diff --git a/tests/expectations/associated_in_body.compat.c b/tests/expectations/associated_in_body.compat.c
--- a/tests/expectations/associated_in_body.compat.c
+++ b/tests/expectations/associated_in_body.compat.c
@@ -14,23 +14,23 @@ typedef struct {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
#ifdef __cplusplus
extern "C" {
diff --git a/tests/expectations/associated_in_body.cpp b/tests/expectations/associated_in_body.cpp
--- a/tests/expectations/associated_in_body.cpp
+++ b/tests/expectations/associated_in_body.cpp
@@ -43,15 +43,15 @@ struct StyleAlignFlags {
static const StyleAlignFlags FLEX_START;
};
/// 'auto'
-inline const StyleAlignFlags StyleAlignFlags::AUTO = StyleAlignFlags{ /* .bits = */ 0 };
+inline const StyleAlignFlags StyleAlignFlags::AUTO = StyleAlignFlags{ /* .bits = */ (uint8_t)0 };
/// 'normal'
-inline const StyleAlignFlags StyleAlignFlags::NORMAL = StyleAlignFlags{ /* .bits = */ 1 };
+inline const StyleAlignFlags StyleAlignFlags::NORMAL = StyleAlignFlags{ /* .bits = */ (uint8_t)1 };
/// 'start'
-inline const StyleAlignFlags StyleAlignFlags::START = StyleAlignFlags{ /* .bits = */ (1 << 1) };
+inline const StyleAlignFlags StyleAlignFlags::START = StyleAlignFlags{ /* .bits = */ (uint8_t)(1 << 1) };
/// 'end'
-inline const StyleAlignFlags StyleAlignFlags::END = StyleAlignFlags{ /* .bits = */ (1 << 2) };
+inline const StyleAlignFlags StyleAlignFlags::END = StyleAlignFlags{ /* .bits = */ (uint8_t)(1 << 2) };
/// 'flex-start'
-inline const StyleAlignFlags StyleAlignFlags::FLEX_START = StyleAlignFlags{ /* .bits = */ (1 << 3) };
+inline const StyleAlignFlags StyleAlignFlags::FLEX_START = StyleAlignFlags{ /* .bits = */ (uint8_t)(1 << 3) };
extern "C" {
diff --git a/tests/expectations/bitflags.c b/tests/expectations/bitflags.c
--- a/tests/expectations/bitflags.c
+++ b/tests/expectations/bitflags.c
@@ -14,22 +14,30 @@ typedef struct {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
-void root(AlignFlags flags);
+typedef struct {
+ uint32_t bits;
+} DebugFlags;
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
+
+void root(AlignFlags flags, DebugFlags bigger_flags);
diff --git a/tests/expectations/bitflags.compat.c b/tests/expectations/bitflags.compat.c
--- a/tests/expectations/bitflags.compat.c
+++ b/tests/expectations/bitflags.compat.c
@@ -14,29 +14,37 @@ typedef struct {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
+
+typedef struct {
+ uint32_t bits;
+} DebugFlags;
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(AlignFlags flags);
+void root(AlignFlags flags, DebugFlags bigger_flags);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/expectations/bitflags.cpp b/tests/expectations/bitflags.cpp
--- a/tests/expectations/bitflags.cpp
+++ b/tests/expectations/bitflags.cpp
@@ -38,18 +38,52 @@ struct AlignFlags {
}
};
/// 'auto'
-static const AlignFlags AlignFlags_AUTO = AlignFlags{ /* .bits = */ 0 };
+static const AlignFlags AlignFlags_AUTO = AlignFlags{ /* .bits = */ (uint8_t)0 };
/// 'normal'
-static const AlignFlags AlignFlags_NORMAL = AlignFlags{ /* .bits = */ 1 };
+static const AlignFlags AlignFlags_NORMAL = AlignFlags{ /* .bits = */ (uint8_t)1 };
/// 'start'
-static const AlignFlags AlignFlags_START = AlignFlags{ /* .bits = */ (1 << 1) };
+static const AlignFlags AlignFlags_START = AlignFlags{ /* .bits = */ (uint8_t)(1 << 1) };
/// 'end'
-static const AlignFlags AlignFlags_END = AlignFlags{ /* .bits = */ (1 << 2) };
+static const AlignFlags AlignFlags_END = AlignFlags{ /* .bits = */ (uint8_t)(1 << 2) };
/// 'flex-start'
-static const AlignFlags AlignFlags_FLEX_START = AlignFlags{ /* .bits = */ (1 << 3) };
+static const AlignFlags AlignFlags_FLEX_START = AlignFlags{ /* .bits = */ (uint8_t)(1 << 3) };
+
+struct DebugFlags {
+ uint32_t bits;
+
+ explicit operator bool() const {
+ return !!bits;
+ }
+ DebugFlags operator~() const {
+ return {static_cast<decltype(bits)>(~bits)};
+ }
+ DebugFlags operator|(const DebugFlags& other) const {
+ return {static_cast<decltype(bits)>(this->bits | other.bits)};
+ }
+ DebugFlags& operator|=(const DebugFlags& other) {
+ *this = (*this | other);
+ return *this;
+ }
+ DebugFlags operator&(const DebugFlags& other) const {
+ return {static_cast<decltype(bits)>(this->bits & other.bits)};
+ }
+ DebugFlags& operator&=(const DebugFlags& other) {
+ *this = (*this & other);
+ return *this;
+ }
+ DebugFlags operator^(const DebugFlags& other) const {
+ return {static_cast<decltype(bits)>(this->bits ^ other.bits)};
+ }
+ DebugFlags& operator^=(const DebugFlags& other) {
+ *this = (*this ^ other);
+ return *this;
+ }
+};
+/// Flag with the topmost bit set of the u32
+static const DebugFlags DebugFlags_BIGGEST_ALLOWED = DebugFlags{ /* .bits = */ (uint32_t)(1 << 31) };
extern "C" {
-void root(AlignFlags flags);
+void root(AlignFlags flags, DebugFlags bigger_flags);
} // extern "C"
diff --git a/tests/expectations/both/associated_in_body.c b/tests/expectations/both/associated_in_body.c
--- a/tests/expectations/both/associated_in_body.c
+++ b/tests/expectations/both/associated_in_body.c
@@ -14,22 +14,22 @@ typedef struct StyleAlignFlags {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
void root(StyleAlignFlags flags);
diff --git a/tests/expectations/both/associated_in_body.compat.c b/tests/expectations/both/associated_in_body.compat.c
--- a/tests/expectations/both/associated_in_body.compat.c
+++ b/tests/expectations/both/associated_in_body.compat.c
@@ -14,23 +14,23 @@ typedef struct StyleAlignFlags {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
#ifdef __cplusplus
extern "C" {
diff --git a/tests/expectations/both/bitflags.c b/tests/expectations/both/bitflags.c
--- a/tests/expectations/both/bitflags.c
+++ b/tests/expectations/both/bitflags.c
@@ -14,22 +14,30 @@ typedef struct AlignFlags {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
-void root(AlignFlags flags);
+typedef struct DebugFlags {
+ uint32_t bits;
+} DebugFlags;
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
+
+void root(AlignFlags flags, DebugFlags bigger_flags);
diff --git a/tests/expectations/both/bitflags.compat.c b/tests/expectations/both/bitflags.compat.c
--- a/tests/expectations/both/bitflags.compat.c
+++ b/tests/expectations/both/bitflags.compat.c
@@ -14,29 +14,37 @@ typedef struct AlignFlags {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
+
+typedef struct DebugFlags {
+ uint32_t bits;
+} DebugFlags;
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(AlignFlags flags);
+void root(AlignFlags flags, DebugFlags bigger_flags);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/expectations/tag/associated_in_body.c b/tests/expectations/tag/associated_in_body.c
--- a/tests/expectations/tag/associated_in_body.c
+++ b/tests/expectations/tag/associated_in_body.c
@@ -14,22 +14,22 @@ struct StyleAlignFlags {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
void root(struct StyleAlignFlags flags);
diff --git a/tests/expectations/tag/associated_in_body.compat.c b/tests/expectations/tag/associated_in_body.compat.c
--- a/tests/expectations/tag/associated_in_body.compat.c
+++ b/tests/expectations/tag/associated_in_body.compat.c
@@ -14,23 +14,23 @@ struct StyleAlignFlags {
/**
* 'auto'
*/
-#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = 0 }
+#define StyleAlignFlags_AUTO (StyleAlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = 1 }
+#define StyleAlignFlags_NORMAL (StyleAlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (1 << 1) }
+#define StyleAlignFlags_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (1 << 2) }
+#define StyleAlignFlags_END (StyleAlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (1 << 3) }
+#define StyleAlignFlags_FLEX_START (StyleAlignFlags){ .bits = (uint8_t)(1 << 3) }
#ifdef __cplusplus
extern "C" {
diff --git a/tests/expectations/tag/bitflags.c b/tests/expectations/tag/bitflags.c
--- a/tests/expectations/tag/bitflags.c
+++ b/tests/expectations/tag/bitflags.c
@@ -14,22 +14,30 @@ struct AlignFlags {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
-void root(struct AlignFlags flags);
+struct DebugFlags {
+ uint32_t bits;
+};
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
+
+void root(struct AlignFlags flags, struct DebugFlags bigger_flags);
diff --git a/tests/expectations/tag/bitflags.compat.c b/tests/expectations/tag/bitflags.compat.c
--- a/tests/expectations/tag/bitflags.compat.c
+++ b/tests/expectations/tag/bitflags.compat.c
@@ -14,29 +14,37 @@ struct AlignFlags {
/**
* 'auto'
*/
-#define AlignFlags_AUTO (AlignFlags){ .bits = 0 }
+#define AlignFlags_AUTO (AlignFlags){ .bits = (uint8_t)0 }
/**
* 'normal'
*/
-#define AlignFlags_NORMAL (AlignFlags){ .bits = 1 }
+#define AlignFlags_NORMAL (AlignFlags){ .bits = (uint8_t)1 }
/**
* 'start'
*/
-#define AlignFlags_START (AlignFlags){ .bits = (1 << 1) }
+#define AlignFlags_START (AlignFlags){ .bits = (uint8_t)(1 << 1) }
/**
* 'end'
*/
-#define AlignFlags_END (AlignFlags){ .bits = (1 << 2) }
+#define AlignFlags_END (AlignFlags){ .bits = (uint8_t)(1 << 2) }
/**
* 'flex-start'
*/
-#define AlignFlags_FLEX_START (AlignFlags){ .bits = (1 << 3) }
+#define AlignFlags_FLEX_START (AlignFlags){ .bits = (uint8_t)(1 << 3) }
+
+struct DebugFlags {
+ uint32_t bits;
+};
+/**
+ * Flag with the topmost bit set of the u32
+ */
+#define DebugFlags_BIGGEST_ALLOWED (DebugFlags){ .bits = (uint32_t)(1 << 31) }
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
-void root(struct AlignFlags flags);
+void root(struct AlignFlags flags, struct DebugFlags bigger_flags);
#ifdef __cplusplus
} // extern "C"
diff --git a/tests/rust/bitflags.rs b/tests/rust/bitflags.rs
--- a/tests/rust/bitflags.rs
+++ b/tests/rust/bitflags.rs
@@ -18,5 +18,13 @@ bitflags! {
}
}
+bitflags! {
+ #[repr(C)]
+ pub struct DebugFlags: u32 {
+ /// Flag with the topmost bit set of the u32
+ const BIGGEST_ALLOWED = 1 << 31;
+ }
+}
+
#[no_mangle]
-pub extern "C" fn root(flags: AlignFlags) {}
+pub extern "C" fn root(flags: AlignFlags, bigger_flags: DebugFlags) {}
| Running cbindgen on a u32 bitflag with a 1<<31 entry produces C++ code that doesn't compile
Assuming you have a setup where `cargo +nightly test` passes everything, apply this patch:
```
diff --git a/tests/rust/bitflags.rs b/tests/rust/bitflags.rs
index 6c3fe4e..017104a 100644
--- a/tests/rust/bitflags.rs
+++ b/tests/rust/bitflags.rs
@@ -13,10 +13,18 @@ bitflags! {
const START = 1 << 1;
/// 'end'
const END = 1 << 2;
/// 'flex-start'
const FLEX_START = 1 << 3;
}
}
+bitflags! {
+ #[repr(C)]
+ pub struct DebugFlags: u32 {
+ /// Flag with the topmost bit set of the u32
+ const BIGGEST_ALLOWED = 1 << 31;
+ }
+}
+
#[no_mangle]
-pub extern "C" fn root(flags: AlignFlags) {}
+pub extern "C" fn root(flags: AlignFlags, bigger_flags: DebugFlags) {}
```
and run the tests. For me there's this failure:
```
Running: "/home/kats/.mozbuild/clang/bin/clang++" "-D" "DEFINED" "-c" "/home/kats/zspace/cbindgen/tests/expectations/bitflags.cpp" "-o" "/home/kats/tmp/cbindgen-test-outputWsIxRN/bitflags.o" "-I" "/home/kats/zspace/cbindgen/tests" "-Wall" "-Werror" "-Wno-attributes" "-std=c++17" "-Wno-deprecated" "-Wno-unused-const-variable" "-Wno-return-type-c-linkage"
thread 'test_bitflags' panicked at 'Output failed to compile: Output { status: ExitStatus(ExitStatus(256)), stdout: "", stderr: "/home/kats/zspace/cbindgen/tests/expectations/bitflags.cpp:83:80: error: constant expression evaluates to -2147483648 which cannot be narrowed to type \'uint32_t\' (aka \'unsigned int\') [-Wc++11-narrowing]\nstatic const DebugFlags DebugFlags_BIGGEST_ALLOWED = DebugFlags{ /* .bits = */ (1 << 31) };\n ^~~~~~~~~\n/home/kats/zspace/cbindgen/tests/expectations/bitflags.cpp:83:80: note: insert an explicit cast to silence this issue\nstatic const DebugFlags DebugFlags_BIGGEST_ALLOWED = DebugFlags{ /* .bits = */ (1 << 31) };\n ^~~~~~~~~\n static_cast<uint32_t>( )\n1 error generated.\n" }', tests/tests.rs:118:5
```
| 6b4181540c146fff75efd500bfb75a2d60403b4c | [
"test_bitflags"
] | [
"bindgen::mangle::generics",
"test_array",
"test_constant",
"test_cfg_field",
"test_body",
"test_assoc_const_conflict",
"test_display_list",
"test_char",
"test_associated_constant_panic",
"test_alias",
"test_destructor_and_copy_ctor",
"test_cfg",
"test_cdecl",
"test_constant_big",
"test_... | [
"test_expand",
"test_expand_dep",
"test_expand_default_features",
"test_expand_dep_v2",
"test_expand_no_default_features",
"test_expand_features"
] | [] | |
92a5e28c084aefc101d2f71f236614d9fcaa1f9e | diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1983,6 +1983,7 @@ impl Build {
if self.pic.unwrap_or(
!target.contains("windows")
&& !target.contains("-none-")
+ && !target.ends_with("-none")
&& !target.contains("uefi"),
) {
cmd.push_cc_arg("-fPIC".into());
| rust-lang__cc-rs-1212 | 1,212 | [
"1211"
] | 1.1 | rust-lang/cc-rs | 2024-09-17T21:22:26Z | diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -269,6 +269,20 @@ fn gnu_x86_64_no_plt() {
test.cmd(0).must_have("-fno-plt");
}
+#[test]
+fn gnu_aarch64_none_no_pic() {
+ for target in &["aarch64-unknown-none-gnu", "aarch64-unknown-none"] {
+ let test = Test::gnu();
+ test.gcc()
+ .target(&target)
+ .host(&target)
+ .file("foo.c")
+ .compile("foo");
+
+ test.cmd(0).must_not_have("-fPIC");
+ }
+}
+
#[test]
fn gnu_set_stdlib() {
reset_env();
| Target strings that end in -none (such as aarch64-unknown-none) should not default to -fPIC
According to the [docs](https://docs.rs/cc/latest/cc/struct.Build.html#method.pic)
> This [pic] option defaults to false for windows-gnu and bare metal targets and to true for all other targets.
This means the bare metal target `aarch64-unknown-none` should default to false, but the current logic only looks for `-none-`, and not `-none`.
| 1d566d4287c428491d8037a561ae195c1bfc6f7a | [
"gnu_aarch64_none_no_pic"
] | [
"tests::test_android_clang_compiler_uses_target_arg_internally",
"main",
"gnu_no_warnings_if_cflags",
"gnu_test_parse_shell_escaped_flags",
"gnu_no_warnings_if_cxxflags",
"gnu_no_dash_dash",
"gnu_include",
"msvc_debug",
"gnu_opt_level_1",
"clang_android",
"gnu_define",
"gnu_set_stdlib",
"gnu... | [] | [] | |
eb3390615747fde57f7098797b2acb1aec80f539 | diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,6 +21,7 @@ rust-version = "1.63"
[dependencies]
jobserver = { version = "0.1.30", default-features = false, optional = true }
+shlex = "1.3.0"
[target.'cfg(unix)'.dependencies]
# Don't turn on the feature "std" for this, see https://github.com/rust-lang/cargo/issues/4866
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -84,6 +84,9 @@
//! * `CC_ENABLE_DEBUG_OUTPUT` - if set, compiler command invocations and exit codes will
//! be logged to stdout. This is useful for debugging build script issues, but can be
//! overly verbose for normal use.
+//! * `CC_SHELL_ESCAPED_FLAGS` - if set, *FLAGS will be parsed as if they were shell
+//! arguments, similar to `make` and `cmake`. For example, `CFLAGS='a "b c" d\ e'` will
+//! be parsed as `["a", "b", "c", "d", "e"]` instead of `["a", "\"b", "c\", "d\\", "e"]`
//! * `CXX...` - see [C++ Support](#c-support).
//!
//! Furthermore, projects using this crate may specify custom environment variables
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -224,6 +227,8 @@ use std::process::Child;
use std::process::Command;
use std::sync::{Arc, RwLock};
+use shlex::Shlex;
+
#[cfg(feature = "parallel")]
mod parallel;
mod windows;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -301,6 +306,7 @@ pub struct Build {
apple_versions_cache: Arc<RwLock<HashMap<Box<str>, Arc<str>>>>,
emit_rerun_if_env_changed: bool,
cached_compiler_family: Arc<RwLock<HashMap<Box<Path>, ToolFamily>>>,
+ shell_escaped_flags: Option<bool>,
}
/// Represents the types of errors that may occur while using cc-rs.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -425,6 +431,7 @@ impl Build {
apple_versions_cache: Arc::new(RwLock::new(HashMap::new())),
emit_rerun_if_env_changed: true,
cached_compiler_family: Arc::default(),
+ shell_escaped_flags: None,
}
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1277,6 +1284,15 @@ impl Build {
self
}
+ /// Configure whether *FLAGS variables are parsed using `shlex`, similarly to `make` and
+ /// `cmake`.
+ ///
+ /// This option defaults to `false`.
+ pub fn shell_escaped_flags(&mut self, shell_escaped_flags: bool) -> &mut Build {
+ self.shell_escaped_flags = Some(shell_escaped_flags);
+ self
+ }
+
#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3634,6 +3650,11 @@ impl Build {
})
}
+ fn get_shell_escaped_flags(&self) -> bool {
+ self.shell_escaped_flags
+ .unwrap_or_else(|| self.getenv("CC_SHELL_ESCAPED_FLAGS").is_some())
+ }
+
fn get_dwarf_version(&self) -> Option<u32> {
// Tentatively matches the DWARF version defaults as of rustc 1.62.
let target = self.get_target().ok()?;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3748,12 +3769,17 @@ impl Build {
}
fn envflags(&self, name: &str) -> Result<Vec<String>, Error> {
- Ok(self
- .getenv_with_target_prefixes(name)?
- .to_string_lossy()
- .split_ascii_whitespace()
- .map(ToString::to_string)
- .collect())
+ let env_os = self.getenv_with_target_prefixes(name)?;
+ let env = env_os.to_string_lossy();
+
+ if self.get_shell_escaped_flags() {
+ Ok(Shlex::new(&env).collect())
+ } else {
+ Ok(env
+ .split_ascii_whitespace()
+ .map(ToString::to_string)
+ .collect())
+ }
}
fn fix_env_for_apple_os(&self, cmd: &mut Command) -> Result<(), Error> {
| rust-lang__cc-rs-1181 | 1,181 | While that might be possible to address in cc-rs, it still seems likely to break in other build systems, such as invocations of make, which don't have a solution to this problem.
@joshtriplett does `cc` forward to other build systems or only expand these flags into `argv` before invoking the compiler (which _should_ be possible and support spaces by splitting on the separator char)? Or is this to maintain feature parity with other build systems outside of `cc-rs` that also process `CFLAGS`?
I'm talking about the latter: cc-rs doesn't seem like the right place to unilaterally propagate a new standard for passing CFLAGS that no other build system will understand.
There admittedly are plenty of people just using `cc` so it's not entirely out of the question. I have mixed feelings about it though, for sure.
> such as invocations of make, which don't have a solution to this problem.
make does have a "solution" for this problem, if you shell escape with backslashes or quotes, it works: https://asciinema.org/a/oR0RRBOmtEX1W9p4GzVQk7mIt
cmake also works with shell escaping in `CFLAGS`: https://asciinema.org/a/2N3CJTWNiJBMCPlagyiHr1WEL
autoconf doesn't work.
I think the ideal solution to this would be `cc` parsing `*FLAGS` with `shlex`, for compatibility with `make` and `cmake`, maybe behind a new environment variable `CC_PARSE_FLAGS_WITH_SHLEX` to not break existing setups.
This is a pretty significant issue in my opinion, given the prevalence of spaces on Windows. | [
"847"
] | 1.1 | rust-lang/cc-rs | 2024-08-12T01:19:17Z | diff --git /dev/null b/tests/cflags_shell_escaped.rs
new file mode 100644
--- /dev/null
+++ b/tests/cflags_shell_escaped.rs
@@ -0,0 +1,24 @@
+mod support;
+
+use crate::support::Test;
+use std::env;
+
+/// This test is in its own module because it modifies the environment and would affect other tests
+/// when run in parallel with them.
+#[test]
+fn gnu_test_parse_shell_escaped_flags() {
+ env::set_var("CFLAGS", "foo \"bar baz\"");
+ env::set_var("CC_SHELL_ESCAPED_FLAGS", "1");
+ let test = Test::gnu();
+ test.gcc().file("foo.c").compile("foo");
+
+ test.cmd(0).must_have("foo").must_have("bar baz");
+
+ env::remove_var("CC_SHELL_ESCAPED_FLAGS");
+ let test = Test::gnu();
+ test.gcc().file("foo.c").compile("foo");
+
+ test.cmd(0)
+ .must_have("foo")
+ .must_have_in_order("\"bar", "baz\"");
+}
| Encoded `CFLAGS` for supporting spaces
According to https://github.com/rust-lang/cc-rs/#external-configuration-via-environment-variables spaces nor escapes for spaces are not supported in e.g. `C(XX)FLAGS`. In [`xbuild`](https://github.com/rust-mobile/xbuild) we [use `CFLAGS` to set a `--sysroot` path](https://github.com/rust-mobile/xbuild/blob/875f933f5908b49436e7176f2c0cfd7f5233ee24/xbuild/src/cargo/mod.rs#L444-L445), and this can occasionally contain spaces on Windows machines (because the toolchain is unpacked to a user folder, and users like to have `Firstname Surname` as username and profile directory).
A likable solution is new `CARGO_ENCODED_RUSTFLAGS`-like variables, where spaces within individual args are supported by requiring the user to replace space delimiters in between separate arguments with the `\x1f` ASCII Unit Separator: https://doc.rust-lang.org/cargo/reference/environment-variables.html, to allow more mechanical piecing-together of these variables without messing around with nested quotes or backslash-escapes.
Referencing https://github.com/rust-mobile/xbuild/issues/124, where this is one of the deciding factors to build our Android compiler support _differently_.
| 1d566d4287c428491d8037a561ae195c1bfc6f7a | [
"gnu_test_parse_shell_escaped_flags"
] | [
"tests::test_android_clang_compiler_uses_target_arg_internally",
"main",
"gnu_no_warnings_if_cflags",
"gnu_no_warnings_if_cxxflags",
"msvc_define",
"compile_intermediates",
"gnu_shared",
"gnu_opt_level_s",
"gnu_no_dash_dash",
"gnu_warnings",
"gnu_std_c",
"gnu_extra_warnings0",
"gnu_extra_war... | [] | [] |
4f312e3f3b2b4623e84518582a3ff17bbae70906 | diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -261,6 +261,9 @@ mod tempfile;
mod utilities;
use utilities::*;
+mod flags;
+use flags::*;
+
#[derive(Debug, Eq, PartialEq, Hash)]
struct CompilerFlag {
compiler: Box<Path>,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -328,6 +331,7 @@ pub struct Build {
emit_rerun_if_env_changed: bool,
shell_escaped_flags: Option<bool>,
build_cache: Arc<BuildCache>,
+ inherit_rustflags: bool,
}
/// Represents the types of errors that may occur while using cc-rs.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -343,10 +347,12 @@ enum ErrorKind {
ToolNotFound,
/// One of the function arguments failed validation.
InvalidArgument,
- /// No known macro is defined for the compiler when discovering tool family
+ /// No known macro is defined for the compiler when discovering tool family.
ToolFamilyMacroNotFound,
- /// Invalid target
+ /// Invalid target.
InvalidTarget,
+ /// Invalid rustc flag.
+ InvalidFlag,
#[cfg(feature = "parallel")]
/// jobserver helpthread failure
JobserverHelpThreadError,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -449,6 +455,7 @@ impl Build {
emit_rerun_if_env_changed: true,
shell_escaped_flags: None,
build_cache: Arc::default(),
+ inherit_rustflags: true,
}
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -563,7 +570,6 @@ impl Build {
/// .flag("unwanted_flag")
/// .remove_flag("unwanted_flag");
/// ```
-
pub fn remove_flag(&mut self, flag: &str) -> &mut Build {
self.flags.retain(|other_flag| &**other_flag != flag);
self
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -677,6 +683,7 @@ impl Build {
.debug(false)
.cpp(self.cpp)
.cuda(self.cuda)
+ .inherit_rustflags(false)
.emit_rerun_if_env_changed(self.emit_rerun_if_env_changed);
if let Some(target) = &self.target {
cfg.target(target);
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1333,6 +1340,15 @@ impl Build {
self
}
+ /// Configure whether cc should automatically inherit compatible flags passed to rustc
+ /// from `CARGO_ENCODED_RUSTFLAGS`.
+ ///
+ /// This option defaults to `true`.
+ pub fn inherit_rustflags(&mut self, inherit_rustflags: bool) -> &mut Build {
+ self.inherit_rustflags = inherit_rustflags;
+ self
+ }
+
#[doc(hidden)]
pub fn __set_env<A, B>(&mut self, a: A, b: B) -> &mut Build
where
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1928,6 +1944,11 @@ impl Build {
cmd.args.push((**flag).into());
}
+ // Add cc flags inherited from matching rustc flags
+ if self.inherit_rustflags {
+ self.add_inherited_rustflags(&mut cmd, &target)?;
+ }
+
for flag in self.flags_supported.iter() {
if self
.is_flag_supported_inner(flag, &cmd.path, &target)
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -2365,6 +2386,23 @@ impl Build {
Ok(())
}
+ fn add_inherited_rustflags(&self, cmd: &mut Tool, target: &TargetInfo) -> Result<(), Error> {
+ let env_os = match self.getenv("CARGO_ENCODED_RUSTFLAGS") {
+ Some(env) => env,
+ // No encoded RUSTFLAGS -> nothing to do
+ None => return Ok(()),
+ };
+
+ let Tool {
+ family, path, args, ..
+ } = cmd;
+
+ let env = env_os.to_string_lossy();
+ let codegen_flags = RustcCodegenFlags::parse(&env)?;
+ codegen_flags.cc_flags(self, path, *family, target, args);
+ Ok(())
+ }
+
fn has_flags(&self) -> bool {
let flags_env_var_name = if self.cpp { "CXXFLAGS" } else { "CFLAGS" };
let flags_env_var_value = self.getenv_with_target_prefixes(flags_env_var_name);
| rust-lang__cc-rs-1279 | 1,279 | Thanks, we definitely want more data to be fetcher from cargoz
Can you provide more details on what rustc/cargo flags it is?
The specific case I'm coming at this with is `-Z branch-protection`, e.g. `-Z branch-protection=pac-ret,bti`.
The corresponding cc flag would be `-mbranch-protection=pac-ret+bti`.
I imagine this would apply to some other flags too and in the end we could just have a `rustc => cc` flag match statement that could be expanded over time.
We can read the flags through `CARGO_ENCODED_RUSTFLAGS` and parse those from there.
Thanks that's a good idea, I would accept a PR for it.
Sounds good, will write up a PR then.
Should this be an opt-in thing with its own builder function? E.g. like
```
cc::Build::new().file("foo.c").inherit_rustc_flags().compile("foo");
```
Or should we have this done by default with some opt-out?
I think opt-out makes more sense, or maybe we don't even need an opt-out mechanism.
AFAIK the current cargo env usage does not have any opt-out mechanism.
List of codegen options that could be interesting (I'm going through the list of [rustc's `-C` options](https://doc.rust-lang.org/rustc/codegen-options/index.html), and matching them to [Clang's options](https://clang.llvm.org/docs/ClangCommandLineReference.html)):
- [x] `-Car`: Deprecated
- [ ] `-Ccode-model`: `-mcmodel`
- [x] `-Ccollapse-macro-debuginfo`: Rust specific
- [x] `-Ccodegen-units`: Rust specific
- [ ] `-Ccontrol-flow-guard`: `-mguard`
- [ ] `-Cdebug-assertions`: Should probably be controlled by something like `CARGO_CFG_DEBUG_ASSERTIONS` instead (except that doesn't currently work).
- [ ] `-Cdebuginfo`: Read `DEBUG` instead (needs to be changed to include all values).
- [ ] `-Cdefault-linker-libraries`: Probably desirable to control this separately between the Rust and C compiler.
- [ ] `-Cdlltool`: ?
- [ ] `-Cembed-bitcode`: `-fembed-bitcode`
- [x] `-Cextra-filename`: Rust specific.
- [ ] `-Cforce-frame-pointers`: `-fno-omit-frame-pointer`
- [ ] `-Cforce-unwind-tables`: ? Maybe some sort of `-fexception` flag?
- [ ] `-Cincremental`: Rust specific.
- [x] `-Cinline-threshold`: Deprecated.
- [ ] `-Cinstrument-coverage`: `-fprofile-generate`?
- [ ] `-Clink-arg` / `-Clink-args`: Need to ignore, since though we could pass these using the `-Xlinker` flag, these flags are intended for the _final_ executable, and `cc` is only producing an intermediary.
- [ ] `-Clink-dead-code`: `-dead_strip`/`--gc-sections`
- [ ] `-Clink-self-contained`: May be Rust specific?
- [x] `-Clinker` / `-Clinker-flavor`: We could possibly query the linker, and use it if it's a C compiler, but that'd probably be unexpected.
- [ ] `-Clinker-plugin-lto`: ?
- [ ] `-Cllvm-args`: Maybe forward these directly to Clang? Or maybe inside `-mllvm`?
- [ ] `-Clto`: `-flto`, though cross-language LTO is hard.
- [x] `-Cmetadata`: Rust specific.
- [x] `-Cno-prepopulate-passes`: Rust specific.
- [ ] `-Cno-redzone`: `-mred-zone`
- [x] `-Cno-stack-check`: Deprecated.
- [ ] `-Cno-vectorize-loops`: `-fno-vectorize`
- [ ] `-Cno-vectorize-slp`: `-fno-slp-vectorize`
- [x] `-Copt-level`: Read `OPT_LEVEL` instead.
- [ ] `-Coverflow-checks`: `-ftrapv`/`-fwrapv`?
- [ ] `-Cpanic`: `-fexceptions`
- [ ] `-Cpasses`: ?
- [x] `-Cprefer-dynamic`: Rust specific.
- [ ] `-Cprofile-generate`: `-fprofile-generate`
- [ ] `-Cprofile-use`: `-fprofile-use`
- [ ] `-Crelocation-model`: `-mdynamic-no-pic`
- [ ] `-Crelro-level`: `-Wl,-z,relro`?
- [ ] `-Cremark`: `-R`?
- [ ] `-Crpath`: ?
- [ ] `-Csave-temps`: `-save-temps`, but might need more to integrate with Cargo?
- [ ] `-Csoft-float`: `-msoft-float`
- [ ] `-Csplit-debuginfo`: Maybe `-gsplit-dwarf`?
- [x] `-Cstrip`: Rust specific (invokes an external tool after compilation).
- [x] `-Csymbol-mangling-version`: Rust specific.
- [ ] `-Ctarget-cpu`: `-march` (because `-Ctarget-cpu` _forces_ that CPU, so `-mcpu` is too weak (?)).
- [ ] `-Ctarget-feature`: Use `CARGO_CFG_TARGET_FEATURE` instead.
- [ ] `-Ctune-cpu`: `-mtune` (or perhaps `-mcpu`?)
| [
"1254"
] | 1.2 | rust-lang/cc-rs | 2024-11-07T17:09:12Z | diff --git /dev/null b/src/flags.rs
new file mode 100644
--- /dev/null
+++ b/src/flags.rs
@@ -0,0 +1,482 @@
+use crate::target::TargetInfo;
+use crate::{Build, Error, ErrorKind, ToolFamily};
+use std::borrow::Cow;
+use std::ffi::OsString;
+use std::path::Path;
+
+#[derive(Debug, PartialEq, Default)]
+pub(crate) struct RustcCodegenFlags {
+ branch_protection: Option<String>,
+ code_model: Option<String>,
+ no_vectorize_loops: bool,
+ no_vectorize_slp: bool,
+ profile_generate: Option<String>,
+ profile_use: Option<String>,
+ control_flow_guard: Option<String>,
+ lto: Option<String>,
+ relocation_model: Option<String>,
+ embed_bitcode: Option<bool>,
+ force_frame_pointers: Option<bool>,
+ link_dead_code: Option<bool>,
+ no_redzone: Option<bool>,
+ soft_float: Option<bool>,
+}
+
+impl RustcCodegenFlags {
+ // Parse flags obtained from CARGO_ENCODED_RUSTFLAGS
+ pub(crate) fn parse(rustflags_env: &str) -> Result<RustcCodegenFlags, Error> {
+ fn is_flag_prefix(flag: &str) -> bool {
+ [
+ "-Z",
+ "-C",
+ "--codegen",
+ "-L",
+ "-l",
+ "-o",
+ "-W",
+ "--warn",
+ "-A",
+ "--allow",
+ "-D",
+ "--deny",
+ "-F",
+ "--forbid",
+ ]
+ .contains(&flag)
+ }
+
+ fn handle_flag_prefix<'a>(prev: &'a str, curr: &'a str) -> Cow<'a, str> {
+ match prev {
+ "--codegen" | "-C" => Cow::from(format!("-C{}", curr)),
+ // Handle flags passed like --codegen=code-model=small
+ _ if curr.starts_with("--codegen=") => Cow::from(format!("-C{}", &curr[10..])),
+ "-Z" => Cow::from(format!("-Z{}", curr)),
+ "-L" | "-l" | "-o" => Cow::from(format!("{}{}", prev, curr)),
+ // Handle lint flags
+ "-W" | "--warn" => Cow::from(format!("-W{}", curr)),
+ "-A" | "--allow" => Cow::from(format!("-A{}", curr)),
+ "-D" | "--deny" => Cow::from(format!("-D{}", curr)),
+ "-F" | "--forbid" => Cow::from(format!("-F{}", curr)),
+ _ => Cow::from(curr),
+ }
+ }
+
+ let mut codegen_flags = Self::default();
+
+ let mut prev_prefix = None;
+ for curr in rustflags_env.split("\u{1f}") {
+ let prev = prev_prefix.take().unwrap_or("");
+ if prev.is_empty() && is_flag_prefix(curr) {
+ prev_prefix = Some(curr);
+ continue;
+ }
+
+ let rustc_flag = handle_flag_prefix(prev, curr);
+ codegen_flags.set_rustc_flag(&rustc_flag)?;
+ }
+
+ Ok(codegen_flags)
+ }
+
+ fn set_rustc_flag(&mut self, flag: &str) -> Result<(), Error> {
+ // Convert a textual representation of a bool-like rustc flag argument into an actual bool
+ fn arg_to_bool(arg: impl AsRef<str>) -> Option<bool> {
+ match arg.as_ref() {
+ "y" | "yes" | "on" | "true" => Some(true),
+ "n" | "no" | "off" | "false" => Some(false),
+ _ => None,
+ }
+ }
+
+ let (flag, value) = if let Some((flag, value)) = flag.split_once('=') {
+ (flag, Some(value.to_owned()))
+ } else {
+ (flag, None)
+ };
+
+ fn flag_ok_or(flag: Option<String>, msg: &'static str) -> Result<String, Error> {
+ flag.ok_or(Error::new(ErrorKind::InvalidFlag, msg))
+ }
+
+ match flag {
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#code-model
+ "-Ccode-model" => {
+ self.code_model = Some(flag_ok_or(value, "-Ccode-model must have a value")?);
+ }
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-loops
+ "-Cno-vectorize-loops" => self.no_vectorize_loops = true,
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-vectorize-slp
+ "-Cno-vectorize-slp" => self.no_vectorize_slp = true,
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-generate
+ "-Cprofile-generate" => {
+ self.profile_generate =
+ Some(flag_ok_or(value, "-Cprofile-generate must have a value")?);
+ }
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#profile-use
+ "-Cprofile-use" => {
+ self.profile_use = Some(flag_ok_or(value, "-Cprofile-use must have a value")?);
+ }
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#control-flow-guard
+ "-Ccontrol-flow-guard" => self.control_flow_guard = value.or(Some("true".into())),
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#lto
+ "-Clto" => self.lto = value.or(Some("true".into())),
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#relocation-model
+ "-Crelocation-model" => {
+ self.relocation_model =
+ Some(flag_ok_or(value, "-Crelocation-model must have a value")?);
+ }
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#embed-bitcode
+ "-Cembed-bitcode" => self.embed_bitcode = value.map_or(Some(true), arg_to_bool),
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#force-frame-pointers
+ "-Cforce-frame-pointers" => {
+ self.force_frame_pointers = value.map_or(Some(true), arg_to_bool)
+ }
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#link-dead-code
+ "-Clink-dead-code" => self.link_dead_code = value.map_or(Some(true), arg_to_bool),
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#no-redzone
+ "-Cno-redzone" => self.no_redzone = value.map_or(Some(true), arg_to_bool),
+ // https://doc.rust-lang.org/rustc/codegen-options/index.html#soft-float
+ // Note: This flag is now deprecated in rustc.
+ "-Csoft-float" => self.soft_float = value.map_or(Some(true), arg_to_bool),
+ // https://doc.rust-lang.org/beta/unstable-book/compiler-flags/branch-protection.html
+ // FIXME: Drop the -Z variant and update the doc link once the option is stabilised
+ "-Zbranch-protection" | "-Cbranch-protection" => {
+ self.branch_protection =
+ Some(flag_ok_or(value, "-Zbranch-protection must have a value")?);
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ // Rust and clang/cc don't agree on what equivalent flags should look like.
+ pub(crate) fn cc_flags(
+ &self,
+ build: &Build,
+ path: &Path,
+ family: ToolFamily,
+ target: &TargetInfo,
+ flags: &mut Vec<OsString>,
+ ) {
+ // Push `flag` to `flags` if it is supported by the currently used CC
+ let mut push_if_supported = |flag: OsString| {
+ if build
+ .is_flag_supported_inner(&flag, path, target)
+ .unwrap_or(false)
+ {
+ flags.push(flag);
+ } else {
+ build.cargo_output.print_warning(&format!(
+ "Inherited flag {:?} is not supported by the currently used CC",
+ flag
+ ));
+ }
+ };
+
+ match family {
+ ToolFamily::Clang { .. } | ToolFamily::Gnu => {
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mbranch-protection
+ if let Some(value) = &self.branch_protection {
+ push_if_supported(
+ format!("-mbranch-protection={}", value.replace(",", "+")).into(),
+ );
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mcmodel
+ if let Some(value) = &self.code_model {
+ push_if_supported(format!("-mcmodel={value}").into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-vectorize
+ if self.no_vectorize_loops {
+ push_if_supported("-fno-vectorize".into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-slp-vectorize
+ if self.no_vectorize_slp {
+ push_if_supported("-fno-slp-vectorize".into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-generate
+ if let Some(value) = &self.profile_generate {
+ push_if_supported(format!("-fprofile-generate={value}").into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fprofile-use
+ if let Some(value) = &self.profile_use {
+ push_if_supported(format!("-fprofile-use={value}").into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mguard
+ if let Some(value) = &self.control_flow_guard {
+ let cc_val = match value.as_str() {
+ "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
+ "nochecks" => Some("cf-nochecks"),
+ "n" | "no" | "off" | "false" => Some("none"),
+ _ => None,
+ };
+ if let Some(cc_val) = cc_val {
+ push_if_supported(format!("-mguard={cc_val}").into());
+ }
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-flto
+ if let Some(value) = &self.lto {
+ let cc_val = match value.as_str() {
+ "y" | "yes" | "on" | "true" | "fat" => Some("full"),
+ "thin" => Some("thin"),
+ _ => None,
+ };
+ if let Some(cc_val) = cc_val {
+ push_if_supported(format!("-flto={cc_val}").into());
+ }
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIC
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fPIE
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mdynamic-no-pic
+ if let Some(value) = &self.relocation_model {
+ let cc_flag = match value.as_str() {
+ "pic" => Some("-fPIC"),
+ "pie" => Some("-fPIE"),
+ "dynamic-no-pic" => Some("-mdynamic-no-pic"),
+ _ => None,
+ };
+ if let Some(cc_flag) = cc_flag {
+ push_if_supported(cc_flag.into());
+ }
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fembed-bitcode
+ if let Some(value) = &self.embed_bitcode {
+ let cc_val = if *value { "all" } else { "off" };
+ push_if_supported(format!("-fembed-bitcode={cc_val}").into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fno-omit-frame-pointer
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fomit-frame-pointer
+ if let Some(value) = &self.force_frame_pointers {
+ let cc_flag = if *value {
+ "-fno-omit-frame-pointer"
+ } else {
+ "-fomit-frame-pointer"
+ };
+ push_if_supported(cc_flag.into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-dead_strip
+ if let Some(value) = &self.link_dead_code {
+ if !value {
+ push_if_supported("-dead_strip".into());
+ }
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mno-red-zone
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mred-zone
+ if let Some(value) = &self.no_redzone {
+ let cc_flag = if *value {
+ "-mno-red-zone"
+ } else {
+ "-mred-zone"
+ };
+ push_if_supported(cc_flag.into());
+ }
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-msoft-float
+ // https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-mno-soft-float
+ if let Some(value) = &self.soft_float {
+ let cc_flag = if *value {
+ "-msoft-float"
+ } else {
+ "-mno-soft-float"
+ };
+ push_if_supported(cc_flag.into());
+ }
+ }
+ ToolFamily::Msvc { .. } => {
+ // https://learn.microsoft.com/en-us/cpp/build/reference/guard-enable-control-flow-guard
+ if let Some(value) = &self.control_flow_guard {
+ let cc_val = match value.as_str() {
+ "y" | "yes" | "on" | "true" | "checks" => Some("cf"),
+ "n" | "no" | "off" | "false" => Some("cf-"),
+ _ => None,
+ };
+ if let Some(cc_val) = cc_val {
+ push_if_supported(format!("/guard:{cc_val}").into());
+ }
+ }
+ // https://learn.microsoft.com/en-us/cpp/build/reference/oy-frame-pointer-omission
+ if let Some(value) = &self.force_frame_pointers {
+ let cc_flag = if *value { "/Oy-" } else { "/Oy" };
+ push_if_supported(cc_flag.into());
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[track_caller]
+ fn check(env: &str, expected: &RustcCodegenFlags) {
+ let actual = RustcCodegenFlags::parse(env).unwrap();
+ assert_eq!(actual, *expected);
+ }
+
+ #[test]
+ fn codegen_type() {
+ let expected = RustcCodegenFlags {
+ code_model: Some("tiny".into()),
+ ..RustcCodegenFlags::default()
+ };
+ check("-Ccode-model=tiny", &expected);
+ check("-C\u{1f}code-model=tiny", &expected);
+ check("--codegen\u{1f}code-model=tiny", &expected);
+ check("--codegen=code-model=tiny", &expected);
+ }
+
+ #[test]
+ fn precedence() {
+ check(
+ "-ccode-model=tiny\u{1f}-Ccode-model=small",
+ &RustcCodegenFlags {
+ code_model: Some("small".into()),
+ ..RustcCodegenFlags::default()
+ },
+ );
+ }
+
+ #[test]
+ fn two_valid_prefixes() {
+ let expected = RustcCodegenFlags::default();
+ check("-L\u{1f}-Clto", &expected);
+ }
+
+ #[test]
+ fn three_valid_prefixes() {
+ let expected = RustcCodegenFlags {
+ lto: Some("true".into()),
+ ..RustcCodegenFlags::default()
+ };
+ check("-L\u{1f}-L\u{1f}-Clto", &expected);
+ }
+
+ #[test]
+ fn all_rustc_flags() {
+ // Throw all possible flags at the parser to catch false positives
+ let flags = [
+ // Set all the flags we recognise first
+ "-Ccode-model=tiny",
+ "-Ccontrol-flow-guard=yes",
+ "-Cembed-bitcode=no",
+ "-Cforce-frame-pointers=yes",
+ "-Clto=false",
+ "-Clink-dead-code=yes",
+ "-Cno-redzone=yes",
+ "-Cno-vectorize-loops",
+ "-Cno-vectorize-slp",
+ "-Cprofile-generate=fooprofile",
+ "-Cprofile-use=fooprofile",
+ "-Crelocation-model=pic",
+ "-Csoft-float=yes",
+ "-Zbranch-protection=bti,pac-ret,leaf",
+ // Set flags we don't recognise but rustc supports next
+ // rustc flags
+ "--cfg",
+ "a",
+ "--check-cfg 'cfg(verbose)",
+ "-L",
+ "/usr/lib/foo",
+ "-l",
+ "static:+whole-archive=mylib",
+ "--crate-type=dylib",
+ "--crate-name=foo",
+ "--edition=2021",
+ "--emit=asm",
+ "--print=crate-name",
+ "-g",
+ "-O",
+ "-o",
+ "foooutput",
+ "--out-dir",
+ "foooutdir",
+ "--target",
+ "aarch64-unknown-linux-gnu",
+ "-W",
+ "missing-docs",
+ "-D",
+ "unused-variables",
+ "--force-warn",
+ "dead-code",
+ "-A",
+ "unused",
+ "-F",
+ "unused",
+ "--cap-lints",
+ "warn",
+ "--version",
+ "--verbose",
+ "-v",
+ "--extern",
+ "foocrate",
+ "--sysroot",
+ "fooroot",
+ "--error-format",
+ "human",
+ "--color",
+ "auto",
+ "--diagnostic-width",
+ "80",
+ "--remap-path-prefix",
+ "foo=bar",
+ "--json=artifact",
+ // Codegen flags
+ "-Car",
+ "-Ccodegen-units=1",
+ "-Ccollapse-macro-debuginfo=yes",
+ "-Cdebug-assertions=yes",
+ "-Cdebuginfo=1",
+ "-Cdefault-linker-libraries=yes",
+ "-Cdlltool=foo",
+ "-Cextra-filename=foo",
+ "-Cforce-unwind-tables=yes",
+ "-Cincremental=foodir",
+ "-Cinline-threshold=6",
+ "-Cinstrument-coverage",
+ "-Clink-arg=-foo",
+ "-Clink-args=-foo",
+ "-Clink-self-contained=yes",
+ "-Clinker=lld",
+ "-Clinker-flavor=ld.lld",
+ "-Clinker-plugin-lto=yes",
+ "-Cllvm-args=foo",
+ "-Cmetadata=foo",
+ "-Cno-prepopulate-passes",
+ "-Cno-stack-check",
+ "-Copt-level=3",
+ "-Coverflow-checks=yes",
+ "-Cpanic=abort",
+ "-Cpasses=foopass",
+ "-Cprefer-dynamic=yes",
+ "-Crelro-level=partial",
+ "-Cremark=all",
+ "-Crpath=yes",
+ "-Csave-temps=yes",
+ "-Csplit-debuginfo=packed",
+ "-Cstrip=symbols",
+ "-Csymbol-mangling-version=v0",
+ "-Ctarget-cpu=native",
+ "-Ctarget-feature=+sve",
+ // Unstable options
+ "-Ztune-cpu=machine",
+ ];
+ check(
+ &flags.join("\u{1f}"),
+ &RustcCodegenFlags {
+ code_model: Some("tiny".into()),
+ control_flow_guard: Some("yes".into()),
+ embed_bitcode: Some(false),
+ force_frame_pointers: Some(true),
+ link_dead_code: Some(true),
+ lto: Some("false".into()),
+ no_redzone: Some(true),
+ no_vectorize_loops: true,
+ no_vectorize_slp: true,
+ profile_generate: Some("fooprofile".into()),
+ profile_use: Some("fooprofile".into()),
+ relocation_model: Some("pic".into()),
+ soft_float: Some(true),
+ branch_protection: Some("bti,pac-ret,leaf".into()),
+ },
+ );
+ }
+}
diff --git /dev/null b/tests/rustflags.rs
new file mode 100644
--- /dev/null
+++ b/tests/rustflags.rs
@@ -0,0 +1,29 @@
+use crate::support::Test;
+mod support;
+
+/// This test is in its own module because it modifies the environment and would affect other tests
+/// when run in parallel with them.
+#[test]
+#[cfg(not(windows))]
+fn inherits_rustflags() {
+ // Sanity check - no flags
+ std::env::set_var("CARGO_ENCODED_RUSTFLAGS", "");
+ let test = Test::gnu();
+ test.gcc().file("foo.c").compile("foo");
+ test.cmd(0)
+ .must_not_have("-fno-omit-frame-pointer")
+ .must_not_have("-mcmodel=small")
+ .must_not_have("-msoft-float");
+
+ // Correctly inherits flags from rustc
+ std::env::set_var(
+ "CARGO_ENCODED_RUSTFLAGS",
+ "-Cforce-frame-pointers=true\u{1f}-Ccode-model=small\u{1f}-Csoft-float",
+ );
+ let test = Test::gnu();
+ test.gcc().file("foo.c").compile("foo");
+ test.cmd(0)
+ .must_have("-fno-omit-frame-pointer")
+ .must_have("-mcmodel=small")
+ .must_have("-msoft-float");
+}
| Mechanism for automatically passing flags used by rustc
When cc-rs is running in a build script, it currently does not check which flags were passed to rustc.
There are some flags which in order to be fully effective need to be passed to both rustc and cc, a good example being AArch64 branch protection - if the Rust code is built with BTI but the C component is not, that will disable BTI for the whole binary.
Would some mechanism for checking which flags were passed to rustc and determining their corresponding cc flags be desirable to have? This could either be in the form of adding them in automatically, a separate function such as `inherit_rustc_flags()` or even just a warning to the user that some flags that should match don't match.
I'm thinking about implementing something along the lines of what I described above, but I wanted to ask for some thoughts from people who work on this crate. Is this desirable in the first place? If so, roughly what direction should I go in with this?
| 29d6ca194cca33f96071355764da436e21c34d12 | [
"inherits_rustflags"
] | [
"target::llvm::tests::test_basic_llvm_triple_guessing",
"target::tests::cannot_parse_extra",
"target::tests::tier1",
"tests::test_android_clang_compiler_uses_target_arg_internally",
"main",
"gnu_no_warnings_if_cflags",
"gnu_test_parse_shell_escaped_flags",
"gnu_no_warnings_if_cxxflags",
"gnu_compile... | [] | [] |
915420c16c134e6bb458ce634c663305a0ef2504 | diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1894,7 +1894,10 @@ impl Build {
// Target flags
match cmd.family {
ToolFamily::Clang => {
- if !(target.contains("android") && cmd.has_internal_target_arg) {
+ if !cmd.has_internal_target_arg
+ && !(target.contains("android")
+ && android_clang_compiler_uses_target_arg_internally(&cmd.path))
+ {
if target.contains("darwin") {
if let Some(arch) =
map_darwin_target_from_rust_to_compiler_architecture(target)
| rust-lang__cc-rs-991 | 991 | [
"990"
] | 1.0 | rust-lang/cc-rs | 2024-03-04T20:08:43Z | diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -617,3 +617,33 @@ fn compile_intermediates() {
assert!(intermediates[1].display().to_string().contains("x86_64"));
assert!(intermediates[2].display().to_string().contains("x86_64"));
}
+
+#[test]
+fn clang_android() {
+ let target = "arm-linux-androideabi";
+
+ // On Windows, we don't use the Android NDK shims for Clang, so verify that
+ // we use "clang" and set the target correctly.
+ #[cfg(windows)]
+ {
+ let test = Test::new();
+ test.shim("clang").shim("llvm-ar");
+ test.gcc()
+ .target(target)
+ .host("x86_64-pc-windows-msvc")
+ .file("foo.c")
+ .compile("foo");
+ test.cmd(0).must_have("--target=arm-linux-androideabi");
+ }
+
+ // On non-Windows, we do use the shims, so make sure that we use the shim
+ // and don't set the target.
+ #[cfg(not(windows))]
+ {
+ let test = Test::new();
+ test.shim("arm-linux-androideabi-clang")
+ .shim("arm-linux-androideabi-ar");
+ test.gcc().target(target).file("foo.c").compile("foo");
+ test.cmd(0).must_not_have("--target=arm-linux-androideabi");
+ }
+}
| 1.0.88 breaks the Rust compile-ui tests for arm-android
When trying to update cc-rs to 1.0.88 in the Rust repo, we hit an error with the compile-ui test for arm-android:
<https://github.com/rust-lang/rust/pull/121854#issuecomment-1973518078>
```
2024-03-01T16:42:03.5816834Z ---- [ui] tests/ui/thread-local/tls.rs stdout ----
2024-03-01T16:42:03.5844499Z --- stderr -------------------------------
2024-03-01T16:42:03.5845537Z error: linking with `/android/ndk/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi19-clang` failed: exit status: 1
2024-03-01T16:42:03.5846544Z |
2024-03-01T16:42:03.5854489Z = note: LC_ALL="C" PATH="/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/x86_64-unknown-linux-gnu/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/android/sdk/emulator:/android/sdk/tools:/android/sdk/platform-tools" VSLANG="1033" "/android/ndk/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi19-clang" "/tmp/rustc0dOpvq/symbols.o" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/thread-local/tls/a.tls.ca29c82538305dca-cgu.0.rcgu.o" "-Wl,--as-needed" "-L" "/checkout/obj/build/arm-linux-androideabi/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/thread-local/tls/auxiliary" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib" "-Wl,-Bdynamic" "-lstd-8e24d49e9c2a7cc4" "-Wl,-Bstatic" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib/libcompiler_builtins-23518b53a80b1f29.rlib" "-Wl,-Bdynamic" "-ldl" "-llog" "-lunwind" "-ldl" "-lm" "-lc" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib" "-o" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/thread-local/tls/a" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-Wl,-O1" "-Wl,--strip-debug" "-nodefaultlibs" "-Wl,-rpath,$ORIGIN/../../../../stage2/lib/rustlib/arm-linux-androideabi/lib" "-Wl,--enable-new-dtags" "-Wl,-z,origin"
2024-03-01T16:42:03.5862557Z = note: ld: error: undefined symbol: __atomic_load_4
2024-03-01T16:42:03.5863027Z >>> referenced by emutls.c
2024-03-01T16:42:03.5864373Z >>> 45c91108d938afe8-emutls.o:(__emutls_get_address) in archive /checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib/libcompiler_builtins-23518b53a80b1f29.rlib
2024-03-01T16:42:03.5865772Z
2024-03-01T16:42:03.5866209Z ld: error: undefined symbol: __atomic_store_4
2024-03-01T16:42:03.5866677Z >>> referenced by emutls.c
2024-03-01T16:42:03.5867943Z >>> 45c91108d938afe8-emutls.o:(__emutls_get_address) in archive /checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/arm-linux-androideabi/lib/libcompiler_builtins-23518b53a80b1f29.rlib
2024-03-01T16:42:03.5869403Z clang-14: error: linker command failed with exit code 1 (use -v to see invocation)
```
I've narrowed down the failure to <https://github.com/rust-lang/cc-rs/commit/53564e00498156c9be00361c4b039952cbf7ff59>
Using 53564e00498156c9be00361c4b039952cbf7ff59 reproduced the issue: <https://github.com/rust-lang/rust/pull/121874#issuecomment-1974171096>
The previous commit did not have the issue: https://github.com/rust-lang/rust/actions/runs/8145164818/job/22260797425?pr=121874
And reverting 53564e00498156c9be00361c4b039952cbf7ff59 from 1.0.88 also did not have the issue: https://github.com/rust-lang/rust/actions/runs/8145164818/job/22260797425?pr=121874
| 2a0bf2b0234a538f96a064bde2b50e6677b27c9c | [
"clang_android"
] | [
"test_android_clang_compiler_uses_target_arg_internally",
"main",
"gnu_no_warnings_if_cflags",
"gnu_no_warnings_if_cxxflags",
"msvc_define",
"msvc_debug",
"gnu_compile_assembly",
"gnu_extra_warnings1",
"compile_intermediates",
"gnu_extra_warnings0",
"gnu_warnings",
"gnu_debug_fp_auto",
"gnu_... | [] | [] | |
29d6ca194cca33f96071355764da436e21c34d12 | diff --git a/src/command_helpers.rs b/src/command_helpers.rs
--- a/src/command_helpers.rs
+++ b/src/command_helpers.rs
@@ -327,6 +327,9 @@ pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<
};
hasher.write(dirname.as_bytes());
+ if let Some(extension) = file.extension() {
+ hasher.write(extension.to_string_lossy().as_bytes());
+ }
let obj = dst
.join(format!("{:016x}-{}", hasher.finish(), basename))
.with_extension("o");
| rust-lang__cc-rs-1295 | 1,295 | Yeah that's problematic. We could solve this two ways:
1. Add the extension to the hash.
2. Rewrite the whole thing to instead keep a `HashMap<OsString, NonZero<u32>>` for the compilation session, with each output file bumping a number in there.
- This would make absolutely sure we never leak information about absolute dirs
- Though might make the build less reproducible if the order of files change?
- Related: https://github.com/rust-lang/cc-rs/pull/1277
@NobodyXu do you know why we're even invoking the compiler for each source file? As far as I know, C compilers support building multiple files and linking them together in one step?
(Of course if we did https://github.com/rust-lang/cc-rs/issues/545 we'd have to do something else)
I think adding extension to the hash is the right solution.
> do you know why we're even invoking the compiler for each source file
Primary reason is for parallel compilation.
Also some people depends on it (extract the file from archive or uses `compile_intermediate`) | [
"1294"
] | 1.2 | rust-lang/cc-rs | 2024-11-19T13:49:54Z | diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -27,7 +27,7 @@ fn gnu_smoke() {
.must_have("-ffunction-sections")
.must_have("-fdata-sections");
test.cmd(1)
- .must_have(test.td.path().join("d1fba762150c532c-foo.o"));
+ .must_have(test.td.path().join("db3b6bfb95261072-foo.o"));
}
#[test]
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -434,7 +434,7 @@ fn msvc_smoke() {
.must_have("-c")
.must_have("-MD");
test.cmd(1)
- .must_have(test.td.path().join("d1fba762150c532c-foo.o"));
+ .must_have(test.td.path().join("db3b6bfb95261072-foo.o"));
}
#[test]
| Two source files with same name, different extension generate same object file name
Hi,
When building a project that has 2 sibling files with same name but different extension, they both result in the same filename for the object file. In my case:
```rs
...
.file("rv003usb.c")
.file("rv003usb.S")
```
produces two `rv003usb.o` files, with the latter overwriting the former. Thus, the resulting build either fails or is missing some symbols. I traced this to this line: https://github.com/rust-lang/cc-rs/blob/29d6ca194cca33f96071355764da436e21c34d12/src/command_helpers.rs#L330-L332
| 29d6ca194cca33f96071355764da436e21c34d12 | [
"gnu_smoke",
"msvc_smoke"
] | [
"target::llvm::tests::test_basic_llvm_triple_guessing",
"target::tests::tier1",
"target::tests::cannot_parse_extra",
"tests::test_android_clang_compiler_uses_target_arg_internally",
"main",
"gnu_no_warnings_if_cflags",
"gnu_test_parse_shell_escaped_flags",
"gnu_no_warnings_if_cxxflags",
"clang_andro... | [] | [] |
e95b9dda33b40ce19dbad67a00c209b20bfab206 | diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -1,4 +1,5 @@
use std::fmt::Display;
+use std::fmt::Write as _;
use serde::ser;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -8,87 +9,83 @@ use crate::Config;
#[derive(Default, Debug)]
pub struct ConfigSerializer {
- keys: Vec<(String, Option<usize>)>,
+ keys: Vec<SerKey>,
pub output: Config,
}
+#[derive(Debug)]
+enum SerKey {
+ Named(String),
+ Seq(usize),
+}
+
+/// Serializer for numbered sequences
+///
+/// This wrapper is present when we are outputting a sequence (numbered indices).
+/// Making this a separate type centralises the handling of sequences
+/// and ensures we don't have any call sites for `ser::SerializeSeq::serialize_element`
+/// that don't do the necessary work of `SeqSerializer::new`.
+///
+/// Existence of this wrapper implies that `.0.keys.last()` is
+/// `Some(SerKey::Seq(next_index))`.
+pub struct SeqSerializer<'a>(&'a mut ConfigSerializer);
+
impl ConfigSerializer {
fn serialize_primitive<T>(&mut self, value: T) -> Result<()>
where
T: Into<Value> + Display,
{
- let key = match self.last_key_index_pair() {
- Some((key, Some(index))) => format!("{}[{}]", key, index),
- Some((key, None)) => key.to_string(),
- None => {
- return Err(ConfigError::Message(format!(
- "key is not found for value {}",
- value
- )))
- }
- };
+ // At some future point we could perhaps retain a cursor into the output `Config`,
+ // rather than reifying the whole thing into a single string with `make_full_key`
+ // and passing that whole path to the `set` method.
+ //
+ // That would be marginally more performant, but more fiddly.
+ let key = self.make_full_key()?;
#[allow(deprecated)]
self.output.set(&key, value.into())?;
Ok(())
}
- fn last_key_index_pair(&self) -> Option<(&str, Option<usize>)> {
- let len = self.keys.len();
- if len > 0 {
- self.keys
- .get(len - 1)
- .map(|&(ref key, opt)| (key.as_str(), opt))
- } else {
- None
- }
- }
+ fn make_full_key(&self) -> Result<String> {
+ let mut keys = self.keys.iter();
- fn inc_last_key_index(&mut self) -> Result<()> {
- let len = self.keys.len();
- if len > 0 {
- self.keys
- .get_mut(len - 1)
- .map(|pair| pair.1 = pair.1.map(|i| i + 1).or(Some(0)))
- .ok_or_else(|| {
- ConfigError::Message(format!("last key is not found in {} keys", len))
- })
- } else {
- Err(ConfigError::Message("keys is empty".to_string()))
- }
- }
+ let mut whole = match keys.next() {
+ Some(SerKey::Named(s)) => s.clone(),
+ _ => {
+ return Err(ConfigError::Message(
+ "top level is not a struct".to_string(),
+ ))
+ }
+ };
- fn make_full_key(&self, key: &str) -> String {
- let len = self.keys.len();
- if len > 0 {
- if let Some(&(ref prev_key, index)) = self.keys.get(len - 1) {
- return if let Some(index) = index {
- format!("{}[{}].{}", prev_key, index, key)
- } else {
- format!("{}.{}", prev_key, key)
- };
+ for k in keys {
+ match k {
+ SerKey::Named(s) => write!(whole, ".{}", s),
+ SerKey::Seq(i) => write!(whole, "[{}]", i),
}
+ .expect("write! to a string failed");
}
- key.to_string()
+
+ Ok(whole)
}
fn push_key(&mut self, key: &str) {
- let full_key = self.make_full_key(key);
- self.keys.push((full_key, None));
+ self.keys.push(SerKey::Named(key.to_string()));
}
- fn pop_key(&mut self) -> Option<(String, Option<usize>)> {
- self.keys.pop()
+ fn pop_key(&mut self) {
+ self.keys.pop();
}
}
impl<'a> ser::Serializer for &'a mut ConfigSerializer {
type Ok = ();
type Error = ConfigError;
- type SerializeSeq = Self;
- type SerializeTuple = Self;
- type SerializeTupleStruct = Self;
- type SerializeTupleVariant = Self;
+ type SerializeSeq = SeqSerializer<'a>;
+ type SerializeTuple = SeqSerializer<'a>;
+ type SerializeTupleStruct = SeqSerializer<'a>;
+ type SerializeTupleVariant = SeqSerializer<'a>;
type SerializeMap = Self;
type SerializeStruct = Self;
type SerializeStructVariant = Self;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -159,7 +156,8 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
for byte in v {
seq.serialize_element(byte)?;
}
- seq.end()
+ seq.end();
+ Ok(())
}
fn serialize_none(self) -> Result<Self::Ok> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -214,7 +212,7 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
- Ok(self)
+ SeqSerializer::new(self)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -234,10 +232,10 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
_name: &'static str,
_variant_index: u32,
variant: &'static str,
- _len: usize,
+ len: usize,
) -> Result<Self::SerializeTupleVariant> {
self.push_key(variant);
- Ok(self)
+ self.serialize_seq(Some(len))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -260,7 +258,21 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
}
}
-impl<'a> ser::SerializeSeq for &'a mut ConfigSerializer {
+impl<'a> SeqSerializer<'a> {
+ fn new(inner: &'a mut ConfigSerializer) -> Result<Self> {
+ inner.keys.push(SerKey::Seq(0));
+
+ Ok(SeqSerializer(inner))
+ }
+
+ fn end(self) -> &'a mut ConfigSerializer {
+ // This ought to be Some(SerKey::Seq(..)) but we don't want to panic if we are buggy
+ let _: Option<SerKey> = self.0.keys.pop();
+ self.0
+ }
+}
+
+impl<'a> ser::SerializeSeq for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -268,17 +280,25 @@ impl<'a> ser::SerializeSeq for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
+ value.serialize(&mut *(self.0))?;
+ match self.0.keys.last_mut() {
+ Some(SerKey::Seq(i)) => *i += 1,
+ _ => {
+ return Err(ConfigError::Message(
+ "config-rs internal error (ser._element but last not Seq!".to_string(),
+ ))
+ }
+ };
Ok(())
}
fn end(self) -> Result<Self::Ok> {
+ self.end();
Ok(())
}
}
-impl<'a> ser::SerializeTuple for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTuple for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -286,17 +306,15 @@ impl<'a> ser::SerializeTuple for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- Ok(())
+ ser::SerializeSeq::end(self)
}
}
-impl<'a> ser::SerializeTupleStruct for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTupleStruct for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -304,17 +322,15 @@ impl<'a> ser::SerializeTupleStruct for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- Ok(())
+ ser::SerializeSeq::end(self)
}
}
-impl<'a> ser::SerializeTupleVariant for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTupleVariant for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -322,13 +338,12 @@ impl<'a> ser::SerializeTupleVariant for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- self.pop_key();
+ let inner = self.end();
+ inner.pop_key();
Ok(())
}
}
| rust-cli__config-rs-465 | 465 | [
"464"
] | 0.13 | rust-cli/config-rs | 2023-10-04T17:23:11Z | diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -717,4 +732,28 @@ mod test {
let actual: Test = config.try_deserialize().unwrap();
assert_eq!(test, actual);
}
+
+ #[test]
+ fn test_nest() {
+ let val = serde_json::json! { {
+ "top": {
+ "num": 1,
+ "array": [2],
+ "nested": [[3,4]],
+ "deep": [{
+ "yes": true,
+ }],
+ "mixed": [
+ { "boolish": false, },
+ 42,
+ ["hi"],
+ { "inner": 66 },
+ 23,
+ ],
+ }
+ } };
+ let config = Config::try_from(&val).unwrap();
+ let output: serde_json::Value = config.try_deserialize().unwrap();
+ assert_eq!(val, output);
+ }
}
| Nested arrays badly mangled
To reproduce:
```
#[test]
fn list() {
let jtxt = r#" { "proxy_ports": [ [1,2] ] } "#;
let jval: serde_json::Value = serde_json::from_str(jtxt).unwrap();
//dbg!(&jval);
let jcfg = config::Config::try_from(&jval).unwrap();
//dbg!(&jcfg);
let jret: serde_json::Value = jcfg.clone().try_deserialize().unwrap();
println!("json roundtrip: {jret:#?}");
let ttxt = r#" proxy_ports = [ [1,2] ] "#;
let tval: toml::Value = toml::from_str(ttxt).unwrap();
//dbg!(&tval);
let tcfg = config::Config::try_from(&tval).unwrap();
//dbg!(&tcfg);
let tret: Result<String, _> = tcfg.clone().try_deserialize()
.map(|v: toml::Value| toml::to_string(&v).unwrap());
println!("toml roundtrip: {tret:#?}");
}
```
Expected output:
```
json roundtrip: Object {
"proxy_ports": Array [
Array [
Number(1),
Number(2),
],
],
}
toml roundtrip: Ok(
"proxy_ports = [[1, 2]]\n"
)
```
Actual output:
```
json roundtrip: Object {
"proxy_ports": Array [
Null,
Number(1),
Number(2),
],
}
toml roundtrip: Err(
invalid type: unit value, expected any valid TOML value,
)
```
Uncommenting the dbgs in the repro above shows this, which seems entirely wrong:
```
[crates/arti/src/onion_proxy.rs:143] &jcfg = Config {
defaults: {},
overrides: {
Subscript(
Identifier(
"proxy_ports",
),
1,
): Value {
origin: None,
kind: I64(
1,
),
},
Subscript(
Identifier(
"proxy_ports",
),
2,
): Value {
origin: None,
kind: I64(
2,
),
},
},
sources: [],
cache: Value {
origin: None,
kind: Table(
{
"proxy_ports": Value {
origin: None,
kind: Array(
[
Value {
origin: None,
kind: Nil,
},
Value {
origin: None,
kind: I64(
1,
),
},
Value {
origin: None,
kind: I64(
2,
),
},
],
),
},
},
),
},
}
```
| c7ab1c3790f4314107bc5d69cd7486482b5f08dc | [
"ser::test::test_nest"
] | [
"path::parser::test::test_child",
"path::parser::test::test_id",
"path::parser::test::test_subscript",
"path::parser::test::test_subscript_neg",
"path::parser::test::test_id_dash",
"ser::test::test_struct",
"value::tests::test_i64",
"test_single_async_file_source",
"test_async_file_sources_with_over... | [] | [] | |
4896caf29a71174eeb6af884bba84bb99ca9bb87 | diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,6 +17,24 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
+[[package]]
+name = "ahash"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
+
[[package]]
name = "android-tzdata"
version = "0.1.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -32,6 +50,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "arraydeque"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
+
[[package]]
name = "async-trait"
version = "0.1.74"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -169,7 +193,7 @@ dependencies = [
"tokio",
"toml",
"warp",
- "yaml-rust",
+ "yaml-rust2",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -531,6 +555,19 @@ name = "hashbrown"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156"
+dependencies = [
+ "ahash",
+ "allocator-api2",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7"
+dependencies = [
+ "hashbrown 0.14.2",
+]
[[package]]
name = "headers"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -771,12 +808,6 @@ version = "0.2.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b"
-[[package]]
-name = "linked-hash-map"
-version = "0.5.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
-
[[package]]
name = "linux-raw-sys"
version = "0.4.10"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2123,10 +2154,32 @@ dependencies = [
]
[[package]]
-name = "yaml-rust"
-version = "0.4.5"
+name = "yaml-rust2"
+version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
+checksum = "498f4d102a79ea1c9d4dd27573c0fc96ad74c023e8da38484e47883076da25fb"
dependencies = [
- "linked-hash-map",
+ "arraydeque",
+ "encoding_rs",
+ "hashlink",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,7 +17,7 @@ maintenance = { status = "actively-developed" }
[features]
default = ["toml", "json", "yaml", "ini", "ron", "json5", "convert-case", "async"]
json = ["serde_json"]
-yaml = ["yaml-rust"]
+yaml = ["yaml-rust2"]
ini = ["rust-ini"]
json5 = ["json5_rs", "serde/derive"]
convert-case = ["convert_case"]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -32,7 +32,7 @@ nom = "7"
async-trait = { version = "0.1", optional = true }
toml = { version = "0.8", optional = true }
serde_json = { version = "1.0", optional = true }
-yaml-rust = { version = "0.4", optional = true }
+yaml-rust2 = { version = "0.8", optional = true }
rust-ini = { version = "0.20", optional = true }
ron = { version = "0.8", optional = true }
json5_rs = { version = "0.4", optional = true, package = "json5" }
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@
[JSON]: https://github.com/serde-rs/json
[TOML]: https://github.com/toml-lang/toml
-[YAML]: https://github.com/chyh1990/yaml-rust
+[YAML]: https://github.com/Ethiraric/yaml-rust2
[INI]: https://github.com/zonyitoo/rust-ini
[RON]: https://github.com/ron-rs/ron
[JSON5]: https://github.com/callum-oakley/json5-rs
diff --git a/src/file/format/mod.rs b/src/file/format/mod.rs
--- a/src/file/format/mod.rs
+++ b/src/file/format/mod.rs
@@ -40,7 +40,7 @@ pub enum FileFormat {
#[cfg(feature = "json")]
Json,
- /// YAML (parsed with yaml_rust)
+ /// YAML (parsed with yaml_rust2)
#[cfg(feature = "yaml")]
Yaml,
diff --git a/src/file/format/yaml.rs b/src/file/format/yaml.rs
--- a/src/file/format/yaml.rs
+++ b/src/file/format/yaml.rs
@@ -2,7 +2,7 @@ use std::error::Error;
use std::fmt;
use std::mem;
-use yaml_rust as yaml;
+use yaml_rust2 as yaml;
use crate::format;
use crate::map::Map;
| rust-cli__config-rs-554 | 554 | more information here: https://github.com/rustsec/advisory-db/issues/1921
I have a PR open to switch to a different crate: https://github.com/mehcode/config-rs/pull/474
If anyone wants to pick up my work there that's appreciated, otherwise I plan to get my PRs for this project when I can spare the time. Presently I'm hoping for that to be in April/May but I keep getting tied up elsewhere ๐ฉ
`serde-yaml` used in https://github.com/mehcode/config-rs/pull/474 is also unmaintained ๐
> `serde-yaml` used in #474 is also unmaintained ๐
Oh I see it was archived with a [final release just 2 days ago](https://github.com/dtolnay/serde-yaml/releases/tag/0.9.34).
Perhaps it could be moved to the same rust org that config-rs is being relocated to for future maintenance? ๐คทโโ๏ธ | [
"553"
] | 0.14 | rust-cli/config-rs | 2024-03-27T06:40:15Z | diff --git a/tests/file_yaml.rs b/tests/file_yaml.rs
--- a/tests/file_yaml.rs
+++ b/tests/file_yaml.rs
@@ -85,8 +85,7 @@ fn test_error_parse() {
assert_eq!(
res.unwrap_err().to_string(),
format!(
- "while parsing a block mapping, did not find expected key at \
- line 2 column 1 in {}",
+ "simple key expect ':' at byte 21 line 3 column 1 in {}",
path_with_extension.display()
)
);
diff --git a/tests/legacy/file_yaml.rs b/tests/legacy/file_yaml.rs
--- a/tests/legacy/file_yaml.rs
+++ b/tests/legacy/file_yaml.rs
@@ -85,8 +85,7 @@ fn test_error_parse() {
assert_eq!(
res.unwrap_err().to_string(),
format!(
- "while parsing a block mapping, did not find expected key at \
- line 2 column 1 in {}",
+ "simple key expect ':' at byte 21 line 3 column 1 in {}",
path_with_extension.display()
)
);
| cargo-audit reports that `yaml-rust` is unmaintained
We are using this crate in https://github.com/rust-vmm/vhost-device/tree/main/vhost-device-vsock
We run `cargo-audit` in our CI which now is reporting that a dependency of this crate is unmaintained:
```
$ cargo audit
Fetching advisory database from `https://github.com/RustSec/advisory-db.git`
Loaded 615 security advisories (from /home/stefano/.cargo/advisory-db)
Updating crates.io index
Scanning Cargo.lock for vulnerabilities (177 crate dependencies)
Crate: yaml-rust
Version: 0.4.5
Warning: unmaintained
Title: yaml-rust is unmaintained.
Date: 2024-03-20
ID: RUSTSEC-2024-0320
URL: https://rustsec.org/advisories/RUSTSEC-2024-0320
Dependency tree:
yaml-rust 0.4.5
โโโ config 0.14.0
โโโ vhost-device-vsock 0.1.0
warning: 1 allowed warning found
```
| e3c1d0b452639478662a44f15ef6d5b6d969bf9b | [
"test_error_parse",
"legacy::file_yaml::test_error_parse"
] | [
"path::parser::test::test_id",
"path::parser::test::test_child",
"path::parser::test::test_id_dash",
"path::parser::test::test_subscript_neg",
"path::parser::test::test_subscript",
"ser::test::test_struct",
"value::tests::test_i64",
"ser::test::test_nest",
"test_single_async_file_source",
"test_as... | [] | [] |
20d37720b0342e68cd3c8c2c2a437b8634ec3642 | diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -39,7 +39,7 @@ impl Default for ConfigKind {
/// A prioritized configuration repository. It maintains a set of
/// configuration sources, fetches values to populate those, and provides
/// them according to the source's priority.
-#[derive(Default, Clone, Debug)]
+#[derive(Clone, Debug)]
pub struct Config {
kind: ConfigKind,
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -47,16 +47,16 @@ pub struct Config {
pub cache: Value,
}
-impl Config {
- pub fn new() -> Self {
- Self {
+impl Default for Config {
+ fn default() -> Self {
+ Config {
kind: ConfigKind::default(),
- // Config root should be instantiated as an empty table
- // to avoid deserialization errors.
cache: Value::new(None, Table::new()),
}
}
+}
+impl Config {
/// Merge in a configuration property source.
pub fn merge<T>(&mut self, source: T) -> Result<&mut Config>
where
| rust-cli__config-rs-184 | 184 | The automatic implementation of `Default` should be removed (I would move `::new` to a manual Default impl and delegate to the Default impl in new) and this should be fixed. Currently `Config::default()` can't be used if you want to rely on a `#[serde(default)]` annotation.
Sounds good. I think I can draft a PR. | [
"113"
] | 0.11 | rust-cli/config-rs | 2021-03-19T09:18:16Z | diff --git a/tests/defaults.rs b/tests/defaults.rs
--- a/tests/defaults.rs
+++ b/tests/defaults.rs
@@ -21,7 +21,7 @@ impl Default for Settings {
#[test]
fn set_defaults() {
- let c = Config::new();
+ let c = Config::default();
let s: Settings = c.try_into().expect("Deserialization failed");
assert_eq!(s.db_host, "default");
diff --git a/tests/empty.rs b/tests/empty.rs
--- a/tests/empty.rs
+++ b/tests/empty.rs
@@ -15,7 +15,9 @@ struct Settings {
#[test]
fn empty_deserializes() {
- let s: Settings = Config::new().try_into().expect("Deserialization failed");
+ let s: Settings = Config::default()
+ .try_into()
+ .expect("Deserialization failed");
assert_eq!(s.foo, 0);
assert_eq!(s.bar, 0);
}
diff --git a/tests/errors.rs b/tests/errors.rs
--- a/tests/errors.rs
+++ b/tests/errors.rs
@@ -120,7 +120,7 @@ inner:
test: ABC
"#;
- let mut cfg = Config::new();
+ let mut cfg = Config::default();
cfg.merge(File::from_str(CFG, FileFormat::Yaml)).unwrap();
let e = cfg.try_into::<Outer>().unwrap_err();
if let ConfigError::Type {
| Does `Config::new()` returns the same as `Config::default()`?
Does `Config::new()` returns (effectively) the same as `Config::default()`? If not, better to document how are they different. If so, should `Config::new()` just delegate to `Config::default()` in the implementation?
| bae775fc78b94ff5c9f29aeda4ade3baf3037a3d | [
"set_defaults",
"empty_deserializes"
] | [
"path::parser::test::test_child",
"path::parser::test::test_id",
"path::parser::test::test_id_dash",
"path::parser::test::test_subscript",
"path::parser::test::test_subscript_neg",
"ser::test::test_struct",
"test_datetime_string",
"test_datetime",
"try_from_defaults",
"test_default",
"test_prefi... | [] | [] |
8b41015dbb231a2e5e0be37698d49924a10b290f | diff --git a/src/de.rs b/src/de.rs
--- a/src/de.rs
+++ b/src/de.rs
@@ -62,25 +62,25 @@ impl<'de> de::Deserializer<'de> for Value {
#[inline]
fn deserialize_u8<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
// FIXME: This should *fail* if the value does not fit in the requets integer type
- visitor.visit_u8(self.into_int()? as u8)
+ visitor.visit_u8(self.into_uint()? as u8)
}
#[inline]
fn deserialize_u16<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
// FIXME: This should *fail* if the value does not fit in the requets integer type
- visitor.visit_u16(self.into_int()? as u16)
+ visitor.visit_u16(self.into_uint()? as u16)
}
#[inline]
fn deserialize_u32<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
// FIXME: This should *fail* if the value does not fit in the requets integer type
- visitor.visit_u32(self.into_int()? as u32)
+ visitor.visit_u32(self.into_uint()? as u32)
}
#[inline]
fn deserialize_u64<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
// FIXME: This should *fail* if the value does not fit in the requets integer type
- visitor.visit_u64(self.into_int()? as u64)
+ visitor.visit_u64(self.into_uint()? as u64)
}
#[inline]
diff --git a/src/value.rs b/src/value.rs
--- a/src/value.rs
+++ b/src/value.rs
@@ -1,3 +1,4 @@
+use std::convert::TryInto;
use std::fmt;
use std::fmt::Display;
diff --git a/src/value.rs b/src/value.rs
--- a/src/value.rs
+++ b/src/value.rs
@@ -269,21 +270,27 @@ impl Value {
pub fn into_int(self) -> Result<i64> {
match self.kind {
ValueKind::I64(value) => Ok(value),
- ValueKind::I128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::I128(value),
- "an signed 64 bit or less integer",
- )),
- ValueKind::U64(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::U64(value),
- "an signed 64 bit or less integer",
- )),
- ValueKind::U128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::U128(value),
- "an signed 64 bit or less integer",
- )),
+ ValueKind::I128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::I128(value),
+ "an signed 64 bit or less integer",
+ )
+ }),
+ ValueKind::U64(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::U64(value),
+ "an signed 64 bit or less integer",
+ )
+ }),
+ ValueKind::U128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::U128(value),
+ "an signed 64 bit or less integer",
+ )
+ }),
ValueKind::String(ref s) => {
match s.to_lowercase().as_ref() {
diff --git a/src/value.rs b/src/value.rs
--- a/src/value.rs
+++ b/src/value.rs
@@ -330,11 +337,13 @@ impl Value {
ValueKind::I64(value) => Ok(value.into()),
ValueKind::I128(value) => Ok(value),
ValueKind::U64(value) => Ok(value.into()),
- ValueKind::U128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::U128(value),
- "an signed 128 bit integer",
- )),
+ ValueKind::U128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::U128(value),
+ "an signed 128 bit integer",
+ )
+ }),
ValueKind::String(ref s) => {
match s.to_lowercase().as_ref() {
diff --git a/src/value.rs b/src/value.rs
--- a/src/value.rs
+++ b/src/value.rs
@@ -380,21 +389,27 @@ impl Value {
pub fn into_uint(self) -> Result<u64> {
match self.kind {
ValueKind::U64(value) => Ok(value),
- ValueKind::U128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::U128(value),
- "an unsigned 64 bit or less integer",
- )),
- ValueKind::I64(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::I64(value),
- "an unsigned 64 bit or less integer",
- )),
- ValueKind::I128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::I128(value),
- "an unsigned 64 bit or less integer",
- )),
+ ValueKind::U128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::U128(value),
+ "an unsigned 64 bit or less integer",
+ )
+ }),
+ ValueKind::I64(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::I64(value),
+ "an unsigned 64 bit or less integer",
+ )
+ }),
+ ValueKind::I128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::I128(value),
+ "an unsigned 64 bit or less integer",
+ )
+ }),
ValueKind::String(ref s) => {
match s.to_lowercase().as_ref() {
diff --git a/src/value.rs b/src/value.rs
--- a/src/value.rs
+++ b/src/value.rs
@@ -440,16 +455,20 @@ impl Value {
match self.kind {
ValueKind::U64(value) => Ok(value.into()),
ValueKind::U128(value) => Ok(value),
- ValueKind::I64(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::I64(value),
- "an unsigned 128 bit or less integer",
- )),
- ValueKind::I128(value) => Err(ConfigError::invalid_type(
- self.origin,
- Unexpected::I128(value),
- "an unsigned 128 bit or less integer",
- )),
+ ValueKind::I64(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::I64(value),
+ "an unsigned 128 bit or less integer",
+ )
+ }),
+ ValueKind::I128(value) => value.try_into().map_err(|_| {
+ ConfigError::invalid_type(
+ self.origin,
+ Unexpected::I128(value),
+ "an unsigned 128 bit or less integer",
+ )
+ }),
ValueKind::String(ref s) => {
match s.to_lowercase().as_ref() {
| rust-cli__config-rs-353 | 353 | [
"352"
] | 0.13 | rust-cli/config-rs | 2022-06-28T13:32:34Z | diff --git a/tests/env.rs b/tests/env.rs
--- a/tests/env.rs
+++ b/tests/env.rs
@@ -130,6 +130,39 @@ fn test_parse_int() {
})
}
+#[test]
+fn test_parse_uint() {
+ // using a struct in an enum here to make serde use `deserialize_any`
+ #[derive(Deserialize, Debug)]
+ #[serde(tag = "tag")]
+ enum TestUintEnum {
+ Uint(TestUint),
+ }
+
+ #[derive(Deserialize, Debug)]
+ struct TestUint {
+ int_val: u32,
+ }
+
+ temp_env::with_var("INT_VAL", Some("42"), || {
+ let environment = Environment::default().try_parsing(true);
+
+ let config = Config::builder()
+ .set_default("tag", "Uint")
+ .unwrap()
+ .add_source(environment)
+ .build()
+ .unwrap();
+
+ let config: TestUintEnum = config.try_deserialize().unwrap();
+
+ assert!(matches!(
+ config,
+ TestUintEnum::Uint(TestUint { int_val: 42 })
+ ));
+ })
+}
+
#[test]
fn test_parse_float() {
// using a struct in an enum here to make serde use `deserialize_any`
diff --git a/tests/env.rs b/tests/env.rs
--- a/tests/env.rs
+++ b/tests/env.rs
@@ -535,3 +568,43 @@ fn test_parse_off_string() {
}
})
}
+
+#[test]
+fn test_parse_int_default() {
+ #[derive(Deserialize, Debug)]
+ struct TestInt {
+ int_val: i32,
+ }
+
+ let environment = Environment::default().try_parsing(true);
+
+ let config = Config::builder()
+ .set_default("int_val", 42_i32)
+ .unwrap()
+ .add_source(environment)
+ .build()
+ .unwrap();
+
+ let config: TestInt = config.try_deserialize().unwrap();
+ assert_eq!(config.int_val, 42);
+}
+
+#[test]
+fn test_parse_uint_default() {
+ #[derive(Deserialize, Debug)]
+ struct TestUint {
+ int_val: u32,
+ }
+
+ let environment = Environment::default().try_parsing(true);
+
+ let config = Config::builder()
+ .set_default("int_val", 42_u32)
+ .unwrap()
+ .add_source(environment)
+ .build()
+ .unwrap();
+
+ let config: TestUint = config.try_deserialize().unwrap();
+ assert_eq!(config.int_val, 42);
+}
diff --git a/tests/integer_range.rs b/tests/integer_range.rs
--- a/tests/integer_range.rs
+++ b/tests/integer_range.rs
@@ -33,3 +33,20 @@ fn nonwrapping_u32() {
let port: u32 = c.get("settings.port").unwrap();
assert_eq!(port, 66000);
}
+
+#[test]
+#[should_panic]
+fn invalid_signedness() {
+ let c = Config::builder()
+ .add_source(config::File::from_str(
+ r#"
+ [settings]
+ port = -1
+ "#,
+ config::FileFormat::Toml,
+ ))
+ .build()
+ .unwrap();
+
+ let _: u32 = c.get("settings.port").unwrap();
+}
| Deserialization fails if set_default is passed an unsigned integer
Small motivating example that demonstrates the issue:
```rs
use config::{Config, Environment};
use serde::Deserialize;
use std::error::Error;
// Using any unsigned type here leads to a runtime deserialization error
// Runs fine when using i8, i16, i32, i64
const DEFAULT_BAR: u32 = 30;
fn main() -> Result<(), Box<dyn Error>> {
#[derive(Deserialize, Debug)]
struct Foo {
bar: u32,
}
let config: Foo = Config::builder()
.add_source(Environment::with_prefix("TEST"))
.set_default("bar", DEFAULT_BAR)?
.build()?
.try_deserialize()?;
dbg!(config.bar);
Ok(())
}
```
Output:
```
Error: invalid type: unsigned integer 64 bit `30`, expected an signed 64 bit or less integer for key `bar`
```
While looking into potentially fixing it, I noticed that `Value::into_uint` is defined but never used. Modifying the `deserialize_u32` method to use `into_uint` instead of `into_int` fixes this issue, but breaks some existing tests. I'm guessing that's because of the next observation:
`Value::into_int` and `Value::into_uint` both seem overly strict. For example, calling `Value::into_uint()` when the kind is a `ValueKind::I64` _always_ fails. Shouldn't we try a conversion using the `TryInto` trait and only fail if the conversion fails?
Draft PR showing what I'm envisioning: https://github.com/mehcode/config-rs/compare/master...kesyog:config-rs:kyogeswaran/deserialize-uints?expand=1
This looks potentially related to #93.
| c7ab1c3790f4314107bc5d69cd7486482b5f08dc | [
"test_parse_uint_default",
"invalid_signedness - should panic"
] | [
"path::parser::test::test_child",
"path::parser::test::test_id_dash",
"path::parser::test::test_subscript",
"path::parser::test::test_id",
"path::parser::test::test_subscript_neg",
"ser::test::test_struct",
"value::tests::test_i64",
"test_single_async_file_source",
"test_async_to_sync_file_sources",... | [] | [] | |
eec8d6d0cb7f65efa338d9b965788e887e28084f | diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -174,7 +174,7 @@ impl ConfigError {
}
/// Alias for a `Result` with the error type set to `ConfigError`.
-pub(crate) type Result<T> = result::Result<T, ConfigError>;
+pub(crate) type Result<T, E = ConfigError> = result::Result<T, E>;
// Forward Debug to Display for readable panic! messages
impl fmt::Debug for ConfigError {
diff --git a/src/path/mod.rs b/src/path/mod.rs
--- a/src/path/mod.rs
+++ b/src/path/mod.rs
@@ -40,11 +40,14 @@ impl std::fmt::Display for ParseError {
impl std::error::Error for ParseError {}
-fn sindex_to_uindex(index: isize, len: usize) -> usize {
+/// Convert a relative index into an absolute index
+fn abs_index(index: isize, len: usize) -> Result<usize, usize> {
if index >= 0 {
- index as usize
+ Ok(index as usize)
+ } else if let Some(index) = len.checked_sub(index.unsigned_abs()) {
+ Ok(index)
} else {
- len - index.unsigned_abs()
+ Err((len as isize + index).unsigned_abs())
}
}
diff --git a/src/path/mod.rs b/src/path/mod.rs
--- a/src/path/mod.rs
+++ b/src/path/mod.rs
@@ -80,13 +83,8 @@ impl Expression {
Self::Subscript(expr, index) => match expr.get(root) {
Some(value) => match value.kind {
ValueKind::Array(ref array) => {
- let index = sindex_to_uindex(index, array.len());
-
- if index >= array.len() {
- None
- } else {
- Some(&array[index])
- }
+ let index = abs_index(index, array.len()).ok()?;
+ array.get(index)
}
_ => None,
diff --git a/src/path/mod.rs b/src/path/mod.rs
--- a/src/path/mod.rs
+++ b/src/path/mod.rs
@@ -141,7 +139,7 @@ impl Expression {
match value.kind {
ValueKind::Array(ref mut array) => {
- let index = sindex_to_uindex(index, array.len());
+ let index = abs_index(index, array.len()).ok()?;
if index >= array.len() {
array.resize(index + 1, Value::new(None, ValueKind::Nil));
diff --git a/src/path/mod.rs b/src/path/mod.rs
--- a/src/path/mod.rs
+++ b/src/path/mod.rs
@@ -216,10 +214,21 @@ impl Expression {
}
if let ValueKind::Array(ref mut array) = parent.kind {
- let uindex = sindex_to_uindex(index, array.len());
- if uindex >= array.len() {
- array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
- }
+ let uindex = match abs_index(index, array.len()) {
+ Ok(uindex) => {
+ if uindex >= array.len() {
+ array.resize(uindex + 1, Value::new(None, ValueKind::Nil));
+ }
+ uindex
+ }
+ Err(insertion) => {
+ array.splice(
+ 0..0,
+ (0..insertion).map(|_| Value::new(None, ValueKind::Nil)),
+ );
+ 0
+ }
+ };
array[uindex] = value;
}
| rust-cli__config-rs-620 | 620 | [
"619"
] | 1.75 | rust-cli/config-rs | 2024-12-19T15:36:48Z | diff --git a/tests/testsuite/errors.rs b/tests/testsuite/errors.rs
--- a/tests/testsuite/errors.rs
+++ b/tests/testsuite/errors.rs
@@ -3,6 +3,52 @@ use snapbox::{assert_data_eq, str};
use config::{Config, ConfigError, File, FileFormat, Map, Value};
+#[test]
+#[cfg(feature = "json")]
+fn test_error_path_index_bounds() {
+ let c = Config::builder()
+ .add_source(File::from_str(
+ r#"
+{
+ "arr": [1]
+}
+"#,
+ FileFormat::Json,
+ ))
+ .build()
+ .unwrap();
+
+ let res = c.get::<usize>("arr[2]");
+ assert!(res.is_err());
+ assert_data_eq!(
+ res.unwrap_err().to_string(),
+ str![[r#"configuration property "arr[2]" not found"#]]
+ );
+}
+
+#[test]
+#[cfg(feature = "json")]
+fn test_error_path_index_negative_bounds() {
+ let c = Config::builder()
+ .add_source(File::from_str(
+ r#"
+{
+ "arr": []
+}
+"#,
+ FileFormat::Json,
+ ))
+ .build()
+ .unwrap();
+
+ let res = c.get::<usize>("arr[-1]");
+ assert!(res.is_err());
+ assert_data_eq!(
+ res.unwrap_err().to_string(),
+ str![[r#"configuration property "arr[-1]" not found"#]]
+ );
+}
+
#[test]
#[cfg(feature = "json")]
fn test_error_parse() {
diff --git a/tests/testsuite/set.rs b/tests/testsuite/set.rs
--- a/tests/testsuite/set.rs
+++ b/tests/testsuite/set.rs
@@ -65,27 +65,44 @@ fn test_set_scalar_path() {
#[cfg(feature = "json")]
fn test_set_arr_path() {
let config = Config::builder()
- .set_override("items[0].name", "Ivan")
+ .set_override("present[0].name", "Ivan")
.unwrap()
- .set_override("data[0].things[1].name", "foo")
+ .set_override("absent[0].things[1].name", "foo")
.unwrap()
- .set_override("data[0].things[1].value", 42)
+ .set_override("absent[0].things[1].value", 42)
.unwrap()
- .set_override("data[1]", 0)
+ .set_override("absent[1]", 0)
.unwrap()
- .set_override("items[2]", "George")
+ .set_override("present[2]", "George")
+ .unwrap()
+ .set_override("reverse[-1]", "Bob")
+ .unwrap()
+ .set_override("reverse[-2]", "Alice")
+ .unwrap()
+ .set_override("empty[-1]", "Bob")
+ .unwrap()
+ .set_override("empty[-2]", "Alice")
.unwrap()
.add_source(File::from_str(
r#"
{
- "items": [
+ "present": [
{
"name": "1"
},
{
"name": "2"
}
- ]
+ ],
+ "reverse": [
+ {
+ "name": "l1"
+ },
+ {
+ "name": "l2"
+ }
+ ],
+ "empty": []
}
"#,
FileFormat::Json,
diff --git a/tests/testsuite/set.rs b/tests/testsuite/set.rs
--- a/tests/testsuite/set.rs
+++ b/tests/testsuite/set.rs
@@ -93,14 +110,18 @@ fn test_set_arr_path() {
.build()
.unwrap();
- assert_eq!(config.get("items[0].name").ok(), Some("Ivan".to_owned()));
+ assert_eq!(config.get("present[0].name").ok(), Some("Ivan".to_owned()));
assert_eq!(
- config.get("data[0].things[1].name").ok(),
+ config.get("absent[0].things[1].name").ok(),
Some("foo".to_owned())
);
- assert_eq!(config.get("data[0].things[1].value").ok(), Some(42));
- assert_eq!(config.get("data[1]").ok(), Some(0));
- assert_eq!(config.get("items[2]").ok(), Some("George".to_owned()));
+ assert_eq!(config.get("absent[0].things[1].value").ok(), Some(42));
+ assert_eq!(config.get("absent[1]").ok(), Some(0));
+ assert_eq!(config.get("present[2]").ok(), Some("George".to_owned()));
+ assert_eq!(config.get("reverse[1]").ok(), Some("Bob".to_owned()));
+ assert_eq!(config.get("reverse[0]").ok(), Some("Alice".to_owned()));
+ assert_eq!(config.get("empty[1]").ok(), Some("Bob".to_owned()));
+ assert_eq!(config.get("empty[0]").ok(), Some("Alice".to_owned()));
}
#[test]
| panic on negative out-of-bounds array path expressions
The following program panics
```rust
// panics(release) with message: 'index out of bounds: the len is 0 but the index is 18446744073709551615'
// panics(debug) with message: 'attempt to subtract with overflow'
fn main() {
let _cfg = config::Config::builder()
// uncomment to prevent panic
// .set_override("a[0]", "0") .unwrap()
.set_override("a[-1]", "0")
.unwrap()
.build()
.unwrap();
}
```
If the out-of-bounds index is positive, then the array is resized implicitly and initialized with new 'nil' values. The resizing logic is flawed when negative indices are involved.
If you change the example to use an index of `-2`, then the (release mode) panic that you get becomes
> thread 'main' panicked at alloc/src/raw_vec.rs:24:5:
capacity overflow
I'm not sure how one should expect the array to be resized when a negative index is out of bounds (or if it should be accepted at all), but am sure that it shouldn't result in a panic.
| eec8d6d0cb7f65efa338d9b965788e887e28084f | [
"errors::test_error_path_index_negative_bounds",
"set::test_set_arr_path"
] | [
"path::parser::test::test_id_dash",
"path::parser::test::test_child",
"path::parser::test::test_id",
"path::parser::test::test_subscript",
"path::parser::test::test_subscript_neg",
"ser::test::test_struct",
"value::tests::test_i64",
"ser::test::test_nest",
"async_builder::test_single_async_file_sour... | [] | [] | |
2ded3480894a82a93d6e4d46c73676b50b76ff24 | diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -1,4 +1,5 @@
use std::fmt::Display;
+use std::fmt::Write as _;
use serde::ser;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -8,87 +9,83 @@ use crate::Config;
#[derive(Default, Debug)]
pub struct ConfigSerializer {
- keys: Vec<(String, Option<usize>)>,
+ keys: Vec<SerKey>,
pub output: Config,
}
+#[derive(Debug)]
+enum SerKey {
+ Named(String),
+ Seq(usize),
+}
+
+/// Serializer for numbered sequences
+///
+/// This wrapper is present when we are outputting a sequence (numbered indices).
+/// Making this a separate type centralises the handling of sequences
+/// and ensures we don't have any call sites for `ser::SerializeSeq::serialize_element`
+/// that don't do the necessary work of `SeqSerializer::new`.
+///
+/// Existence of this wrapper implies that `.0.keys.last()` is
+/// `Some(SerKey::Seq(next_index))`.
+pub struct SeqSerializer<'a>(&'a mut ConfigSerializer);
+
impl ConfigSerializer {
fn serialize_primitive<T>(&mut self, value: T) -> Result<()>
where
T: Into<Value> + Display,
{
- let key = match self.last_key_index_pair() {
- Some((key, Some(index))) => format!("{}[{}]", key, index),
- Some((key, None)) => key.to_string(),
- None => {
- return Err(ConfigError::Message(format!(
- "key is not found for value {}",
- value
- )))
- }
- };
+ // At some future point we could perhaps retain a cursor into the output `Config`,
+ // rather than reifying the whole thing into a single string with `make_full_key`
+ // and passing that whole path to the `set` method.
+ //
+ // That would be marginally more performant, but more fiddly.
+ let key = self.make_full_key()?;
#[allow(deprecated)]
self.output.set(&key, value.into())?;
Ok(())
}
- fn last_key_index_pair(&self) -> Option<(&str, Option<usize>)> {
- let len = self.keys.len();
- if len > 0 {
- self.keys
- .get(len - 1)
- .map(|&(ref key, opt)| (key.as_str(), opt))
- } else {
- None
- }
- }
+ fn make_full_key(&self) -> Result<String> {
+ let mut keys = self.keys.iter();
- fn inc_last_key_index(&mut self) -> Result<()> {
- let len = self.keys.len();
- if len > 0 {
- self.keys
- .get_mut(len - 1)
- .map(|pair| pair.1 = pair.1.map(|i| i + 1).or(Some(0)))
- .ok_or_else(|| {
- ConfigError::Message(format!("last key is not found in {} keys", len))
- })
- } else {
- Err(ConfigError::Message("keys is empty".to_string()))
- }
- }
+ let mut whole = match keys.next() {
+ Some(SerKey::Named(s)) => s.clone(),
+ _ => {
+ return Err(ConfigError::Message(
+ "top level is not a struct".to_string(),
+ ))
+ }
+ };
- fn make_full_key(&self, key: &str) -> String {
- let len = self.keys.len();
- if len > 0 {
- if let Some(&(ref prev_key, index)) = self.keys.get(len - 1) {
- return if let Some(index) = index {
- format!("{}[{}].{}", prev_key, index, key)
- } else {
- format!("{}.{}", prev_key, key)
- };
+ for k in keys {
+ match k {
+ SerKey::Named(s) => write!(whole, ".{}", s),
+ SerKey::Seq(i) => write!(whole, "[{}]", i),
}
+ .expect("write! to a string failed");
}
- key.to_string()
+
+ Ok(whole)
}
fn push_key(&mut self, key: &str) {
- let full_key = self.make_full_key(key);
- self.keys.push((full_key, None));
+ self.keys.push(SerKey::Named(key.to_string()));
}
- fn pop_key(&mut self) -> Option<(String, Option<usize>)> {
- self.keys.pop()
+ fn pop_key(&mut self) {
+ self.keys.pop();
}
}
impl<'a> ser::Serializer for &'a mut ConfigSerializer {
type Ok = ();
type Error = ConfigError;
- type SerializeSeq = Self;
- type SerializeTuple = Self;
- type SerializeTupleStruct = Self;
- type SerializeTupleVariant = Self;
+ type SerializeSeq = SeqSerializer<'a>;
+ type SerializeTuple = SeqSerializer<'a>;
+ type SerializeTupleStruct = SeqSerializer<'a>;
+ type SerializeTupleVariant = SeqSerializer<'a>;
type SerializeMap = Self;
type SerializeStruct = Self;
type SerializeStructVariant = Self;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -159,7 +156,8 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
for byte in v {
seq.serialize_element(byte)?;
}
- seq.end()
+ seq.end();
+ Ok(())
}
fn serialize_none(self) -> Result<Self::Ok> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -214,7 +212,7 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
- Ok(self)
+ SeqSerializer::new(self)
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -234,10 +232,10 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
_name: &'static str,
_variant_index: u32,
variant: &'static str,
- _len: usize,
+ len: usize,
) -> Result<Self::SerializeTupleVariant> {
self.push_key(variant);
- Ok(self)
+ self.serialize_seq(Some(len))
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -260,7 +258,21 @@ impl<'a> ser::Serializer for &'a mut ConfigSerializer {
}
}
-impl<'a> ser::SerializeSeq for &'a mut ConfigSerializer {
+impl<'a> SeqSerializer<'a> {
+ fn new(inner: &'a mut ConfigSerializer) -> Result<Self> {
+ inner.keys.push(SerKey::Seq(0));
+
+ Ok(SeqSerializer(inner))
+ }
+
+ fn end(self) -> &'a mut ConfigSerializer {
+ // This ought to be Some(SerKey::Seq(..)) but we don't want to panic if we are buggy
+ let _: Option<SerKey> = self.0.keys.pop();
+ self.0
+ }
+}
+
+impl<'a> ser::SerializeSeq for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -268,17 +280,25 @@ impl<'a> ser::SerializeSeq for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
+ value.serialize(&mut *(self.0))?;
+ match self.0.keys.last_mut() {
+ Some(SerKey::Seq(i)) => *i += 1,
+ _ => {
+ return Err(ConfigError::Message(
+ "config-rs internal error (ser._element but last not Seq!".to_string(),
+ ))
+ }
+ };
Ok(())
}
fn end(self) -> Result<Self::Ok> {
+ self.end();
Ok(())
}
}
-impl<'a> ser::SerializeTuple for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTuple for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -286,17 +306,15 @@ impl<'a> ser::SerializeTuple for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- Ok(())
+ ser::SerializeSeq::end(self)
}
}
-impl<'a> ser::SerializeTupleStruct for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTupleStruct for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -304,17 +322,15 @@ impl<'a> ser::SerializeTupleStruct for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- Ok(())
+ ser::SerializeSeq::end(self)
}
}
-impl<'a> ser::SerializeTupleVariant for &'a mut ConfigSerializer {
+impl<'a> ser::SerializeTupleVariant for SeqSerializer<'a> {
type Ok = ();
type Error = ConfigError;
diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -322,13 +338,12 @@ impl<'a> ser::SerializeTupleVariant for &'a mut ConfigSerializer {
where
T: ?Sized + ser::Serialize,
{
- self.inc_last_key_index()?;
- value.serialize(&mut **self)?;
- Ok(())
+ ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<Self::Ok> {
- self.pop_key();
+ let inner = self.end();
+ inner.pop_key();
Ok(())
}
}
| rust-cli__config-rs-486 | 486 | [
"464"
] | 0.13 | rust-cli/config-rs | 2023-10-23T16:38:33Z | diff --git a/src/ser.rs b/src/ser.rs
--- a/src/ser.rs
+++ b/src/ser.rs
@@ -717,4 +732,28 @@ mod test {
let actual: Test = config.try_deserialize().unwrap();
assert_eq!(test, actual);
}
+
+ #[test]
+ fn test_nest() {
+ let val = serde_json::json! { {
+ "top": {
+ "num": 1,
+ "array": [2],
+ "nested": [[3,4]],
+ "deep": [{
+ "yes": true,
+ }],
+ "mixed": [
+ { "boolish": false, },
+ 42,
+ ["hi"],
+ { "inner": 66 },
+ 23,
+ ],
+ }
+ } };
+ let config = Config::try_from(&val).unwrap();
+ let output: serde_json::Value = config.try_deserialize().unwrap();
+ assert_eq!(val, output);
+ }
}
| Nested arrays badly mangled
To reproduce:
```
#[test]
fn list() {
let jtxt = r#" { "proxy_ports": [ [1,2] ] } "#;
let jval: serde_json::Value = serde_json::from_str(jtxt).unwrap();
//dbg!(&jval);
let jcfg = config::Config::try_from(&jval).unwrap();
//dbg!(&jcfg);
let jret: serde_json::Value = jcfg.clone().try_deserialize().unwrap();
println!("json roundtrip: {jret:#?}");
let ttxt = r#" proxy_ports = [ [1,2] ] "#;
let tval: toml::Value = toml::from_str(ttxt).unwrap();
//dbg!(&tval);
let tcfg = config::Config::try_from(&tval).unwrap();
//dbg!(&tcfg);
let tret: Result<String, _> = tcfg.clone().try_deserialize()
.map(|v: toml::Value| toml::to_string(&v).unwrap());
println!("toml roundtrip: {tret:#?}");
}
```
Expected output:
```
json roundtrip: Object {
"proxy_ports": Array [
Array [
Number(1),
Number(2),
],
],
}
toml roundtrip: Ok(
"proxy_ports = [[1, 2]]\n"
)
```
Actual output:
```
json roundtrip: Object {
"proxy_ports": Array [
Null,
Number(1),
Number(2),
],
}
toml roundtrip: Err(
invalid type: unit value, expected any valid TOML value,
)
```
Uncommenting the dbgs in the repro above shows this, which seems entirely wrong:
```
[crates/arti/src/onion_proxy.rs:143] &jcfg = Config {
defaults: {},
overrides: {
Subscript(
Identifier(
"proxy_ports",
),
1,
): Value {
origin: None,
kind: I64(
1,
),
},
Subscript(
Identifier(
"proxy_ports",
),
2,
): Value {
origin: None,
kind: I64(
2,
),
},
},
sources: [],
cache: Value {
origin: None,
kind: Table(
{
"proxy_ports": Value {
origin: None,
kind: Array(
[
Value {
origin: None,
kind: Nil,
},
Value {
origin: None,
kind: I64(
1,
),
},
Value {
origin: None,
kind: I64(
2,
),
},
],
),
},
},
),
},
}
```
| c7ab1c3790f4314107bc5d69cd7486482b5f08dc | [
"ser::test::test_nest"
] | [
"path::parser::test::test_id",
"path::parser::test::test_child",
"path::parser::test::test_id_dash",
"path::parser::test::test_subscript_neg",
"path::parser::test::test_subscript",
"ser::test::test_struct",
"value::tests::test_i64",
"test_single_async_file_source",
"test_async_file_sources_with_over... | [] | [] | |
ad29f8f83566366671e6affd3887079d7165f5f9 | diff --git a/src/de.rs b/src/de.rs
--- a/src/de.rs
+++ b/src/de.rs
@@ -215,7 +215,7 @@ impl<'de> de::MapAccess<'de> for MapAccess {
K: de::DeserializeSeed<'de>,
{
if let Some(&(ref key_s, _)) = self.elements.front() {
- let key_de = StrDeserializer(key_s);
+ let key_de = Value::new(None, key_s as &str);
let key = de::DeserializeSeed::deserialize(seed, key_de)?;
Ok(Some(key))
| rust-cli__config-rs-119 | 119 | It just seems that we don't support it on our end probably due to oversight. This would be a bug that needs fixing.
I've hit this too and tried to report it to serde (because to me it looked like the generated Deserialize must have been wrong).
Anyway, I also have a workaround, look [here](https://github.com/serde-rs/serde/issues/1415) โ the trick with flattening another structure in. I don't know why it helps yet, though.
Huh. The code path for flatten might be strange. It's definitely our fault for the normal case though. Enums are handled different in the deserializer and we just are missing that.
I just wanted to ask, if the code is in master now, would it make sense to release it as part of 0.9.2, not waiting for full 0.10.0?
Released as 0.9.2
This seems not to work fully yet, this still fails :-( :
```rust
use std::collections::HashMap;
use config::{Config, File, FileFormat};
use serde::Deserialize;
#[derive(Debug, Eq, PartialEq, Hash, Deserialize)]
enum X {
A,
B,
}
const CFG: &str = r#"
A = "hello"
B = "world"
"#;
fn main() {
let mut config = Config::new();
config.merge(File::from_str(CFG, FileFormat::Toml)).unwrap();
let c: HashMap<X, String> = config.try_into().unwrap();
}
```
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: invalid type: string "b", expected enum X', src/libcore/result.rs:999:5
```
By the wayโฆ should I open a separate issue for the fact it tries to feed it with lower-case `b` instead of the `B` I put into the configuration? (but it still fails even if I rename the enum to accept lower-case version).
It does seem to work in value-position in a struct, though.
Can we reopen? Or should I open a new one?
Enums as keys are not supported yet and I doubt they will ever be. Configuration sources are transformed into simple intermediate representation, which is tree built of maps/arrays and strings/numbers as leafs. And keys can only be strings in these maps. Then this intermediate representation is transformed into whatever you ask, within certain limits imposed by simple config structure.
Enums with trivial constructors can be deserialized from string values with corresponding names. More complex enums are deserialized from config maps/arrays, as everything else.
If you want to get complex data structures deserialized from config, you will need to do additional work. In your example it is possible to get Map<String, String> first, and then simply deserialize enum from string.
With regards to lower-case - here is the issue about that https://github.com/mehcode/config-rs/issues/65
Right, I'm only interest in the case where it is a simple enum, without any carried data โ I just want to limit the choices of what might be used as the key. That sounds like something that should be possible in theory (the complex enums as keys is probably not possible because it doesn't make sense in the tree structure).
By the way, I discovered a workaround that works now (without additional post-processing of the config data structure). I can first `try_into` into a `serde_json::Value` and go from there.
Hm.. enums as configuration keys is a bit out-of-scope but I think we could make it work though. I'll leave this open to think through that. | [
"74"
] | 0.9 | rust-cli/config-rs | 2019-08-23T07:12:03Z | diff --git a/tests/Settings.toml b/tests/Settings.toml
--- a/tests/Settings.toml
+++ b/tests/Settings.toml
@@ -9,6 +9,7 @@ code = 53
boolean_s_parse = "fals"
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+quarks = ["up", "down", "strange", "charm", "bottom", "top"]
[diodes]
green = "off"
diff --git a/tests/Settings.toml b/tests/Settings.toml
--- a/tests/Settings.toml
+++ b/tests/Settings.toml
@@ -40,3 +41,13 @@ rating = 4.5
[place.creator]
name = "John Smith"
+
+[proton]
+up = 2
+down = 1
+
+[divisors]
+1 = 1
+2 = 2
+4 = 3
+5 = 2
diff --git a/tests/get.rs b/tests/get.rs
--- a/tests/get.rs
+++ b/tests/get.rs
@@ -9,7 +9,7 @@ extern crate serde_derive;
use config::*;
use float_cmp::ApproxEqUlps;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
#[derive(Debug, Deserialize)]
struct Place {
diff --git a/tests/get.rs b/tests/get.rs
--- a/tests/get.rs
+++ b/tests/get.rs
@@ -225,3 +225,42 @@ fn test_enum() {
assert_eq!(s.diodes["blue"], Diode::Blinking(300, 700));
assert_eq!(s.diodes["white"], Diode::Pattern{name: "christmas".into(), inifinite: true,});
}
+
+#[test]
+fn test_enum_key() {
+ #[derive(Debug, Deserialize, PartialEq, Eq, Hash)]
+ enum Quark {
+ Up,
+ Down,
+ Strange,
+ Charm,
+ Bottom,
+ Top,
+ }
+
+ #[derive(Debug, Deserialize)]
+ struct Settings {
+ proton: HashMap<Quark, usize>,
+ // Just to make sure that set keys work too.
+ quarks: HashSet<Quark>,
+ }
+
+ let c = make();
+ let s: Settings = c.try_into().unwrap();
+
+ assert_eq!(s.proton[&Quark::Up], 2);
+ assert_eq!(s.quarks.len(), 6);
+}
+
+#[test]
+fn test_int_key() {
+ #[derive(Debug, Deserialize, PartialEq)]
+ struct Settings {
+ divisors: HashMap<u32, u32>,
+ }
+
+ let c = make();
+ let s: Settings = c.try_into().unwrap();
+ assert_eq!(s.divisors[&4], 3);
+ assert_eq!(s.divisors.len(), 4);
+}
| Support Enum?
Got this error when try it with config-rs:
```
Err(invalid type: string "master", expected enum Mode)
```
Below is the struct and toml file:
```
#[derive(Debug, Deserialize)]
struct Database {
url: String,
mode: Mode,
}
#[derive(Debug, Deserialize)]
enum Mode {
Master,
Slave,
}
```
```
[database]
url = "postgres://postgres@localhost"
mode = "master"
```
toml supports Enum
https://github.com/alexcrichton/toml-rs/pull/165
am I doing anything wrong?
| ad29f8f83566366671e6affd3887079d7165f5f9 | [
"test_int_key",
"test_enum_key"
] | [
"path::parser::test::test_child",
"path::parser::test::test_id",
"path::parser::test::test_subscript",
"ser::test::test_struct",
"path::parser::test::test_subscript_neg",
"path::parser::test::test_id_dash",
"test_datetime_string",
"test_datetime",
"set_defaults",
"try_from_defaults",
"empty_dese... | [] | [] |
db19a77e8eb00ca813e093c99093906e47b12296 | diff --git a/src/docker/provided_images.rs b/src/docker/provided_images.rs
--- a/src/docker/provided_images.rs
+++ b/src/docker/provided_images.rs
@@ -78,16 +78,6 @@ pub static PROVIDED_IMAGES: &[ProvidedImage] = &[
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
sub: None
},
- ProvidedImage {
- name: "mips64-unknown-linux-muslabi64",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
- ProvidedImage {
- name: "mips64el-unknown-linux-muslabi64",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
ProvidedImage {
name: "powerpc-unknown-linux-gnu",
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
diff --git a/src/docker/provided_images.rs b/src/docker/provided_images.rs
--- a/src/docker/provided_images.rs
+++ b/src/docker/provided_images.rs
@@ -163,16 +153,6 @@ pub static PROVIDED_IMAGES: &[ProvidedImage] = &[
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
sub: None
},
- ProvidedImage {
- name: "mips-unknown-linux-musl",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
- ProvidedImage {
- name: "mipsel-unknown-linux-musl",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
ProvidedImage {
name: "aarch64-linux-android",
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
diff --git a/src/docker/provided_images.rs b/src/docker/provided_images.rs
--- a/src/docker/provided_images.rs
+++ b/src/docker/provided_images.rs
@@ -243,16 +223,6 @@ pub static PROVIDED_IMAGES: &[ProvidedImage] = &[
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
sub: None
},
- ProvidedImage {
- name: "sparcv9-sun-solaris",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
- ProvidedImage {
- name: "x86_64-sun-solaris",
- platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
- sub: None
- },
ProvidedImage {
name: "x86_64-unknown-illumos",
platforms: &[ImagePlatform::X86_64_UNKNOWN_LINUX_GNU],
diff --git a/xtask/src/build_docker_image.rs b/xtask/src/build_docker_image.rs
--- a/xtask/src/build_docker_image.rs
+++ b/xtask/src/build_docker_image.rs
@@ -137,6 +137,7 @@ pub fn build_docker_image(
targets = get_matrix()
.iter()
.filter(|m| m.os.starts_with("ubuntu"))
+ .filter(|m| !m.disabled)
.map(|m| m.to_image_target())
.collect();
} else {
diff --git a/xtask/src/ci/target_matrix.rs b/xtask/src/ci/target_matrix.rs
--- a/xtask/src/ci/target_matrix.rs
+++ b/xtask/src/ci/target_matrix.rs
@@ -34,6 +34,7 @@ pub enum TargetMatrixSub {
impl TargetMatrix {
pub(crate) fn run(&self) -> Result<(), color_eyre::Report> {
let mut matrix: Vec<CiTarget> = get_matrix().clone();
+ matrix.retain(|t| !t.disabled);
let mut is_default_try = false;
let pr: Option<String>;
let (prs, mut app) = match self {
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs
--- a/xtask/src/codegen.rs
+++ b/xtask/src/codegen.rs
@@ -5,11 +5,7 @@ use std::fmt::Write;
use crate::util::{get_cargo_workspace, get_matrix};
#[derive(Args, Debug)]
-pub struct Codegen {
- /// Provide verbose diagnostic output.
- #[clap(short, long)]
- verbose: bool,
-}
+pub struct Codegen {}
pub fn codegen(Codegen { .. }: Codegen) -> cross::Result<()> {
let path = get_cargo_workspace().join("src/docker/provided_images.rs");
diff --git a/xtask/src/codegen.rs b/xtask/src/codegen.rs
--- a/xtask/src/codegen.rs
+++ b/xtask/src/codegen.rs
@@ -28,7 +24,7 @@ pub static PROVIDED_IMAGES: &[ProvidedImage] = &["#,
for image_target in get_matrix()
.iter()
- .filter(|i| i.builds_image() && i.to_image_target().is_toolchain_image())
+ .filter(|i| i.builds_image() && i.to_image_target().is_toolchain_image() && !i.disabled)
{
write!(
&mut images,
| cross-rs__cross-1432 | 1,432 | [
"1425"
] | 0.2 | cross-rs/cross | 2024-02-01T20:55:10Z | diff --git a/ci/test-zig-image.sh b/ci/test-zig-image.sh
--- a/ci/test-zig-image.sh
+++ b/ci/test-zig-image.sh
@@ -16,8 +16,9 @@ ci_dir=$(realpath "${ci_dir}")
TARGETS=(
"aarch64-unknown-linux-gnu"
"aarch64-unknown-linux-musl"
- "i586-unknown-linux-gnu"
- "i586-unknown-linux-musl"
+ # disabled, see https://github.com/cross-rs/cross/issues/1425
+ #"i586-unknown-linux-gnu"
+ #"i586-unknown-linux-musl"
)
# on CI, it sets `CROSS_TARGET_ZIG_IMAGE` rather than `CROSS_BUILD_ZIG_IMAGE`
diff --git a/ci/test.sh b/ci/test.sh
--- a/ci/test.sh
+++ b/ci/test.sh
@@ -48,6 +48,10 @@ main() {
# don't use xargo: should have native support just from rustc
rustup toolchain add nightly
CROSS+=("+nightly")
+ elif [[ "${TARGET}" == "riscv64gc-unknown-linux-gnu" ]]; then
+ # FIXME: riscv64gc-unknown-linux-gnu is broken on rustc 1.75, see https://github.com/cross-rs/cross/issues/1423
+ rustup toolchain add 1.70
+ CROSS+=("+1.70")
fi
if (( ${STD:-0} )); then
diff --git a/ci/test.sh b/ci/test.sh
--- a/ci/test.sh
+++ b/ci/test.sh
@@ -89,6 +93,7 @@ main() {
popd
rm -rf "${td}"
+ # thumb targets are tested in later steps
elif [[ "${TARGET}" != thumb* ]]; then
td=$(mkcargotemp -d)
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -154,6 +154,7 @@ runners = "qemu-user qemu-system"
build-std = true
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1422
target = "mips64-unknown-linux-muslabi64"
os = "ubuntu-latest"
cpp = true
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -163,6 +164,7 @@ run = true
build-std = true
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1422
target = "mips64el-unknown-linux-muslabi64"
os = "ubuntu-latest"
# FIXME: Lacking partial C++ support due to missing compiler builtins.
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -302,6 +304,7 @@ run = true
runners = "qemu-user"
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1422
target = "mips-unknown-linux-musl"
os = "ubuntu-latest"
cpp = true
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -311,6 +314,7 @@ run = true
build-std = true
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1422
target = "mipsel-unknown-linux-musl"
os = "ubuntu-latest"
cpp = true
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -380,13 +384,14 @@ cpp = true
std = true
run = true
+[[target]]
# Disabled for now, see https://github.com/rust-lang/rust/issues/98216 & https://github.com/cross-rs/cross/issues/634
-# [[target]]
-# target = "asmjs-unknown-emscripten"
-# os = "ubuntu-latest"
-# cpp = true
-# std = true
-# run = true
+disabled = true
+target = "asmjs-unknown-emscripten"
+os = "ubuntu-latest"
+cpp = true
+std = true
+run = true
[[target]]
target = "wasm32-unknown-emscripten"
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -433,6 +438,7 @@ dylib = true
std = true
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1424
target = "sparcv9-sun-solaris"
os = "ubuntu-latest"
cpp = true
diff --git a/targets.toml b/targets.toml
--- a/targets.toml
+++ b/targets.toml
@@ -440,6 +446,7 @@ dylib = true
std = true
[[target]]
+disabled = true # https://github.com/cross-rs/cross/issues/1424
target = "x86_64-sun-solaris"
os = "ubuntu-latest"
cpp = true
diff --git a/xtask/src/ci/target_matrix.rs b/xtask/src/ci/target_matrix.rs
--- a/xtask/src/ci/target_matrix.rs
+++ b/xtask/src/ci/target_matrix.rs
@@ -411,6 +412,7 @@ mod tests {
#[track_caller]
fn run<'a>(args: impl IntoIterator<Item = &'a str>) -> Vec<CiTarget> {
let mut matrix = get_matrix().clone();
+ matrix.retain_mut(|t| !t.disabled);
TargetMatrixArgs::try_parse_from(args)
.unwrap()
.filter(&mut matrix);
diff --git a/xtask/src/ci/target_matrix.rs b/xtask/src/ci/target_matrix.rs
--- a/xtask/src/ci/target_matrix.rs
+++ b/xtask/src/ci/target_matrix.rs
@@ -468,7 +470,9 @@ mod tests {
#[test]
fn all() {
let matrix = run([]);
- assert_eq!(get_matrix(), &matrix);
+ let mut all = get_matrix().clone();
+ all.retain(|t| !t.disabled);
+ assert_eq!(&all, &matrix);
}
#[test]
diff --git a/xtask/src/util.rs b/xtask/src/util.rs
--- a/xtask/src/util.rs
+++ b/xtask/src/util.rs
@@ -64,6 +64,12 @@ pub struct CiTarget {
/// if `true` test no std support as if std does exists. If `false` build https://github.com/rust-lang/compiler-builtins
#[serde(skip_serializing_if = "Option::is_none")]
pub std: Option<bool>,
+ #[serde(skip_serializing_if = "is_false", default)]
+ pub disabled: bool,
+}
+
+pub fn is_false(b: &bool) -> bool {
+ !*b
}
impl CiTarget {
| Fix zig image
[zig](https://github.com/cross-rs/cross/actions/runs/7703230077/job/20993312365) - โ
```
Running `/target/debug/build/hellopp-4198e14c1842cfb5/build-script-build`
The following warnings were emitted during compilation:
warning: hellopp@0.1.0: error: unsupported linker arg: -melf_i386
error: failed to run custom build command for `hellopp v0.1.0 (/tmp/tmp.JaHyf9r5NC)`
Caused by:
process didn't exit successfully: `/target/debug/build/hellopp-4198e14c1842cfb5/build-script-build` (exit status: 1)
--- stdout
TARGET = Some("i586-unknown-linux-musl")
OPT_LEVEL = Some("0")
HOST = Some("x86_64-unknown-linux-gnu")
CXX_i586-unknown-linux-musl = None
CXX_i586_unknown_linux_musl = Some("/target/.zig-cache/cargo-zigbuild/0.17.3/zigcxx-i586-unknown-linux-musl.sh")
CXXFLAGS_i586-unknown-linux-musl = None
CXXFLAGS_i586_unknown_linux_musl = None
TARGET_CXXFLAGS = None
CXXFLAGS = None
CRATE_CC_NO_DEFAULTS = None
DEBUG = Some("true")
CARGO_CFG_TARGET_FEATURE = None
running: "/target/.zig-cache/cargo-zigbuild/0.17.3/zigcxx-i586-unknown-linux-musl.sh" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-fno-omit-frame-pointer" "-m32" "-march=pentium" "-Wl,-melf_i386" "-Wall" "-Wextra" "-o" "/target/i586-unknown-linux-musl/debug/build/hellopp-d2cec04140b3245e/out/hellopp.o" "-c" "hellopp.cc"
cargo:warning=error: unsupported linker arg: -melf_i386
exit status: 1
--- stderr
error occurred: Command "/target/.zig-cache/cargo-zigbuild/0.17.3/zigcxx-i586-unknown-linux-musl.sh" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-fno-omit-frame-pointer" "-m32" "-march=pentium" "-Wl,-melf_i386" "-Wall" "-Wextra" "-o" "/target/i586-unknown-linux-musl/debug/build/hellopp-d2cec04140b3245e/out/hellopp.o" "-c" "hellopp.cc" with args "zigcxx-i586-unknown-linux-musl.sh" did not execute successfully (status code exit status: 1).
```
this error is https://github.com/rust-cross/cargo-zigbuild/issues/96
I'm not sure if this is our fault or zigbuild
| d8631fe4f4e8bb4c4b24417a35544857fb42ee22 | [
"codegen::ensure_correct_codegen"
] | [
"changelog::tests::change_log_type_from_header",
"changelog::tests::changelog_contents_deserialize",
"changelog::tests::changelog_type_sort",
"changelog::tests::changelog_entry_display",
"changelog::tests::test_id_type_parse_changelog",
"changelog::tests::test_id_type_parse_stem",
"ci::target_matrix::te... | [] | [] | |
7b2c645a1a076646cedb10f1a8b0e53b20bd4a9d | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
### Fixed
+- #781 - ensure `target.$(...)` config options override `build` ones.
- #771 - fix parsing of `DOCKER_OPTS`.
- #727 - add `PKG_CONFIG_PATH` to all `*-linux-gnu` images.
- #722 - boolean environment variables are evaluated as truthy or falsey.
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -137,13 +137,13 @@ impl Config {
(None, None)
};
- match (env_build, toml_build) {
+ match (env_target, toml_target) {
(Some(value), _) => return Some(value),
(None, Some(value)) => return Some(value),
(None, None) => {}
};
- match (env_target, toml_target) {
+ match (env_build, toml_build) {
(Some(value), _) => return Some(value),
(None, Some(value)) => return Some(value),
(None, None) => {}
| cross-rs__cross-781 | 781 | [
"773"
] | 0.2 | cross-rs/cross | 2022-06-11T02:15:12Z | diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -360,7 +360,7 @@ mod tests {
map.insert("CROSS_TARGET_AARCH64_UNKNOWN_LINUX_GNU_XARGO", "true");
let env = Environment::new(Some(map));
let config = Config::new_with(Some(toml(TOML_BUILD_XARGO_FALSE)?), env);
- assert!(matches!(config.xargo(&target()), Some(false)));
+ assert!(matches!(config.xargo(&target()), Some(true)));
Ok(())
}
| Incorrect Environment Variable/Config Logic
### Checklist
- [X] I've looked through the [issues and pull requests](https://github.com/cross-rs/cross/issues?q=) for similar reports
### Describe your issue
The code for parsing some environment variable logic (for example, `xargo`) is as follows:
```rust
pub fn xargo(&self, target: &Target) -> Result<Option<bool>> {
let (build_xargo, target_xargo) = self.env.xargo(target);
let (toml_build_xargo, toml_target_xargo) = if let Some(ref toml) = self.toml {
toml.xargo(target)
} else {
(None, None)
};
match (build_xargo, toml_build_xargo) {
(Some(xargo), _) => return Ok(Some(xargo)),
(None, Some(xargo)) => return Ok(Some(xargo)),
(None, None) => {}
};
match (target_xargo, toml_target_xargo) {
(Some(xargo), _) => return Ok(Some(xargo)),
(None, Some(xargo)) => return Ok(Some(xargo)),
(None, None) => {}
};
Ok(None)
}
```
This means that if `build.env.xargo = true`, or `CROSS_BUILD_XARGO`, these will override the settings present in `target.$(...).env.xargo` and `CROSS_TARGET_$(...)_XARGO`. We should prefer more specific to less specific: if someone wants to enable `xargo` for all but a single target, it should respect that.
For example:
```toml
[build.env]
xargo = true
[target.aarch64-unknown-linux-gnu.env]
xargo = false
```
This means we should use `xargo` for all targets **but** `aarch64-unknown-linux-gnu`, but we currently use it for all targets.
### What target(s) are you cross-compiling for?
_No response_
### Which operating system is the host (e.g computer cross is on) running?
- [ ] macOS
- [ ] Windows
- [ ] Linux / BSD
- [ ] other OS (specify in description)
### What architecture is the host?
- [ ] x86_64 / AMD64
- [ ] arm32
- [ ] arm64 (including Mac M1)
### What container engine is cross using?
- [ ] docker
- [ ] podman
- [ ] other container engine (specify in description)
### cross version
cross 0.2.1 (ee2fc1b 2022-06-09)
### Example
_No response_
### Additional information / notes
_No response_
| d8631fe4f4e8bb4c4b24417a35544857fb42ee22 | [
"config::tests::test_config::env_target_and_toml_build_xargo_then_use_toml"
] | [
"config::tests::test_config::env_and_toml_build_xargo_then_use_env",
"config::tests::test_config::env_and_toml_default_target_then_use_env",
"config::tests::test_config::no_env_and_no_toml_default_target_then_none",
"config::tests::test_config::no_env_but_toml_default_target_then_use_toml",
"config::tests::... | [] | [] | |
1d9d31080c641d37d5213992f12a557d8e47664e | diff --git /dev/null b/.changes/1183.json
new file mode 100644
--- /dev/null
+++ b/.changes/1183.json
@@ -0,0 +1,5 @@
+{
+ "description": "resolve issue when using `pre-build` and `image.toolchain` in `Cargo.toml`",
+ "type": "fixed",
+ "issues": [1182]
+}
diff --git a/src/docker/custom.rs b/src/docker/custom.rs
--- a/src/docker/custom.rs
+++ b/src/docker/custom.rs
@@ -25,7 +25,7 @@ pub enum Dockerfile<'a> {
},
}
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
pub enum PreBuild {
/// A path to a file to copy or a single line to `RUN` if line comes from env
Single { line: String, env: bool },
diff --git a/src/docker/custom.rs b/src/docker/custom.rs
--- a/src/docker/custom.rs
+++ b/src/docker/custom.rs
@@ -33,6 +33,21 @@ pub enum PreBuild {
Lines(Vec<String>),
}
+impl serde::Serialize for PreBuild {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ match self {
+ PreBuild::Single { line, .. } => serializer.serialize_str(line),
+ PreBuild::Lines(lines) => {
+ use serde::ser::SerializeSeq;
+ let mut seq = serializer.serialize_seq(Some(lines.len()))?;
+ for line in lines {
+ seq.serialize_element(line)?;
+ }
+ seq.end()
+ }
+ }
+ }
+}
impl FromStr for PreBuild {
type Err = std::convert::Infallible;
diff --git a/src/docker/image.rs b/src/docker/image.rs
--- a/src/docker/image.rs
+++ b/src/docker/image.rs
@@ -104,8 +104,8 @@ impl std::fmt::Display for PossibleImage {
/// The architecture/platform to use in the image
///
/// https://github.com/containerd/containerd/blob/release/1.6/platforms/platforms.go#L63
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(try_from = "&str")]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
+#[serde(try_from = "String")]
pub struct ImagePlatform {
/// CPU architecture, x86_64, aarch64 etc
pub architecture: Architecture,
diff --git a/src/docker/image.rs b/src/docker/image.rs
--- a/src/docker/image.rs
+++ b/src/docker/image.rs
@@ -141,14 +141,20 @@ impl Default for ImagePlatform {
}
}
-impl TryFrom<&str> for ImagePlatform {
+impl TryFrom<String> for ImagePlatform {
type Error = <Self as std::str::FromStr>::Err;
- fn try_from(value: &str) -> Result<Self, Self::Error> {
+ fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse()
}
}
+impl Serialize for ImagePlatform {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(&format!("{}={}", self.docker_platform(), self.target))
+ }
+}
+
impl std::str::FromStr for ImagePlatform {
type Err = eyre::Report;
// [os/arch[/variant]=]toolchain
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -70,8 +70,8 @@ pub use self::rustc::{TargetList, VersionMetaExt};
pub const CROSS_LABEL_DOMAIN: &str = "org.cross-rs";
#[allow(non_camel_case_types)]
-#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Hash, Serialize)]
-#[serde(from = "&str")]
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Hash)]
+#[serde(from = "&str", into = "String")]
#[serde(rename_all = "snake_case")]
pub enum TargetTriple {
Other(String),
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -261,6 +261,12 @@ impl From<String> for TargetTriple {
}
}
+impl Serialize for TargetTriple {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(self.triple())
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
#[serde(from = "String")]
pub enum Target {
| cross-rs__cross-1183 | 1,183 | This should work in `Cargo.toml`, the issue is how we're doing the deserialization
https://github.com/cross-rs/cross/blob/1d9d31080c641d37d5213992f12a557d8e47664e/src/cross_toml.rs#L177
and https://github.com/cross-rs/cross/blob/1d9d31080c641d37d5213992f12a557d8e47664e/src/docker/image.rs#L108-L108
Alright, that was wrong, it's a bit more "wierd".
When merging, we create a `CrossToml` from the metadata here:
https://github.com/cross-rs/cross/blob/1d9d31080c641d37d5213992f12a557d8e47664e/src/cross_toml.rs#L213-L213
this works fine in most cases, however, when the serialization does not match the deserialization, this fails when they do not match (i.e it can be either a toml string or array).
Solution is to serialize https://github.com/cross-rs/cross/blob/1d9d31080c641d37d5213992f12a557d8e47664e/src/docker/image.rs#L104-L117 as a string
| [
"1182"
] | 0.2 | cross-rs/cross | 2023-01-06T02:55:04Z | diff --git a/src/cross_toml.rs b/src/cross_toml.rs
--- a/src/cross_toml.rs
+++ b/src/cross_toml.rs
@@ -855,6 +855,29 @@ mod tests {
Ok(())
}
+ #[test]
+ pub fn fully_populated_roundtrip() -> Result<()> {
+ let cfg = r#"
+ [target.a]
+ xargo = false
+ build-std = true
+ image.name = "local"
+ image.toolchain = ["x86_64-unknown-linux-gnu"]
+ dockerfile.file = "Dockerfile"
+ dockerfile.context = ".."
+ pre-build = ["sh"]
+ zig = true
+
+ [target.b]
+ pre-build = "sh"
+ zig = "2.17"
+ "#;
+
+ let (cfg, _) = CrossToml::parse_from_cross(cfg, &mut m!())?;
+ serde_json::from_value::<CrossToml>(serde_json::to_value(cfg)?)?;
+ Ok(())
+ }
+
#[test]
pub fn merge() -> Result<()> {
let cfg1_str = r#"
diff --git a/src/tests/toml.rs b/src/tests/toml.rs
--- a/src/tests/toml.rs
+++ b/src/tests/toml.rs
@@ -61,14 +61,17 @@ fn toml_check() -> Result<(), Box<dyn std::error::Error>> {
text_line_no(&contents, fence.range().start),
);
let mut msg_info = crate::shell::MessageInfo::default();
- assert!(if !cargo {
+ let toml = if !cargo {
crate::cross_toml::CrossToml::parse_from_cross(&fence_content, &mut msg_info)?
} else {
crate::cross_toml::CrossToml::parse_from_cargo(&fence_content, &mut msg_info)?
.unwrap_or_default()
- }
- .1
- .is_empty());
+ };
+ assert!(toml.1.is_empty());
+
+ // TODO: Add serde_path_to_error
+ // Check if roundtrip works, needed for merging Cross.toml and Cargo.toml
+ serde_json::from_value::<crate::cross_toml::CrossToml>(serde_json::to_value(toml.0)?)?;
}
}
Ok(())
| Config in Cargo.toml: invalid type: map, expected a string for key `target.x86_64-unknown-freebsd.image`
### Checklist
- [X] I've looked through the [issues and pull requests](https://github.com/cross-rs/cross/issues?q=) for similar reports
### Describe your issue
Related: https://github.com/cross-rs/cross/issues/657
### What target(s) are you cross-compiling for?
x86_64-unknown-freebsd
### Which operating system is the host (e.g computer cross is on) running?
- [X] macOS
- [ ] Windows
- [ ] Linux / BSD
- [ ] other OS (specify in description)
### What architecture is the host?
- [ ] x86_64 / AMD64
- [ ] arm32
- [X] arm64 (including Mac M1)
### What container engine is cross using?
- [X] docker
- [ ] podman
- [ ] other container engine (specify in description)
### cross version
cross 0.2.4
### Example
```console
$ cargo new foo && cd $_
$ cat <<'EOF' >> Cargo.toml
๏ปฟ๏ปฟ๏ปฟ[package.metadata.cross.target.x86_64-unknown-freebsd]
image.name = "ghcr.io/cross-rs/x86_64-unknown-freebsd:local"
image.toolchain = ["linux/arm64/v8=aarch64-unknown-linux-gnu"]
EOF
$ cross build --target x86_64-unknown-freebsd --release
```
Using cross 0.2.4 from nixpkgs or crates.io, I get:
```
Error:
0: invalid type: map, expected a string for key `target.x86_64-unknown-freebsd.image`
```
Using cross from `main`, I get a different error:
```console
$ cargo install cross --git https://github.com/cross-rs/cross
$ cross --version
cross 0.2.4 (1d9d310 2023-01-05)
$ cross build --target x86_64-unknown-freebsd --release
Error:
0: invalid type: string "linux/arm64/v8=aarch64-unknown-linux-gnu", expected a borrowed string for key `target.x86_64-unknown-freebsd.image.toolchain`
Location:
src/cross_toml.rs:181
```
If I instead put (what I believe to be) the analogous table into `Cross.toml`, I get the same error with nixpkgs and crates.io but it works fine from `main`:
```console
$ cat <<'EOF' > Cross.toml
[target.x86_64-unknown-freebsd]
image.name = "ghcr.io/cross-rs/x86_64-unknown-freebsd:local"
image.toolchain = ["linux/arm64/v8=aarch64-unknown-linux-gnu"]
EOF
$ cross --version
cross 0.2.4 (1d9d310 2023-01-05)
[cross] warning: `cross` does not provide a Docker image for target aarch64-apple-darwin, specify a custom image in `Cross.toml`.
[cross] note: Falling back to `cargo` on the host.
cargo 1.66.0 (d65d197ad 2022-11-15)
$ cross build --target x86_64-unknown-freebsd --release
Compiling foo v0.1.0 (/private/var/folders/kb/tw_lp_xd2_bbv0hqk4m0bvt80000gn/T/tmp.ililnMNd9D/foo)
Finished release [optimized] target(s) in 8.52s
```
Using the current `main`, as recommended in the README, is it expected that this table works from `Cross.toml` but not from `Cargo.toml`?
Thanks for your work on a cool project!
### Additional information / notes
_No response_
| d8631fe4f4e8bb4c4b24417a35544857fb42ee22 | [
"tests::toml::toml_check",
"cross_toml::tests::fully_populated_roundtrip"
] | [
"cli::tests::is_verbose_test",
"config::tests::test_config::env_target_and_toml_build_xargo_then_use_toml",
"config::tests::test_config::env_target_and_toml_target_xargo_target_then_use_env",
"config::tests::test_config::env_and_toml_default_target_then_use_env",
"config::tests::test_config::toml_build_pass... | [] | [] |
f059d1a924deac59aacc4a3560a91e52ce32164e | diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased] - ReleaseDate
+### Added
+
+- #890 - support rootless docker via the `CROSS_ROOTLESS_CONTAINER_ENGINE` environment variable.
+
### Changed
- #869 - ensure cargo configuration environment variable flags are passed to the docker container.
diff --git a/src/docker/shared.rs b/src/docker/shared.rs
--- a/src/docker/shared.rs
+++ b/src/docker/shared.rs
@@ -6,7 +6,7 @@ use std::{env, fs};
use super::custom::Dockerfile;
use super::engine::*;
use crate::cargo::{cargo_metadata_with_args, CargoMetadata};
-use crate::config::Config;
+use crate::config::{bool_from_envvar, Config};
use crate::errors::*;
use crate::extensions::{CommandExt, SafeCommand};
use crate::file::{self, write_file, PathExt, ToUtf8};
diff --git a/src/docker/shared.rs b/src/docker/shared.rs
--- a/src/docker/shared.rs
+++ b/src/docker/shared.rs
@@ -399,8 +399,17 @@ pub(crate) fn group_id() -> String {
}
pub(crate) fn docker_user_id(docker: &mut Command, engine_type: EngineType) {
- // We need to specify the user for Docker, but not for Podman.
- if engine_type == EngineType::Docker {
+ // by default, docker runs as root so we need to specify the user
+ // so the resulting file permissions are for the current user.
+ // since we can have rootless docker, we provide an override.
+ let is_rootless = env::var("CROSS_ROOTLESS_CONTAINER_ENGINE")
+ .ok()
+ .and_then(|s| match s.as_ref() {
+ "auto" => None,
+ b => Some(bool_from_envvar(b)),
+ })
+ .unwrap_or_else(|| engine_type != EngineType::Docker);
+ if !is_rootless {
docker.args(&["--user", &format!("{}:{}", user_id(), group_id(),)]);
}
}
| cross-rs__cross-890 | 890 | [
"889"
] | 0.2 | cross-rs/cross | 2022-07-01T04:45:06Z | diff --git a/src/docker/shared.rs b/src/docker/shared.rs
--- a/src/docker/shared.rs
+++ b/src/docker/shared.rs
@@ -648,6 +657,50 @@ pub fn path_hash(path: &Path) -> Result<String> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::id;
+
+ #[test]
+ fn test_docker_user_id() {
+ let var = "CROSS_ROOTLESS_CONTAINER_ENGINE";
+ let old = env::var(var);
+ env::remove_var(var);
+
+ let rootful = format!("\"engine\" \"--user\" \"{}:{}\"", id::user(), id::group());
+ let rootless = "\"engine\"".to_string();
+
+ let test = |engine, expected| {
+ let mut cmd = Command::new("engine");
+ docker_user_id(&mut cmd, engine);
+ assert_eq!(expected, &format!("{cmd:?}"));
+ };
+ test(EngineType::Docker, &rootful);
+ test(EngineType::Podman, &rootless);
+ test(EngineType::PodmanRemote, &rootless);
+ test(EngineType::Other, &rootless);
+
+ env::set_var(var, "0");
+ test(EngineType::Docker, &rootful);
+ test(EngineType::Podman, &rootful);
+ test(EngineType::PodmanRemote, &rootful);
+ test(EngineType::Other, &rootful);
+
+ env::set_var(var, "1");
+ test(EngineType::Docker, &rootless);
+ test(EngineType::Podman, &rootless);
+ test(EngineType::PodmanRemote, &rootless);
+ test(EngineType::Other, &rootless);
+
+ env::set_var(var, "auto");
+ test(EngineType::Docker, &rootful);
+ test(EngineType::Podman, &rootless);
+ test(EngineType::PodmanRemote, &rootless);
+ test(EngineType::Other, &rootless);
+
+ match old {
+ Ok(v) => env::set_var(var, v),
+ Err(_) => env::remove_var(var),
+ }
+ }
mod mount_finder {
use super::*;
| Support Rootless Docker
### Checklist
- [X] I've looked through the [issues and pull requests](https://github.com/cross-rs/cross/issues?q=) for similar request
- [ ] This feature could be solved with a [custom docker image](https://github.com/cross-rs/cross#custom-docker-images) (optional)
### Describe your request
Currently, if using rootless docker, `cross` fails to run. This is because we automatically add `--user 1000:1000` permissions (or the current UID/GID) when running Docker. This is an issue, because there is now rootless docker:
First, install rootless docker:
```bash
$ dockerd-rootless-setuptool.sh install # this may require a --force if the rootful docker is available.
```
Then, use the rootless context and try to touch a file:
```bash
$ docker context use rootless
rootless
Current context is now "rootless"
$ docker run --user 1000:1000 -it --rm -v "$PWD":/project -w /project ubuntu:20.04 bash
groups: cannot find name for group ID 1000
$ touch a
touch: cannot touch 'a': Permission denied
```
This can be solved by allowing an environment variable to override our default, good assumptions of whether the container engine is rootful or not.
### Describe why this would be a good inclusion for `cross`
Currently, detecting rootful/rootless mode is quite difficult, or expensive computationally, and the defaults are quite good:
- Podman always runs rootless
- Docker mostly runs rootful
Therefore, just making these assumptions generally works. However, this is an issue if rootless docker exists, or we have another container engine that runs as root. In short, we need to be able to override setting `--user 1000:1000` permissions. This likely could best be done with a `CROSS_ROOTLESS_CONTAINER_ENGINE`, which is an `Option<bool>`, parsed via `bool_from_envvar`. If it's not present, use the sensible default. If it is present, force the presence or absence of lower user permissions.
This also should simplify supporting new container engines, since we can handle those with varying behavior quite easily, without any code changes, until we can provide reasonable defaults for them, such as in #588.
| d8631fe4f4e8bb4c4b24417a35544857fb42ee22 | [
"docker::shared::tests::test_docker_user_id"
] | [
"config::tests::test_config::env_and_toml_default_target_then_use_env",
"config::tests::test_config::env_target_and_toml_build_xargo_then_use_toml",
"config::tests::test_config::no_env_and_no_toml_default_target_then_none",
"config::tests::test_config::env_and_toml_build_xargo_then_use_env",
"config::tests:... | [] | [] | |
7c06ad9f8b195d2a1867b176bf9335721f3186cd | diff --git a/xtask/src/util.rs b/xtask/src/util.rs
--- a/xtask/src/util.rs
+++ b/xtask/src/util.rs
@@ -165,17 +165,23 @@ impl std::str::FromStr for ImageTarget {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
- if let Some((target, sub)) = s.split_once('.') {
- Ok(ImageTarget {
- name: target.to_string(),
- sub: Some(sub.to_string()),
- })
- } else {
- Ok(ImageTarget {
- name: s.to_string(),
- sub: None,
- })
+ // we designate certain targets like `x86_64-unknown-linux-gnu.centos`,
+ // where `centos` is a subtype of `x86_64-unknown-linux-gnu`. however,
+ // LLVM triples can also contain `.` characters, such as with
+ // `thumbv8m.main-none-eabihf`, so we make sure it's only at the end.
+ if let Some((target, sub)) = s.rsplit_once('.') {
+ if sub.chars().all(|x| char::is_ascii_alphabetic(&x)) {
+ return Ok(ImageTarget {
+ name: target.to_string(),
+ sub: Some(sub.to_string()),
+ });
+ }
}
+
+ Ok(ImageTarget {
+ name: s.to_string(),
+ sub: None,
+ })
}
}
| cross-rs__cross-1022 | 1,022 | [
"1020"
] | 0.2 | cross-rs/cross | 2022-09-12T17:54:54Z | diff --git a/xtask/src/util.rs b/xtask/src/util.rs
--- a/xtask/src/util.rs
+++ b/xtask/src/util.rs
@@ -270,6 +276,40 @@ mod tests {
use cross::shell::Verbosity;
use std::collections::BTreeMap;
+ #[test]
+ fn test_parse_image_target() {
+ assert_eq!(
+ ImageTarget {
+ name: "x86_64-unknown-linux-gnu".to_owned(),
+ sub: None,
+ },
+ "x86_64-unknown-linux-gnu".parse().unwrap()
+ );
+ assert_eq!(
+ ImageTarget {
+ name: "x86_64-unknown-linux-gnu".to_owned(),
+ sub: Some("centos".to_owned()),
+ },
+ "x86_64-unknown-linux-gnu.centos".parse().unwrap()
+ );
+ assert_eq!(
+ ImageTarget {
+ name: "thumbv8m.main-none-eabihf".to_owned(),
+ sub: None,
+ },
+ "thumbv8m.main-none-eabihf".parse().unwrap()
+ );
+ assert_eq!(
+ ImageTarget {
+ name: "thumbv8m.main-unknown-linux-gnueabihf".to_owned(),
+ sub: Some("alpine".to_owned()),
+ },
+ "thumbv8m.main-unknown-linux-gnueabihf.alpine"
+ .parse()
+ .unwrap()
+ );
+ }
+
#[test]
fn check_ubuntu_base() -> cross::Result<()> {
// count all the entries of FROM for our images
| Future-Proofing Images with Subs
Rust triples are allowed to contain `.` characters, although I believe this is limited only to the architecture portion of the triple (and not the OS, vendor, or environment). For example, `thumbv8m.main-none-eabihf` is a valid LLVM triple. This means that splitting on a `.` character isn't necessarily going to give us our desired sub, and might produce erroneous results in the future.
We can get a bit more clarity looking at the comments in the [llvm/ADT/Triple.h](https://llvm.org/doxygen/Triple_8h_source.html) header. First, we want too look into the [parser](https://llvm.org/doxygen/Triple_8cpp_source.html#l00941), in `std::string Triple::normalize(StringRef Str)`. This isn't too bad, since it splits off into `parseArch`, `parseSubArch`, `parseVendor`, `parseOS`, and `parseEnvironment`.
We can see `parseArch` has some known values, and special cases for ARM and BPF-family architectures. The vendors are hard-coded and only accepted ASCII lowercase letters. The OSes and environments only expect strings **starting** with ASCII numbers and letters, but are flexible for any possible characters (other than `-`) at the end of each identifier. The architecture field, however, will accept `.` characters for a few targets.
In short, the following code isn't generalizable enough: this will cause an invalid target/sub to be parsed from some valid Rust triples:
https://github.com/cross-rs/cross/blob/7c06ad9f8b195d2a1867b176bf9335721f3186cd/xtask/src/util.rs#L164-L180
| d8631fe4f4e8bb4c4b24417a35544857fb42ee22 | [
"util::tests::test_parse_image_target"
] | [
"changelog::tests::change_log_type_from_header",
"changelog::tests::changelog_type_sort",
"changelog::tests::changelog_entry_display",
"changelog::tests::changelog_contents_deserialize",
"changelog::tests::test_id_type_parse_changelog",
"changelog::tests::test_id_type_parse_stem",
"changelog::tests::rea... | [] | [] | |
f7063d9160671ab3be4b4add8d19271abb022cbd | diff --git a/src/event.rs b/src/event.rs
--- a/src/event.rs
+++ b/src/event.rs
@@ -73,6 +73,7 @@
//! them (`event-*`).
use std::fmt;
+use std::hash::{Hash, Hasher};
use std::time::Duration;
use bitflags::bitflags;
diff --git a/src/event.rs b/src/event.rs
--- a/src/event.rs
+++ b/src/event.rs
@@ -385,7 +386,7 @@ bitflags! {
/// Represents a key event.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
-#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
+#[derive(Debug, PartialOrd, Clone, Copy)]
pub struct KeyEvent {
/// The key itself.
pub code: KeyCode,
diff --git a/src/event.rs b/src/event.rs
--- a/src/event.rs
+++ b/src/event.rs
@@ -397,6 +398,23 @@ impl KeyEvent {
pub fn new(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
KeyEvent { code, modifiers }
}
+
+ // modifies the KeyEvent,
+ // so that KeyModifiers::SHIFT is present iff
+ // an uppercase char is present.
+ fn normalize_case(mut self) -> KeyEvent {
+ let c = match self.code {
+ KeyCode::Char(c) => c,
+ _ => return self,
+ };
+
+ if c.is_ascii_uppercase() {
+ self.modifiers.insert(KeyModifiers::SHIFT);
+ } else if self.modifiers.contains(KeyModifiers::SHIFT) {
+ self.code = KeyCode::Char(c.to_ascii_uppercase())
+ }
+ self
+ }
}
impl From<KeyCode> for KeyEvent {
diff --git a/src/event.rs b/src/event.rs
--- a/src/event.rs
+++ b/src/event.rs
@@ -408,6 +426,30 @@ impl From<KeyCode> for KeyEvent {
}
}
+impl PartialEq for KeyEvent {
+ fn eq(&self, other: &KeyEvent) -> bool {
+ let KeyEvent {
+ code: lhs_code,
+ modifiers: lhs_modifiers,
+ } = self.normalize_case();
+ let KeyEvent {
+ code: rhs_code,
+ modifiers: rhs_modifiers,
+ } = other.normalize_case();
+ (lhs_code == rhs_code) && (lhs_modifiers == rhs_modifiers)
+ }
+}
+
+impl Eq for KeyEvent {}
+
+impl Hash for KeyEvent {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ let KeyEvent { code, modifiers } = self.normalize_case();
+ code.hash(state);
+ modifiers.hash(state);
+ }
+}
+
/// Represents a key.
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
| crossterm-rs__crossterm-541 | 541 | [
"517"
] | 0.19 | crossterm-rs/crossterm | 2021-02-20T17:23:01Z | diff --git a/src/event.rs b/src/event.rs
--- a/src/event.rs
+++ b/src/event.rs
@@ -466,3 +508,41 @@ pub(crate) enum InternalEvent {
#[cfg(unix)]
CursorPosition(u16, u16),
}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::hash_map::DefaultHasher;
+ use std::hash::{Hash, Hasher};
+
+ use super::{KeyCode, KeyEvent, KeyModifiers};
+
+ #[test]
+ fn test_equality() {
+ let lowercase_d_with_shift = KeyEvent::new(KeyCode::Char('d'), KeyModifiers::SHIFT);
+ let uppercase_d_with_shift = KeyEvent::new(KeyCode::Char('D'), KeyModifiers::SHIFT);
+ let uppercase_d = KeyEvent::new(KeyCode::Char('D'), KeyModifiers::NONE);
+ assert_eq!(lowercase_d_with_shift, uppercase_d_with_shift);
+ assert_eq!(uppercase_d, uppercase_d_with_shift);
+ }
+
+ #[test]
+ fn test_hash() {
+ let lowercase_d_with_shift_hash = {
+ let mut hasher = DefaultHasher::new();
+ KeyEvent::new(KeyCode::Char('d'), KeyModifiers::SHIFT).hash(&mut hasher);
+ hasher.finish()
+ };
+ let uppercase_d_with_shift_hash = {
+ let mut hasher = DefaultHasher::new();
+ KeyEvent::new(KeyCode::Char('D'), KeyModifiers::SHIFT).hash(&mut hasher);
+ hasher.finish()
+ };
+ let uppercase_d_hash = {
+ let mut hasher = DefaultHasher::new();
+ KeyEvent::new(KeyCode::Char('D'), KeyModifiers::NONE).hash(&mut hasher);
+ hasher.finish()
+ };
+ assert_eq!(lowercase_d_with_shift_hash, uppercase_d_with_shift_hash);
+ assert_eq!(uppercase_d_hash, uppercase_d_with_shift_hash);
+ }
+}
| KeyEvent's KeyCode's case could be normalized to be less redundant
**Is your feature request related to a problem? Please describe.**
It is a little frustrating when comparing something like
```
KeyEvent { KeyCode::Char('a'), KeyModifiers::SHIFT } == KeyEvent { KeyCode::Char('A'), KeyModifiers::SHIFT }
```
and getting false, when chances are these are the same. This also leads to issues where if a lowercase keycode is combined with the shift key modifier (or an uppercase without shift), it will always be unequal to the output of something like read().
**Describe the solution you'd like**
When deriving Eq/PartialEq it could convert to the same casing for both the left and right hand side before comparison.
**Describe alternatives you've considered in any**
The casing for KeyCode could be normalized at construction. This was my first idea, but it is possible some people might be pulling the character out of the keycode with the assumption it will preserve casing, and this would be a breaking change.
**Additional context**
Came across this when writing tests for combining key modifiers (`KeyModifiers::SHIFT | KeyModifiers::ALT` type thing) and found it unusual that I had to specify casing both as a modifier and in the char.
| f7063d9160671ab3be4b4add8d19271abb022cbd | [
"event::tests::test_equality",
"event::tests::test_hash"
] | [
"event::filter::tests::test_cursor_position_filter_filters_cursor_position",
"event::filter::tests::test_event_filter_filters_events",
"event::filter::tests::test_event_filter_filters_internal_events",
"event::read::tests::test_poll_continues_after_error",
"event::read::tests::test_poll_fails_without_event_... | [] | [] | |
128eddeafcea5194d529c4788ecd4afeb16eaf01 | diff --git a/src/event/sys/unix/parse.rs b/src/event/sys/unix/parse.rs
--- a/src/event/sys/unix/parse.rs
+++ b/src/event/sys/unix/parse.rs
@@ -95,13 +95,22 @@ pub(crate) fn parse_event(buffer: &[u8], input_available: bool) -> Result<Option
_ => parse_utf8_char(buffer).map(|maybe_char| {
maybe_char
.map(KeyCode::Char)
- .map(Into::into)
+ .map(char_code_to_event)
.map(Event::Key)
.map(InternalEvent::Event)
}),
}
}
+// converts KeyCode to KeyEvent (adds shift modifier in case of uppercase characters)
+fn char_code_to_event(code: KeyCode) -> KeyEvent {
+ let modifiers = match code {
+ KeyCode::Char(c) if c.is_uppercase() => KeyModifiers::SHIFT,
+ _ => KeyModifiers::empty(),
+ };
+ KeyEvent::new(code, modifiers)
+}
+
pub(crate) fn parse_csi(buffer: &[u8]) -> Result<Option<InternalEvent>> {
assert!(buffer.starts_with(&[b'\x1B', b'['])); // ESC [
| crossterm-rs__crossterm-423 | 423 | [
"421"
] | 0.17 | crossterm-rs/crossterm | 2020-04-22T09:41:11Z | diff --git a/src/event/sys/unix/parse.rs b/src/event/sys/unix/parse.rs
--- a/src/event/sys/unix/parse.rs
+++ b/src/event/sys/unix/parse.rs
@@ -553,7 +562,10 @@ mod tests {
// parse_utf8_char
assert_eq!(
parse_event("ลฝ".as_bytes(), false).unwrap(),
- Some(InternalEvent::Event(Event::Key(KeyCode::Char('ลฝ').into()))),
+ Some(InternalEvent::Event(Event::Key(KeyEvent::new(
+ KeyCode::Char('ลฝ'),
+ KeyModifiers::SHIFT
+ )))),
);
}
diff --git a/src/event/sys/unix/parse.rs b/src/event/sys/unix/parse.rs
--- a/src/event/sys/unix/parse.rs
+++ b/src/event/sys/unix/parse.rs
@@ -714,4 +726,26 @@ mod tests {
// 'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
assert!(parse_utf8_char(&[0xF0, 0x28, 0x8C, 0x28]).is_err());
}
+
+ #[test]
+ fn test_parse_char_event_lowercase() {
+ assert_eq!(
+ parse_event("c".as_bytes(), false).unwrap(),
+ Some(InternalEvent::Event(Event::Key(KeyEvent::new(
+ KeyCode::Char('c'),
+ KeyModifiers::empty()
+ )))),
+ );
+ }
+
+ #[test]
+ fn test_parse_char_event_uppercase() {
+ assert_eq!(
+ parse_event("C".as_bytes(), false).unwrap(),
+ Some(InternalEvent::Event(Event::Key(KeyEvent::new(
+ KeyCode::Char('C'),
+ KeyModifiers::SHIFT
+ )))),
+ );
+ }
}
| KeyEvent modifier inconsistent for capital letters
**Describe the bug**
As discussed in the Discord: I observed that on *nix platforms the KeyEvent of a capital letter does not contain the Shift modifier and on Windows it does.
**To Reproduce**
run the example `event-poll-read` and press a capital letter (e.g Shift+D)
on mac:
```
Event::Key(KeyEvent { code: Char('D'), modifiers: NONE })
```
on windows (cmd.exe and PowerShell)
```
Event::Key(KeyEvent { code: Char('D'), modifiers: SHIFT })
```
**Expected behaviour**
The same consistent behaviour, not sending the Shift-Modifier.
| 128eddeafcea5194d529c4788ecd4afeb16eaf01 | [
"event::sys::unix::parse::tests::test_parse_char_event_uppercase",
"event::sys::unix::parse::tests::test_parse_event_subsequent_calls"
] | [
"event::filter::tests::test_cursor_position_filter_filters_cursor_position",
"event::filter::tests::test_event_filter_filters_events",
"event::filter::tests::test_event_filter_filters_internal_events",
"event::read::tests::test_poll_continues_after_error",
"event::read::tests::test_poll_fails_without_event_... | [] | [] | |
fce58c879a748f3159216f68833100aa16141ab0 | diff --git a/src/style.rs b/src/style.rs
--- a/src/style.rs
+++ b/src/style.rs
@@ -161,9 +161,23 @@ pub fn style<D: Display>(val: D) -> StyledContent<D> {
///
/// This does not always provide a good result.
pub fn available_color_count() -> u16 {
- env::var("TERM")
- .map(|x| if x.contains("256color") { 256 } else { 8 })
- .unwrap_or(8)
+ #[cfg(windows)]
+ {
+ // Check if we're running in a pseudo TTY, which supports true color.
+ // Fall back to env vars otherwise for other terminals on Windows.
+ if crate::ansi_support::supports_ansi() {
+ return u16::MAX;
+ }
+ }
+
+ const DEFAULT: u16 = 8;
+ env::var("COLORTERM")
+ .or_else(|_| env::var("TERM"))
+ .map_or(DEFAULT, |x| match x {
+ _ if x.contains("24bit") || x.contains("truecolor") => u16::MAX,
+ _ if x.contains("256") => 256,
+ _ => DEFAULT,
+ })
}
/// Forces colored output on or off globally, overriding NO_COLOR.
| crossterm-rs__crossterm-885 | 885 | For that matter, just checking `TERM` is not sufficient on any platform. See helper functions used by the cli/go-ch link above: <https://github.com/cli/go-gh/blob/dbd982eba2a041d88d398cce01cb708c4c3503f7/pkg/term/env.go#L170-L184>. | [
"882"
] | 0.27 | crossterm-rs/crossterm | 2024-05-04T16:30:14Z | diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -89,6 +89,7 @@ futures-timer = "3.0"
async-std = "1.12"
serde_json = "1.0"
serial_test = "2.0.0"
+temp-env = "0.3.6"
#
# Examples
diff --git a/src/style.rs b/src/style.rs
--- a/src/style.rs
+++ b/src/style.rs
@@ -519,3 +533,89 @@ impl_display!(for ResetColor);
fn parse_next_u8<'a>(iter: &mut impl Iterator<Item = &'a str>) -> Option<u8> {
iter.next().and_then(|s| s.parse().ok())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // On Windows many env var tests will fail so we need to conditionally check for ANSI support.
+ // This allows other terminals on Windows to still assert env var support.
+ macro_rules! skip_windows_ansi_supported {
+ () => {
+ #[cfg(windows)]
+ {
+ if crate::ansi_support::supports_ansi() {
+ return;
+ }
+ }
+ };
+ }
+
+ #[cfg_attr(windows, test)]
+ #[cfg(windows)]
+ fn windows_always_truecolor() {
+ // This should always be true on supported Windows 10+,
+ // but downlevel Windows clients and other terminals may fail `cargo test` otherwise.
+ if crate::ansi_support::supports_ansi() {
+ assert_eq!(u16::MAX, available_color_count());
+ };
+ }
+
+ #[test]
+ fn colorterm_overrides_term() {
+ skip_windows_ansi_supported!();
+ temp_env::with_vars(
+ [
+ ("COLORTERM", Some("truecolor")),
+ ("TERM", Some("xterm-256color")),
+ ],
+ || {
+ assert_eq!(u16::MAX, available_color_count());
+ },
+ );
+ }
+
+ #[test]
+ fn term_24bits() {
+ skip_windows_ansi_supported!();
+ temp_env::with_vars(
+ [("COLORTERM", None), ("TERM", Some("xterm-24bits"))],
+ || {
+ assert_eq!(u16::MAX, available_color_count());
+ },
+ );
+ }
+
+ #[test]
+ fn term_256color() {
+ skip_windows_ansi_supported!();
+ temp_env::with_vars(
+ [("COLORTERM", None), ("TERM", Some("xterm-256color"))],
+ || {
+ assert_eq!(256u16, available_color_count());
+ },
+ );
+ }
+
+ #[test]
+ fn default_color_count() {
+ skip_windows_ansi_supported!();
+ temp_env::with_vars([("COLORTERM", None::<&str>), ("TERM", None)], || {
+ assert_eq!(8, available_color_count());
+ });
+ }
+
+ #[test]
+ fn unsupported_term_colorterm_values() {
+ skip_windows_ansi_supported!();
+ temp_env::with_vars(
+ [
+ ("COLORTERM", Some("gibberish")),
+ ("TERM", Some("gibberish")),
+ ],
+ || {
+ assert_eq!(8u16, available_color_count());
+ },
+ );
+ }
+}
| available_color_count is wrong on Windows
**Describe the bug**
Windows pseudo-TTYs support true color, yes `crossterm::style::available_color_count` reports 8. You need to query if you're in a pseudo-terminal which, BTW, means you can do just about any VT100 sequence including keyboard support, though I'm not sure what "progressive keyboard support" means.
A better detection of what colors are supported can be found at <https://github.com/cli/go-gh/blob/dbd982eba2a041d88d398cce01cb708c4c3503f7/pkg/term/env.go#L70-L72>. I worked on that for the GitHub CLI (was refactored into cli/go-gh from cli/cli) along with colleagues on the Windows terminal team that own conhost and conpty - both of which support VT100 sequences since some version of Windows 10 (TH2, maybe? Anything older isn't supported anyway.)
**To Reproduce**
Steps to reproduce the behavior:
1. Write a simple bin:
```rust
fn main() {
println!("{}", crossterm::style::available_color_count());
}
```
3. Run `cargo run`
**Expected behavior**
`256` is printed to stdout.
**OS**
- Windows 11
**Terminal/Console**
- Windows Terminal; though, conhost.exe supports this - which cmd.exe and powershell.exe/pwsh.exe use by default unless you default to wt.exe, which uses conpty.exe. Effectively, conpty is dead on built-in terminals and shells.
| fce58c879a748f3159216f68833100aa16141ab0 | [
"style::tests::colorterm_overrides_term",
"style::tests::term_24bits"
] | [
"event::filter::tests::test_cursor_position_filter_filters_cursor_position",
"event::filter::tests::test_event_filter_filters_internal_events",
"event::filter::tests::test_event_filter_filters_events",
"event::filter::tests::test_keyboard_enhancement_status_filter_filters_keyboard_enhancement_status",
"even... | [] | [] |
13213b7a85cc1b5dcac0848bb664f34d463ac7e7 | diff --git a/gen/cmd/src/app.rs b/gen/cmd/src/app.rs
--- a/gen/cmd/src/app.rs
+++ b/gen/cmd/src/app.rs
@@ -65,18 +65,25 @@ pub(super) fn from_args() -> Opt {
.unwrap_or_default()
.map(str::to_owned)
.collect();
- let output = match matches.value_of_os(OUTPUT) {
- None => Output::Stdout,
- Some(path) if path == "-" => Output::Stdout,
- Some(path) => Output::File(PathBuf::from(path)),
- };
+
+ let mut outputs = Vec::new();
+ for path in matches.values_of_os(OUTPUT).unwrap_or_default() {
+ outputs.push(if path == "-" {
+ Output::Stdout
+ } else {
+ Output::File(PathBuf::from(path))
+ });
+ }
+ if outputs.is_empty() {
+ outputs.push(Output::Stdout);
+ }
Opt {
input,
cxx_impl_annotations,
header,
include,
- output,
+ outputs,
}
}
diff --git a/gen/cmd/src/app.rs b/gen/cmd/src/app.rs
--- a/gen/cmd/src/app.rs
+++ b/gen/cmd/src/app.rs
@@ -142,6 +149,7 @@ not specified.
.long(OUTPUT)
.short("o")
.takes_value(true)
+ .multiple(true)
.validator_os(validate_utf8)
.help(HELP)
}
diff --git a/gen/cmd/src/main.rs b/gen/cmd/src/main.rs
--- a/gen/cmd/src/main.rs
+++ b/gen/cmd/src/main.rs
@@ -25,7 +25,7 @@ struct Opt {
header: bool,
cxx_impl_annotations: Option<String>,
include: Vec<String>,
- output: Output,
+ outputs: Vec<Output>,
}
fn main() {
diff --git a/gen/cmd/src/main.rs b/gen/cmd/src/main.rs
--- a/gen/cmd/src/main.rs
+++ b/gen/cmd/src/main.rs
@@ -35,35 +35,54 @@ fn main() {
}
}
+enum Kind {
+ GeneratedHeader,
+ GeneratedImplementation,
+ Header,
+}
+
fn try_main() -> Result<()> {
let opt = app::from_args();
- let gen_header = opt.header || opt.output.ends_with(".h");
+ let mut outputs = Vec::new();
+ let mut gen_header = false;
+ let mut gen_implementation = false;
+ for output in opt.outputs {
+ let kind = if opt.input.is_none() {
+ Kind::Header
+ } else if opt.header || output.ends_with(".h") {
+ gen_header = true;
+ Kind::GeneratedHeader
+ } else {
+ gen_implementation = true;
+ Kind::GeneratedImplementation
+ };
+ outputs.push((output, kind));
+ }
let gen = gen::Opt {
include: opt.include,
cxx_impl_annotations: opt.cxx_impl_annotations,
gen_header,
- gen_implementation: !gen_header,
+ gen_implementation,
};
- let content;
- let content = match (opt.input, gen_header) {
- (Some(input), true) => {
- content = gen::generate_from_path(&input, &gen).header;
- content.as_slice()
- }
- (Some(input), false) => {
- content = gen::generate_from_path(&input, &gen).implementation;
- content.as_slice()
- }
- (None, true) => include::HEADER.as_bytes(),
- (None, false) => unreachable!(), // enforced by required_unless
+ let generated_code = if let Some(input) = opt.input {
+ gen::generate_from_path(&input, &gen)
+ } else {
+ Default::default()
};
- match opt.output {
- Output::Stdout => drop(io::stdout().write_all(content)),
- Output::File(path) => fs::write(path, content)?,
+ for (output, kind) in outputs {
+ let content = match kind {
+ Kind::GeneratedHeader => &generated_code.header,
+ Kind::GeneratedImplementation => &generated_code.implementation,
+ Kind::Header => include::HEADER.as_bytes(),
+ };
+ match output {
+ Output::Stdout => drop(io::stdout().write_all(content)),
+ Output::File(path) => fs::write(path, content)?,
+ }
}
Ok(())
diff --git a/gen/src/mod.rs b/gen/src/mod.rs
--- a/gen/src/mod.rs
+++ b/gen/src/mod.rs
@@ -50,6 +50,7 @@ pub struct Opt {
}
/// Results of code generation.
+#[derive(Default)]
pub struct GeneratedCode {
/// The bytes of a C++ header file.
pub header: Vec<u8>,
| dtolnay__cxx-319 | 319 | [
"64"
] | 0.4 | dtolnay/cxx | 2020-09-24T15:35:19Z | diff --git a/gen/cmd/src/test.rs b/gen/cmd/src/test.rs
--- a/gen/cmd/src/test.rs
+++ b/gen/cmd/src/test.rs
@@ -32,7 +32,7 @@ OPTIONS:
parse or even require the given paths to exist; they simply go
into the generated C++ code as #include lines.
\x20
- -o, --output <output>
+ -o, --output <output>...
Path of file to write as output. Output goes to stdout if -o is
not specified.
\x20
| Consider allowing one cxxbridge cli invocation to emit both header and cc
As currently implemented, two invocations of the cli command are required and the output goes to stdout.
```bash
$ cxxbridge path/to/lib.rs --header > generated.h
$ cxxbridge path/to/lib.rs > generated.cc
```
In some Starlark-based environments (or others) it turns out to be desirable to emit both outputs from a single invocation.
```python
genrule(
name = "gen",
src = "...",
cmd = "$(exe //path/to:cxxbridge-cmd) ${SRC}",
outs = {
"header": ["generated.h"],
"source": ["generated.cc"],
},
)
```
| c86633d53c1150048cbcb2605403ffb227c853b4 | [
"app::test::test_help"
] | [
"gen::tests::test_cpp",
"gen::tests::test_annotation"
] | [] | [] | |
1549106cb02a216c2182e3c75cfc8aad13834d13 | diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -619,7 +619,6 @@ fn write_cxx_function_shim(out: &mut OutFile, efn: &ExternFn, impl_annotations:
}
match &efn.ret {
Some(Type::Ref(_)) => write!(out, "&"),
- Some(Type::Str(_)) if !indirect_return => write!(out, "::rust::Str::Repr("),
Some(Type::SliceRefU8(_)) if !indirect_return => {
write!(out, "::rust::Slice<uint8_t>::Repr(")
}
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -659,7 +658,7 @@ fn write_cxx_function_shim(out: &mut OutFile, efn: &ExternFn, impl_annotations:
match &efn.ret {
Some(Type::RustBox(_)) => write!(out, ".into_raw()"),
Some(Type::UniquePtr(_)) => write!(out, ".release()"),
- Some(Type::Str(_)) | Some(Type::SliceRefU8(_)) if !indirect_return => write!(out, ")"),
+ Some(Type::SliceRefU8(_)) if !indirect_return => write!(out, ")"),
_ => {}
}
if indirect_return {
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -866,7 +865,6 @@ fn write_rust_function_shim_impl(
write!(out, ", ");
}
match &arg.ty {
- Type::Str(_) => write!(out, "::rust::Str::Repr("),
Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr("),
ty if out.types.needs_indirect_abi(ty) => write!(out, "&"),
_ => {}
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -875,7 +873,7 @@ fn write_rust_function_shim_impl(
match &arg.ty {
Type::RustBox(_) => write!(out, ".into_raw()"),
Type::UniquePtr(_) => write!(out, ".release()"),
- Type::Str(_) | Type::SliceRefU8(_) => write!(out, ")"),
+ Type::SliceRefU8(_) => write!(out, ")"),
ty if ty != RustString && out.types.needs_indirect_abi(ty) => write!(out, "$.value"),
_ => {}
}
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -939,7 +937,6 @@ fn write_indirect_return_type(out: &mut OutFile, ty: &Type) {
write_type(out, &ty.inner);
write!(out, " *");
}
- Type::Str(_) => write!(out, "::rust::Str::Repr"),
Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr"),
_ => write_type(out, ty),
}
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -967,7 +964,6 @@ fn write_extern_return_type_space(out: &mut OutFile, ty: &Option<Type>) {
write_type(out, &ty.inner);
write!(out, " *");
}
- Some(Type::Str(_)) => write!(out, "::rust::Str::Repr "),
Some(Type::SliceRefU8(_)) => write!(out, "::rust::Slice<uint8_t>::Repr "),
Some(ty) if out.types.needs_indirect_abi(ty) => write!(out, "void "),
_ => write_return_type(out, ty),
diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -980,7 +976,6 @@ fn write_extern_arg(out: &mut OutFile, arg: &Var) {
write_type_space(out, &ty.inner);
write!(out, "*");
}
- Type::Str(_) => write!(out, "::rust::Str::Repr "),
Type::SliceRefU8(_) => write!(out, "::rust::Slice<uint8_t>::Repr "),
_ => write_type_space(out, &arg.ty),
}
diff --git a/include/cxx.h b/include/cxx.h
--- a/include/cxx.h
+++ b/include/cxx.h
@@ -79,19 +79,11 @@ class Str final {
Str(const Str &) noexcept = default;
~Str() noexcept = default;
- // Repr is PRIVATE; must not be used other than by our generated code.
- //
+private:
// Not necessarily ABI compatible with &str. Codegen will translate to
// cxx::rust_str::RustStr which matches this layout.
- struct Repr final {
- const char *ptr;
- size_t len;
- };
- Str(Repr) noexcept;
- explicit operator Repr() const noexcept;
-
-private:
- Repr repr;
+ const char *ptr;
+ size_t len;
};
#endif // CXXBRIDGE05_RUST_STR
diff --git a/src/cxx.cc b/src/cxx.cc
--- a/src/cxx.cc
+++ b/src/cxx.cc
@@ -115,33 +115,33 @@ std::ostream &operator<<(std::ostream &os, const String &s) {
return os;
}
-Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(1), 0}) {}
+Str::Str() noexcept : ptr(reinterpret_cast<const char *>(1)), len(0) {}
-static void initStr(Str::Repr repr) {
- if (!cxxbridge05$str$valid(repr.ptr, repr.len)) {
+static void initStr(const char *ptr, size_t len) {
+ if (!cxxbridge05$str$valid(ptr, len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
-Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) {
- initStr(this->repr);
+Str::Str(const std::string &s) : ptr(s.data()), len(s.length()) {
+ initStr(this->ptr, this->len);
}
-Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) {
+Str::Str(const char *s) : ptr(s), len(std::strlen(s)) {
assert(s != nullptr);
- initStr(this->repr);
+ initStr(this->ptr, this->len);
}
Str::Str(const char *s, size_t len)
- : repr(
- Repr{s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
- len}) {
+ : ptr(s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s),
+ len(len) {
assert(s != nullptr || len == 0);
- initStr(this->repr);
+ initStr(this->ptr, this->len);
}
Str &Str::operator=(Str other) noexcept {
- this->repr = other.repr;
+ this->ptr = other.ptr;
+ this->len = other.len;
return *this;
}
diff --git a/src/cxx.cc b/src/cxx.cc
--- a/src/cxx.cc
+++ b/src/cxx.cc
@@ -149,15 +149,11 @@ Str::operator std::string() const {
return std::string(this->data(), this->size());
}
-const char *Str::data() const noexcept { return this->repr.ptr; }
-
-size_t Str::size() const noexcept { return this->repr.len; }
-
-size_t Str::length() const noexcept { return this->repr.len; }
+const char *Str::data() const noexcept { return this->ptr; }
-Str::Str(Repr repr_) noexcept : repr(repr_) {}
+size_t Str::size() const noexcept { return this->len; }
-Str::operator Repr() const noexcept { return this->repr; }
+size_t Str::length() const noexcept { return this->len; }
std::ostream &operator<<(std::ostream &os, const Str &s) {
os.write(s.data(), s.size());
| dtolnay__cxx-391 | 391 | [
"118"
] | 0.5 | dtolnay/cxx | 2020-11-01T00:37:53Z | diff --git a/tests/cxx_gen.rs b/tests/cxx_gen.rs
--- a/tests/cxx_gen.rs
+++ b/tests/cxx_gen.rs
@@ -18,7 +18,7 @@ fn test_extern_c_function() {
let output = str::from_utf8(&generated.implementation).unwrap();
// To avoid continual breakage we won't test every byte.
// Let's look for the major features.
- assert!(output.contains("void cxxbridge05$do_cpp_thing(::rust::Str::Repr foo)"));
+ assert!(output.contains("void cxxbridge05$do_cpp_thing(::rust::Str foo)"));
}
#[test]
diff --git a/tests/cxx_gen.rs b/tests/cxx_gen.rs
--- a/tests/cxx_gen.rs
+++ b/tests/cxx_gen.rs
@@ -28,5 +28,5 @@ fn test_impl_annotation() {
let source = BRIDGE0.parse().unwrap();
let generated = generate_header_and_cc(source, &opt).unwrap();
let output = str::from_utf8(&generated.implementation).unwrap();
- assert!(output.contains("ANNOTATION void cxxbridge05$do_cpp_thing(::rust::Str::Repr foo)"));
+ assert!(output.contains("ANNOTATION void cxxbridge05$do_cpp_thing(::rust::Str foo)"));
}
| Remove Str::Repr nested struct from cxx.h
This should be implemented some other way. It shouldn't be necessary to include this "private" public nested struct which is only supposed to be used by our code generator. Instead the code generator should be built using only public constructors and member functions on rust::Str.
| f47403fccd1222f407fe316aad1a5a3cb0c777cf | [
"test_impl_annotation",
"test_extern_c_function"
] | [
"test_c_method_calls",
"test_c_ns_method_calls",
"test_c_call_r",
"test_c_return",
"test_c_take",
"test_c_try_return",
"test_enum_representations",
"test_extern_opaque",
"test_extern_trivial",
"test_rust_name_attribute",
"test_deref_null - should panic",
"src/extern_type.rs - extern_type::Exte... | [] | [] | |
e35673d7debe16222c1667131e51969c093e225c | diff --git a/gen/src/write.rs b/gen/src/write.rs
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -1245,7 +1245,12 @@ fn write_unique_ptr_common(out: &mut OutFile, ty: &Type, types: &Types) {
let instance = to_mangled(&out.namespace, ty);
let can_construct_from_value = match ty {
- Type::Ident(ident) => types.structs.contains_key(ident),
+ // Some aliases are to opaque types; some are to trivial types.
+ // We can't know at code generation time, so we generate both C++
+ // and Rust side bindings for a "new" method anyway. But the Rust
+ // code can't be called for Opaque types because the 'new'
+ // method is not implemented.
+ Type::Ident(ident) => types.structs.contains_key(ident) || types.aliases.contains_key(ident),
_ => false,
};
diff --git a/macro/src/expand.rs b/macro/src/expand.rs
--- a/macro/src/expand.rs
+++ b/macro/src/expand.rs
@@ -814,7 +814,7 @@ fn expand_unique_ptr(
let link_release = format!("{}release", prefix);
let link_drop = format!("{}drop", prefix);
- let new_method = if types.structs.contains_key(ident) {
+ let new_method = if types.structs.contains_key(ident) || types.aliases.contains_key(ident) {
Some(quote! {
fn __new(mut value: Self) -> *mut ::std::ffi::c_void {
extern "C" {
diff --git a/src/unique_ptr.rs b/src/unique_ptr.rs
--- a/src/unique_ptr.rs
+++ b/src/unique_ptr.rs
@@ -1,5 +1,7 @@
use crate::cxx_string::CxxString;
use crate::cxx_vector::{self, CxxVector, VectorElement};
+use crate::ExternType;
+use crate::kind::Trivial;
use core::ffi::c_void;
use core::fmt::{self, Debug, Display};
use core::marker::PhantomData;
diff --git a/src/unique_ptr.rs b/src/unique_ptr.rs
--- a/src/unique_ptr.rs
+++ b/src/unique_ptr.rs
@@ -32,7 +34,9 @@ where
}
/// Allocates memory on the heap and makes a UniquePtr pointing to it.
- pub fn new(value: T) -> Self {
+ pub fn new(value: T) -> Self
+ where
+ T: ExternType<Kind = Trivial> {
UniquePtr {
repr: T::__new(value),
ty: PhantomData,
| dtolnay__cxx-361 | 361 | [
"360"
] | 0.5 | dtolnay/cxx | 2020-10-12T23:21:03Z | diff --git a/tests/BUCK b/tests/BUCK
--- a/tests/BUCK
+++ b/tests/BUCK
@@ -3,7 +3,10 @@ load("//tools/buck:rust_cxx_bridge.bzl", "rust_cxx_bridge")
rust_test(
name = "test",
srcs = ["test.rs"],
- deps = [":ffi"],
+ deps = [
+ ":ffi",
+ "//:cxx",
+ ],
)
rust_library(
diff --git a/tests/BUILD b/tests/BUILD
--- a/tests/BUILD
+++ b/tests/BUILD
@@ -6,7 +6,10 @@ rust_test(
name = "test",
size = "small",
srcs = ["test.rs"],
- deps = [":cxx_test_suite"],
+ deps = [
+ ":cxx_test_suite",
+ "//:cxx",
+ ],
)
rust_library(
diff --git a/tests/ffi/lib.rs b/tests/ffi/lib.rs
--- a/tests/ffi/lib.rs
+++ b/tests/ffi/lib.rs
@@ -16,13 +16,13 @@ mod other {
#[repr(C)]
pub struct D {
- d: u64,
+ pub d: u64,
}
#[repr(C)]
pub struct E {
- e: u64,
e_str: CxxString,
+ e: u64,
}
unsafe impl ExternType for D {
diff --git a/tests/test.rs b/tests/test.rs
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -199,6 +199,7 @@ fn test_extern_trivial() {
check!(ffi2::c_take_trivial(d));
let d = ffi2::c_return_trivial_ptr();
check!(ffi2::c_take_trivial_ptr(d));
+ cxx::UniquePtr::new(ffi2::D { d: 42 });
}
#[test]
diff --git /dev/null b/tests/ui/unique_ptr_to_opaque.rs
new file mode 100644
--- /dev/null
+++ b/tests/ui/unique_ptr_to_opaque.rs
@@ -0,0 +1,26 @@
+mod outside {
+ #[repr(C)]
+ pub struct C {
+ pub a: u8,
+ }
+ unsafe impl cxx::ExternType for C {
+ type Id = cxx::type_id!("C");
+ type Kind = cxx::kind::Opaque;
+ }
+}
+
+
+#[cxx::bridge]
+mod ffi {
+ impl UniquePtr<C> {}
+
+ extern "C" {
+ type C = crate::outside::C;
+ }
+
+ impl UniquePtr<C> {}
+}
+
+fn main() {
+ cxx::UniquePtr::new(outside::C { a: 4 } );
+}
diff --git /dev/null b/tests/ui/unique_ptr_to_opaque.stderr
new file mode 100644
--- /dev/null
+++ b/tests/ui/unique_ptr_to_opaque.stderr
@@ -0,0 +1,7 @@
+error[E0271]: type mismatch resolving `<outside::C as ExternType>::Kind == Trivial`
+ --> $DIR/unique_ptr_to_opaque.rs:25:5
+ |
+25 | cxx::UniquePtr::new(outside::C { a: 4 } );
+ | ^^^^^^^^^^^^^^^^^^^ expected enum `Trivial`, found enum `cxx::kind::Opaque`
+ |
+ = note: required by `UniquePtr::<T>::new`
| Allow UniquePtr::new on Trivial ExternTypes
Example from autocxx:
```rust
mod ffi {
unsafe impl cxx::ExternType for bindgen::A {
type Id = cxx::type_id!("A");
type Kind = cxx::kind::Trivial;
}
mod bindgen {
#[repr(C)]
pub struct A {
pub a: u32,
}
}
#[cxx::bridge]
pub mod cxxbridge {
impl UniquePtr<A> {}
extern "C" {
include!("input.h");
type A = super::bindgen::A;
}
}
}
fn main() {
let a = ffi::cxxbridge::A { a: 14 };
let _ = cxx::UniquePtr::new(a);
}
```
fails because it hits this `unreachable!`:
```rust
// Methods are private; not intended to be implemented outside of cxxbridge
// codebase.
pub unsafe trait UniquePtrTarget {
//...
#[doc(hidden)]
fn __new(value: Self) -> *mut c_void
where
Self: Sized,
{
// Opaque C types do not get this method because they can never exist by
// value on the Rust side of the bridge.
let _ = value;
unreachable!()
}
//...
}
```
The fix is for `expand_unique_ptr` in `expand.rs` to generate a `__new` method under slightly more circumstances, when an extern type is known to be trivial.
| f47403fccd1222f407fe316aad1a5a3cb0c777cf | [
"test_extern_trivial"
] | [
"test_impl_annotation",
"test_extern_c_function",
"test_c_method_calls",
"test_c_call_r",
"test_enum_representations",
"test_c_return",
"test_c_try_return",
"test_c_take",
"test_extern_opaque",
"test_rust_name_attribute",
"test_deref_null - should panic",
"src/extern_type.rs - extern_type::Ext... | [] | [] | |
bbf32a9e81e8965e77b5b4035b10c5ccab3ad070 | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -35,7 +35,7 @@ pub use self::query::{
OrderByExpr, Query, Select, SelectInto, SelectItem, SetExpr, SetOperator, TableAlias,
TableFactor, TableWithJoins, Top, Values, With,
};
-pub use self::value::{DateTimeField, TrimWhereField, Value};
+pub use self::value::{escape_quoted_string, DateTimeField, TrimWhereField, Value};
mod data_type;
mod ddl;
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3749,6 +3749,8 @@ impl<'a> Parser<'a> {
// ignore the <separator> and treat the multiple strings as
// a single <literal>."
Token::SingleQuotedString(s) => Ok(Some(Ident::with_quote('\'', s))),
+ // Support for MySql dialect double qouted string, `AS "HOUR"` for example
+ Token::DoubleQuotedString(s) => Ok(Some(Ident::with_quote('\"', s))),
not_an_ident => {
if after_as {
return self.expected("an identifier after AS", not_an_ident);
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3832,6 +3834,7 @@ impl<'a> Parser<'a> {
match self.next_token() {
Token::Word(w) => Ok(w.to_ident()),
Token::SingleQuotedString(s) => Ok(Ident::with_quote('\'', s)),
+ Token::DoubleQuotedString(s) => Ok(Ident::with_quote('\"', s)),
unexpected => self.expected("identifier", unexpected),
}
}
| apache__datafusion-sqlparser-rs-697 | 697 | [
"690"
] | 0.26 | apache/datafusion-sqlparser-rs | 2022-10-31T05:44:57Z | diff --git a/src/test_utils.rs b/src/test_utils.rs
--- a/src/test_utils.rs
+++ b/src/test_utils.rs
@@ -142,6 +142,8 @@ pub fn all_dialects() -> TestedDialects {
Box::new(SnowflakeDialect {}),
Box::new(HiveDialect {}),
Box::new(RedshiftSqlDialect {}),
+ Box::new(MySqlDialect {}),
+ Box::new(BigQueryDialect {}),
],
}
}
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -115,6 +115,115 @@ fn parse_cast_type() {
bigquery().verified_only_select(sql);
}
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn bigquery() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(BigQueryDialect {})],
diff --git a/tests/sqlparser_clickhouse.rs b/tests/sqlparser_clickhouse.rs
--- a/tests/sqlparser_clickhouse.rs
+++ b/tests/sqlparser_clickhouse.rs
@@ -152,6 +152,168 @@ fn parse_kill() {
);
}
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = clickhouse().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ clickhouse().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ clickhouse().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = clickhouse().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn clickhouse() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(ClickHouseDialect {})],
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -886,61 +886,6 @@ fn parse_not_precedence() {
);
}
-#[test]
-fn parse_like() {
- fn chk(negated: bool) {
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}LIKE '%a'",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::Like {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: None,
- },
- select.selection.unwrap()
- );
-
- // Test with escape char
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::Like {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: Some('\\'),
- },
- select.selection.unwrap()
- );
-
- // This statement tests that LIKE and NOT LIKE have the same precedence.
- // This was previously mishandled (#81).
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::IsNull(Box::new(Expr::Like {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: None,
- })),
- select.selection.unwrap()
- );
- }
- chk(false);
- chk(true);
-}
-
#[test]
fn parse_null_like() {
let sql = "SELECT \
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1035,60 +980,6 @@ fn parse_ilike() {
chk(true);
}
-#[test]
-fn parse_similar_to() {
- fn chk(negated: bool) {
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::SimilarTo {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: None,
- },
- select.selection.unwrap()
- );
-
- // Test with escape char
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::SimilarTo {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: Some('\\'),
- },
- select.selection.unwrap()
- );
-
- // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
- let sql = &format!(
- "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
- if negated { "NOT " } else { "" }
- );
- let select = verified_only_select(sql);
- assert_eq!(
- Expr::IsNull(Box::new(Expr::SimilarTo {
- expr: Box::new(Expr::Identifier(Ident::new("name"))),
- negated,
- pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
- escape_char: Some('\\'),
- })),
- select.selection.unwrap()
- );
- }
- chk(false);
- chk(true);
-}
-
#[test]
fn parse_in_list() {
fn chk(negated: bool) {
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3445,59 +3336,6 @@ fn parse_unnest() {
);
}
-#[test]
-fn parse_delimited_identifiers() {
- // check that quoted identifiers in any position remain quoted after serialization
- let select = verified_only_select(
- r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
- );
- // check FROM
- match only(select.from).relation {
- TableFactor::Table {
- name,
- alias,
- args,
- with_hints,
- } => {
- assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
- assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
- assert!(args.is_none());
- assert!(with_hints.is_empty());
- }
- _ => panic!("Expecting TableFactor::Table"),
- }
- // check SELECT
- assert_eq!(3, select.projection.len());
- assert_eq!(
- &Expr::CompoundIdentifier(vec![
- Ident::with_quote('"', "alias"),
- Ident::with_quote('"', "bar baz"),
- ]),
- expr_from_projection(&select.projection[0]),
- );
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
- args: vec![],
- over: None,
- distinct: false,
- special: false,
- }),
- expr_from_projection(&select.projection[1]),
- );
- match &select.projection[2] {
- SelectItem::ExprWithAlias { expr, alias } => {
- assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
- assert_eq!(&Ident::with_quote('"', "column alias"), alias);
- }
- _ => panic!("Expected ExprWithAlias"),
- }
-
- verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
- verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
- //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
-}
-
#[test]
fn parse_parens() {
use self::BinaryOperator::*;
diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs
--- a/tests/sqlparser_hive.rs
+++ b/tests/sqlparser_hive.rs
@@ -15,7 +15,10 @@
//! Test SQL syntax specific to Hive. The parser based on the generic dialect
//! is also tested (on the inputs it can handle).
-use sqlparser::ast::{CreateFunctionUsing, Expr, Ident, ObjectName, Statement, UnaryOperator};
+use sqlparser::ast::{
+ CreateFunctionUsing, Expr, Function, Ident, ObjectName, SelectItem, Statement, TableFactor,
+ UnaryOperator, Value,
+};
use sqlparser::dialect::{GenericDialect, HiveDialect};
use sqlparser::parser::ParserError;
use sqlparser::test_utils::*;
diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs
--- a/tests/sqlparser_hive.rs
+++ b/tests/sqlparser_hive.rs
@@ -300,6 +303,168 @@ fn filter_as_alias() {
println!("{}", hive().one_statement_parses_to(sql, expected));
}
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = hive().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ hive().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ hive().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = hive().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn hive() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(HiveDialect {})],
diff --git a/tests/sqlparser_mssql.rs b/tests/sqlparser_mssql.rs
--- a/tests/sqlparser_mssql.rs
+++ b/tests/sqlparser_mssql.rs
@@ -140,6 +140,168 @@ fn parse_mssql_create_role() {
}
}
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = ms_and_generic().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ ms_and_generic().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ ms_and_generic().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = ms_and_generic().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn ms() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(MsSqlDialect {})],
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -1966,3 +1966,165 @@ fn parse_create_role() {
}
}
}
+
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = pg().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ pg().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ pg().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = pg().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
diff --git a/tests/sqlparser_redshift.rs b/tests/sqlparser_redshift.rs
--- a/tests/sqlparser_redshift.rs
+++ b/tests/sqlparser_redshift.rs
@@ -95,6 +95,168 @@ fn test_double_quotes_over_db_schema_table_name() {
);
}
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = redshift().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ redshift().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ redshift().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = redshift().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn redshift() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(RedshiftSqlDialect {})],
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -159,6 +159,168 @@ fn parse_json_using_colon() {
snowflake().one_statement_parses_to("SELECT a:b::int FROM t", "SELECT CAST(a:b AS INT) FROM t");
}
+#[test]
+fn parse_delimited_identifiers() {
+ // check that quoted identifiers in any position remain quoted after serialization
+ let select = snowflake().verified_only_select(
+ r#"SELECT "alias"."bar baz", "myfun"(), "simple id" AS "column alias" FROM "a table" AS "alias""#,
+ );
+ // check FROM
+ match only(select.from).relation {
+ TableFactor::Table {
+ name,
+ alias,
+ args,
+ with_hints,
+ } => {
+ assert_eq!(vec![Ident::with_quote('"', "a table")], name.0);
+ assert_eq!(Ident::with_quote('"', "alias"), alias.unwrap().name);
+ assert!(args.is_none());
+ assert!(with_hints.is_empty());
+ }
+ _ => panic!("Expecting TableFactor::Table"),
+ }
+ // check SELECT
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::CompoundIdentifier(vec![
+ Ident::with_quote('"', "alias"),
+ Ident::with_quote('"', "bar baz"),
+ ]),
+ expr_from_projection(&select.projection[0]),
+ );
+ assert_eq!(
+ &Expr::Function(Function {
+ name: ObjectName(vec![Ident::with_quote('"', "myfun")]),
+ args: vec![],
+ over: None,
+ distinct: false,
+ special: false,
+ }),
+ expr_from_projection(&select.projection[1]),
+ );
+ match &select.projection[2] {
+ SelectItem::ExprWithAlias { expr, alias } => {
+ assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
+ assert_eq!(&Ident::with_quote('"', "column alias"), alias);
+ }
+ _ => panic!("Expected ExprWithAlias"),
+ }
+
+ snowflake().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
+ snowflake().verified_stmt(r#"ALTER TABLE foo ADD CONSTRAINT "bar" PRIMARY KEY (baz)"#);
+ //TODO verified_stmt(r#"UPDATE foo SET "bar" = 5"#);
+}
+
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = snowflake().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn snowflake() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(SnowflakeDialect {})],
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -133,6 +133,115 @@ fn test_placeholder() {
);
}
+#[test]
+fn parse_like() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that LIKE and NOT LIKE have the same precedence.
+ // This was previously mishandled (#81).
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}LIKE '%a' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::Like {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
+#[test]
+fn parse_similar_to() {
+ fn chk(negated: bool) {
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: None,
+ },
+ select.selection.unwrap()
+ );
+
+ // Test with escape char
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\'",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ },
+ select.selection.unwrap()
+ );
+
+ // This statement tests that SIMILAR TO and NOT SIMILAR TO have the same precedence.
+ let sql = &format!(
+ "SELECT * FROM customers WHERE name {}SIMILAR TO '%a' ESCAPE '\\' IS NULL",
+ if negated { "NOT " } else { "" }
+ );
+ let select = sqlite().verified_only_select(sql);
+ assert_eq!(
+ Expr::IsNull(Box::new(Expr::SimilarTo {
+ expr: Box::new(Expr::Identifier(Ident::new("name"))),
+ negated,
+ pattern: Box::new(Expr::Value(Value::SingleQuotedString("%a".to_string()))),
+ escape_char: Some('\\'),
+ })),
+ select.selection.unwrap()
+ );
+ }
+ chk(false);
+ chk(true);
+}
+
fn sqlite() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(SQLiteDialect {})],
| Fix test-util `fn all_dialects()` to test all dialects actually
This is for internal but some fixes may be for users.
In [tests/sqlparser_common.rs](https://github.com/sqlparser-rs/sqlparser-rs/blob/main/tests/sqlparser_common.rs) (โ ๏ธ linked page may freeze your browser), a lot of test cases depend on [fn all_dialects()](https://github.com/sqlparser-rs/sqlparser-rs/blob/914810d36617581c2380ae9c0f501116a7d810b6/src/test_utils.rs#L135) to test all dialects.
But this `fn all_dialects()` doesn't include `MySqlDialect` and `BigQueryDialect` currently.
So we should include those to `all_dialects` and fix failed test cases after changing.
Change all_dialects to add MySqlDialect and BigQueryDialect ([src/test_utils.rs](https://github.com/sqlparser-rs/sqlparser-rs/blob/914810d36617581c2380ae9c0f501116a7d810b6/src/test_utils.rs#L135)):
```rs
pub fn all_dialects() -> TestedDialects {
TestedDialects {
dialects: vec![
Box::new(GenericDialect {}),
Box::new(PostgreSqlDialect {}),
Box::new(MsSqlDialect {}),
Box::new(AnsiDialect {}),
Box::new(SnowflakeDialect {}),
Box::new(HiveDialect {}),
Box::new(RedshiftSqlDialect {}),
Box::new(MySqlDialect {}), // Added
Box::new(BigQueryDialect {}), // Added
],
}
}
```
Test results after changing above:
```
failures:
parse_at_timezone
parse_collate
parse_collate_after_parens
parse_delete_statement
parse_delimited_identifiers
parse_like
parse_similar_to
test result: FAILED. 187 passed; 7 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s
error: test failed, to rerun pass '--test sqlparser_common'
```
| bbf32a9e81e8965e77b5b4035b10c5ccab3ad070 | [
"parse_at_timezone",
"parse_collate",
"parse_collate_after_parens",
"parse_delete_statement"
] | [
"dialect::tests::test_is_dialect",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_cube_display",
"ast::tests::test_rollup_display",
"tokenizer::tests::tokenize_bitwise_op",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_window_frame_default",
"ast... | [] | [] | |
814367a6abe319bb8c9e030a4a804cd6c9cf2231 | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5254,7 +5254,9 @@ impl<'a> Parser<'a> {
let table = self.parse_table_and_joins()?;
self.expect_keyword(Keyword::SET)?;
let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
- let from = if self.parse_keyword(Keyword::FROM) && dialect_of!(self is PostgreSqlDialect) {
+ let from = if self.parse_keyword(Keyword::FROM)
+ && dialect_of!(self is GenericDialect | PostgreSqlDialect | BigQueryDialect | SnowflakeDialect | RedshiftSqlDialect | MsSqlDialect)
+ {
Some(self.parse_table_and_joins()?)
} else {
None
| apache__datafusion-sqlparser-rs-694 | 694 | Thanks for the report. A contribution PR would be most welcome
I'll take a look. | [
"534"
] | 0.26 | apache/datafusion-sqlparser-rs | 2022-10-28T14:28:54Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -24,7 +24,7 @@ use sqlparser::ast::SelectItem::UnnamedExpr;
use sqlparser::ast::*;
use sqlparser::dialect::{
AnsiDialect, BigQueryDialect, ClickHouseDialect, GenericDialect, HiveDialect, MsSqlDialect,
- MySqlDialect, PostgreSqlDialect, SQLiteDialect, SnowflakeDialect,
+ MySqlDialect, PostgreSqlDialect, RedshiftSqlDialect, SQLiteDialect, SnowflakeDialect,
};
use sqlparser::keywords::ALL_KEYWORDS;
use sqlparser::parser::{Parser, ParserError};
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -186,6 +186,96 @@ fn parse_update() {
);
}
+#[test]
+fn parse_update_set_from() {
+ let sql = "UPDATE t1 SET name = t2.name FROM (SELECT name, id FROM t1 GROUP BY id) AS t2 WHERE t1.id = t2.id";
+ let dialects = TestedDialects {
+ dialects: vec![
+ Box::new(GenericDialect {}),
+ Box::new(PostgreSqlDialect {}),
+ Box::new(BigQueryDialect {}),
+ Box::new(SnowflakeDialect {}),
+ Box::new(RedshiftSqlDialect {}),
+ Box::new(MsSqlDialect {}),
+ ],
+ };
+ let stmt = dialects.verified_stmt(sql);
+ assert_eq!(
+ stmt,
+ Statement::Update {
+ table: TableWithJoins {
+ relation: TableFactor::Table {
+ name: ObjectName(vec![Ident::new("t1")]),
+ alias: None,
+ args: None,
+ with_hints: vec![],
+ },
+ joins: vec![],
+ },
+ assignments: vec![Assignment {
+ id: vec![Ident::new("name")],
+ value: Expr::CompoundIdentifier(vec![Ident::new("t2"), Ident::new("name")])
+ }],
+ from: Some(TableWithJoins {
+ relation: TableFactor::Derived {
+ lateral: false,
+ subquery: Box::new(Query {
+ with: None,
+ body: Box::new(SetExpr::Select(Box::new(Select {
+ distinct: false,
+ top: None,
+ projection: vec![
+ SelectItem::UnnamedExpr(Expr::Identifier(Ident::new("name"))),
+ SelectItem::UnnamedExpr(Expr::Identifier(Ident::new("id"))),
+ ],
+ into: None,
+ from: vec![TableWithJoins {
+ relation: TableFactor::Table {
+ name: ObjectName(vec![Ident::new("t1")]),
+ alias: None,
+ args: None,
+ with_hints: vec![],
+ },
+ joins: vec![],
+ }],
+ lateral_views: vec![],
+ selection: None,
+ group_by: vec![Expr::Identifier(Ident::new("id"))],
+ cluster_by: vec![],
+ distribute_by: vec![],
+ sort_by: vec![],
+ having: None,
+ qualify: None
+ }))),
+ order_by: vec![],
+ limit: None,
+ offset: None,
+ fetch: None,
+ lock: None,
+ }),
+ alias: Some(TableAlias {
+ name: Ident::new("t2"),
+ columns: vec![],
+ })
+ },
+ joins: vec![],
+ }),
+ selection: Some(Expr::BinaryOp {
+ left: Box::new(Expr::CompoundIdentifier(vec![
+ Ident::new("t1"),
+ Ident::new("id")
+ ])),
+ op: BinaryOperator::Eq,
+ right: Box::new(Expr::CompoundIdentifier(vec![
+ Ident::new("t2"),
+ Ident::new("id")
+ ])),
+ }),
+ returning: None,
+ }
+ );
+}
+
#[test]
fn parse_update_with_table_alias() {
let sql = "UPDATE users AS u SET u.username = 'new_user' WHERE u.username = 'old_user'";
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -489,86 +489,6 @@ PHP โฑ USD $
//assert_eq!(sql, ast.to_string());
}
-#[test]
-fn parse_update_set_from() {
- let sql = "UPDATE t1 SET name = t2.name FROM (SELECT name, id FROM t1 GROUP BY id) AS t2 WHERE t1.id = t2.id";
- let stmt = pg().verified_stmt(sql);
- assert_eq!(
- stmt,
- Statement::Update {
- table: TableWithJoins {
- relation: TableFactor::Table {
- name: ObjectName(vec![Ident::new("t1")]),
- alias: None,
- args: None,
- with_hints: vec![],
- },
- joins: vec![],
- },
- assignments: vec![Assignment {
- id: vec![Ident::new("name")],
- value: Expr::CompoundIdentifier(vec![Ident::new("t2"), Ident::new("name")])
- }],
- from: Some(TableWithJoins {
- relation: TableFactor::Derived {
- lateral: false,
- subquery: Box::new(Query {
- with: None,
- body: Box::new(SetExpr::Select(Box::new(Select {
- distinct: false,
- top: None,
- projection: vec![
- SelectItem::UnnamedExpr(Expr::Identifier(Ident::new("name"))),
- SelectItem::UnnamedExpr(Expr::Identifier(Ident::new("id"))),
- ],
- into: None,
- from: vec![TableWithJoins {
- relation: TableFactor::Table {
- name: ObjectName(vec![Ident::new("t1")]),
- alias: None,
- args: None,
- with_hints: vec![],
- },
- joins: vec![],
- }],
- lateral_views: vec![],
- selection: None,
- group_by: vec![Expr::Identifier(Ident::new("id"))],
- cluster_by: vec![],
- distribute_by: vec![],
- sort_by: vec![],
- having: None,
- qualify: None
- }))),
- order_by: vec![],
- limit: None,
- offset: None,
- fetch: None,
- lock: None,
- }),
- alias: Some(TableAlias {
- name: Ident::new("t2"),
- columns: vec![],
- })
- },
- joins: vec![],
- }),
- selection: Some(Expr::BinaryOp {
- left: Box::new(Expr::CompoundIdentifier(vec![
- Ident::new("t1"),
- Ident::new("id")
- ])),
- op: BinaryOperator::Eq,
- right: Box::new(Expr::CompoundIdentifier(vec![
- Ident::new("t2"),
- Ident::new("id")
- ])),
- }),
- returning: None,
- }
- );
-}
-
#[test]
fn test_copy_from() {
let stmt = pg().verified_stmt("COPY users FROM 'data.csv'");
| UPDATE ... FROM ( subquery ) only supported in PostgreSQL
Hi ๐
The `UPDATE <table> FROM (SELECT ...)` statement is only supported with `PostgreSQL` dialect.
It should be also supported for other technologies.
Here are a few examples:
- [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#update_statement)
- [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/update.html)
- [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/c_Examples_of_UPDATE_statements.html)
- [SQL Server](https://docs.microsoft.com/fr-fr/sql/t-sql/queries/update-transact-sql?view=sql-server-ver16)
| bbf32a9e81e8965e77b5b4035b10c5ccab3ad070 | [
"parse_update_set_from"
] | [
"ast::tests::test_window_frame_default",
"dialect::tests::test_is_dialect",
"tokenizer::tests::tokenize_comment",
"tokenizer::tests::tokenize_bitwise_op",
"tokenizer::tests::tokenize_explain_analyze_select",
"tokenizer::tests::tokenize_invalid_string_cols",
"ast::helpers::stmt_create_table::tests::test_... | [] | [] |
1e0460a7dfad4a6767d718a9d849b23c8b61ee80 | diff --git a/src/dialect/snowflake.rs b/src/dialect/snowflake.rs
--- a/src/dialect/snowflake.rs
+++ b/src/dialect/snowflake.rs
@@ -22,9 +22,7 @@ use crate::ast::helpers::stmt_data_loading::{
DataLoadingOption, DataLoadingOptionType, DataLoadingOptions, StageLoadSelectItem,
StageParamsObject,
};
-use crate::ast::{
- CommentDef, Ident, ObjectName, RowAccessPolicy, Statement, Tag, WrappedCollection,
-};
+use crate::ast::{Ident, ObjectName, RowAccessPolicy, Statement, Tag, WrappedCollection};
use crate::dialect::{Dialect, Precedence};
use crate::keywords::Keyword;
use crate::parser::{Parser, ParserError};
diff --git a/src/dialect/snowflake.rs b/src/dialect/snowflake.rs
--- a/src/dialect/snowflake.rs
+++ b/src/dialect/snowflake.rs
@@ -210,13 +208,9 @@ pub fn parse_create_table(
builder = builder.copy_grants(true);
}
Keyword::COMMENT => {
- parser.expect_token(&Token::Eq)?;
- let next_token = parser.next_token();
- let comment = match next_token.token {
- Token::SingleQuotedString(str) => Some(CommentDef::WithEq(str)),
- _ => parser.expected("comment", next_token)?,
- };
- builder = builder.comment(comment);
+ // Rewind the COMMENT keyword
+ parser.prev_token();
+ builder = builder.comment(parser.parse_optional_inline_comment()?);
}
Keyword::AS => {
let query = parser.parse_boxed_query()?;
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5871,12 +5871,9 @@ impl<'a> Parser<'a> {
// Excludes Hive dialect here since it has been handled after table column definitions.
if !dialect_of!(self is HiveDialect) && self.parse_keyword(Keyword::COMMENT) {
- let _ = self.consume_token(&Token::Eq);
- let next_token = self.next_token();
- comment = match next_token.token {
- Token::SingleQuotedString(str) => Some(CommentDef::WithoutEq(str)),
- _ => self.expected("comment", next_token)?,
- }
+ // rewind the COMMENT keyword
+ self.prev_token();
+ comment = self.parse_optional_inline_comment()?
};
// Parse optional `AS ( query )`
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5957,6 +5954,24 @@ impl<'a> Parser<'a> {
})
}
+ pub fn parse_optional_inline_comment(&mut self) -> Result<Option<CommentDef>, ParserError> {
+ let comment = if self.parse_keyword(Keyword::COMMENT) {
+ let has_eq = self.consume_token(&Token::Eq);
+ let next_token = self.next_token();
+ match next_token.token {
+ Token::SingleQuotedString(str) => Some(if has_eq {
+ CommentDef::WithEq(str)
+ } else {
+ CommentDef::WithoutEq(str)
+ }),
+ _ => self.expected("comment", next_token)?,
+ }
+ } else {
+ None
+ };
+ Ok(comment)
+ }
+
pub fn parse_optional_procedure_parameters(
&mut self,
) -> Result<Option<Vec<ProcedureParam>>, ParserError> {
| apache__datafusion-sqlparser-rs-1453 | 1,453 | [
"1452"
] | 0.51 | apache/datafusion-sqlparser-rs | 2024-10-02T12:57:48Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -47,6 +47,7 @@ mod test_utils;
#[cfg(test)]
use pretty_assertions::assert_eq;
+use sqlparser::ast::ColumnOption::Comment;
use sqlparser::ast::Expr::{Identifier, UnaryOp};
use sqlparser::test_utils::all_dialects_except;
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -9841,6 +9842,37 @@ fn test_comment_hash_syntax() {
dialects.verified_only_select_with_canonical(sql, canonical);
}
+#[test]
+fn test_parse_inline_comment() {
+ let sql =
+ "CREATE TABLE t0 (id INT COMMENT 'comment without equal') COMMENT = 'comment with equal'";
+ // Hive dialect doesn't support `=` in table comment, please refer:
+ // [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
+ match all_dialects_except(|d| d.is::<HiveDialect>()).verified_stmt(sql) {
+ Statement::CreateTable(CreateTable {
+ columns, comment, ..
+ }) => {
+ assert_eq!(
+ columns,
+ vec![ColumnDef {
+ name: Ident::new("id".to_string()),
+ data_type: DataType::Int(None),
+ collation: None,
+ options: vec![ColumnOptionDef {
+ name: None,
+ option: Comment("comment without equal".to_string()),
+ }]
+ }]
+ );
+ assert_eq!(
+ comment.unwrap(),
+ CommentDef::WithEq("comment with equal".to_string())
+ );
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn test_buffer_reuse() {
let d = GenericDialect {};
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -713,11 +713,11 @@ fn parse_create_table_primary_and_unique_key_characteristic_test() {
#[test]
fn parse_create_table_comment() {
- let canonical = "CREATE TABLE foo (bar INT) COMMENT 'baz'";
+ let without_equal = "CREATE TABLE foo (bar INT) COMMENT 'baz'";
let with_equal = "CREATE TABLE foo (bar INT) COMMENT = 'baz'";
- for sql in [canonical, with_equal] {
- match mysql().one_statement_parses_to(sql, canonical) {
+ for sql in [without_equal, with_equal] {
+ match mysql().verified_stmt(sql) {
Statement::CreateTable(CreateTable { name, comment, .. }) => {
assert_eq!(name.to_string(), "foo");
assert_eq!(comment.expect("Should exist").to_string(), "baz");
| Table comment is always parsed as CommentDef::WithoutEq
Say I have the following table:
```sql
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ๅฃๅบงๅ
้จID',
user_name VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id),
) COMMENT = 'users of the service';
```
And I parse and re-build it with sqlparser like this:
```rust
use sqlparser::{
dialect,
parser::Parser,
};
pub fn test() {
let dialect = dialect::GenericDialect {};
let parsed = Parser::parse_sql(&dialect, r#"
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ๅฃๅบงๅ
้จID',
user_name VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
) COMMENT = 'users of the service';
"#);
let binding = parsed.unwrap();
let stmt = binding.first().unwrap();
println!("{}", stmt.to_string());
}
```
then I got the following result:
```
CREATE TABLE users (user_id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ๅฃๅบงๅ
้จID', user_name VARCHAR(255) NOT NULL, PRIMARY KEY (user_id)) COMMENT 'users of the service'
```
It looks like a table comment is always treated as `CommentDef::WithoutEq` here.
https://github.com/apache/datafusion-sqlparser-rs/blob/main/src/parser/mod.rs#L5877
| ee90373d35e47823c7c0b3afc39beafd1d29f9ca | [
"test_parse_inline_comment",
"parse_create_table_comment"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_cube_display",
"ast::tests::test_one_or_many_with_parens_as_ref",
"... | [] | [] | |
71c35d4dfddc89cfdd8f67bdc4c5d4e701a355e8 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5024,6 +5024,27 @@ impl<'a> Parser<'a> {
break;
}
}
+
+ // BigQuery accepts any number of quoted identifiers of a table name.
+ // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_identifiers
+ if dialect_of!(self is BigQueryDialect)
+ && idents.iter().any(|ident| ident.value.contains('.'))
+ {
+ idents = idents
+ .into_iter()
+ .flat_map(|ident| {
+ ident
+ .value
+ .split('.')
+ .map(|value| Ident {
+ value: value.into(),
+ quote_style: ident.quote_style,
+ })
+ .collect::<Vec<_>>()
+ })
+ .collect()
+ }
+
Ok(ObjectName(idents))
}
| apache__datafusion-sqlparser-rs-971 | 971 | Why do you care whether it's parsed as `[Ident("d.s.t")]` or `[Ident("d"), Ident("s"), Ident("t")]`? Maybe you could consume both.
The method is here
https://github.com/sqlparser-rs/sqlparser-rs/blob/097e7ad56ed09e5757fbf0719d07194aa93521e8/src/parser.rs#L4684-L4695
and can be customized like this
https://github.com/sqlparser-rs/sqlparser-rs/blob/097e7ad56ed09e5757fbf0719d07194aa93521e8/src/parser.rs#L6422-L6426 | [
"889"
] | 0.37 | apache/datafusion-sqlparser-rs | 2023-09-20T19:42:47Z | diff --git a/src/test_utils.rs b/src/test_utils.rs
--- a/src/test_utils.rs
+++ b/src/test_utils.rs
@@ -159,6 +159,24 @@ impl TestedDialects {
}
}
+ /// Ensures that `sql` parses as a single [`Select`], and that additionally:
+ ///
+ /// 1. parsing `sql` results in the same [`Statement`] as parsing
+ /// `canonical`.
+ ///
+ /// 2. re-serializing the result of parsing `sql` produces the same
+ /// `canonical` sql string
+ pub fn verified_only_select_with_canonical(&self, query: &str, canonical: &str) -> Select {
+ let q = match self.one_statement_parses_to(query, canonical) {
+ Statement::Query(query) => *query,
+ _ => panic!("Expected Query"),
+ };
+ match *q.body {
+ SetExpr::Select(s) => *s,
+ _ => panic!("Expected SetExpr::Select"),
+ }
+ }
+
/// Ensures that `sql` parses as an [`Expr`], and that
/// re-serializing the parse result produces the same `sql`
/// string (is not modified after a serialization round-trip).
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -13,6 +13,8 @@
#[macro_use]
mod test_utils;
+use std::ops::Deref;
+
use sqlparser::ast::*;
use sqlparser::dialect::{BigQueryDialect, GenericDialect};
use test_utils::*;
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -84,9 +86,24 @@ fn parse_raw_literal() {
#[test]
fn parse_table_identifiers() {
- fn test_table_ident(ident: &str, expected: Vec<Ident>) {
+ /// Parses a table identifier ident and verifies that re-serializing the
+ /// parsed identifier produces the original ident string.
+ ///
+ /// In some cases, re-serializing the result of the parsed ident is not
+ /// expected to produce the original ident string. canonical is provided
+ /// instead as the canonical representation of the identifier for comparison.
+ /// For example, re-serializing the result of ident `foo.bar` produces
+ /// the equivalent canonical representation `foo`.`bar`
+ fn test_table_ident(ident: &str, canonical: Option<&str>, expected: Vec<Ident>) {
let sql = format!("SELECT 1 FROM {ident}");
- let select = bigquery().verified_only_select(&sql);
+ let canonical = canonical.map(|ident| format!("SELECT 1 FROM {ident}"));
+
+ let select = if let Some(canonical) = canonical {
+ bigquery().verified_only_select_with_canonical(&sql, canonical.deref())
+ } else {
+ bigquery().verified_only_select(&sql)
+ };
+
assert_eq!(
select.from,
vec![TableWithJoins {
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -102,26 +119,30 @@ fn parse_table_identifiers() {
},]
);
}
+
fn test_table_ident_err(ident: &str) {
let sql = format!("SELECT 1 FROM {ident}");
assert!(bigquery().parse_sql_statements(&sql).is_err());
}
- test_table_ident("da-sh-es", vec![Ident::new("da-sh-es")]);
+ test_table_ident("da-sh-es", None, vec![Ident::new("da-sh-es")]);
- test_table_ident("`spa ce`", vec![Ident::with_quote('`', "spa ce")]);
+ test_table_ident("`spa ce`", None, vec![Ident::with_quote('`', "spa ce")]);
test_table_ident(
"`!@#$%^&*()-=_+`",
+ None,
vec![Ident::with_quote('`', "!@#$%^&*()-=_+")],
);
test_table_ident(
"_5abc.dataField",
+ None,
vec![Ident::new("_5abc"), Ident::new("dataField")],
);
test_table_ident(
"`5abc`.dataField",
+ None,
vec![Ident::with_quote('`', "5abc"), Ident::new("dataField")],
);
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -129,6 +150,7 @@ fn parse_table_identifiers() {
test_table_ident(
"abc5.dataField",
+ None,
vec![Ident::new("abc5"), Ident::new("dataField")],
);
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -136,13 +158,76 @@ fn parse_table_identifiers() {
test_table_ident(
"`GROUP`.dataField",
+ None,
vec![Ident::with_quote('`', "GROUP"), Ident::new("dataField")],
);
// TODO: this should be error
// test_table_ident_err("GROUP.dataField");
- test_table_ident("abc5.GROUP", vec![Ident::new("abc5"), Ident::new("GROUP")]);
+ test_table_ident(
+ "abc5.GROUP",
+ None,
+ vec![Ident::new("abc5"), Ident::new("GROUP")],
+ );
+
+ test_table_ident(
+ "`foo.bar.baz`",
+ Some("`foo`.`bar`.`baz`"),
+ vec![
+ Ident::with_quote('`', "foo"),
+ Ident::with_quote('`', "bar"),
+ Ident::with_quote('`', "baz"),
+ ],
+ );
+
+ test_table_ident(
+ "`foo.bar`.`baz`",
+ Some("`foo`.`bar`.`baz`"),
+ vec![
+ Ident::with_quote('`', "foo"),
+ Ident::with_quote('`', "bar"),
+ Ident::with_quote('`', "baz"),
+ ],
+ );
+
+ test_table_ident(
+ "`foo`.`bar.baz`",
+ Some("`foo`.`bar`.`baz`"),
+ vec![
+ Ident::with_quote('`', "foo"),
+ Ident::with_quote('`', "bar"),
+ Ident::with_quote('`', "baz"),
+ ],
+ );
+
+ test_table_ident(
+ "`foo`.`bar`.`baz`",
+ Some("`foo`.`bar`.`baz`"),
+ vec![
+ Ident::with_quote('`', "foo"),
+ Ident::with_quote('`', "bar"),
+ Ident::with_quote('`', "baz"),
+ ],
+ );
+
+ test_table_ident(
+ "`5abc.dataField`",
+ Some("`5abc`.`dataField`"),
+ vec![
+ Ident::with_quote('`', "5abc"),
+ Ident::with_quote('`', "dataField"),
+ ],
+ );
+
+ test_table_ident(
+ "`_5abc.da-sh-es`",
+ Some("`_5abc`.`da-sh-es`"),
+ vec![
+ Ident::with_quote('`', "_5abc"),
+ Ident::with_quote('`', "da-sh-es"),
+ ],
+ );
}
#[test]
| BigQuery ignores identifiers in FROM clause
tl;dr - SELECT * from d.s.t and SELECT * from \`d.s.t\` are equivalent in BigQuery and should return the same response from sqlparser.
Let's say I have database d, with schema s and table t.
In Snowflake, the following query will work - SELECT * FROM d.s.t
However, the following query will fail - SELECT * from "d.s.t" as Snowflake will look for a table called d.s.t
However, in BigQuery:
SELECT * from d.s.t and SELECT * from \`d.s.t\` are equivalent and both work. I agree it's not expected and confusing.
I really want to support this in someway in sqlparser: If the Dialect is BigQuery, ignore the identifiers in the FROM clause.
(I'm getting the wrong result for SELECT * from \`d.s.t\`, the table is with one value instead of 3).
As I'm not a Rust developer, any guidance with this one? Every manipulation i'm trying to do is already after the words are tokenised, so I don't have a way to ignore the identifier.
Appreciate your guidance here!
Thank you!
| 71c35d4dfddc89cfdd8f67bdc4c5d4e701a355e8 | [
"parse_table_identifiers"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_rollup_display",
"ast::tests::test... | [] | [] |
2593dcfb79bb8709a6014673d47ffefcf9a68e20 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3941,9 +3941,15 @@ impl<'a> Parser<'a> {
match next_token.token {
Token::Word(w) if w.keyword == Keyword::PRIMARY || w.keyword == Keyword::UNIQUE => {
let is_primary = w.keyword == Keyword::PRIMARY;
- if is_primary {
- self.expect_keyword(Keyword::KEY)?;
- }
+
+ // parse optional [KEY]
+ let _ = self.parse_keyword(Keyword::KEY);
+
+ // optional constraint name
+ let name = self
+ .maybe_parse(|parser| parser.parse_identifier())
+ .or(name);
+
let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
Ok(Some(TableConstraint::Unique {
name,
| apache__datafusion-sqlparser-rs-962 | 962 | <img width="1090" alt="image" src="https://github.com/sqlparser-rs/sqlparser-rs/assets/82564604/004df0e9-f7e5-40ce-910a-58afb7878710">
<img width="922" alt="image" src="https://github.com/sqlparser-rs/sqlparser-rs/assets/82564604/3a1eb52f-e961-4587-a711-8b54edb3568d">
Should we add a branch judgment, if the next token is the keyword Key, then continue to iterate downward?
| [
"961"
] | 0.37 | apache/datafusion-sqlparser-rs | 2023-08-31T11:42:51Z | diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -297,6 +297,62 @@ fn parse_create_table_auto_increment() {
}
}
+#[test]
+fn parse_create_table_unique_key() {
+ let sql = "CREATE TABLE foo (id INT PRIMARY KEY AUTO_INCREMENT, bar INT NOT NULL, UNIQUE KEY bar_key (bar))";
+ let canonical = "CREATE TABLE foo (id INT PRIMARY KEY AUTO_INCREMENT, bar INT NOT NULL, CONSTRAINT bar_key UNIQUE (bar))";
+ match mysql().one_statement_parses_to(sql, canonical) {
+ Statement::CreateTable {
+ name,
+ columns,
+ constraints,
+ ..
+ } => {
+ assert_eq!(name.to_string(), "foo");
+ assert_eq!(
+ vec![TableConstraint::Unique {
+ name: Some(Ident::new("bar_key")),
+ columns: vec![Ident::new("bar")],
+ is_primary: false
+ }],
+ constraints
+ );
+ assert_eq!(
+ vec![
+ ColumnDef {
+ name: Ident::new("id"),
+ data_type: DataType::Int(None),
+ collation: None,
+ options: vec![
+ ColumnOptionDef {
+ name: None,
+ option: ColumnOption::Unique { is_primary: true },
+ },
+ ColumnOptionDef {
+ name: None,
+ option: ColumnOption::DialectSpecific(vec![Token::make_keyword(
+ "AUTO_INCREMENT"
+ )]),
+ },
+ ],
+ },
+ ColumnDef {
+ name: Ident::new("bar"),
+ data_type: DataType::Int(None),
+ collation: None,
+ options: vec![ColumnOptionDef {
+ name: None,
+ option: ColumnOption::NotNull,
+ },],
+ },
+ ],
+ columns
+ );
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn parse_create_table_comment() {
let canonical = "CREATE TABLE foo (bar INT) COMMENT 'baz'";
| Error: SchemaParse(ParserError("Expected a list of columns in parentheses, found: KEY"))
The SQL statement I want to parse is:
```sql
CREATE TABLE `funds_sale` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '',
PRIMARY KEY (`id`, `cid`),
UNIQUE KEY `uk_bill_str` (`cid`, `bill_str`),
KEY `idx_biz_str` (`cid`, `biz_str`)
) ENGINE = InnoDB AUTO_INCREMENT = 878936 DEFAULT CHARSET = utf8mb4 COMMENT = ''
```
but I encountered an error.
```rust
Error: SchemaParse(ParserError("Expected a list of columns in parentheses, found: KEY"))
```
| 71c35d4dfddc89cfdd8f67bdc4c5d4e701a355e8 | [
"parse_create_table_unique_key"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_window_frame_default",
"ast::tests::test_interval_display",
"ast::tests::test_rollup_display",
"dialect::tests::t... | [] | [] |
f60a6f758ce12aa84fa3801a38c9501f55f245ef | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -1540,8 +1540,15 @@ pub enum Statement {
///
/// Note: This is a MySQL-specific statement.
Use { db_name: Ident },
- /// `{ BEGIN [ TRANSACTION | WORK ] | START TRANSACTION } ...`
- StartTransaction { modes: Vec<TransactionMode> },
+ /// `START [ TRANSACTION | WORK ] | START TRANSACTION } ...`
+ /// If `begin` is false.
+ ///
+ /// `BEGIN [ TRANSACTION | WORK ] | START TRANSACTION } ...`
+ /// If `begin` is true
+ StartTransaction {
+ modes: Vec<TransactionMode>,
+ begin: bool,
+ },
/// `SET TRANSACTION ...`
SetTransaction {
modes: Vec<TransactionMode>,
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -2720,8 +2727,15 @@ impl fmt::Display for Statement {
}
Ok(())
}
- Statement::StartTransaction { modes } => {
- write!(f, "START TRANSACTION")?;
+ Statement::StartTransaction {
+ modes,
+ begin: syntax_begin,
+ } => {
+ if *syntax_begin {
+ write!(f, "BEGIN TRANSACTION")?;
+ } else {
+ write!(f, "START TRANSACTION")?;
+ }
if !modes.is_empty() {
write!(f, " {}", display_comma_separated(modes))?;
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6877,6 +6877,7 @@ impl<'a> Parser<'a> {
self.expect_keyword(Keyword::TRANSACTION)?;
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
+ begin: false,
})
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6884,6 +6885,7 @@ impl<'a> Parser<'a> {
let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
+ begin: true,
})
}
| apache__datafusion-sqlparser-rs-935 | 935 | [
"919"
] | 0.36 | apache/datafusion-sqlparser-rs | 2023-07-25T11:35:11Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5732,7 +5732,7 @@ fn lateral_derived() {
#[test]
fn parse_start_transaction() {
match verified_stmt("START TRANSACTION READ ONLY, READ WRITE, ISOLATION LEVEL SERIALIZABLE") {
- Statement::StartTransaction { modes } => assert_eq!(
+ Statement::StartTransaction { modes, .. } => assert_eq!(
modes,
vec![
TransactionMode::AccessMode(TransactionAccessMode::ReadOnly),
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5749,7 +5749,7 @@ fn parse_start_transaction() {
"START TRANSACTION READ ONLY READ WRITE ISOLATION LEVEL SERIALIZABLE",
"START TRANSACTION READ ONLY, READ WRITE, ISOLATION LEVEL SERIALIZABLE",
) {
- Statement::StartTransaction { modes } => assert_eq!(
+ Statement::StartTransaction { modes, .. } => assert_eq!(
modes,
vec![
TransactionMode::AccessMode(TransactionAccessMode::ReadOnly),
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5761,9 +5761,9 @@ fn parse_start_transaction() {
}
verified_stmt("START TRANSACTION");
- one_statement_parses_to("BEGIN", "START TRANSACTION");
- one_statement_parses_to("BEGIN WORK", "START TRANSACTION");
- one_statement_parses_to("BEGIN TRANSACTION", "START TRANSACTION");
+ one_statement_parses_to("BEGIN", "BEGIN TRANSACTION");
+ one_statement_parses_to("BEGIN WORK", "BEGIN TRANSACTION");
+ one_statement_parses_to("BEGIN TRANSACTION", "BEGIN TRANSACTION");
verified_stmt("START TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
verified_stmt("START TRANSACTION ISOLATION LEVEL READ COMMITTED");
| "BEGIN TRANSACTION" gets stringified as "START TRANSACTION"
Parsing the following:
```sql
BEGIN;
```
and then calling `.to_string()` on the parsed statement, results in
```sql
START TRANSACTION;
```
The `START` syntax in not supported in SQLite. But ideally, the parser would keep track of which variant of the syntax was used, and be able to use it in the `Format` implementation.
| 9a39afbe07b6eecd8819fe1f7d9af2b4aad3a6d7 | [
"parse_start_transaction"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_window_frame_default",
"ast::tests... | [] | [] | |
481551c0753312550fc5f4d94319e9a92497caad | diff --git a/src/ast/value.rs b/src/ast/value.rs
--- a/src/ast/value.rs
+++ b/src/ast/value.rs
@@ -123,6 +123,7 @@ impl fmt::Display for Value {
pub enum DateTimeField {
Year,
Month,
+ Week,
Day,
Hour,
Minute,
diff --git a/src/ast/value.rs b/src/ast/value.rs
--- a/src/ast/value.rs
+++ b/src/ast/value.rs
@@ -149,6 +150,7 @@ impl fmt::Display for DateTimeField {
f.write_str(match self {
DateTimeField::Year => "YEAR",
DateTimeField::Month => "MONTH",
+ DateTimeField::Week => "WEEK",
DateTimeField::Day => "DAY",
DateTimeField::Hour => "HOUR",
DateTimeField::Minute => "MINUTE",
diff --git a/src/keywords.rs b/src/keywords.rs
--- a/src/keywords.rs
+++ b/src/keywords.rs
@@ -518,6 +518,7 @@ define_keywords!(
VERSIONING,
VIEW,
VIRTUAL,
+ WEEK,
WHEN,
WHENEVER,
WHERE,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -909,6 +909,7 @@ impl<'a> Parser<'a> {
Token::Word(w) => match w.keyword {
Keyword::YEAR => Ok(DateTimeField::Year),
Keyword::MONTH => Ok(DateTimeField::Month),
+ Keyword::WEEK => Ok(DateTimeField::Week),
Keyword::DAY => Ok(DateTimeField::Day),
Keyword::HOUR => Ok(DateTimeField::Hour),
Keyword::MINUTE => Ok(DateTimeField::Minute),
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -966,6 +967,7 @@ impl<'a> Parser<'a> {
if [
Keyword::YEAR,
Keyword::MONTH,
+ Keyword::WEEK,
Keyword::DAY,
Keyword::HOUR,
Keyword::MINUTE,
| apache__datafusion-sqlparser-rs-436 | 436 | [
"435"
] | 0.15 | apache/datafusion-sqlparser-rs | 2022-03-11T02:39:58Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1384,6 +1384,7 @@ fn parse_extract() {
one_statement_parses_to("SELECT EXTRACT(year from d)", "SELECT EXTRACT(YEAR FROM d)");
verified_stmt("SELECT EXTRACT(MONTH FROM d)");
+ verified_stmt("SELECT EXTRACT(WEEK FROM d)");
verified_stmt("SELECT EXTRACT(DAY FROM d)");
verified_stmt("SELECT EXTRACT(HOUR FROM d)");
verified_stmt("SELECT EXTRACT(MINUTE FROM d)");
| extract operator: add support for `week` keywords
Support ` EXTRACT(WEEK FROM to_timestamp('2020-09-08T12:00:00+00:00'))`
| 803fd6c970cced96442c56d5952e8cf671bf10e3 | [
"parse_extract"
] | [
"ast::tests::test_cube_display",
"ast::tests::test_rollup_display",
"dialect::tests::test_is_dialect",
"ast::tests::test_window_frame_default",
"ast::tests::test_grouping_sets_display",
"parser::tests::test_prev_index",
"tokenizer::tests::tokenize_comment",
"tokenizer::tests::tokenize_bitwise_op",
"... | [] | [] | |
f60a6f758ce12aa84fa3801a38c9501f55f245ef | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -957,17 +957,18 @@ impl<'a> Parser<'a> {
}
pub fn parse_time_functions(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
- let (args, order_by) = if self.consume_token(&Token::LParen) {
- self.parse_optional_args_with_orderby()?
+ let (args, order_by, special) = if self.consume_token(&Token::LParen) {
+ let (args, order_by) = self.parse_optional_args_with_orderby()?;
+ (args, order_by, false)
} else {
- (vec![], vec![])
+ (vec![], vec![], true)
};
Ok(Expr::Function(Function {
name,
args,
over: None,
distinct: false,
- special: false,
+ special,
order_by,
}))
}
| apache__datafusion-sqlparser-rs-930 | 930 | Thanks @lovasoa the "do we have trailing parens" is already tracked by the "special" flag:
https://github.com/sqlparser-rs/sqlparser-rs/blob/eb288487a6a938b45004deda850e550a74fcf935/src/ast/mod.rs#L3494-L3496
https://github.com/sqlparser-rs/sqlparser-rs/blob/eb288487a6a938b45004deda850e550a74fcf935/src/ast/mod.rs#L3522-L3523
Perhaps we just need to adjust the mysql dialect to set that too | [
"918"
] | 0.36 | apache/datafusion-sqlparser-rs | 2023-07-22T21:24:00Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6703,90 +6703,37 @@ fn parse_offset_and_limit() {
#[test]
fn parse_time_functions() {
- let sql = "SELECT CURRENT_TIMESTAMP()";
- let select = verified_only_select(sql);
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::new("CURRENT_TIMESTAMP")]),
- args: vec![],
- over: None,
- distinct: false,
- special: false,
- order_by: vec![],
- }),
- expr_from_projection(&select.projection[0])
- );
-
- // Validating Parenthesis
- one_statement_parses_to("SELECT CURRENT_TIMESTAMP", sql);
-
- let sql = "SELECT CURRENT_TIME()";
- let select = verified_only_select(sql);
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::new("CURRENT_TIME")]),
- args: vec![],
- over: None,
- distinct: false,
- special: false,
- order_by: vec![],
- }),
- expr_from_projection(&select.projection[0])
- );
-
- // Validating Parenthesis
- one_statement_parses_to("SELECT CURRENT_TIME", sql);
-
- let sql = "SELECT CURRENT_DATE()";
- let select = verified_only_select(sql);
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::new("CURRENT_DATE")]),
- args: vec![],
- over: None,
- distinct: false,
- special: false,
- order_by: vec![],
- }),
- expr_from_projection(&select.projection[0])
- );
-
- // Validating Parenthesis
- one_statement_parses_to("SELECT CURRENT_DATE", sql);
-
- let sql = "SELECT LOCALTIME()";
- let select = verified_only_select(sql);
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::new("LOCALTIME")]),
+ fn test_time_function(func_name: &'static str) {
+ let sql = format!("SELECT {}()", func_name);
+ let select = verified_only_select(&sql);
+ let select_localtime_func_call_ast = Function {
+ name: ObjectName(vec![Ident::new(func_name)]),
args: vec![],
over: None,
distinct: false,
special: false,
order_by: vec![],
- }),
- expr_from_projection(&select.projection[0])
- );
-
- // Validating Parenthesis
- one_statement_parses_to("SELECT LOCALTIME", sql);
+ };
+ assert_eq!(
+ &Expr::Function(select_localtime_func_call_ast.clone()),
+ expr_from_projection(&select.projection[0])
+ );
- let sql = "SELECT LOCALTIMESTAMP()";
- let select = verified_only_select(sql);
- assert_eq!(
- &Expr::Function(Function {
- name: ObjectName(vec![Ident::new("LOCALTIMESTAMP")]),
- args: vec![],
- over: None,
- distinct: false,
- special: false,
- order_by: vec![],
- }),
- expr_from_projection(&select.projection[0])
- );
+ // Validating Parenthesis
+ let sql_without_parens = format!("SELECT {}", func_name);
+ let mut ast_without_parens = select_localtime_func_call_ast.clone();
+ ast_without_parens.special = true;
+ assert_eq!(
+ &Expr::Function(ast_without_parens.clone()),
+ expr_from_projection(&verified_only_select(&sql_without_parens).projection[0])
+ );
+ }
- // Validating Parenthesis
- one_statement_parses_to("SELECT LOCALTIMESTAMP", sql);
+ test_time_function("CURRENT_TIMESTAMP");
+ test_time_function("CURRENT_TIME");
+ test_time_function("CURRENT_DATE");
+ test_time_function("LOCALTIME");
+ test_time_function("LOCALTIMESTAMP");
}
#[test]
| sqlparser breaks CURRENT_TIMESTAMP for sqlite
In [SQLPage](https://github.com/lovasoa/SQLpage), we parse SQL queries using sqlparser in order to be able to modify them, and then dump them as text to run them on the database. This requires the process of parsing and then stringifying back not to break the semantics nor the syntax of the query.
However, the following SQLite query:
```sql
SELECT CURRENT_TIMESTAMP;
```
when parsed and then dumped back, gives:
```sql
SELECT CURRENT_TIMESTAMP();
```
This breaks the syntax for SQLite, which gives
```
sqlite> SELECT CURRENT_TIMESTAMP();
Error: in prepare, near "(": syntax error (1)
```
| 9a39afbe07b6eecd8819fe1f7d9af2b4aad3a6d7 | [
"parse_time_functions"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_window_frame_default",
"dialect::t... | [] | [] |
48fa79d744fdc9c3aa1060c7eb35ea962eeb6837 | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3774,7 +3774,12 @@ impl<'a> Parser<'a> {
});
}
- let variable = self.parse_object_name()?;
+ let variable = if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE]) {
+ ObjectName(vec!["TIMEZONE".into()])
+ } else {
+ self.parse_object_name()?
+ };
+
if variable.to_string().eq_ignore_ascii_case("NAMES")
&& dialect_of!(self is MySqlDialect | GenericDialect)
{
| apache__datafusion-sqlparser-rs-617 | 617 | @435201823 which sqlparser version did you use that worked? i switched back to 0.5.0 but it still not works | [
"303"
] | 0.23 | apache/datafusion-sqlparser-rs | 2022-09-19T17:37:31Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4663,6 +4663,52 @@ fn parse_set_transaction() {
}
}
+#[test]
+fn parse_set_variable() {
+ match verified_stmt("SET SOMETHING = '1'") {
+ Statement::SetVariable {
+ local,
+ hivevar,
+ variable,
+ value,
+ } => {
+ assert!(!local);
+ assert!(!hivevar);
+ assert_eq!(variable, ObjectName(vec!["SOMETHING".into()]));
+ assert_eq!(
+ value,
+ vec![Expr::Value(Value::SingleQuotedString("1".into()))]
+ );
+ }
+ _ => unreachable!(),
+ }
+
+ one_statement_parses_to("SET SOMETHING TO '1'", "SET SOMETHING = '1'");
+}
+
+#[test]
+fn parse_set_time_zone() {
+ match verified_stmt("SET TIMEZONE = 'UTC'") {
+ Statement::SetVariable {
+ local,
+ hivevar,
+ variable,
+ value,
+ } => {
+ assert!(!local);
+ assert!(!hivevar);
+ assert_eq!(variable, ObjectName(vec!["TIMEZONE".into()]));
+ assert_eq!(
+ value,
+ vec![Expr::Value(Value::SingleQuotedString("UTC".into()))]
+ );
+ }
+ _ => unreachable!(),
+ }
+
+ one_statement_parses_to("SET TIME ZONE TO 'UTC'", "SET TIMEZONE = 'UTC'");
+}
+
#[test]
fn parse_commit() {
match verified_stmt("COMMIT") {
| can not parse "SET TIME ZONE 'UTC'"
It was normal to parse "SET TIME ZONE 'UTC'" a few days ago. Today I tried to parse "SET TIME ZONE 'UTC'" and there was an error.
```
pub fn sql_parse_test() {
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::Parser;
let sql = r#"set time zone 'UTC'"#;
let dialect = GenericDialect {};
let ast = Parser::parse_sql(&dialect, sql).unwrap();
println!("AST: {:?}", ast);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sql_parse() {
sql_parse_test();
}
}
```
```
called `Result::unwrap()` on an `Err` value: ParserError("Expected equals sign or TO, found: zone")
thread 'func::sql_parse_test::tests::test_sql_parse' panicked at 'called `Result::unwrap()` on an `Err` value: ParserError("Expected equals sign or TO, found: zone")', src\func\sql_parse_test.rs:9:48
```
| fccae77c5e3056214b2d06902577925ec8d5549d | [
"parse_set_time_zone"
] | [
"ast::tests::test_grouping_sets_display",
"ast::tests::test_cube_display",
"ast::tests::test_window_frame_default",
"dialect::tests::test_is_dialect",
"parser::tests::test_prev_index",
"ast::tests::test_rollup_display",
"tokenizer::tests::tokenize_bitwise_op",
"parser::tests::test_parse_limit",
"tok... | [] | [] |
0bb49cea9908e0d7389a46519e368efeeab89e79 | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -570,7 +570,7 @@ impl<'a> Parser<'a> {
})
}
}
- Token::Placeholder(_) => {
+ Token::Placeholder(_) | Token::Colon | Token::AtSign => {
self.prev_token();
Ok(Expr::Value(self.parse_value()?))
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -1774,7 +1774,7 @@ impl<'a> Parser<'a> {
.iter()
.any(|d| kw.keyword == *d) =>
{
- break
+ break;
}
Token::RParen | Token::EOF => break,
_ => continue,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3026,6 +3026,11 @@ impl<'a> Parser<'a> {
Token::EscapedStringLiteral(ref s) => Ok(Value::EscapedStringLiteral(s.to_string())),
Token::HexStringLiteral(ref s) => Ok(Value::HexStringLiteral(s.to_string())),
Token::Placeholder(ref s) => Ok(Value::Placeholder(s.to_string())),
+ tok @ Token::Colon | tok @ Token::AtSign => {
+ let ident = self.parse_identifier()?;
+ let placeholder = tok.to_string() + &ident.value;
+ Ok(Value::Placeholder(placeholder))
+ }
unexpected => self.expected("a value", unexpected),
}
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4844,12 +4849,12 @@ impl<'a> Parser<'a> {
Some(_) => {
return Err(ParserError::ParserError(
"expected UPDATE, DELETE or INSERT in merge clause".to_string(),
- ))
+ ));
}
None => {
return Err(ParserError::ParserError(
"expected UPDATE, DELETE or INSERT in merge clause".to_string(),
- ))
+ ));
}
},
);
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -677,13 +677,14 @@ impl<'a> Tokenizer<'a> {
}
}
'@' => self.consume_and_return(chars, Token::AtSign),
- '?' => self.consume_and_return(chars, Token::Placeholder(String::from("?"))),
+ '?' => {
+ chars.next();
+ let s = peeking_take_while(chars, |ch| ch.is_numeric());
+ Ok(Some(Token::Placeholder(String::from("?") + &s)))
+ }
'$' => {
chars.next();
- let s = peeking_take_while(
- chars,
- |ch| matches!(ch, '0'..='9' | 'A'..='Z' | 'a'..='z'),
- );
+ let s = peeking_take_while(chars, |ch| ch.is_alphanumeric() || ch == '_');
Ok(Some(Token::Placeholder(String::from("$") + &s)))
}
//whitespace check (including unicode chars) should be last as it covers some of the chars above
| apache__datafusion-sqlparser-rs-604 | 604 | [
"603"
] | 0.22 | apache/datafusion-sqlparser-rs | 2022-09-05T19:50:24Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -22,6 +22,7 @@
mod test_utils;
use matches::assert_matches;
+use sqlparser::ast::SelectItem::UnnamedExpr;
use sqlparser::ast::*;
use sqlparser::dialect::{
AnsiDialect, BigQueryDialect, ClickHouseDialect, GenericDialect, HiveDialect, MsSqlDialect,
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5213,6 +5214,17 @@ fn test_placeholder() {
rows: OffsetRows::None,
}),
);
+
+ let sql = "SELECT $fromage_franรงais, :x, ?123";
+ let ast = dialects.verified_only_select(sql);
+ assert_eq!(
+ ast.projection,
+ vec![
+ UnnamedExpr(Expr::Value(Value::Placeholder("$fromage_franรงais".into()))),
+ UnnamedExpr(Expr::Value(Value::Placeholder(":x".into()))),
+ UnnamedExpr(Expr::Value(Value::Placeholder("?123".into()))),
+ ]
+ );
}
#[test]
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -16,8 +16,10 @@
#[macro_use]
mod test_utils;
+
use test_utils::*;
+use sqlparser::ast::SelectItem::UnnamedExpr;
use sqlparser::ast::*;
use sqlparser::dialect::{GenericDialect, SQLiteDialect};
use sqlparser::tokenizer::Token;
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -73,14 +75,14 @@ fn parse_create_table_auto_increment() {
options: vec![
ColumnOptionDef {
name: None,
- option: ColumnOption::Unique { is_primary: true }
+ option: ColumnOption::Unique { is_primary: true },
},
ColumnOptionDef {
name: None,
option: ColumnOption::DialectSpecific(vec![Token::make_keyword(
"AUTOINCREMENT"
- )])
- }
+ )]),
+ },
],
}],
columns
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -118,6 +120,19 @@ fn parse_create_sqlite_quote() {
}
}
+#[test]
+fn test_placeholder() {
+ // In postgres, this would be the absolute value operator '@' applied to the column 'xxx'
+ // But in sqlite, this is a named parameter.
+ // see https://www.sqlite.org/lang_expr.html#varparam
+ let sql = "SELECT @xxx";
+ let ast = sqlite().verified_only_select(sql);
+ assert_eq!(
+ ast.projection[0],
+ UnnamedExpr(Expr::Value(Value::Placeholder("@xxx".into()))),
+ );
+}
+
fn sqlite() -> TestedDialects {
TestedDialects {
dialects: vec![Box::new(SQLiteDialect {})],
| Placeholders can contain underscores
The following prepared statement [parses correctly](http://sqlfiddle.com/#!5/9eecb7/15986) in SQLite:
```sql
select $a_b_c_hรฉhรฉ;
```
However, it fails to parse in sqlparser-rs, which only accepts `[a-zA-Z0-9]` in placeholders.
| 0bb49cea9908e0d7389a46519e368efeeab89e79 | [
"test_placeholder"
] | [
"ast::tests::test_cube_display",
"ast::tests::test_rollup_display",
"ast::tests::test_window_frame_default",
"tokenizer::tests::tokenize_comment_at_eof",
"tokenizer::tests::tokenize_comment",
"dialect::tests::test_is_dialect",
"ast::tests::test_grouping_sets_display",
"tokenizer::tests::tokenize_expla... | [] | [] | |
31ba0012f747c9e2fc551b95fd2ee3bfa46b12e6 | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -331,13 +331,14 @@ pub enum Expr {
substring_from: Option<Box<Expr>>,
substring_for: Option<Box<Expr>>,
},
- /// TRIM([BOTH | LEADING | TRAILING] <expr> [FROM <expr>])\
+ /// TRIM([BOTH | LEADING | TRAILING] [<expr> FROM] <expr>)\
/// Or\
/// TRIM(<expr>)
Trim {
expr: Box<Expr>,
- // ([BOTH | LEADING | TRAILING], <expr>)
- trim_where: Option<(TrimWhereField, Box<Expr>)>,
+ // ([BOTH | LEADING | TRAILING]
+ trim_where: Option<TrimWhereField>,
+ trim_what: Option<Box<Expr>>,
},
/// `expr COLLATE collation`
Collate {
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -629,10 +630,17 @@ impl fmt::Display for Expr {
}
Expr::IsDistinctFrom(a, b) => write!(f, "{} IS DISTINCT FROM {}", a, b),
Expr::IsNotDistinctFrom(a, b) => write!(f, "{} IS NOT DISTINCT FROM {}", a, b),
- Expr::Trim { expr, trim_where } => {
+ Expr::Trim {
+ expr,
+ trim_where,
+ trim_what,
+ } => {
write!(f, "TRIM(")?;
- if let Some((ident, trim_char)) = trim_where {
- write!(f, "{} {} FROM {}", ident, trim_char, expr)?;
+ if let Some(ident) = trim_where {
+ write!(f, "{} ", ident)?;
+ }
+ if let Some(trim_char) = trim_what {
+ write!(f, "{} FROM {}", trim_char, expr)?;
} else {
write!(f, "{}", expr)?;
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -874,29 +874,37 @@ impl<'a> Parser<'a> {
})
}
- /// TRIM (WHERE 'text' FROM 'text')\
+ /// TRIM ([WHERE] ['text' FROM] 'text')\
/// TRIM ('text')
pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError> {
self.expect_token(&Token::LParen)?;
- let mut where_expr = None;
+ let mut trim_where = None;
if let Token::Word(word) = self.peek_token() {
if [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING]
.iter()
.any(|d| word.keyword == *d)
{
- let trim_where = self.parse_trim_where()?;
- let sub_expr = self.parse_expr()?;
- self.expect_keyword(Keyword::FROM)?;
- where_expr = Some((trim_where, Box::new(sub_expr)));
+ trim_where = Some(self.parse_trim_where()?);
}
}
let expr = self.parse_expr()?;
- self.expect_token(&Token::RParen)?;
-
- Ok(Expr::Trim {
- expr: Box::new(expr),
- trim_where: where_expr,
- })
+ if self.parse_keyword(Keyword::FROM) {
+ let trim_what = Box::new(expr);
+ let expr = self.parse_expr()?;
+ self.expect_token(&Token::RParen)?;
+ Ok(Expr::Trim {
+ expr: Box::new(expr),
+ trim_where,
+ trim_what: Some(trim_what),
+ })
+ } else {
+ self.expect_token(&Token::RParen)?;
+ Ok(Expr::Trim {
+ expr: Box::new(expr),
+ trim_where,
+ trim_what: None,
+ })
+ }
}
pub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError> {
| apache__datafusion-sqlparser-rs-573 | 573 | [
"568"
] | 0.20 | apache/datafusion-sqlparser-rs | 2022-08-12T20:35:41Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3928,7 +3928,15 @@ fn parse_trim() {
"SELECT TRIM(TRAILING 'xyz' FROM 'xyzfooxyz')",
);
+ one_statement_parses_to(
+ "SELECT TRIM('xyz' FROM 'xyzfooxyz')",
+ "SELECT TRIM('xyz' FROM 'xyzfooxyz')",
+ );
one_statement_parses_to("SELECT TRIM(' foo ')", "SELECT TRIM(' foo ')");
+ one_statement_parses_to(
+ "SELECT TRIM(LEADING ' foo ')",
+ "SELECT TRIM(LEADING ' foo ')",
+ );
assert_eq!(
ParserError::ParserError("Expected ), found: 'xyz'".to_owned()),
| Trim syntax without trimWhere and From not supported.
Postgresql syntax for trim `trim ( [ LEADING | TRAILING | BOTH ] [ characters text ] FROM string text ) โ text` allows the pattern of
`trim(chars from string)`.
sqlparser currently fails with this combo of no leading/trailing/both flag and the `from` keyword specified.
Happy to work on a pr for this fix
| 31ba0012f747c9e2fc551b95fd2ee3bfa46b12e6 | [
"parse_trim"
] | [
"ast::tests::test_rollup_display",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_window_frame_default",
"dialect::tests::test_is_dialect",
"parser::tests::test_prev_index",
"tokenizer::tests::tokenize_bitwise_op",
"tokenizer::tests::tokenize_comment_at_eo... | [] | [] | |
f7f14df4b14256a05f1dd41c7b03552fd8ea0fa1 | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -880,9 +880,9 @@ pub enum WindowFrameBound {
/// `CURRENT ROW`
CurrentRow,
/// `<N> PRECEDING` or `UNBOUNDED PRECEDING`
- Preceding(Option<u64>),
+ Preceding(Option<Box<Expr>>),
/// `<N> FOLLOWING` or `UNBOUNDED FOLLOWING`.
- Following(Option<u64>),
+ Following(Option<Box<Expr>>),
}
impl fmt::Display for WindowFrameBound {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -620,7 +620,6 @@ impl<'a> Parser<'a> {
} else {
None
};
-
Ok(Expr::Function(Function {
name,
args,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -682,7 +681,10 @@ impl<'a> Parser<'a> {
let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
None
} else {
- Some(self.parse_literal_uint()?)
+ Some(Box::new(match self.peek_token() {
+ Token::SingleQuotedString(_) => self.parse_interval()?,
+ _ => self.parse_expr()?,
+ }))
};
if self.parse_keyword(Keyword::PRECEDING) {
Ok(WindowFrameBound::Preceding(rows))
| apache__datafusion-sqlparser-rs-655 | 655 | [
"631"
] | 0.25 | apache/datafusion-sqlparser-rs | 2022-10-05T11:01:52Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2865,13 +2865,17 @@ fn parse_window_functions() {
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), \
avg(bar) OVER (ORDER BY a \
RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING), \
+ sum(bar) OVER (ORDER BY a \
+ RANGE BETWEEN INTERVAL '1' DAY PRECEDING AND INTERVAL '1 MONTH' FOLLOWING), \
+ COUNT(*) OVER (ORDER BY a \
+ RANGE BETWEEN INTERVAL '1 DAY' PRECEDING AND INTERVAL '1 DAY' FOLLOWING), \
max(baz) OVER (ORDER BY a \
ROWS UNBOUNDED PRECEDING), \
sum(qux) OVER (ORDER BY a \
GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING) \
FROM foo";
let select = verified_only_select(sql);
- assert_eq!(5, select.projection.len());
+ assert_eq!(7, select.projection.len());
assert_eq!(
&Expr::Function(Function {
name: ObjectName(vec![Ident::new("row_number")]),
| Support "date" and "timestamp" inside window frame RANGE Queries
# Support INTERVAL in window RANGE Queries
Currently, we do not support the queries taking `date` or `timestamp` for range inside window frames. Following query
```sql
SELECT
COUNT(*) OVER (ORDER BY ts RANGE BETWEEN '1 DAY' PRECEDING AND '1 DAY' FOLLOWING)
FROM t;
```
produces the error below:
```sql
ParserError("Expected literal int, found: INTERVAL")
```
Relevant section in the code, where window frame bounds are parsed can be found here.
[sqlparser-rs/parser.rs at 6afd194e947cfd800376f424ff7c300ee385cd9e ยท sqlparser-rs/sqlparser-rs](https://github.com/sqlparser-rs/sqlparser-rs/blob/6afd194e947cfd800376f424ff7c300ee385cd9e/src/parser.rs#L679)
| cacdf3305f33319bed4e870227cdd541b4c9f947 | [
"parse_window_functions"
] | [
"ast::tests::test_cube_display",
"ast::tests::test_window_frame_default",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"parser::tests::test_parse_data_type::test_ansii_character_string_types",
"parser::tests::test_parse_data_type::test_ansii_datetime_types",
"dialect::tes... | [] | [] | |
fccae77c5e3056214b2d06902577925ec8d5549d | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3142,6 +3142,10 @@ impl<'a> Parser<'a> {
Ok(DataType::Char(self.parse_optional_precision()?))
}
}
+ Keyword::CLOB => Ok(DataType::Clob(self.parse_precision()?)),
+ Keyword::BINARY => Ok(DataType::Binary(self.parse_precision()?)),
+ Keyword::VARBINARY => Ok(DataType::Varbinary(self.parse_precision()?)),
+ Keyword::BLOB => Ok(DataType::Blob(self.parse_precision()?)),
Keyword::UUID => Ok(DataType::Uuid),
Keyword::DATE => Ok(DataType::Date),
Keyword::DATETIME => Ok(DataType::Datetime),
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3355,6 +3359,13 @@ impl<'a> Parser<'a> {
}
}
+ pub fn parse_precision(&mut self) -> Result<u64, ParserError> {
+ self.expect_token(&Token::LParen)?;
+ let n = self.parse_literal_uint()?;
+ self.expect_token(&Token::RParen)?;
+ Ok(n)
+ }
+
pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> {
if self.consume_token(&Token::LParen) {
let n = self.parse_literal_uint()?;
| apache__datafusion-sqlparser-rs-618 | 618 | I think this would make a nice contribution to the library -- feel free to make a PR ๐ | [
"518"
] | 0.23 | apache/datafusion-sqlparser-rs | 2022-09-21T15:48:43Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1647,6 +1647,46 @@ fn parse_cast() {
},
expr_from_projection(only(&select.projection))
);
+
+ let sql = "SELECT CAST(id AS CLOB(50)) FROM customer";
+ let select = verified_only_select(sql);
+ assert_eq!(
+ &Expr::Cast {
+ expr: Box::new(Expr::Identifier(Ident::new("id"))),
+ data_type: DataType::Clob(50)
+ },
+ expr_from_projection(only(&select.projection))
+ );
+
+ let sql = "SELECT CAST(id AS BINARY(50)) FROM customer";
+ let select = verified_only_select(sql);
+ assert_eq!(
+ &Expr::Cast {
+ expr: Box::new(Expr::Identifier(Ident::new("id"))),
+ data_type: DataType::Binary(50)
+ },
+ expr_from_projection(only(&select.projection))
+ );
+
+ let sql = "SELECT CAST(id AS VARBINARY(50)) FROM customer";
+ let select = verified_only_select(sql);
+ assert_eq!(
+ &Expr::Cast {
+ expr: Box::new(Expr::Identifier(Ident::new("id"))),
+ data_type: DataType::Varbinary(50)
+ },
+ expr_from_projection(only(&select.projection))
+ );
+
+ let sql = "SELECT CAST(id AS BLOB(50)) FROM customer";
+ let select = verified_only_select(sql);
+ assert_eq!(
+ &Expr::Cast {
+ expr: Box::new(Expr::Identifier(Ident::new("id"))),
+ data_type: DataType::Blob(50)
+ },
+ expr_from_projection(only(&select.projection))
+ );
}
#[test]
| VARBINARY or BLOB columns not parsed
I see the DataType enum has variants for these but it doesn't parse them correctly, or perhaps I am doing something wrong.
Sql:
```mysql
CREATE TABLE IF NOT EXISTS `data` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`key` VARCHAR(255) NOT NULL,
`secret` BLOB(255) NOT NULL,
PRIMARY KEY (`id`))
# or
CREATE TABLE IF NOT EXISTS `data` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`key` VARCHAR(255) NOT NULL,
`secret` VARBINARY(255) NOT NULL,
PRIMARY KEY (`id`))
```
Error:
```
unexpected end of input, sql parser error: Expected ',' or ')' after column definition, found:
( input: 'CREATE TABLE IF NOT EXISTS `data` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL,
`key` VARCHAR(255) NOT NULL, `secret` BLOB (255) NOT NULL, PRIMARY KEY (`id`))'
```
| fccae77c5e3056214b2d06902577925ec8d5549d | [
"parse_cast"
] | [
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_window_frame_default",
"dialect::tests::test_is_dialect",
"parser::tests::test_prev_index",
"parser::tests::test_parse_limit",
"tokenizer::tests::tokenize_bitwise_op",
"tok... | [] | [] |
20f7ac59e38d52e293476b7ad844e7f744a16c43 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -1474,6 +1474,11 @@ impl<'a> Parser<'a> {
let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Rollup(result))
+ } else if self.consume_tokens(&[Token::LParen, Token::RParen]) {
+ // PostgreSQL allow to use empty tuple as a group by expression,
+ // e.g. `GROUP BY (), name`. Please refer to GROUP BY Clause section in
+ // [PostgreSQL](https://www.postgresql.org/docs/16/sql-select.html)
+ Ok(Expr::Tuple(vec![]))
} else {
self.parse_expr()
}
| apache__datafusion-sqlparser-rs-1347 | 1,347 | I would recommend finding a sql reference for the syntax (aka which database invented / used this syntax) to understand what `()` means in this context and then update the parser accordingly
() is usually used in GROUPING SETS, ROLLUP, etc. It is used to include "single group" into the list of sets, for example:
```sql
SELECT count(*), o_orderkey, o_custkey
FROM orders
GROUP BY GROUPING SETS ((), (o_orderkey, o_custkey));
```
Will return something like:
```
count | o_orderkey | o_custkey
-------+------------+-----------
4 | |
1 | 1 | 1
1 | 4 | 4
1 | 3 | 3
1 | 2 | 2
```
It seems that the parser supports this kind of syntax though. `GROUP BY ()` is rarely used on its own and is more of a side-product of GROUPING SETS.
It seems that the behaviour is [different on different backends,](https://blog.jooq.org/how-to-group-by-nothing-in-sql/) which means that this feature can be implemented differently for different backends really... For Postgres, it will be enough to treat `GROUP BY ()` as an absence of group by, but for MySQL it would actually make a difference.
Since this feature is rarely used and I can do without it on my end, I guess you can close this issue @alamb .
Thanks for the update @michael-2956 -- since this is an actual feature gap I'll plan to leave this issue open in case anyone else runs into the limitation and might benefit from your research.
Hi @alamb @iffyio, I would like to take this task, and I want to hear your thoughts before starting the implementation.
We can implement this feature with following ways:
1. Add a dedicated group by type like GroupByExpr::All, maybe call it `GroupByExpr::Nothing`
2. Regard `()` as a special case for `GroupByExpr::Expressions` and add an value like Value::Nothing, then return `GroupByExpr::Expressions(vec![Value::Nothing])` to represent the group by nothing clause
I think the better solution is to use `GroupByExpr::Expressions(vec![])` to represent the `group by nothing` condition, but it's now used to represent the `GROUP BY` clause doesn't exist and we should not break this pattern. So I prefer using solution 1 which adds a new enum value GroupByExpr::Nothing for this purpose. What do you think?
Sounds good! Representing it as an new variant sounds reasonable to me! (i.e. option 1. with `GroupBy::Nothing`)
@iffyio Thank you! | [
"1092"
] | 0.48 | apache/datafusion-sqlparser-rs | 2024-07-19T10:57:16Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -42,6 +42,7 @@ mod test_utils;
#[cfg(test)]
use pretty_assertions::assert_eq;
+use sqlparser::ast::Expr::Identifier;
use sqlparser::test_utils::all_dialects_except;
#[test]
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -10131,3 +10132,30 @@ fn parse_auto_increment_too_large() {
assert!(res.is_err(), "{res:?}");
}
+
+#[test]
+fn test_group_by_nothing() {
+ let Select { group_by, .. } = all_dialects_where(|d| d.supports_group_by_expr())
+ .verified_only_select("SELECT count(1) FROM t GROUP BY ()");
+ {
+ std::assert_eq!(
+ GroupByExpr::Expressions(vec![Expr::Tuple(vec![])], vec![]),
+ group_by
+ );
+ }
+
+ let Select { group_by, .. } = all_dialects_where(|d| d.supports_group_by_expr())
+ .verified_only_select("SELECT name, count(1) FROM t GROUP BY name, ()");
+ {
+ std::assert_eq!(
+ GroupByExpr::Expressions(
+ vec![
+ Identifier(Ident::new("name".to_string())),
+ Expr::Tuple(vec![])
+ ],
+ vec![]
+ ),
+ group_by
+ );
+ }
+}
| GROUP BY () not supported
Hello. First of all, thanks for this amazing project!
I've ran into an issue that explicit `GROUP BY ()` is not supported.
For example, when we write:
`SELECT SUM (value) from sales`,
it is supposed to be the same as:
`SELECT SUM (value) from sales group by ()`,
but the latter is not parseable by the parser. It produces:
`ParserError("Expected an expression:, found: )")`.
I suppose that the issue is that it expects a row expression there, but () is just a special syntax for grouping by nothing.
You technically can specify `GROUP BY (), value`, which would just group by `value`, but if only () is present it treats all rows like a single group.
How would you suggest fixing this?
| 20f7ac59e38d52e293476b7ad844e7f744a16c43 | [
"test_group_by_nothing"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_rollup_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_cube_display",
"dialect::tests::... | [] | [] |
9108bffc9a021aa1f5137381c8f3aec47e71e319 | diff --git a/src/ast/helpers/stmt_create_table.rs b/src/ast/helpers/stmt_create_table.rs
--- a/src/ast/helpers/stmt_create_table.rs
+++ b/src/ast/helpers/stmt_create_table.rs
@@ -496,9 +496,9 @@ impl TryFrom<Statement> for CreateTableBuilder {
}
}
-/// Helper return type when parsing configuration for a BigQuery `CREATE TABLE` statement.
+/// Helper return type when parsing configuration for a `CREATE TABLE` statement.
#[derive(Default)]
-pub(crate) struct BigQueryTableConfiguration {
+pub(crate) struct CreateTableConfiguration {
pub partition_by: Option<Box<Expr>>,
pub cluster_by: Option<WrappedCollection<Vec<Ident>>>,
pub options: Option<Vec<SqlOption>>,
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -31,7 +31,7 @@ use recursion::RecursionCounter;
use IsLateral::*;
use IsOptional::*;
-use crate::ast::helpers::stmt_create_table::{BigQueryTableConfiguration, CreateTableBuilder};
+use crate::ast::helpers::stmt_create_table::{CreateTableBuilder, CreateTableConfiguration};
use crate::ast::*;
use crate::dialect::*;
use crate::keywords::{Keyword, ALL_KEYWORDS};
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5416,11 +5416,7 @@ impl<'a> Parser<'a> {
None
};
- let big_query_config = if dialect_of!(self is BigQueryDialect | GenericDialect) {
- self.parse_optional_big_query_create_table_config()?
- } else {
- Default::default()
- };
+ let create_table_config = self.parse_optional_create_table_config()?;
// Parse optional `AS ( query )`
let query = if self.parse_keyword(Keyword::AS) {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5505,39 +5501,46 @@ impl<'a> Parser<'a> {
.collation(collation)
.on_commit(on_commit)
.on_cluster(on_cluster)
- .partition_by(big_query_config.partition_by)
- .cluster_by(big_query_config.cluster_by)
- .options(big_query_config.options)
+ .partition_by(create_table_config.partition_by)
+ .cluster_by(create_table_config.cluster_by)
+ .options(create_table_config.options)
.primary_key(primary_key)
.strict(strict)
.build())
}
- /// Parse configuration like partitioning, clustering information during big-query table creation.
- /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_2>
- fn parse_optional_big_query_create_table_config(
+ /// Parse configuration like partitioning, clustering information during the table creation.
+ ///
+ /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_2)
+ /// [PostgreSQL](https://www.postgresql.org/docs/current/ddl-partitioning.html)
+ fn parse_optional_create_table_config(
&mut self,
- ) -> Result<BigQueryTableConfiguration, ParserError> {
- let mut partition_by = None;
- if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
- partition_by = Some(Box::new(self.parse_expr()?));
+ ) -> Result<CreateTableConfiguration, ParserError> {
+ let partition_by = if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
+ && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
+ {
+ Some(Box::new(self.parse_expr()?))
+ } else {
+ None
};
let mut cluster_by = None;
- if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
- cluster_by = Some(WrappedCollection::NoWrapping(
- self.parse_comma_separated(|p| p.parse_identifier(false))?,
- ));
- };
-
let mut options = None;
- if let Token::Word(word) = self.peek_token().token {
- if word.keyword == Keyword::OPTIONS {
- options = Some(self.parse_options(Keyword::OPTIONS)?);
- }
- };
+ if dialect_of!(self is BigQueryDialect | GenericDialect) {
+ if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
+ cluster_by = Some(WrappedCollection::NoWrapping(
+ self.parse_comma_separated(|p| p.parse_identifier(false))?,
+ ));
+ };
+
+ if let Token::Word(word) = self.peek_token().token {
+ if word.keyword == Keyword::OPTIONS {
+ options = Some(self.parse_options(Keyword::OPTIONS)?);
+ }
+ };
+ }
- Ok(BigQueryTableConfiguration {
+ Ok(CreateTableConfiguration {
partition_by,
cluster_by,
options,
| apache__datafusion-sqlparser-rs-1338 | 1,338 | [
"1281"
] | 0.48 | apache/datafusion-sqlparser-rs | 2024-07-10T13:09:35Z | diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -4039,6 +4039,50 @@ fn parse_create_table_with_alias() {
}
}
+#[test]
+fn parse_create_table_with_partition_by() {
+ let sql = "CREATE TABLE t1 (a INT, b TEXT) PARTITION BY RANGE(a)";
+ match pg_and_generic().verified_stmt(sql) {
+ Statement::CreateTable(create_table) => {
+ assert_eq!("t1", create_table.name.to_string());
+ assert_eq!(
+ vec![
+ ColumnDef {
+ name: "a".into(),
+ data_type: DataType::Int(None),
+ collation: None,
+ options: vec![]
+ },
+ ColumnDef {
+ name: "b".into(),
+ data_type: DataType::Text,
+ collation: None,
+ options: vec![]
+ }
+ ],
+ create_table.columns
+ );
+ match *create_table.partition_by.unwrap() {
+ Expr::Function(f) => {
+ assert_eq!("RANGE", f.name.to_string());
+ assert_eq!(
+ FunctionArguments::List(FunctionArgumentList {
+ duplicate_treatment: None,
+ clauses: vec![],
+ args: vec![FunctionArg::Unnamed(FunctionArgExpr::Expr(
+ Expr::Identifier(Ident::new("a"))
+ ))],
+ }),
+ f.args
+ );
+ }
+ _ => unreachable!(),
+ }
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn parse_join_constraint_unnest_alias() {
assert_eq!(
| Partition by not supported - postgre
Have this query:
```
CREATE TABLE measurement (
city_id int not null,
logdate date not null,
peaktemp int,
unitsales int
) PARTITION BY RANGE (logdate);
```
Got this error:
`sql parser error: Expected end of statement, found: PARTITION at Line: 7, Column 7
`
Doc:
https://www.postgresql.org/docs/current/ddl-partitioning.html
| 20f7ac59e38d52e293476b7ad844e7f744a16c43 | [
"parse_create_table_with_partition_by"
] | [
"ast::tests::test_window_frame_default",
"dialect::tests::identifier_quote_style",
"dialect::tests::test_dialect_from_str",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_cube_display",
"dialect::tests::test_is_dialect",
... | [] | [] | |
7ea47c71fb01e88053ca276e33af38bb23ccb92f | diff --git a/src/ast/data_type.rs b/src/ast/data_type.rs
--- a/src/ast/data_type.rs
+++ b/src/ast/data_type.rs
@@ -219,6 +219,10 @@ pub enum DataType {
/// [hive]: https://docs.cloudera.com/cdw-runtime/cloud/impala-sql-reference/topics/impala-struct.html
/// [bigquery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#struct_type
Struct(Vec<StructField>),
+ /// No type specified - only used with
+ /// [`SQLiteDialect`](crate::dialect::SQLiteDialect), from statements such
+ /// as `CREATE TABLE t1 (a)`.
+ Unspecified,
}
impl fmt::Display for DataType {
diff --git a/src/ast/data_type.rs b/src/ast/data_type.rs
--- a/src/ast/data_type.rs
+++ b/src/ast/data_type.rs
@@ -379,6 +383,7 @@ impl fmt::Display for DataType {
write!(f, "STRUCT")
}
}
+ DataType::Unspecified => Ok(()),
}
}
}
diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs
--- a/src/ast/ddl.rs
+++ b/src/ast/ddl.rs
@@ -516,7 +516,11 @@ pub struct ColumnDef {
impl fmt::Display for ColumnDef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{} {}", self.name, self.data_type)?;
+ if self.data_type == DataType::Unspecified {
+ write!(f, "{}", self.name)?;
+ } else {
+ write!(f, "{} {}", self.name, self.data_type)?;
+ }
if let Some(collation) = &self.collation {
write!(f, " COLLATE {collation}")?;
}
diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs
--- a/src/dialect/mod.rs
+++ b/src/dialect/mod.rs
@@ -65,7 +65,9 @@ macro_rules! dialect_of {
/// encapsulates the parsing differences between dialects.
///
/// [`GenericDialect`] is the most permissive dialect, and parses the union of
-/// all the other dialects, when there is no ambiguity.
+/// all the other dialects, when there is no ambiguity. However, it does not
+/// currently allow `CREATE TABLE` statements without types specified for all
+/// columns; use [`SQLiteDialect`] if you require that.
///
/// # Examples
/// Most users create a [`Dialect`] directly, as shown on the [module
diff --git a/src/dialect/sqlite.rs b/src/dialect/sqlite.rs
--- a/src/dialect/sqlite.rs
+++ b/src/dialect/sqlite.rs
@@ -16,6 +16,11 @@ use crate::keywords::Keyword;
use crate::parser::{Parser, ParserError};
/// A [`Dialect`] for [SQLite](https://www.sqlite.org)
+///
+/// This dialect allows columns in a
+/// [`CREATE TABLE`](https://sqlite.org/lang_createtable.html) statement with no
+/// type specified, as in `CREATE TABLE t1 (a)`. In the AST, these columns will
+/// have the data type [`Unspecified`](crate::ast::DataType::Unspecified).
#[derive(Debug)]
pub struct SQLiteDialect {}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4183,7 +4183,11 @@ impl<'a> Parser<'a> {
pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError> {
let name = self.parse_identifier()?;
- let data_type = self.parse_data_type()?;
+ let data_type = if self.is_column_type_sqlite_unspecified() {
+ DataType::Unspecified
+ } else {
+ self.parse_data_type()?
+ };
let mut collation = if self.parse_keyword(Keyword::COLLATE) {
Some(self.parse_object_name()?)
} else {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4219,6 +4223,29 @@ impl<'a> Parser<'a> {
})
}
+ fn is_column_type_sqlite_unspecified(&mut self) -> bool {
+ if dialect_of!(self is SQLiteDialect) {
+ match self.peek_token().token {
+ Token::Word(word) => matches!(
+ word.keyword,
+ Keyword::CONSTRAINT
+ | Keyword::PRIMARY
+ | Keyword::NOT
+ | Keyword::UNIQUE
+ | Keyword::CHECK
+ | Keyword::DEFAULT
+ | Keyword::COLLATE
+ | Keyword::REFERENCES
+ | Keyword::GENERATED
+ | Keyword::AS
+ ),
+ _ => true, // e.g. comma immediately after column name
+ }
+ } else {
+ false
+ }
+ }
+
pub fn parse_optional_column_option(&mut self) -> Result<Option<ColumnOption>, ParserError> {
if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
Ok(Some(ColumnOption::CharacterSet(self.parse_object_name()?)))
| apache__datafusion-sqlparser-rs-1075 | 1,075 | @alamb I was wondering; this seems to be a mutually exclusive logic.
Other databases require the data type, while SQLite doesn't.
Is it reasonable to assume that the GenericDialect behavior would be to allow untyped columns...?
> Is it reasonable to assume that the GenericDialect behavior would be to allow untyped columns...?
I think if that was technically feasible and not too disruptive, it would be a nice feature
I think the rules in SQLite are that the symbol after the column name is the data type unless it's one of the keywords introducing a column constraint: CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT, COLLATE, REFERENCES, GENERATED, or AS. I'm basing this on the [diagrams on this page](https://sqlite.org/lang_createtable.html).
Is it sufficient to allow the check here to be skipped for SQLite:
https://github.com/sqlparser-rs/sqlparser-rs/blob/c887c4e54558db3d3940c23300a384b1752cdeaf/src/parser/mod.rs#L5322
And then make `parse_data_type` return a `Result<Option<DataType>, ParserError>`? Or is that too simplistic and will give us keywords like `PRIMARY` as the data type?
Is the aim with `GenericDialect` to make a compromise between different SQL dialects - in which case it should probably reject this as it's invalid for most engines - or to parse SQL that's valid for any supported dialect? | [
"743"
] | 0.41 | apache/datafusion-sqlparser-rs | 2023-12-24T11:49:33Z | diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -221,6 +221,11 @@ fn parse_create_table_gencol() {
sqlite_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2) STORED)");
}
+#[test]
+fn parse_create_table_untyped() {
+ sqlite().verified_stmt("CREATE TABLE t1 (a, b AS (a * 2), c NOT NULL)");
+}
+
#[test]
fn test_placeholder() {
// In postgres, this would be the absolute value operator '@' applied to the column 'xxx'
| SQLite dialect doesn't support typeless columns
SQLite supports untyped columns in the schema, like in this example:
```sql
CREATE TABLE log_data (
log_id INTEGER NOT NULL,
key TEXT NOT NULL,
value,
PRIMARY KEY (log_id, key),
FOREIGN KEY(log_id) REFERENCES logs(id) ON DELETE CASCADE
);
```
Unfortunately, parsing this `CREATE TABLE` statement with current `sqlparser` (0.27) results in:
```
sql parser error: Expected a data type name, found: ,
```
| 3ec337ec5f44bbb406c5806cb98643403f196fd2 | [
"parse_create_table_untyped"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_cube_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_rollup_display",
"ast::tests::test... | [] | [] |
8d97330d42fa9acf63d8bf6412b762948e025496 | diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs
--- a/src/ast/ddl.rs
+++ b/src/ast/ddl.rs
@@ -600,6 +600,8 @@ pub enum ColumnOption {
sequence_options: Option<Vec<SequenceOptions>>,
generation_expr: Option<Expr>,
generation_expr_mode: Option<GeneratedExpressionMode>,
+ /// false if 'GENERATED ALWAYS' is skipped (option starts with AS)
+ generated_keyword: bool,
},
}
diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs
--- a/src/ast/ddl.rs
+++ b/src/ast/ddl.rs
@@ -641,6 +643,7 @@ impl fmt::Display for ColumnOption {
sequence_options,
generation_expr,
generation_expr_mode,
+ generated_keyword,
} => {
if let Some(expr) = generation_expr {
let modifier = match generation_expr_mode {
diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs
--- a/src/ast/ddl.rs
+++ b/src/ast/ddl.rs
@@ -648,7 +651,11 @@ impl fmt::Display for ColumnOption {
Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
Some(GeneratedExpressionMode::Stored) => " STORED",
};
- write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
+ if *generated_keyword {
+ write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
+ } else {
+ write!(f, "AS ({expr}){modifier}")?;
+ }
Ok(())
} else {
// Like Postgres - generated from sequence
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4282,6 +4282,10 @@ impl<'a> Parser<'a> {
Ok(Some(ColumnOption::OnUpdate(expr)))
} else if self.parse_keyword(Keyword::GENERATED) {
self.parse_optional_column_option_generated()
+ } else if self.parse_keyword(Keyword::AS)
+ && dialect_of!(self is MySqlDialect | SQLiteDialect | DuckDbDialect | GenericDialect)
+ {
+ self.parse_optional_column_option_as()
} else {
Ok(None)
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4300,6 +4304,7 @@ impl<'a> Parser<'a> {
sequence_options: Some(sequence_options),
generation_expr: None,
generation_expr_mode: None,
+ generated_keyword: true,
}))
} else if self.parse_keywords(&[
Keyword::BY,
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4317,6 +4322,7 @@ impl<'a> Parser<'a> {
sequence_options: Some(sequence_options),
generation_expr: None,
generation_expr_mode: None,
+ generated_keyword: true,
}))
} else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::AS]) {
if self.expect_token(&Token::LParen).is_ok() {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4341,6 +4347,7 @@ impl<'a> Parser<'a> {
sequence_options: None,
generation_expr: Some(expr),
generation_expr_mode: expr_mode,
+ generated_keyword: true,
}))
} else {
Ok(None)
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -4350,6 +4357,32 @@ impl<'a> Parser<'a> {
}
}
+ fn parse_optional_column_option_as(&mut self) -> Result<Option<ColumnOption>, ParserError> {
+ // Some DBs allow 'AS (expr)', shorthand for GENERATED ALWAYS AS
+ self.expect_token(&Token::LParen)?;
+ let expr = self.parse_expr()?;
+ self.expect_token(&Token::RParen)?;
+
+ let (gen_as, expr_mode) = if self.parse_keywords(&[Keyword::STORED]) {
+ (
+ GeneratedAs::ExpStored,
+ Some(GeneratedExpressionMode::Stored),
+ )
+ } else if self.parse_keywords(&[Keyword::VIRTUAL]) {
+ (GeneratedAs::Always, Some(GeneratedExpressionMode::Virtual))
+ } else {
+ (GeneratedAs::Always, None)
+ };
+
+ Ok(Some(ColumnOption::Generated {
+ generated_as: gen_as,
+ sequence_options: None,
+ generation_expr: Some(expr),
+ generation_expr_mode: expr_mode,
+ generated_keyword: false,
+ }))
+ }
+
pub fn parse_referential_action(&mut self) -> Result<ReferentialAction, ParserError> {
if self.parse_keyword(Keyword::RESTRICT) {
Ok(ReferentialAction::Restrict)
| apache__datafusion-sqlparser-rs-1058 | 1,058 | #1051 fixed `VIRTUAL`. I'll work on making `GENERATED ALWAYS` optional, but probably not until next week. | [
"1050"
] | 0.40 | apache/datafusion-sqlparser-rs | 2023-11-29T10:30:35Z | diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -517,6 +517,10 @@ fn parse_create_table_gencol() {
let sql_stored = "CREATE TABLE t1 (a INT, b INT GENERATED ALWAYS AS (a * 2) STORED)";
mysql_and_generic().verified_stmt(sql_stored);
+
+ mysql_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2))");
+ mysql_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2) VIRTUAL)");
+ mysql_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2) STORED)");
}
#[test]
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -215,6 +215,10 @@ fn parse_create_table_gencol() {
let sql_stored = "CREATE TABLE t1 (a INT, b INT GENERATED ALWAYS AS (a * 2) STORED)";
sqlite_and_generic().verified_stmt(sql_stored);
+
+ sqlite_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2))");
+ sqlite_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2) VIRTUAL)");
+ sqlite_and_generic().verified_stmt("CREATE TABLE t1 (a INT, b INT AS (a * 2) STORED)");
}
#[test]
| Support more forms of generated columns for SQLite dialect
SQLite allows some ways of defining a generated column which sqlparser currently rejects.
First, the `GENERATED ALWAYS` keywords are optional:
```rust
Parser::parse_sql(&SQLiteDialect {},
"CREATE TABLE t1(a INT, b INT AS (a * 2) STORED);")?;
```
```
Error: sql parser error: Expected ',' or ')' after column definition, found: AS at Line: 1, Column 30
```
Second, the clause can have a `VIRTUAL` keyword stuck on the end (instead of `STORED`). This is the default behaviour anyway, just made explicit.
```rust
Parser::parse_sql(&SQLiteDialect {},
"CREATE TABLE t1(a INT, b INT GENERATED ALWAYS AS (a * 2) VIRTUAL);")?;
```
```
Error: sql parser error: Expected ',' or ')' after column definition, found: VIRTUAL at Line: 1, Column 58
```
~~I think the distinction of stored-or-not is also not exposed in the AST at present.~~
I can have a go at fixing one or both of these, but I wanted to record the issue clearly first.
| 8d97330d42fa9acf63d8bf6412b762948e025496 | [
"parse_create_table_gencol"
] | [
"ast::tests::test_grouping_sets_display",
"ast::tests::test_cube_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_interval_display",
"ast::tests::test_rollup_display",
"ast::tests::test... | [] | [] |
f16c1afed0fa273228e74a633f3885c9c6609911 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3611,21 +3611,13 @@ impl<'a> Parser<'a> {
/// Parse a UNCACHE TABLE statement
pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError> {
- let has_table = self.parse_keyword(Keyword::TABLE);
- if has_table {
- let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
- let table_name = self.parse_object_name(false)?;
- if self.peek_token().token == Token::EOF {
- Ok(Statement::UNCache {
- table_name,
- if_exists,
- })
- } else {
- self.expected("an `EOF`", self.peek_token())
- }
- } else {
- self.expected("a `TABLE` keyword", self.peek_token())
- }
+ self.expect_keyword(Keyword::TABLE)?;
+ let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
+ let table_name = self.parse_object_name(false)?;
+ Ok(Statement::UNCache {
+ table_name,
+ if_exists,
+ })
}
/// SQLite-specific `CREATE VIRTUAL TABLE`
| apache__datafusion-sqlparser-rs-1320 | 1,320 | Thanks for the report -- sure sounds like a bug to me
i'll take this | [
"1244"
] | 0.47 | apache/datafusion-sqlparser-rs | 2024-06-20T10:36:02Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8451,19 +8451,19 @@ fn parse_uncache_table() {
let res = parse_sql_statements("UNCACHE TABLE 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected: an `EOF`, found: foo".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: foo".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("UNCACHE 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected: a `TABLE` keyword, found: 'table_name'".to_string()),
+ ParserError::ParserError("Expected: TABLE, found: 'table_name'".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("UNCACHE IF EXISTS 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected: a `TABLE` keyword, found: IF".to_string()),
+ ParserError::ParserError("Expected: TABLE, found: IF".to_string()),
res.unwrap_err()
);
}
| UNCACHE fails to parse with a semicolon
`parse_sql` normally doesn't care whether a single statement is terminated by a semicolon or end of string, but when parsing `UNCACHE` it does.
This deviation seems like a bug.
Discovered on sqlparser v0.43.1, tested on v0.45.0:
```rust
use sqlparser::{
dialect::GenericDialect,
parser::{Parser, ParserError},
};
fn main() {
let dialect = GenericDialect {};
// With other SQL, semicolon being there or not does not seem to matter:
{
let no_semicolon = Parser::parse_sql(&dialect, "select 1");
assert!(no_semicolon.is_ok());
}
{
let with_semicolon = Parser::parse_sql(&dialect, "select 1;");
assert!(with_semicolon.is_ok());
}
// With the UNCACHE statement, it does seem to matter.
// Parsing only works when the semicolon is omitted:
{
let no_semicolon = Parser::parse_sql(&dialect, "uncache table foo");
println!("no semicolon: {no_semicolon:?}");
assert!(no_semicolon.is_ok());
}
{
// BUG
let with_semicolon = Parser::parse_sql(&dialect, "uncache table foo;");
println!("with semicolon: {with_semicolon:?}");
assert_eq!(
with_semicolon,
Err(ParserError::ParserError(
"Expected an `EOF`, found: ; at Line: 1, Column 18".to_string()
))
);
}
}
```
| 17e5c0c1b6c3c52e5ffd0d2caa4aad7bd7d35958 | [
"parse_uncache_table"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_interval_display",
"ast::tests::test... | [] | [] |
79af31b6727fbe60e21705f4bbf8dafc59516e42 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3116,7 +3116,7 @@ impl<'a> Parser<'a> {
/// Report `found` was encountered instead of `expected`
pub fn expected<T>(&self, expected: &str, found: TokenWithLocation) -> Result<T, ParserError> {
parser_err!(
- format!("Expected {expected}, found: {found}"),
+ format!("Expected: {expected}, found: {found}"),
found.location
)
}
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -429,7 +429,7 @@ impl fmt::Display for Location {
write!(
f,
// TODO: use standard compiler location syntax (<path>:<line>:<col>)
- " at Line: {}, Column {}",
+ " at Line: {}, Column: {}",
self.line, self.column,
)
}
| apache__datafusion-sqlparser-rs-1319 | 1,319 | Thanks fr the report. I agree it looks like a bug. PRs to fix it most welcome
I think i can take this on. (don't know how i can assign this) | [
"1259"
] | 0.47 | apache/datafusion-sqlparser-rs | 2024-06-19T19:08:08Z | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -11581,7 +11581,7 @@ mod tests {
assert_eq!(
ast,
Err(ParserError::TokenizerError(
- "Unterminated string literal at Line: 1, Column 5".to_string()
+ "Unterminated string literal at Line: 1, Column: 5".to_string()
))
);
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -11593,7 +11593,7 @@ mod tests {
assert_eq!(
ast,
Err(ParserError::ParserError(
- "Expected [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: a at Line: 1, Column 16"
+ "Expected: [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: a at Line: 1, Column: 16"
.to_string()
))
);
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -1816,7 +1816,7 @@ mod tests {
use std::error::Error;
assert!(err.source().is_none());
}
- assert_eq!(err.to_string(), "test at Line: 1, Column 1");
+ assert_eq!(err.to_string(), "test at Line: 1, Column: 1");
}
#[test]
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -535,7 +535,7 @@ fn parse_invalid_brackets() {
bigquery_and_generic()
.parse_sql_statements(sql)
.unwrap_err(),
- ParserError::ParserError("Expected (, found: >".to_string())
+ ParserError::ParserError("Expected: (, found: >".to_string())
);
let sql = "CREATE TABLE table (x STRUCT<STRUCT<INT64>>>)";
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -544,7 +544,7 @@ fn parse_invalid_brackets() {
.parse_sql_statements(sql)
.unwrap_err(),
ParserError::ParserError(
- "Expected ',' or ')' after column definition, found: >".to_string()
+ "Expected: ',' or ')' after column definition, found: >".to_string()
)
);
}
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -1753,11 +1753,11 @@ fn parse_merge_invalid_statements() {
for (sql, err_msg) in [
(
"MERGE T USING U ON TRUE WHEN MATCHED BY TARGET AND 1 THEN DELETE",
- "Expected THEN, found: BY",
+ "Expected: THEN, found: BY",
),
(
"MERGE T USING U ON TRUE WHEN MATCHED BY SOURCE AND 1 THEN DELETE",
- "Expected THEN, found: BY",
+ "Expected: THEN, found: BY",
),
(
"MERGE T USING U ON TRUE WHEN NOT MATCHED BY SOURCE THEN INSERT(a) VALUES (b)",
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -1898,13 +1898,13 @@ fn parse_big_query_declare() {
let error_sql = "DECLARE x";
assert_eq!(
- ParserError::ParserError("Expected a data type name, found: EOF".to_owned()),
+ ParserError::ParserError("Expected: a data type name, found: EOF".to_owned()),
bigquery().parse_sql_statements(error_sql).unwrap_err()
);
let error_sql = "DECLARE x 42";
assert_eq!(
- ParserError::ParserError("Expected a data type name, found: 42".to_owned()),
+ ParserError::ParserError("Expected: a data type name, found: 42".to_owned()),
bigquery().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -2069,7 +2069,7 @@ fn test_bigquery_create_function() {
"AS ((SELECT 1 FROM mytable)) ",
"OPTIONS(a = [1, 2])",
),
- "Expected end of statement, found: OPTIONS",
+ "Expected: end of statement, found: OPTIONS",
),
(
concat!(
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -2077,7 +2077,7 @@ fn test_bigquery_create_function() {
"IMMUTABLE ",
"AS ((SELECT 1 FROM mytable)) ",
),
- "Expected AS, found: IMMUTABLE",
+ "Expected: AS, found: IMMUTABLE",
),
(
concat!(
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -2085,7 +2085,7 @@ fn test_bigquery_create_function() {
"AS \"console.log('hello');\" ",
"LANGUAGE js ",
),
- "Expected end of statement, found: LANGUAGE",
+ "Expected: end of statement, found: LANGUAGE",
),
];
for (sql, error) in error_sqls {
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -2116,7 +2116,7 @@ fn test_bigquery_trim() {
// missing comma separation
let error_sql = "SELECT TRIM('xyz' 'a')";
assert_eq!(
- ParserError::ParserError("Expected ), found: 'a'".to_owned()),
+ ParserError::ParserError("Expected: ), found: 'a'".to_owned()),
bigquery().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -115,7 +115,7 @@ fn parse_replace_into() {
let sql = "REPLACE INTO public.customer (id, name, active) VALUES (1, 2, 3)";
assert_eq!(
- ParserError::ParserError("Unsupported statement REPLACE at Line: 1, Column 9".to_string()),
+ ParserError::ParserError("Unsupported statement REPLACE at Line: 1, Column: 9".to_string()),
Parser::parse_sql(&dialect, sql,).unwrap_err(),
)
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -199,7 +199,7 @@ fn parse_insert_default_values() {
let insert_with_columns_and_default_values = "INSERT INTO test_table (test_col) DEFAULT VALUES";
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: DEFAULT".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: DEFAULT".to_string()
),
parse_sql_statements(insert_with_columns_and_default_values).unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -207,20 +207,20 @@ fn parse_insert_default_values() {
let insert_with_default_values_and_hive_after_columns =
"INSERT INTO test_table DEFAULT VALUES (some_column)";
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: (".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: (".to_string()),
parse_sql_statements(insert_with_default_values_and_hive_after_columns).unwrap_err()
);
let insert_with_default_values_and_hive_partition =
"INSERT INTO test_table DEFAULT VALUES PARTITION (some_column)";
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: PARTITION".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: PARTITION".to_string()),
parse_sql_statements(insert_with_default_values_and_hive_partition).unwrap_err()
);
let insert_with_default_values_and_values_list = "INSERT INTO test_table DEFAULT VALUES (1)";
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: (".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: (".to_string()),
parse_sql_statements(insert_with_default_values_and_values_list).unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -319,14 +319,14 @@ fn parse_update() {
let sql = "UPDATE t WHERE 1";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected SET, found: WHERE".to_string()),
+ ParserError::ParserError("Expected: SET, found: WHERE".to_string()),
res.unwrap_err()
);
let sql = "UPDATE t SET a = 1 extrabadstuff";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: extrabadstuff".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: extrabadstuff".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -577,7 +577,7 @@ fn parse_delete_without_from_error() {
let dialects = all_dialects_except(|d| d.is::<BigQueryDialect>() || d.is::<GenericDialect>());
let res = dialects.parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected FROM, found: WHERE".to_string()),
+ ParserError::ParserError("Expected: FROM, found: WHERE".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -892,7 +892,7 @@ fn parse_select_distinct_on() {
fn parse_select_distinct_missing_paren() {
let result = parse_sql_statements("SELECT DISTINCT (name, id FROM customer");
assert_eq!(
- ParserError::ParserError("Expected ), found: FROM".to_string()),
+ ParserError::ParserError("Expected: ), found: FROM".to_string()),
result.unwrap_err(),
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -936,7 +936,7 @@ fn parse_select_into() {
let sql = "SELECT * INTO table0 asdf FROM table1";
let result = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: asdf".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: asdf".to_string()),
result.unwrap_err()
)
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -973,7 +973,7 @@ fn parse_select_wildcard() {
let sql = "SELECT * + * FROM foo;";
let result = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: +".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: +".to_string()),
result.unwrap_err(),
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1002,7 +1002,7 @@ fn parse_column_aliases() {
assert_eq!(&Expr::Value(number("1")), right.as_ref());
assert_eq!(&Ident::new("newname"), alias);
} else {
- panic!("Expected ExprWithAlias")
+ panic!("Expected: ExprWithAlias")
}
// alias without AS is parsed correctly:
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1013,13 +1013,13 @@ fn parse_column_aliases() {
fn test_eof_after_as() {
let res = parse_sql_statements("SELECT foo AS");
assert_eq!(
- ParserError::ParserError("Expected an identifier after AS, found: EOF".to_string()),
+ ParserError::ParserError("Expected: an identifier after AS, found: EOF".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("SELECT 1 FROM foo AS");
assert_eq!(
- ParserError::ParserError("Expected an identifier after AS, found: EOF".to_string()),
+ ParserError::ParserError("Expected: an identifier after AS, found: EOF".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1104,7 +1104,7 @@ fn parse_not() {
fn parse_invalid_infix_not() {
let res = parse_sql_statements("SELECT c FROM t WHERE c NOT (");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: NOT".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: NOT".to_string()),
res.unwrap_err(),
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1177,11 +1177,11 @@ fn parse_exponent_in_select() -> Result<(), ParserError> {
let select = match select.pop().unwrap() {
Statement::Query(inner) => *inner,
- _ => panic!("Expected Query"),
+ _ => panic!("Expected: Query"),
};
let select = match *select.body {
SetExpr::Select(inner) => *inner,
- _ => panic!("Expected SetExpr::Select"),
+ _ => panic!("Expected: SetExpr::Select"),
};
assert_eq!(
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1810,7 +1810,7 @@ fn parse_in_error() {
let sql = "SELECT * FROM customers WHERE segment in segment";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected (, found: segment".to_string()),
+ ParserError::ParserError("Expected: (, found: segment".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2023,14 +2023,14 @@ fn parse_tuple_invalid() {
let sql = "select (1";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected ), found: EOF".to_string()),
+ ParserError::ParserError("Expected: ), found: EOF".to_string()),
res.unwrap_err()
);
let sql = "select (), 2";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: )".to_string()),
+ ParserError::ParserError("Expected: an expression:, found: )".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2442,7 +2442,7 @@ fn parse_extract() {
let dialects = all_dialects_except(|d| d.is::<SnowflakeDialect>() || d.is::<GenericDialect>());
let res = dialects.parse_sql_statements("SELECT EXTRACT(JIFFY FROM d)");
assert_eq!(
- ParserError::ParserError("Expected date/time field, found: JIFFY".to_string()),
+ ParserError::ParserError("Expected: date/time field, found: JIFFY".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2481,7 +2481,7 @@ fn parse_ceil_datetime() {
let dialects = all_dialects_except(|d| d.is::<SnowflakeDialect>() || d.is::<GenericDialect>());
let res = dialects.parse_sql_statements("SELECT CEIL(d TO JIFFY) FROM df");
assert_eq!(
- ParserError::ParserError("Expected date/time field, found: JIFFY".to_string()),
+ ParserError::ParserError("Expected: date/time field, found: JIFFY".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2508,7 +2508,7 @@ fn parse_floor_datetime() {
let dialects = all_dialects_except(|d| d.is::<SnowflakeDialect>() || d.is::<GenericDialect>());
let res = dialects.parse_sql_statements("SELECT FLOOR(d TO JIFFY) FROM df");
assert_eq!(
- ParserError::ParserError("Expected date/time field, found: JIFFY".to_string()),
+ ParserError::ParserError("Expected: date/time field, found: JIFFY".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2709,7 +2709,7 @@ fn parse_window_function_null_treatment_arg() {
let sql = "SELECT LAG(1 IGNORE NULLS) IGNORE NULLS OVER () FROM t1";
assert_eq!(
dialects.parse_sql_statements(sql).unwrap_err(),
- ParserError::ParserError("Expected end of statement, found: NULLS".to_string())
+ ParserError::ParserError("Expected: end of statement, found: NULLS".to_string())
);
let sql = "SELECT LAG(1 IGNORE NULLS) IGNORE NULLS OVER () FROM t1";
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2717,7 +2717,7 @@ fn parse_window_function_null_treatment_arg() {
all_dialects_where(|d| !d.supports_window_function_null_treatment_arg())
.parse_sql_statements(sql)
.unwrap_err(),
- ParserError::ParserError("Expected ), found: IGNORE".to_string())
+ ParserError::ParserError("Expected: ), found: IGNORE".to_string())
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -2907,13 +2907,13 @@ fn parse_create_table() {
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected \',\' or \')\' after column definition, found: GARBAGE"));
+ .contains("Expected: \',\' or \')\' after column definition, found: GARBAGE"));
let res = parse_sql_statements("CREATE TABLE t (a int NOT NULL CONSTRAINT foo)");
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected constraint details after CONSTRAINT <name>"));
+ .contains("Expected: constraint details after CONSTRAINT <name>"));
}
#[test]
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3052,7 +3052,7 @@ fn parse_create_table_with_constraint_characteristics() {
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected \',\' or \')\' after column definition, found: NOT"));
+ .contains("Expected: \',\' or \')\' after column definition, found: NOT"));
let res = parse_sql_statements("CREATE TABLE t (
a int NOT NULL,
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3061,7 +3061,7 @@ fn parse_create_table_with_constraint_characteristics() {
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected \',\' or \')\' after column definition, found: ENFORCED"));
+ .contains("Expected: \',\' or \')\' after column definition, found: ENFORCED"));
let res = parse_sql_statements("CREATE TABLE t (
a int NOT NULL,
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3070,7 +3070,7 @@ fn parse_create_table_with_constraint_characteristics() {
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected \',\' or \')\' after column definition, found: INITIALLY"));
+ .contains("Expected: \',\' or \')\' after column definition, found: INITIALLY"));
}
#[test]
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3161,7 +3161,7 @@ fn parse_create_table_column_constraint_characteristics() {
assert!(res
.unwrap_err()
.to_string()
- .contains("Expected one of DEFERRED or IMMEDIATE, found: BADVALUE"));
+ .contains("Expected: one of DEFERRED or IMMEDIATE, found: BADVALUE"));
let res = parse_sql_statements(
"CREATE TABLE t (a int NOT NULL UNIQUE INITIALLY IMMEDIATE DEFERRABLE INITIALLY DEFERRED)",
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -3260,7 +3260,7 @@ fn parse_create_table_hive_array() {
assert_eq!(
dialects.parse_sql_statements(sql).unwrap_err(),
- ParserError::ParserError("Expected >, found: )".to_string())
+ ParserError::ParserError("Expected: >, found: )".to_string())
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4035,7 +4035,7 @@ fn parse_alter_table_alter_column_type() {
let res =
dialect.parse_sql_statements(&format!("{alter_stmt} ALTER COLUMN is_active TYPE TEXT"));
assert_eq!(
- ParserError::ParserError("Expected SET/DROP NOT NULL, SET DEFAULT, or SET DATA TYPE after ALTER COLUMN, found: TYPE".to_string()),
+ ParserError::ParserError("Expected: SET/DROP NOT NULL, SET DEFAULT, or SET DATA TYPE after ALTER COLUMN, found: TYPE".to_string()),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4043,7 +4043,7 @@ fn parse_alter_table_alter_column_type() {
"{alter_stmt} ALTER COLUMN is_active SET DATA TYPE TEXT USING 'text'"
));
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: USING".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: USING".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4082,7 +4082,7 @@ fn parse_alter_table_drop_constraint() {
let res = parse_sql_statements(&format!("{alter_stmt} DROP CONSTRAINT is_active TEXT"));
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: TEXT".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: TEXT".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4091,14 +4091,14 @@ fn parse_alter_table_drop_constraint() {
fn parse_bad_constraint() {
let res = parse_sql_statements("ALTER TABLE tab ADD");
assert_eq!(
- ParserError::ParserError("Expected identifier, found: EOF".to_string()),
+ ParserError::ParserError("Expected: identifier, found: EOF".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("CREATE TABLE tab (foo int,");
assert_eq!(
ParserError::ParserError(
- "Expected column name or constraint definition, found: EOF".to_string()
+ "Expected: column name or constraint definition, found: EOF".to_string()
),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4440,7 +4440,7 @@ fn parse_window_clause() {
let dialects = all_dialects_except(|d| d.is::<BigQueryDialect>() || d.is::<GenericDialect>());
let res = dialects.parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected (, found: window2".to_string()),
+ ParserError::ParserError("Expected: (, found: window2".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -4851,13 +4851,13 @@ fn parse_interval() {
let result = parse_sql_statements("SELECT INTERVAL '1' SECOND TO SECOND");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: SECOND".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: SECOND".to_string()),
result.unwrap_err(),
);
let result = parse_sql_statements("SELECT INTERVAL '10' HOUR (1) TO HOUR (2)");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: (".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: (".to_string()),
result.unwrap_err(),
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5198,13 +5198,13 @@ fn parse_table_function() {
let res = parse_sql_statements("SELECT * FROM TABLE '1' AS a");
assert_eq!(
- ParserError::ParserError("Expected (, found: \'1\'".to_string()),
+ ParserError::ParserError("Expected: (, found: \'1\'".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("SELECT * FROM TABLE (FUN(a) AS a");
assert_eq!(
- ParserError::ParserError("Expected ), found: AS".to_string()),
+ ParserError::ParserError("Expected: ), found: AS".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5752,7 +5752,7 @@ fn parse_natural_join() {
let sql = "SELECT * FROM t1 natural";
assert_eq!(
- ParserError::ParserError("Expected a join type after NATURAL, found: EOF".to_string()),
+ ParserError::ParserError("Expected: a join type after NATURAL, found: EOF".to_string()),
parse_sql_statements(sql).unwrap_err(),
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5833,7 +5833,7 @@ fn parse_join_syntax_variants() {
let res = parse_sql_statements("SELECT * FROM a OUTER JOIN b ON 1");
assert_eq!(
- ParserError::ParserError("Expected APPLY, found: JOIN".to_string()),
+ ParserError::ParserError("Expected: APPLY, found: JOIN".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5871,7 +5871,7 @@ fn parse_ctes() {
Expr::Subquery(ref subquery) => {
assert_ctes_in_select(&cte_sqls, subquery.as_ref());
}
- _ => panic!("Expected subquery"),
+ _ => panic!("Expected: subquery"),
}
// CTE in a derived table
let sql = &format!("SELECT * FROM ({with})");
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5880,13 +5880,13 @@ fn parse_ctes() {
TableFactor::Derived { subquery, .. } => {
assert_ctes_in_select(&cte_sqls, subquery.as_ref())
}
- _ => panic!("Expected derived table"),
+ _ => panic!("Expected: derived table"),
}
// CTE in a view
let sql = &format!("CREATE VIEW v AS {with}");
match verified_stmt(sql) {
Statement::CreateView { query, .. } => assert_ctes_in_select(&cte_sqls, &query),
- _ => panic!("Expected CREATE VIEW"),
+ _ => panic!("Expected: CREATE VIEW"),
}
// CTE in a CTE...
let sql = &format!("WITH outer_cte AS ({with}) SELECT * FROM outer_cte");
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6047,7 +6047,7 @@ fn parse_multiple_statements() {
// Check that forgetting the semicolon results in an error:
let res = parse_sql_statements(&(sql1.to_owned() + " " + sql2_kw + sql2_rest));
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: ".to_string() + sql2_kw),
+ ParserError::ParserError("Expected: end of statement, found: ".to_string() + sql2_kw),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6102,7 +6102,7 @@ fn parse_overlay() {
"SELECT OVERLAY('abccccde' PLACING 'abc' FROM 3 FOR 12)",
);
assert_eq!(
- ParserError::ParserError("Expected PLACING, found: FROM".to_owned()),
+ ParserError::ParserError("Expected: PLACING, found: FROM".to_owned()),
parse_sql_statements("SELECT OVERLAY('abccccde' FROM 3)").unwrap_err(),
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6151,7 +6151,7 @@ fn parse_trim() {
);
assert_eq!(
- ParserError::ParserError("Expected ), found: 'xyz'".to_owned()),
+ ParserError::ParserError("Expected: ), found: 'xyz'".to_owned()),
parse_sql_statements("SELECT TRIM(FOO 'xyz' FROM 'xyzfooxyz')").unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6173,7 +6173,7 @@ fn parse_trim() {
options: None,
};
assert_eq!(
- ParserError::ParserError("Expected ), found: 'a'".to_owned()),
+ ParserError::ParserError("Expected: ), found: 'a'".to_owned()),
all_expected_snowflake
.parse_sql_statements("SELECT TRIM('xyz', 'a')")
.unwrap_err()
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6210,7 +6210,7 @@ fn parse_exists_subquery() {
.parse_sql_statements("SELECT EXISTS (");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: EOF".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: EOF".to_string()
),
res.unwrap_err(),
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6219,7 +6219,7 @@ fn parse_exists_subquery() {
.parse_sql_statements("SELECT EXISTS (NULL)");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: NULL".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: NULL".to_string()
),
res.unwrap_err(),
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6581,7 +6581,7 @@ fn parse_drop_table() {
let sql = "DROP TABLE";
assert_eq!(
- ParserError::ParserError("Expected identifier, found: EOF".to_string()),
+ ParserError::ParserError("Expected: identifier, found: EOF".to_string()),
parse_sql_statements(sql).unwrap_err(),
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6613,7 +6613,7 @@ fn parse_drop_view() {
fn parse_invalid_subquery_without_parens() {
let res = parse_sql_statements("SELECT SELECT 1 FROM bar WHERE 1=1 FROM baz");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: 1".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: 1".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6826,7 +6826,7 @@ fn lateral_derived() {
let sql = "SELECT * FROM LATERAL UNNEST ([10,20,30]) as numbers WITH OFFSET;";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: WITH".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: WITH".to_string()),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6834,7 +6834,7 @@ fn lateral_derived() {
let res = parse_sql_statements(sql);
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: b".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: b".to_string()
),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -6952,19 +6952,19 @@ fn parse_start_transaction() {
let res = parse_sql_statements("START TRANSACTION ISOLATION LEVEL BAD");
assert_eq!(
- ParserError::ParserError("Expected isolation level, found: BAD".to_string()),
+ ParserError::ParserError("Expected: isolation level, found: BAD".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("START TRANSACTION BAD");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: BAD".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: BAD".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("START TRANSACTION READ ONLY,");
assert_eq!(
- ParserError::ParserError("Expected transaction mode, found: EOF".to_string()),
+ ParserError::ParserError("Expected: transaction mode, found: EOF".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -7050,8 +7050,8 @@ fn parse_set_variable() {
}
let error_sqls = [
- ("SET (a, b, c) = (1, 2, 3", "Expected ), found: EOF"),
- ("SET (a, b, c) = 1, 2, 3", "Expected (, found: 1"),
+ ("SET (a, b, c) = (1, 2, 3", "Expected: ), found: EOF"),
+ ("SET (a, b, c) = 1, 2, 3", "Expected: (, found: 1"),
];
for (sql, error) in error_sqls {
assert_eq!(
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8051,19 +8051,19 @@ fn parse_offset_and_limit() {
// Can't repeat OFFSET / LIMIT
let res = parse_sql_statements("SELECT foo FROM bar OFFSET 2 OFFSET 2");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: OFFSET".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: OFFSET".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("SELECT foo FROM bar LIMIT 2 LIMIT 2");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: LIMIT".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: LIMIT".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("SELECT foo FROM bar OFFSET 2 LIMIT 2 OFFSET 2");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: OFFSET".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: OFFSET".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8132,7 +8132,7 @@ fn parse_position_negative() {
let sql = "SELECT POSITION(foo IN) from bar";
let res = parse_sql_statements(sql);
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: )".to_string()),
+ ParserError::ParserError("Expected: an expression:, found: )".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8190,7 +8190,7 @@ fn parse_is_boolean() {
let res = parse_sql_statements(sql);
assert_eq!(
ParserError::ParserError(
- "Expected [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: 0"
+ "Expected: [NOT] NULL or TRUE|FALSE or [NOT] DISTINCT FROM after IS, found: 0"
.to_string()
),
res.unwrap_err()
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8383,7 +8383,7 @@ fn parse_cache_table() {
let res = parse_sql_statements("CACHE TABLE 'table_name' foo");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8391,7 +8391,7 @@ fn parse_cache_table() {
let res = parse_sql_statements("CACHE flag TABLE 'table_name' OPTIONS('K1'='V1') foo");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8399,7 +8399,7 @@ fn parse_cache_table() {
let res = parse_sql_statements("CACHE TABLE 'table_name' AS foo");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
),
res.unwrap_err()
);
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8407,26 +8407,26 @@ fn parse_cache_table() {
let res = parse_sql_statements("CACHE flag TABLE 'table_name' OPTIONS('K1'='V1') AS foo");
assert_eq!(
ParserError::ParserError(
- "Expected SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
+ "Expected: SELECT, VALUES, or a subquery in the query body, found: foo".to_string()
),
res.unwrap_err()
);
let res = parse_sql_statements("CACHE 'table_name'");
assert_eq!(
- ParserError::ParserError("Expected a `TABLE` keyword, found: 'table_name'".to_string()),
+ ParserError::ParserError("Expected: a `TABLE` keyword, found: 'table_name'".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("CACHE 'table_name' OPTIONS('K1'='V1')");
assert_eq!(
- ParserError::ParserError("Expected a `TABLE` keyword, found: OPTIONS".to_string()),
+ ParserError::ParserError("Expected: a `TABLE` keyword, found: OPTIONS".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("CACHE flag 'table_name' OPTIONS('K1'='V1')");
assert_eq!(
- ParserError::ParserError("Expected a `TABLE` keyword, found: 'table_name'".to_string()),
+ ParserError::ParserError("Expected: a `TABLE` keyword, found: 'table_name'".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8451,19 +8451,19 @@ fn parse_uncache_table() {
let res = parse_sql_statements("UNCACHE TABLE 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected an `EOF`, found: foo".to_string()),
+ ParserError::ParserError("Expected: an `EOF`, found: foo".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("UNCACHE 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected a `TABLE` keyword, found: 'table_name'".to_string()),
+ ParserError::ParserError("Expected: a `TABLE` keyword, found: 'table_name'".to_string()),
res.unwrap_err()
);
let res = parse_sql_statements("UNCACHE IF EXISTS 'table_name' foo");
assert_eq!(
- ParserError::ParserError("Expected a `TABLE` keyword, found: IF".to_string()),
+ ParserError::ParserError("Expected: a `TABLE` keyword, found: IF".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8927,7 +8927,7 @@ fn parse_trailing_comma() {
.parse_sql_statements("CREATE TABLE employees (name text, age int,)")
.unwrap_err(),
ParserError::ParserError(
- "Expected column name or constraint definition, found: )".to_string()
+ "Expected: column name or constraint definition, found: )".to_string()
)
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8955,7 +8955,7 @@ fn parse_projection_trailing_comma() {
trailing_commas
.parse_sql_statements("SELECT * FROM track ORDER BY milliseconds,")
.unwrap_err(),
- ParserError::ParserError("Expected an expression:, found: EOF".to_string())
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_string())
);
assert_eq!(
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8963,7 +8963,7 @@ fn parse_projection_trailing_comma() {
.parse_sql_statements("CREATE TABLE employees (name text, age int,)")
.unwrap_err(),
ParserError::ParserError(
- "Expected column name or constraint definition, found: )".to_string()
+ "Expected: column name or constraint definition, found: )".to_string()
),
);
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -9962,14 +9962,14 @@ fn tests_select_values_without_parens_and_set_op() {
assert_eq!(SetOperator::Union, op);
match *left {
SetExpr::Select(_) => {}
- _ => panic!("Expected a SELECT statement"),
+ _ => panic!("Expected: a SELECT statement"),
}
match *right {
SetExpr::Select(_) => {}
- _ => panic!("Expected a SELECT statement"),
+ _ => panic!("Expected: a SELECT statement"),
}
}
- _ => panic!("Expected a SET OPERATION"),
+ _ => panic!("Expected: a SET OPERATION"),
}
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -10003,7 +10003,7 @@ fn parse_select_wildcard_with_except() {
.parse_sql_statements("SELECT * EXCEPT () FROM employee_table")
.unwrap_err()
.to_string(),
- "sql parser error: Expected identifier, found: )"
+ "sql parser error: Expected: identifier, found: )"
);
}
diff --git a/tests/sqlparser_databricks.rs b/tests/sqlparser_databricks.rs
--- a/tests/sqlparser_databricks.rs
+++ b/tests/sqlparser_databricks.rs
@@ -64,7 +64,7 @@ fn test_databricks_exists() {
let res = databricks().parse_sql_statements("SELECT EXISTS (");
assert_eq!(
// TODO: improve this error message...
- ParserError::ParserError("Expected an expression:, found: EOF".to_string()),
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_string()),
res.unwrap_err(),
);
}
diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs
--- a/tests/sqlparser_hive.rs
+++ b/tests/sqlparser_hive.rs
@@ -284,7 +284,7 @@ fn set_statement_with_minus() {
assert_eq!(
hive().parse_sql_statements("SET hive.tez.java.opts = -"),
Err(ParserError::ParserError(
- "Expected variable value, found: EOF".to_string()
+ "Expected: variable value, found: EOF".to_string()
))
)
}
diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs
--- a/tests/sqlparser_hive.rs
+++ b/tests/sqlparser_hive.rs
@@ -327,14 +327,14 @@ fn parse_create_function() {
assert_eq!(
unsupported_dialects.parse_sql_statements(sql).unwrap_err(),
ParserError::ParserError(
- "Expected an object type after CREATE, found: FUNCTION".to_string()
+ "Expected: an object type after CREATE, found: FUNCTION".to_string()
)
);
let sql = "CREATE TEMPORARY FUNCTION mydb.myfunc AS 'org.random.class.Name' USING JAR";
assert_eq!(
hive().parse_sql_statements(sql).unwrap_err(),
- ParserError::ParserError("Expected literal string, found: EOF".to_string()),
+ ParserError::ParserError("Expected: literal string, found: EOF".to_string()),
);
}
diff --git a/tests/sqlparser_hive.rs b/tests/sqlparser_hive.rs
--- a/tests/sqlparser_hive.rs
+++ b/tests/sqlparser_hive.rs
@@ -398,7 +398,7 @@ fn parse_delimited_identifiers() {
assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
assert_eq!(&Ident::with_quote('"', "column alias"), alias);
}
- _ => panic!("Expected ExprWithAlias"),
+ _ => panic!("Expected: ExprWithAlias"),
}
hive().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
diff --git a/tests/sqlparser_mssql.rs b/tests/sqlparser_mssql.rs
--- a/tests/sqlparser_mssql.rs
+++ b/tests/sqlparser_mssql.rs
@@ -481,7 +481,7 @@ fn parse_convert() {
let error_sql = "SELECT CONVERT(INT, 'foo',) FROM T";
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: )".to_owned()),
+ ParserError::ParserError("Expected: an expression:, found: )".to_owned()),
ms().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -2518,7 +2518,7 @@ fn parse_fulltext_expression() {
}
#[test]
-#[should_panic = "Expected FULLTEXT or SPATIAL option without constraint name, found: cons"]
+#[should_panic = "Expected: FULLTEXT or SPATIAL option without constraint name, found: cons"]
fn parse_create_table_with_fulltext_definition_should_not_accept_constraint_name() {
mysql_and_generic().verified_stmt("CREATE TABLE tb (c1 INT, CONSTRAINT cons FULLTEXT (c1))");
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -648,7 +648,7 @@ fn parse_alter_table_alter_column_add_generated() {
"ALTER TABLE t ALTER COLUMN id ADD GENERATED ( INCREMENT 1 MINVALUE 1 )",
);
assert_eq!(
- ParserError::ParserError("Expected AS, found: (".to_string()),
+ ParserError::ParserError("Expected: AS, found: (".to_string()),
res.unwrap_err()
);
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -656,14 +656,14 @@ fn parse_alter_table_alter_column_add_generated() {
"ALTER TABLE t ALTER COLUMN id ADD GENERATED AS IDENTITY ( INCREMENT )",
);
assert_eq!(
- ParserError::ParserError("Expected a value, found: )".to_string()),
+ ParserError::ParserError("Expected: a value, found: )".to_string()),
res.unwrap_err()
);
let res =
pg().parse_sql_statements("ALTER TABLE t ALTER COLUMN id ADD GENERATED AS IDENTITY (");
assert_eq!(
- ParserError::ParserError("Expected ), found: EOF".to_string()),
+ ParserError::ParserError("Expected: ), found: EOF".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -733,25 +733,25 @@ fn parse_create_table_if_not_exists() {
fn parse_bad_if_not_exists() {
let res = pg().parse_sql_statements("CREATE TABLE NOT EXISTS uk_cities ()");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: EXISTS".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: EXISTS".to_string()),
res.unwrap_err()
);
let res = pg().parse_sql_statements("CREATE TABLE IF EXISTS uk_cities ()");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: EXISTS".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: EXISTS".to_string()),
res.unwrap_err()
);
let res = pg().parse_sql_statements("CREATE TABLE IF uk_cities ()");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: uk_cities".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: uk_cities".to_string()),
res.unwrap_err()
);
let res = pg().parse_sql_statements("CREATE TABLE IF NOT uk_cities ()");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: NOT".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: NOT".to_string()),
res.unwrap_err()
);
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -1300,21 +1300,21 @@ fn parse_set() {
assert_eq!(
pg_and_generic().parse_sql_statements("SET"),
Err(ParserError::ParserError(
- "Expected identifier, found: EOF".to_string()
+ "Expected: identifier, found: EOF".to_string()
)),
);
assert_eq!(
pg_and_generic().parse_sql_statements("SET a b"),
Err(ParserError::ParserError(
- "Expected equals sign or TO, found: b".to_string()
+ "Expected: equals sign or TO, found: b".to_string()
)),
);
assert_eq!(
pg_and_generic().parse_sql_statements("SET a ="),
Err(ParserError::ParserError(
- "Expected variable value, found: EOF".to_string()
+ "Expected: variable value, found: EOF".to_string()
)),
);
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -2685,7 +2685,7 @@ fn parse_json_table_is_not_reserved() {
name: ObjectName(name),
..
} => assert_eq!("JSON_TABLE", name[0].value),
- other => panic!("Expected JSON_TABLE to be parsed as a table name, but got {other:?}"),
+ other => panic!("Expected: JSON_TABLE to be parsed as a table name, but got {other:?}"),
}
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -2874,7 +2874,7 @@ fn parse_escaped_literal_string() {
.parse_sql_statements(sql)
.unwrap_err()
.to_string(),
- "sql parser error: Unterminated encoded string literal at Line: 1, Column 8"
+ "sql parser error: Unterminated encoded string literal at Line: 1, Column: 8"
);
let sql = r"SELECT E'\u0001', E'\U0010FFFF', E'\xC', E'\x25', E'\2', E'\45', E'\445'";
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -2917,7 +2917,7 @@ fn parse_escaped_literal_string() {
.parse_sql_statements(sql)
.unwrap_err()
.to_string(),
- "sql parser error: Unterminated encoded string literal at Line: 1, Column 8"
+ "sql parser error: Unterminated encoded string literal at Line: 1, Column: 8"
);
}
}
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -3455,7 +3455,7 @@ fn parse_delimited_identifiers() {
assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
assert_eq!(&Ident::with_quote('"', "column alias"), alias);
}
- _ => panic!("Expected ExprWithAlias"),
+ _ => panic!("Expected: ExprWithAlias"),
}
pg().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -385,14 +385,14 @@ fn test_snowflake_create_invalid_local_global_table() {
assert_eq!(
snowflake().parse_sql_statements("CREATE LOCAL GLOBAL TABLE my_table (a INT)"),
Err(ParserError::ParserError(
- "Expected an SQL statement, found: LOCAL".to_string()
+ "Expected: an SQL statement, found: LOCAL".to_string()
))
);
assert_eq!(
snowflake().parse_sql_statements("CREATE GLOBAL LOCAL TABLE my_table (a INT)"),
Err(ParserError::ParserError(
- "Expected an SQL statement, found: GLOBAL".to_string()
+ "Expected: an SQL statement, found: GLOBAL".to_string()
))
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -402,21 +402,21 @@ fn test_snowflake_create_invalid_temporal_table() {
assert_eq!(
snowflake().parse_sql_statements("CREATE TEMP TEMPORARY TABLE my_table (a INT)"),
Err(ParserError::ParserError(
- "Expected an object type after CREATE, found: TEMPORARY".to_string()
+ "Expected: an object type after CREATE, found: TEMPORARY".to_string()
))
);
assert_eq!(
snowflake().parse_sql_statements("CREATE TEMP VOLATILE TABLE my_table (a INT)"),
Err(ParserError::ParserError(
- "Expected an object type after CREATE, found: VOLATILE".to_string()
+ "Expected: an object type after CREATE, found: VOLATILE".to_string()
))
);
assert_eq!(
snowflake().parse_sql_statements("CREATE TEMP TRANSIENT TABLE my_table (a INT)"),
Err(ParserError::ParserError(
- "Expected an object type after CREATE, found: TRANSIENT".to_string()
+ "Expected: an object type after CREATE, found: TRANSIENT".to_string()
))
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -851,7 +851,7 @@ fn parse_semi_structured_data_traversal() {
.parse_sql_statements("SELECT a:42")
.unwrap_err()
.to_string(),
- "sql parser error: Expected variant object key name, found: 42"
+ "sql parser error: Expected: variant object key name, found: 42"
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -908,7 +908,7 @@ fn parse_delimited_identifiers() {
assert_eq!(&Expr::Identifier(Ident::with_quote('"', "simple id")), expr);
assert_eq!(&Ident::with_quote('"', "column alias"), alias);
}
- _ => panic!("Expected ExprWithAlias"),
+ _ => panic!("Expected: ExprWithAlias"),
}
snowflake().verified_stmt(r#"CREATE TABLE "foo" ("bar" "int")"#);
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1034,7 +1034,7 @@ fn test_select_wildcard_with_exclude_and_rename() {
.parse_sql_statements("SELECT * RENAME col_a AS col_b EXCLUDE col_z FROM data")
.unwrap_err()
.to_string(),
- "sql parser error: Expected end of statement, found: EXCLUDE"
+ "sql parser error: Expected: end of statement, found: EXCLUDE"
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1134,13 +1134,13 @@ fn parse_snowflake_declare_cursor() {
let error_sql = "DECLARE c1 CURSOR SELECT id FROM invoices";
assert_eq!(
- ParserError::ParserError("Expected FOR, found: SELECT".to_owned()),
+ ParserError::ParserError("Expected: FOR, found: SELECT".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
let error_sql = "DECLARE c1 CURSOR res";
assert_eq!(
- ParserError::ParserError("Expected FOR, found: res".to_owned()),
+ ParserError::ParserError("Expected: FOR, found: res".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1188,13 +1188,13 @@ fn parse_snowflake_declare_result_set() {
let error_sql = "DECLARE res RESULTSET DEFAULT";
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: EOF".to_owned()),
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
let error_sql = "DECLARE res RESULTSET :=";
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: EOF".to_owned()),
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1280,19 +1280,19 @@ fn parse_snowflake_declare_variable() {
let error_sql = "DECLARE profit INT 2";
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: 2".to_owned()),
+ ParserError::ParserError("Expected: end of statement, found: 2".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
let error_sql = "DECLARE profit INT DEFAULT";
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: EOF".to_owned()),
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
let error_sql = "DECLARE profit DEFAULT";
assert_eq!(
- ParserError::ParserError("Expected an expression:, found: EOF".to_owned()),
+ ParserError::ParserError("Expected: an expression:, found: EOF".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1327,7 +1327,7 @@ fn parse_snowflake_declare_multi_statements() {
let error_sql = "DECLARE profit DEFAULT 42 c1 CURSOR FOR res;";
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: c1".to_owned()),
+ ParserError::ParserError("Expected: end of statement, found: c1".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -1902,7 +1902,7 @@ fn test_snowflake_trim() {
// missing comma separation
let error_sql = "SELECT TRIM('xyz' 'a')";
assert_eq!(
- ParserError::ParserError("Expected ), found: 'a'".to_owned()),
+ ParserError::ParserError("Expected: ), found: 'a'".to_owned()),
snowflake().parse_sql_statements(error_sql).unwrap_err()
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -2064,7 +2064,7 @@ fn test_select_wildcard_with_ilike_double_quote() {
let res = snowflake().parse_sql_statements(r#"SELECT * ILIKE "%id" FROM tbl"#);
assert_eq!(
res.unwrap_err().to_string(),
- "sql parser error: Expected ilike pattern, found: \"%id\""
+ "sql parser error: Expected: ilike pattern, found: \"%id\""
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -2073,7 +2073,7 @@ fn test_select_wildcard_with_ilike_number() {
let res = snowflake().parse_sql_statements(r#"SELECT * ILIKE 42 FROM tbl"#);
assert_eq!(
res.unwrap_err().to_string(),
- "sql parser error: Expected ilike pattern, found: 42"
+ "sql parser error: Expected: ilike pattern, found: 42"
);
}
diff --git a/tests/sqlparser_snowflake.rs b/tests/sqlparser_snowflake.rs
--- a/tests/sqlparser_snowflake.rs
+++ b/tests/sqlparser_snowflake.rs
@@ -2082,7 +2082,7 @@ fn test_select_wildcard_with_ilike_replace() {
let res = snowflake().parse_sql_statements(r#"SELECT * ILIKE '%id%' EXCLUDE col FROM tbl"#);
assert_eq!(
res.unwrap_err().to_string(),
- "sql parser error: Expected end of statement, found: EXCLUDE"
+ "sql parser error: Expected: end of statement, found: EXCLUDE"
);
}
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -428,7 +428,7 @@ fn invalid_empty_list() {
let sql = "SELECT * FROM t1 WHERE a IN (,,)";
let sqlite = sqlite_with_options(ParserOptions::new().with_trailing_commas(true));
assert_eq!(
- "sql parser error: Expected an expression:, found: ,",
+ "sql parser error: Expected: an expression:, found: ,",
sqlite.parse_sql_statements(sql).unwrap_err().to_string()
);
}
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -452,17 +452,17 @@ fn parse_start_transaction_with_modifier() {
};
let res = unsupported_dialects.parse_sql_statements("BEGIN DEFERRED");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: DEFERRED".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: DEFERRED".to_string()),
res.unwrap_err(),
);
let res = unsupported_dialects.parse_sql_statements("BEGIN IMMEDIATE");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: IMMEDIATE".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: IMMEDIATE".to_string()),
res.unwrap_err(),
);
let res = unsupported_dialects.parse_sql_statements("BEGIN EXCLUSIVE");
assert_eq!(
- ParserError::ParserError("Expected end of statement, found: EXCLUSIVE".to_string()),
+ ParserError::ParserError("Expected: end of statement, found: EXCLUSIVE".to_string()),
res.unwrap_err(),
);
}
| Add missing colon to sql parser error message after "Column" and "Expected"
sql parser error messages are missing a colon after "Column" and "Excepted"
How it is:
`sql parser error: Expected (, found: 2345 at Line: 2, Column 8`
How it should be IMO:
`sql parser error: Expected: (, found: 2345 at Line: 2, Column: 8`
| 17e5c0c1b6c3c52e5ffd0d2caa4aad7bd7d35958 | [
"parser::tests::test_parser_error_loc",
"parser::tests::test_tokenizer_error_loc",
"tokenizer::tests::tokenizer_error_impl",
"parse_big_query_declare",
"parse_invalid_brackets",
"parse_merge_invalid_statements",
"parse_trailing_comma",
"test_bigquery_trim",
"test_bigquery_create_function",
"parse_... | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_rollup_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_cube_display",
"ast::tests::test... | [] | [] |
0330f9def5ebd6b7813dc4656f40edc717dbd0a3 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -42,6 +42,9 @@ pub enum ParserError {
RecursionLimitExceeded,
}
+// avoid clippy type_complexity warnings
+type ParsedAction = (Keyword, Option<Vec<Ident>>);
+
// Use `Parser::expected` instead, if possible
macro_rules! parser_err {
($MSG:expr, $loc:expr) => {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3278,6 +3281,29 @@ impl<'a> Parser<'a> {
ret
}
+ pub fn parse_actions_list(&mut self) -> Result<Vec<ParsedAction>, ParserError> {
+ let mut values = vec![];
+ loop {
+ values.push(self.parse_grant_permission()?);
+ if !self.consume_token(&Token::Comma) {
+ break;
+ } else if self.options.trailing_commas {
+ match self.peek_token().token {
+ Token::Word(kw) if kw.keyword == Keyword::ON => {
+ break;
+ }
+ Token::RParen
+ | Token::SemiColon
+ | Token::EOF
+ | Token::RBracket
+ | Token::RBrace => break,
+ _ => continue,
+ }
+ }
+ }
+ Ok(values)
+ }
+
/// Parse a comma-separated list of 1+ items accepted by `F`
pub fn parse_comma_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError>
where
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3291,9 +3317,7 @@ impl<'a> Parser<'a> {
} else if self.options.trailing_commas {
match self.peek_token().token {
Token::Word(kw)
- if keywords::RESERVED_FOR_COLUMN_ALIAS
- .iter()
- .any(|d| kw.keyword == *d) =>
+ if keywords::RESERVED_FOR_COLUMN_ALIAS.contains(&kw.keyword) =>
{
break;
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9556,11 +9580,8 @@ impl<'a> Parser<'a> {
with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
}
} else {
- let old_value = self.options.trailing_commas;
- self.options.trailing_commas = false;
-
let (actions, err): (Vec<_>, Vec<_>) = self
- .parse_comma_separated(Parser::parse_grant_permission)?
+ .parse_actions_list()?
.into_iter()
.map(|(kw, columns)| match kw {
Keyword::DELETE => Ok(Action::Delete),
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9582,8 +9603,6 @@ impl<'a> Parser<'a> {
})
.partition(Result::is_ok);
- self.options.trailing_commas = old_value;
-
if !err.is_empty() {
let errors: Vec<Keyword> = err.into_iter().filter_map(|x| x.err()).collect();
return Err(ParserError::ParserError(format!(
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9629,7 +9648,7 @@ impl<'a> Parser<'a> {
Ok((privileges, objects))
}
- pub fn parse_grant_permission(&mut self) -> Result<(Keyword, Option<Vec<Ident>>), ParserError> {
+ pub fn parse_grant_permission(&mut self) -> Result<ParsedAction, ParserError> {
if let Some(kw) = self.parse_one_of_keywords(&[
Keyword::CONNECT,
Keyword::CREATE,
| apache__datafusion-sqlparser-rs-1318 | 1,318 | [
"1211"
] | 0.47 | apache/datafusion-sqlparser-rs | 2024-06-17T22:41:52Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8894,6 +8894,11 @@ fn parse_trailing_comma() {
"CREATE TABLE employees (name TEXT, age INT)",
);
+ trailing_commas.one_statement_parses_to(
+ "GRANT USAGE, SELECT, INSERT, ON p TO u",
+ "GRANT USAGE, SELECT, INSERT ON p TO u",
+ );
+
trailing_commas.verified_stmt("SELECT album_id, name FROM track");
trailing_commas.verified_stmt("SELECT * FROM track ORDER BY milliseconds");
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -8913,6 +8918,13 @@ fn parse_trailing_comma() {
ParserError::ParserError("Expected an expression, found: from".to_string())
);
+ assert_eq!(
+ trailing_commas
+ .parse_sql_statements("REVOKE USAGE, SELECT, ON p TO u")
+ .unwrap_err(),
+ ParserError::ParserError("Expected a privilege keyword, found: ON".to_string())
+ );
+
assert_eq!(
trailing_commas
.parse_sql_statements("CREATE TABLE employees (name text, age int,)")
| Error on some `GRANT`s when trailing commas are enabled
# How to reproduce
```rs
use sqlparser::{
dialect::GenericDialect,
parser::{Parser, ParserError, ParserOptions},
};
fn main() -> Result<(), ParserError> {
let dialect = GenericDialect {};
let options = ParserOptions::new().with_trailing_commas(true);
let result = Parser::new(&dialect)
.with_options(options)
.try_with_sql("GRANT USAGE, SELECT ON SEQUENCE p TO u")?
.parse_statements();
println!("{:?}", result);
Ok(())
}
```
# Output
```rs
Err(ParserError("Expected ON, found: SELECT at Line: 1, Column 14"))
```
# Expected Output
Should parse successfully.
```rs
Ok([Grant { privileges: Actions([Usage, Select { columns: None }]), objects: Sequenc
es([ObjectName([Ident { value: "p", quote_style: None }])]), grantees: [Ident { valu
e: "u", quote_style: None }], with_grant_option: false, granted_by: None }])
```
# Cause
`parse_comma_separated` guesses that the comma is a trailing comma since it's followed by a reserved keyword (SELECT).
| 17e5c0c1b6c3c52e5ffd0d2caa4aad7bd7d35958 | [
"parse_trailing_comma"
] | [
"ast::tests::test_cube_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_window_frame_default",
"dialect::tes... | [] | [] | |
be77ce50ca34958f94bc05d92795b38ca286614a | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -20,7 +20,10 @@ use alloc::{
vec,
vec::Vec,
};
-use core::fmt;
+use core::{
+ fmt::{self, Display},
+ str::FromStr,
+};
use log::debug;
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -3260,6 +3263,18 @@ impl<'a> Parser<'a> {
}
}
+ fn parse<T: FromStr>(s: String, loc: Location) -> Result<T, ParserError>
+ where
+ <T as FromStr>::Err: Display,
+ {
+ s.parse::<T>().map_err(|e| {
+ ParserError::ParserError(format!(
+ "Could not parse '{s}' as {}: {e}{loc}",
+ core::any::type_name::<T>()
+ ))
+ })
+ }
+
/// Parse a comma-separated list of 1+ SelectItem
pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError> {
// BigQuery and Snowflake allow trailing commas, but only in project lists
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -5281,7 +5296,7 @@ impl<'a> Parser<'a> {
let _ = self.consume_token(&Token::Eq);
let next_token = self.next_token();
match next_token.token {
- Token::Number(s, _) => Some(s.parse::<u32>().expect("literal int")),
+ Token::Number(s, _) => Some(Self::parse::<u32>(s, next_token.location)?),
_ => self.expected("literal int", next_token)?,
}
} else {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -6725,10 +6740,7 @@ impl<'a> Parser<'a> {
// The call to n.parse() returns a bigdecimal when the
// bigdecimal feature is enabled, and is otherwise a no-op
// (i.e., it returns the input string).
- Token::Number(ref n, l) => match n.parse() {
- Ok(n) => Ok(Value::Number(n, l)),
- Err(e) => parser_err!(format!("Could not parse '{n}' as number: {e}"), location),
- },
+ Token::Number(n, l) => Ok(Value::Number(Self::parse(n, location)?, l)),
Token::SingleQuotedString(ref s) => Ok(Value::SingleQuotedString(s.to_string())),
Token::DoubleQuotedString(ref s) => Ok(Value::DoubleQuotedString(s.to_string())),
Token::TripleSingleQuotedString(ref s) => {
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -6820,9 +6832,7 @@ impl<'a> Parser<'a> {
pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError> {
let next_token = self.next_token();
match next_token.token {
- Token::Number(s, _) => s.parse::<u64>().map_err(|e| {
- ParserError::ParserError(format!("Could not parse '{s}' as u64: {e}"))
- }),
+ Token::Number(s, _) => Self::parse::<u64>(s, next_token.location),
_ => self.expected("literal int", next_token),
}
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9282,7 +9292,7 @@ impl<'a> Parser<'a> {
return self.expected("literal number", next_token);
};
self.expect_token(&Token::RBrace)?;
- RepetitionQuantifier::AtMost(n.parse().expect("literal int"))
+ RepetitionQuantifier::AtMost(Self::parse(n, token.location)?)
}
Token::Number(n, _) if self.consume_token(&Token::Comma) => {
let next_token = self.next_token();
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9290,12 +9300,12 @@ impl<'a> Parser<'a> {
Token::Number(m, _) => {
self.expect_token(&Token::RBrace)?;
RepetitionQuantifier::Range(
- n.parse().expect("literal int"),
- m.parse().expect("literal int"),
+ Self::parse(n, token.location)?,
+ Self::parse(m, token.location)?,
)
}
Token::RBrace => {
- RepetitionQuantifier::AtLeast(n.parse().expect("literal int"))
+ RepetitionQuantifier::AtLeast(Self::parse(n, token.location)?)
}
_ => {
return self.expected("} or upper bound", next_token);
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9304,7 +9314,7 @@ impl<'a> Parser<'a> {
}
Token::Number(n, _) => {
self.expect_token(&Token::RBrace)?;
- RepetitionQuantifier::Exactly(n.parse().expect("literal int"))
+ RepetitionQuantifier::Exactly(Self::parse(n, token.location)?)
}
_ => return self.expected("quantifier range", token),
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -10326,7 +10336,7 @@ impl<'a> Parser<'a> {
} else {
let next_token = self.next_token();
let quantity = match next_token.token {
- Token::Number(s, _) => s.parse::<u64>().expect("literal int"),
+ Token::Number(s, _) => Self::parse::<u64>(s, next_token.location)?,
_ => self.expected("literal int", next_token)?,
};
Some(TopQuantity::Constant(quantity))
| apache__datafusion-sqlparser-rs-1305 | 1,305 | [
"1303"
] | 0.47 | apache/datafusion-sqlparser-rs | 2024-06-10T19:49:29Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -9991,3 +9991,18 @@ fn parse_select_wildcard_with_except() {
"sql parser error: Expected identifier, found: )"
);
}
+
+#[test]
+fn parse_auto_increment_too_large() {
+ let dialect = GenericDialect {};
+ let u64_max = u64::MAX;
+ let sql =
+ format!("CREATE TABLE foo (bar INT NOT NULL AUTO_INCREMENT) AUTO_INCREMENT=1{u64_max}");
+
+ let res = Parser::new(&dialect)
+ .try_with_sql(&sql)
+ .expect("tokenize to work")
+ .parse_statements();
+
+ assert!(res.is_err(), "{res:?}");
+}
| Return error when AUTO_INCREMENT offset is too large
Currently passing a too large `AUTO_INCREMENT` value will cause a panic.
```
panicked at src/parser/mod.rs:5284:62:
literal int: ParseIntError { kind: PosOverflow }
```
Discovered by running the fuzz target.
| 17e5c0c1b6c3c52e5ffd0d2caa4aad7bd7d35958 | [
"parse_auto_increment_too_large"
] | [
"ast::tests::test_window_frame_default",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_interval_display",
"dialect::tests::test_dialect_from_str",
"dialect::tests::test_is_dialect",
"ast::tests::test_rollup_display",
"tokenize... | [] | [] | |
a86c58b1c93960d50476713ff56e02bf94d41436 | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -4908,6 +4908,10 @@ pub enum FunctionArgumentClause {
///
/// See <https://trino.io/docs/current/functions/aggregate.html>.
OnOverflow(ListAggOnOverflow),
+ /// The `SEPARATOR` clause to the [`GROUP_CONCAT`] function in MySQL.
+ ///
+ /// [`GROUP_CONCAT`]: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
+ Separator(Value),
}
impl fmt::Display for FunctionArgumentClause {
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -4921,6 +4925,7 @@ impl fmt::Display for FunctionArgumentClause {
}
FunctionArgumentClause::Limit(limit) => write!(f, "LIMIT {limit}"),
FunctionArgumentClause::OnOverflow(on_overflow) => write!(f, "{on_overflow}"),
+ FunctionArgumentClause::Separator(sep) => write!(f, "SEPARATOR {sep}"),
}
}
}
diff --git a/src/keywords.rs b/src/keywords.rs
--- a/src/keywords.rs
+++ b/src/keywords.rs
@@ -616,6 +616,7 @@ define_keywords!(
SELECT,
SEMI,
SENSITIVE,
+ SEPARATOR,
SEQUENCE,
SEQUENCEFILE,
SEQUENCES,
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9451,6 +9451,12 @@ impl<'a> Parser<'a> {
clauses.push(FunctionArgumentClause::Limit(self.parse_expr()?));
}
+ if dialect_of!(self is GenericDialect | MySqlDialect)
+ && self.parse_keyword(Keyword::SEPARATOR)
+ {
+ clauses.push(FunctionArgumentClause::Separator(self.parse_value()?));
+ }
+
if let Some(on_overflow) = self.parse_listagg_on_overflow()? {
clauses.push(FunctionArgumentClause::OnOverflow(on_overflow));
}
| apache__datafusion-sqlparser-rs-1256 | 1,256 | [
"1225"
] | 0.46 | apache/datafusion-sqlparser-rs | 2024-05-04T17:22:54Z | diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -2706,3 +2706,14 @@ fn parse_json_table() {
}
);
}
+
+#[test]
+fn test_group_concat() {
+ // examples taken from mysql docs
+ // https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
+ mysql_and_generic().verified_expr("GROUP_CONCAT(DISTINCT test_score)");
+ mysql_and_generic().verified_expr("GROUP_CONCAT(test_score ORDER BY test_score)");
+ mysql_and_generic().verified_expr("GROUP_CONCAT(test_score SEPARATOR ' ')");
+ mysql_and_generic()
+ .verified_expr("GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')");
+}
| feat: Support Mysql GROUP_CONCAT
https://dev.mysql.com/doc/refman/8.3/en/aggregate-functions.html#function_group-concat
```sql
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
```
And for StarRocks.
| 5ed13b5af3e87c88cce6b26c6ae0475cc84cdfd2 | [
"test_group_concat"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_interval_display",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_rollup_display",
"ast::tests::test... | [] | [] | |
0b5722afbfb60c3e3a354bc7c7dc02cb7803b807 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -6576,7 +6576,7 @@ impl<'a> Parser<'a> {
))))
}
}
- Keyword::STRUCT if dialect_of!(self is BigQueryDialect) => {
+ Keyword::STRUCT if dialect_of!(self is BigQueryDialect | GenericDialect) => {
self.prev_token();
let (field_defs, _trailing_bracket) =
self.parse_struct_type_def(Self::parse_big_query_struct_field_def)?;
| apache__datafusion-sqlparser-rs-1241 | 1,241 | [
"1240"
] | 0.45 | apache/datafusion-sqlparser-rs | 2024-04-28T10:56:42Z | diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -350,7 +350,7 @@ fn parse_create_table_with_options() {
#[test]
fn parse_nested_data_types() {
let sql = "CREATE TABLE table (x STRUCT<a ARRAY<INT64>, b BYTES(42)>, y ARRAY<STRUCT<INT64>>)";
- match bigquery().one_statement_parses_to(sql, sql) {
+ match bigquery_and_generic().one_statement_parses_to(sql, sql) {
Statement::CreateTable { name, columns, .. } => {
assert_eq!(name, ObjectName(vec!["table".into()]));
assert_eq!(
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -395,19 +395,25 @@ fn parse_nested_data_types() {
fn parse_invalid_brackets() {
let sql = "SELECT STRUCT<INT64>>(NULL)";
assert_eq!(
- bigquery().parse_sql_statements(sql).unwrap_err(),
+ bigquery_and_generic()
+ .parse_sql_statements(sql)
+ .unwrap_err(),
ParserError::ParserError("unmatched > in STRUCT literal".to_string())
);
let sql = "SELECT STRUCT<STRUCT<INT64>>>(NULL)";
assert_eq!(
- bigquery().parse_sql_statements(sql).unwrap_err(),
+ bigquery_and_generic()
+ .parse_sql_statements(sql)
+ .unwrap_err(),
ParserError::ParserError("Expected (, found: >".to_string())
);
let sql = "CREATE TABLE table (x STRUCT<STRUCT<INT64>>>)";
assert_eq!(
- bigquery().parse_sql_statements(sql).unwrap_err(),
+ bigquery_and_generic()
+ .parse_sql_statements(sql)
+ .unwrap_err(),
ParserError::ParserError(
"Expected ',' or ')' after column definition, found: >".to_string()
)
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -445,7 +451,7 @@ fn parse_typeless_struct_syntax() {
// typeless struct syntax https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typeless_struct_syntax
// syntax: STRUCT( expr1 [AS field_name] [, ... ])
let sql = "SELECT STRUCT(1, 2, 3), STRUCT('abc'), STRUCT(1, t.str_col), STRUCT(1 AS a, 'abc' AS b), STRUCT(str_col AS abc)";
- let select = bigquery().verified_only_select(sql);
+ let select = bigquery_and_generic().verified_only_select(sql);
assert_eq!(5, select.projection.len());
assert_eq!(
&Expr::Struct {
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -505,7 +511,7 @@ fn parse_typeless_struct_syntax() {
}
#[test]
-fn parse_typed_struct_syntax() {
+fn parse_typed_struct_syntax_bigquery() {
// typed struct syntax https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typed_struct_syntax
// syntax: STRUCT<[field_name] field_type, ...>( expr1 [, ... ])
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -789,7 +795,291 @@ fn parse_typed_struct_syntax() {
}
#[test]
-fn parse_typed_struct_with_field_name() {
+fn parse_typed_struct_syntax_bigquery_and_generic() {
+ // typed struct syntax https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typed_struct_syntax
+ // syntax: STRUCT<[field_name] field_type, ...>( expr1 [, ... ])
+
+ let sql = r#"SELECT STRUCT<INT64>(5), STRUCT<x INT64, y STRING>(1, t.str_col), STRUCT<arr ARRAY<FLOAT64>, str STRUCT<BOOL>>(nested_col)"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(number("5")),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Int64,
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![
+ Expr::Value(number("1")),
+ Expr::CompoundIdentifier(vec![
+ Ident {
+ value: "t".into(),
+ quote_style: None,
+ },
+ Ident {
+ value: "str_col".into(),
+ quote_style: None,
+ },
+ ]),
+ ],
+ fields: vec![
+ StructField {
+ field_name: Some(Ident {
+ value: "x".into(),
+ quote_style: None,
+ }),
+ field_type: DataType::Int64
+ },
+ StructField {
+ field_name: Some(Ident {
+ value: "y".into(),
+ quote_style: None,
+ }),
+ field_type: DataType::String(None)
+ },
+ ]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Identifier(Ident {
+ value: "nested_col".into(),
+ quote_style: None,
+ }),],
+ fields: vec![
+ StructField {
+ field_name: Some("arr".into()),
+ field_type: DataType::Array(ArrayElemTypeDef::AngleBracket(Box::new(
+ DataType::Float64
+ )))
+ },
+ StructField {
+ field_name: Some("str".into()),
+ field_type: DataType::Struct(vec![StructField {
+ field_name: None,
+ field_type: DataType::Bool
+ }])
+ },
+ ]
+ },
+ expr_from_projection(&select.projection[2])
+ );
+
+ let sql = r#"SELECT STRUCT<x STRUCT, y ARRAY<STRUCT>>(nested_col)"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(1, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Identifier(Ident {
+ value: "nested_col".into(),
+ quote_style: None,
+ }),],
+ fields: vec![
+ StructField {
+ field_name: Some("x".into()),
+ field_type: DataType::Struct(Default::default())
+ },
+ StructField {
+ field_name: Some("y".into()),
+ field_type: DataType::Array(ArrayElemTypeDef::AngleBracket(Box::new(
+ DataType::Struct(Default::default())
+ )))
+ },
+ ]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+
+ let sql = r#"SELECT STRUCT<BOOL>(true), STRUCT<BYTES(42)>(B'abc')"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(2, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(Value::Boolean(true)),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Bool
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(Value::SingleQuotedByteStringLiteral(
+ "abc".into()
+ )),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Bytes(Some(42))
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+
+ let sql = r#"SELECT STRUCT<DATE>('2011-05-05'), STRUCT<DATETIME>(DATETIME '1999-01-01 01:23:34.45'), STRUCT<FLOAT64>(5.0), STRUCT<INT64>(1)"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(4, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(Value::SingleQuotedString(
+ "2011-05-05".to_string()
+ )),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Date
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::Datetime(None),
+ value: "1999-01-01 01:23:34.45".to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Datetime(None)
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(number("5.0")),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Float64
+ }]
+ },
+ expr_from_projection(&select.projection[2])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(number("1")),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Int64
+ }]
+ },
+ expr_from_projection(&select.projection[3])
+ );
+
+ let sql = r#"SELECT STRUCT<INTERVAL>(INTERVAL '1-2 3 4:5:6.789999'), STRUCT<JSON>(JSON '{"class" : {"students" : [{"name" : "Jane"}]}}')"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(2, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Interval(ast::Interval {
+ value: Box::new(Expr::Value(Value::SingleQuotedString(
+ "1-2 3 4:5:6.789999".to_string()
+ ))),
+ leading_field: None,
+ leading_precision: None,
+ last_field: None,
+ fractional_seconds_precision: None
+ }),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Interval
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::JSON,
+ value: r#"{"class" : {"students" : [{"name" : "Jane"}]}}"#.to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::JSON
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+
+ let sql = r#"SELECT STRUCT<STRING(42)>('foo'), STRUCT<TIMESTAMP>(TIMESTAMP '2008-12-25 15:30:00 America/Los_Angeles'), STRUCT<TIME>(TIME '15:30:00')"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(3, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(Value::SingleQuotedString("foo".to_string())),],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::String(Some(42))
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::Timestamp(None, TimezoneInfo::None),
+ value: "2008-12-25 15:30:00 America/Los_Angeles".to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Timestamp(None, TimezoneInfo::None)
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::Time(None, TimezoneInfo::None),
+ value: "15:30:00".to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Time(None, TimezoneInfo::None)
+ }]
+ },
+ expr_from_projection(&select.projection[2])
+ );
+
+ let sql = r#"SELECT STRUCT<NUMERIC>(NUMERIC '1'), STRUCT<BIGNUMERIC>(BIGNUMERIC '1')"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(2, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::Numeric(ExactNumberInfo::None),
+ value: "1".to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::Numeric(ExactNumberInfo::None)
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::TypedString {
+ data_type: DataType::BigNumeric(ExactNumberInfo::None),
+ value: "1".to_string()
+ },],
+ fields: vec![StructField {
+ field_name: None,
+ field_type: DataType::BigNumeric(ExactNumberInfo::None)
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+}
+
+#[test]
+fn parse_typed_struct_with_field_name_bigquery() {
let sql = r#"SELECT STRUCT<x INT64>(5), STRUCT<y STRING>("foo")"#;
let select = bigquery().verified_only_select(sql);
assert_eq!(2, select.projection.len());
diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -835,6 +1125,53 @@ fn parse_typed_struct_with_field_name() {
);
}
+#[test]
+fn parse_typed_struct_with_field_name_bigquery_and_generic() {
+ let sql = r#"SELECT STRUCT<x INT64>(5), STRUCT<y STRING>('foo')"#;
+ let select = bigquery().verified_only_select(sql);
+ assert_eq!(2, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(number("5")),],
+ fields: vec![StructField {
+ field_name: Some(Ident::from("x")),
+ field_type: DataType::Int64
+ }]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(Value::SingleQuotedString("foo".to_string())),],
+ fields: vec![StructField {
+ field_name: Some(Ident::from("y")),
+ field_type: DataType::String(None)
+ }]
+ },
+ expr_from_projection(&select.projection[1])
+ );
+
+ let sql = r#"SELECT STRUCT<x INT64, y INT64>(5, 5)"#;
+ let select = bigquery_and_generic().verified_only_select(sql);
+ assert_eq!(1, select.projection.len());
+ assert_eq!(
+ &Expr::Struct {
+ values: vec![Expr::Value(number("5")), Expr::Value(number("5")),],
+ fields: vec![
+ StructField {
+ field_name: Some(Ident::from("x")),
+ field_type: DataType::Int64
+ },
+ StructField {
+ field_name: Some(Ident::from("y")),
+ field_type: DataType::Int64
+ }
+ ]
+ },
+ expr_from_projection(&select.projection[0])
+ );
+}
+
#[test]
fn parse_table_identifiers() {
/// Parses a table identifier ident and verifies that re-serializing the
| Support Struct datatype parsing for GenericDialect
Current BigQueryDialect is capable of parsing struct data type such as
```
create table t (s struct<n int, s varchar>);
```
According to [README](https://github.com/sqlparser-rs/sqlparser-rs/tree/0b5722afbfb60c3e3a354bc7c7dc02cb7803b807?tab=readme-ov-file#new-syntax), this feature should also support GenericDialect, however in current code, before parsing this syntax, we [only allow BigQueryDialect to have this syntax](https://github.com/sqlparser-rs/sqlparser-rs/blob/2f437db2a68724e4ae709df22f53999d24804ac7/src/parser/mod.rs#L5280)
| 0b5722afbfb60c3e3a354bc7c7dc02cb7803b807 | [
"parse_invalid_brackets",
"parse_nested_data_types",
"parse_typed_struct_syntax_bigquery_and_generic"
] | [
"ast::tests::test_cube_display",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_interval_display",
"ast::tests::test_window_frame_default",
"ast::tests... | [] | [] | |
929c646bba9cdef6bf774b53bae0c19e0798ef2d | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -559,13 +559,18 @@ pub enum Expr {
/// ```sql
/// SUBSTRING(<expr> [FROM <expr>] [FOR <expr>])
/// ```
+ /// or
+ /// ```sql
+ /// SUBSTRING(<expr>, <expr>, <expr>)
+ /// ```
Substring {
expr: Box<Expr>,
substring_from: Option<Box<Expr>>,
substring_for: Option<Box<Expr>>,
- // Some dialects use `SUBSTRING(expr [FROM start] [FOR len])` syntax while others omit FROM,
- // FOR keywords (e.g. Microsoft SQL Server). This flags is used for formatting.
+ /// false if the expression is represented using the `SUBSTRING(expr [FROM start] [FOR len])` syntax
+ /// true if the expression is represented using the `SUBSTRING(expr, start, len)` syntax
+ /// This flag is used for formatting.
special: bool,
},
/// ```sql
diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs
--- a/src/dialect/mod.rs
+++ b/src/dialect/mod.rs
@@ -135,10 +135,6 @@ pub trait Dialect: Debug + Any {
fn supports_group_by_expr(&self) -> bool {
false
}
- /// Returns true if the dialect supports `SUBSTRING(expr [FROM start] [FOR len])` expressions
- fn supports_substring_from_for_expr(&self) -> bool {
- true
- }
/// Returns true if the dialect supports `(NOT) IN ()` expressions
fn supports_in_empty_list(&self) -> bool {
false
diff --git a/src/dialect/mssql.rs b/src/dialect/mssql.rs
--- a/src/dialect/mssql.rs
+++ b/src/dialect/mssql.rs
@@ -40,8 +40,4 @@ impl Dialect for MsSqlDialect {
fn convert_type_before_value(&self) -> bool {
true
}
-
- fn supports_substring_from_for_expr(&self) -> bool {
- false
- }
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -1525,47 +1525,27 @@ impl<'a> Parser<'a> {
}
pub fn parse_substring_expr(&mut self) -> Result<Expr, ParserError> {
- if self.dialect.supports_substring_from_for_expr() {
- // PARSE SUBSTRING (EXPR [FROM 1] [FOR 3])
- self.expect_token(&Token::LParen)?;
- let expr = self.parse_expr()?;
- let mut from_expr = None;
- if self.parse_keyword(Keyword::FROM) || self.consume_token(&Token::Comma) {
- from_expr = Some(self.parse_expr()?);
- }
-
- let mut to_expr = None;
- if self.parse_keyword(Keyword::FOR) || self.consume_token(&Token::Comma) {
- to_expr = Some(self.parse_expr()?);
- }
- self.expect_token(&Token::RParen)?;
-
- Ok(Expr::Substring {
- expr: Box::new(expr),
- substring_from: from_expr.map(Box::new),
- substring_for: to_expr.map(Box::new),
- special: false,
- })
- } else {
- // PARSE SUBSTRING(EXPR, start, length)
- self.expect_token(&Token::LParen)?;
- let expr = self.parse_expr()?;
-
- self.expect_token(&Token::Comma)?;
- let from_expr = Some(self.parse_expr()?);
-
- self.expect_token(&Token::Comma)?;
- let to_expr = Some(self.parse_expr()?);
-
- self.expect_token(&Token::RParen)?;
+ // PARSE SUBSTRING (EXPR [FROM 1] [FOR 3])
+ self.expect_token(&Token::LParen)?;
+ let expr = self.parse_expr()?;
+ let mut from_expr = None;
+ let special = self.consume_token(&Token::Comma);
+ if special || self.parse_keyword(Keyword::FROM) {
+ from_expr = Some(self.parse_expr()?);
+ }
- Ok(Expr::Substring {
- expr: Box::new(expr),
- substring_from: from_expr.map(Box::new),
- substring_for: to_expr.map(Box::new),
- special: true,
- })
+ let mut to_expr = None;
+ if self.parse_keyword(Keyword::FOR) || self.consume_token(&Token::Comma) {
+ to_expr = Some(self.parse_expr()?);
}
+ self.expect_token(&Token::RParen)?;
+
+ Ok(Expr::Substring {
+ expr: Box::new(expr),
+ substring_from: from_expr.map(Box::new),
+ substring_for: to_expr.map(Box::new),
+ special,
+ })
}
pub fn parse_overlay_expr(&mut self) -> Result<Expr, ParserError> {
| apache__datafusion-sqlparser-rs-1173 | 1,173 | Perhaps https://github.com/sqlparser-rs/sqlparser-rs/issues/914 is related, and the easiest fix is probably to add this to `src/dialect/sqlite.rs`
```
fn supports_substring_from_for_expr(&self) -> bool {
false
}
```
See https://github.com/sqlparser-rs/sqlparser-rs/pull/947/files#diff-6f6a082c3ddfc1f16cc4a455e3e2e2d2508f77b682ab18cabee69471bbb3edb3R37 for how this was implemented for `mssql.rs`
Hmm, I'd prefer always allowing parsing of both, and have the exact syntax variant stored in the parsed syntax tree.
Changing the dialect won't help with correct serialization.
> and have the exact syntax variant stored in the parsed syntax tree.
I agree this would be best.
What it means in practice is to add some field / structure to the AST node that distinguishes between the two syntaxes
It seems like there is already a `special` flag:
https://docs.rs/sqlparser/latest/sqlparser/ast/enum.Expr.html#variant.Substring.field.special
Maybe that needs to be expanded to an enum or something ๐ค
What does the current "special" flag mean?
> What does the current "special" flag mean?
๐ค it appears to be for the case described in this issue:
https://github.com/sqlparser-rs/sqlparser-rs/blob/ef4668075b659be8d83c8e6795f310e32c3f6946/src/ast/mod.rs#L567-L569
(it would be nice if that comment was `///` so it appeared in the docstrings too
@alamb I added `special` in that case based on our discussion at https://github.com/sqlparser-rs/sqlparser-rs/issues/914#issuecomment-1641943127. However, I'm certainly in favor of changing that.
Just some history, the original question at https://github.com/sqlparser-rs/sqlparser-rs/issues/914#issue-1799558232 asks about recommended approaches to modifying the AST to represent the `SUBSTRING` forms:
> From looking at the `Display` impl for `Expr`, the dialect does not appear to be available, so would an acceptable alternative be to modify the `Expr::Substring` type and parser to store information describing the specific `SUBSTRING` variant?
In that issue, the suggestion at https://github.com/sqlparser-rs/sqlparser-rs/issues/914#issuecomment-1641943127 was to introduce `special` which follows the same pattern for `CURRENT_TIMESTAMP` vs `CURRENT_TIMESTAMP()` at https://github.com/sqlparser-rs/sqlparser-rs/blob/eb288487a6a938b45004deda850e550a74fcf935/src/ast/mod.rs#L3496.
For a given dialect, parsing and not rejecting both forms of `SUBSTRING` when not supported by that dialect might be an issue, but for those dialects that support both forms, I agree that the original form should be represented in the AST.
> modify the Expr::Substring type and parser to store information describing the specific SUBSTRING variant?
I think this makes sense to me at a high level (store in the AST information about what specific SUBSTRING variant was in the orignal query so that it can be reconstructed).
Thanks @jmaness | [
"1168"
] | 0.44 | apache/datafusion-sqlparser-rs | 2024-03-13T11:13:27Z | diff --git a/src/dialect/mod.rs b/src/dialect/mod.rs
--- a/src/dialect/mod.rs
+++ b/src/dialect/mod.rs
@@ -325,10 +321,6 @@ mod tests {
self.0.supports_group_by_expr()
}
- fn supports_substring_from_for_expr(&self) -> bool {
- self.0.supports_substring_from_for_expr()
- }
-
fn supports_in_empty_list(&self) -> bool {
self.0.supports_in_empty_list()
}
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -5761,45 +5761,12 @@ fn parse_scalar_subqueries() {
#[test]
fn parse_substring() {
- let from_for_supported_dialects = TestedDialects {
- dialects: vec![
- Box::new(GenericDialect {}),
- Box::new(PostgreSqlDialect {}),
- Box::new(AnsiDialect {}),
- Box::new(SnowflakeDialect {}),
- Box::new(HiveDialect {}),
- Box::new(RedshiftSqlDialect {}),
- Box::new(MySqlDialect {}),
- Box::new(BigQueryDialect {}),
- Box::new(SQLiteDialect {}),
- Box::new(DuckDbDialect {}),
- ],
- options: None,
- };
-
- let from_for_unsupported_dialects = TestedDialects {
- dialects: vec![Box::new(MsSqlDialect {})],
- options: None,
- };
-
- from_for_supported_dialects
- .one_statement_parses_to("SELECT SUBSTRING('1')", "SELECT SUBSTRING('1')");
-
- from_for_supported_dialects.one_statement_parses_to(
- "SELECT SUBSTRING('1' FROM 1)",
- "SELECT SUBSTRING('1' FROM 1)",
- );
-
- from_for_supported_dialects.one_statement_parses_to(
- "SELECT SUBSTRING('1' FROM 1 FOR 3)",
- "SELECT SUBSTRING('1' FROM 1 FOR 3)",
- );
-
- from_for_unsupported_dialects
- .one_statement_parses_to("SELECT SUBSTRING('1', 1, 3)", "SELECT SUBSTRING('1', 1, 3)");
-
- from_for_supported_dialects
- .one_statement_parses_to("SELECT SUBSTRING('1' FOR 3)", "SELECT SUBSTRING('1' FOR 3)");
+ verified_stmt("SELECT SUBSTRING('1')");
+ verified_stmt("SELECT SUBSTRING('1' FROM 1)");
+ verified_stmt("SELECT SUBSTRING('1' FROM 1 FOR 3)");
+ verified_stmt("SELECT SUBSTRING('1', 1, 3)");
+ verified_stmt("SELECT SUBSTRING('1', 1)");
+ verified_stmt("SELECT SUBSTRING('1' FOR 3)");
}
#[test]
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -1911,7 +1911,7 @@ fn parse_substring_in_select() {
let sql = "SELECT DISTINCT SUBSTRING(description, 0, 1) FROM test";
match mysql().one_statement_parses_to(
sql,
- "SELECT DISTINCT SUBSTRING(description FROM 0 FOR 1) FROM test",
+ "SELECT DISTINCT SUBSTRING(description, 0, 1) FROM test",
) {
Statement::Query(query) => {
assert_eq!(
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -1927,7 +1927,7 @@ fn parse_substring_in_select() {
})),
substring_from: Some(Box::new(Expr::Value(number("0")))),
substring_for: Some(Box::new(Expr::Value(number("1")))),
- special: false,
+ special: true,
})],
into: None,
from: vec![TableWithJoins {
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -413,6 +413,18 @@ fn parse_single_quoted_identified() {
sqlite().verified_only_select("SELECT 't'.*, t.'x' FROM 't'");
// TODO: add support for select 't'.x
}
+
+#[test]
+fn parse_substring() {
+ // SQLite supports the SUBSTRING function since v3.34, but does not support the SQL standard
+ // SUBSTRING(expr FROM start FOR length) syntax.
+ // https://www.sqlite.org/lang_corefunc.html#substr
+ sqlite().verified_only_select("SELECT SUBSTRING('SQLITE', 3, 4)");
+ sqlite().verified_only_select("SELECT SUBSTR('SQLITE', 3, 4)");
+ sqlite().verified_only_select("SELECT SUBSTRING('SQLITE', 3)");
+ sqlite().verified_only_select("SELECT SUBSTR('SQLITE', 3)");
+}
+
#[test]
fn parse_window_function_with_filter() {
for func_name in [
| SUBSTRING function calls are always formatted as ` SUBSTRING(... FROM ... FOR ...)`
Parsing the following valid SQLite statement:
```sql
select substring('xxx', 1, 2)
```
then dumping the parsed result as sql results in the following syntax, which is invalid in SQLite:
```sql
select SUBSTRING('xxx' FROM 1 FOR 2)
```
| 44727891713114b72546facf21a335606380845a | [
"parse_substring",
"parse_substring_in_select"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_interval_display",
"ast::tests::test_cube_display",
"ast::tests::test_window_frame_default",
"ast::tests::test_grouping_sets_display",
"ast::tests... | [] | [] |
3ec337ec5f44bbb406c5806cb98643403f196fd2 | diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -8470,11 +8470,24 @@ impl<'a> Parser<'a> {
})
}
+ fn parse_pragma_value(&mut self) -> Result<Value, ParserError> {
+ match self.parse_value()? {
+ v @ Value::SingleQuotedString(_) => Ok(v),
+ v @ Value::DoubleQuotedString(_) => Ok(v),
+ v @ Value::Number(_, _) => Ok(v),
+ v @ Value::Placeholder(_) => Ok(v),
+ _ => {
+ self.prev_token();
+ self.expected("number or string or ? placeholder", self.peek_token())
+ }
+ }
+ }
+
// PRAGMA [schema-name '.'] pragma-name [('=' pragma-value) | '(' pragma-value ')']
pub fn parse_pragma(&mut self) -> Result<Statement, ParserError> {
let name = self.parse_object_name()?;
if self.consume_token(&Token::LParen) {
- let value = self.parse_number_value()?;
+ let value = self.parse_pragma_value()?;
self.expect_token(&Token::RParen)?;
Ok(Statement::Pragma {
name,
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -8484,7 +8497,7 @@ impl<'a> Parser<'a> {
} else if self.consume_token(&Token::Eq) {
Ok(Statement::Pragma {
name,
- value: Some(self.parse_number_value()?),
+ value: Some(self.parse_pragma_value()?),
is_eq: true,
})
} else {
| apache__datafusion-sqlparser-rs-1101 | 1,101 | [
"1100"
] | 0.41 | apache/datafusion-sqlparser-rs | 2024-01-18T06:25:38Z | diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -70,6 +70,54 @@ fn pragma_funciton_style() {
}
}
+#[test]
+fn pragma_eq_string_style() {
+ let sql = "PRAGMA table_info = 'sqlite_master'";
+ match sqlite_and_generic().verified_stmt(sql) {
+ Statement::Pragma {
+ name,
+ value: Some(val),
+ is_eq: true,
+ } => {
+ assert_eq!("table_info", name.to_string());
+ assert_eq!("'sqlite_master'", val.to_string());
+ }
+ _ => unreachable!(),
+ }
+}
+
+#[test]
+fn pragma_function_string_style() {
+ let sql = "PRAGMA table_info(\"sqlite_master\")";
+ match sqlite_and_generic().verified_stmt(sql) {
+ Statement::Pragma {
+ name,
+ value: Some(val),
+ is_eq: false,
+ } => {
+ assert_eq!("table_info", name.to_string());
+ assert_eq!("\"sqlite_master\"", val.to_string());
+ }
+ _ => unreachable!(),
+ }
+}
+
+#[test]
+fn pragma_eq_placehoder_style() {
+ let sql = "PRAGMA table_info = ?";
+ match sqlite_and_generic().verified_stmt(sql) {
+ Statement::Pragma {
+ name,
+ value: Some(val),
+ is_eq: true,
+ } => {
+ assert_eq!("table_info", name.to_string());
+ assert_eq!("?", val.to_string());
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn parse_create_table_without_rowid() {
let sql = "CREATE TABLE t (a INT) WITHOUT ROWID";
| Support sqlite PRAGMA statements with string values
Hi, first of all, thank you for the amazing project.
I'm working on a DB client and need the ability to parse such statements:
```
PRAGMA table_info("sqlite_master")
PRAGMA table_info = "sqlite_master"
```
Which can be parsed and passed to SQLite on other DB clients.
| 3ec337ec5f44bbb406c5806cb98643403f196fd2 | [
"pragma_eq_string_style",
"pragma_function_string_style"
] | [
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_window_frame_default",
"dialect::tests::test_is_dialect",
"dialect::tests::test_dialect_from_str",
"parser::tests::mysql_parse_index_table_constraint",
"parser::tests::test_mysql_partition_selection",
"parser::tests::... | [] | [] | |
885aa93465d0f984f4ff55cdff67f1be84472dc8 | diff --git a/src/ast/data_type.rs b/src/ast/data_type.rs
--- a/src/ast/data_type.rs
+++ b/src/ast/data_type.rs
@@ -373,6 +373,10 @@ pub enum DataType {
///
/// [postgresql]: https://www.postgresql.org/docs/current/plpgsql-trigger.html
Trigger,
+ /// Any data type, used in BigQuery UDF definitions for templated parameters
+ ///
+ /// [bigquery]: https://cloud.google.com/bigquery/docs/user-defined-functions#templated-sql-udf-parameters
+ AnyType,
}
impl fmt::Display for DataType {
diff --git a/src/ast/data_type.rs b/src/ast/data_type.rs
--- a/src/ast/data_type.rs
+++ b/src/ast/data_type.rs
@@ -383,7 +387,6 @@ impl fmt::Display for DataType {
DataType::CharacterVarying(size) => {
format_character_string_type(f, "CHARACTER VARYING", size)
}
-
DataType::CharVarying(size) => format_character_string_type(f, "CHAR VARYING", size),
DataType::Varchar(size) => format_character_string_type(f, "VARCHAR", size),
DataType::Nvarchar(size) => format_character_string_type(f, "NVARCHAR", size),
diff --git a/src/ast/data_type.rs b/src/ast/data_type.rs
--- a/src/ast/data_type.rs
+++ b/src/ast/data_type.rs
@@ -626,6 +629,7 @@ impl fmt::Display for DataType {
}
DataType::Unspecified => Ok(()),
DataType::Trigger => write!(f, "TRIGGER"),
+ DataType::AnyType => write!(f, "ANY TYPE"),
}
}
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -8382,6 +8382,10 @@ impl<'a> Parser<'a> {
Ok(DataType::Tuple(field_defs))
}
Keyword::TRIGGER => Ok(DataType::Trigger),
+ Keyword::ANY if self.peek_keyword(Keyword::TYPE) => {
+ let _ = self.parse_keyword(Keyword::TYPE);
+ Ok(DataType::AnyType)
+ }
_ => {
self.prev_token();
let type_name = self.parse_object_name(false)?;
| apache__datafusion-sqlparser-rs-1602 | 1,602 | Jus adding to the context that is is working in BigQuery - see screenshot:
<img width="1126" alt="Screenshot 2024-12-13 at 16 16 57" src="https://github.com/user-attachments/assets/a73cf6d4-4bfe-4940-ac54-910c64d42382" />
| [
"1601"
] | 0.53 | apache/datafusion-sqlparser-rs | 2024-12-13T15:00:01Z | diff --git a/tests/sqlparser_bigquery.rs b/tests/sqlparser_bigquery.rs
--- a/tests/sqlparser_bigquery.rs
+++ b/tests/sqlparser_bigquery.rs
@@ -2212,3 +2212,19 @@ fn test_any_value() {
bigquery_and_generic().verified_expr("ANY_VALUE(fruit HAVING MAX sold)");
bigquery_and_generic().verified_expr("ANY_VALUE(fruit HAVING MIN sold)");
}
+
+#[test]
+fn test_any_type() {
+ bigquery().verified_stmt(concat!(
+ "CREATE OR REPLACE TEMPORARY FUNCTION ",
+ "my_function(param1 ANY TYPE) ",
+ "AS (",
+ "(SELECT 1)",
+ ")",
+ ));
+}
+
+#[test]
+fn test_any_type_dont_break_custom_type() {
+ bigquery_and_generic().verified_stmt("CREATE TABLE foo (x ANY)");
+}
| Fails to parse BigQuery UDF with "ANY TYPE" parameters
EDIT: The "proper" name for this pattern is "Templated, SQL UDF Parameters", which can be further elaborated in the BQ Docs: https://cloud.google.com/bigquery/docs/user-defined-functions#templated-sql-udf-parameters
trying to parse this simple function like this:
```
fn main() {
let sql = "
CREATE TEMP FUNCTION my_function(are_map ANY TYPE)
AS (
(SELECT 1)
);
";
let ast = Parser::parse_sql(&BigQueryDialect, sql).unwrap();
for stmt in &ast {
println!("{:?}", stmt);
}
}
```
Yields this error:
```
thread 'main' panicked at src/main.rs:18:56:
called `Result::unwrap()` on an `Err` value: ParserError("Expected: ), found: TYPE at Line: 2, Column: 46")
```
I can try to have a look at this , seems relatively straightforward to fix!
| 885aa93465d0f984f4ff55cdff67f1be84472dc8 | [
"test_any_type"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::spans::tests::test_join",
"ast::spans::tests::test_cte",
"ast::tests::test_cube_display",
"ast::tests::test_interval_display",
"ast::tests::test_grouping_sets... | [] | [] |
e16b24679a1e87dd54ce9565e87e818dce4d4a0a | diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -2943,6 +2943,7 @@ pub enum Statement {
StartTransaction {
modes: Vec<TransactionMode>,
begin: bool,
+ transaction: Option<BeginTransactionKind>,
/// Only for SQLite
modifier: Option<TransactionModifier>,
},
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -4518,16 +4519,20 @@ impl fmt::Display for Statement {
Statement::StartTransaction {
modes,
begin: syntax_begin,
+ transaction,
modifier,
} => {
if *syntax_begin {
if let Some(modifier) = *modifier {
- write!(f, "BEGIN {} TRANSACTION", modifier)?;
+ write!(f, "BEGIN {}", modifier)?;
} else {
- write!(f, "BEGIN TRANSACTION")?;
+ write!(f, "BEGIN")?;
}
} else {
- write!(f, "START TRANSACTION")?;
+ write!(f, "START")?;
+ }
+ if let Some(transaction) = transaction {
+ write!(f, " {transaction}")?;
}
if !modes.is_empty() {
write!(f, " {}", display_comma_separated(modes))?;
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -5022,6 +5027,24 @@ pub enum TruncateCascadeOption {
Restrict,
}
+/// Transaction started with [ TRANSACTION | WORK ]
+#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
+#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
+#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
+pub enum BeginTransactionKind {
+ Transaction,
+ Work,
+}
+
+impl Display for BeginTransactionKind {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ BeginTransactionKind::Transaction => write!(f, "TRANSACTION"),
+ BeginTransactionKind::Work => write!(f, "WORK"),
+ }
+ }
+}
+
/// Can use to describe options in create sequence or table column type identity
/// [ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -12099,6 +12099,7 @@ impl<'a> Parser<'a> {
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
begin: false,
+ transaction: Some(BeginTransactionKind::Transaction),
modifier: None,
})
}
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -12115,10 +12116,15 @@ impl<'a> Parser<'a> {
} else {
None
};
- let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
+ let transaction = match self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]) {
+ Some(Keyword::TRANSACTION) => Some(BeginTransactionKind::Transaction),
+ Some(Keyword::WORK) => Some(BeginTransactionKind::Work),
+ _ => None,
+ };
Ok(Statement::StartTransaction {
modes: self.parse_transaction_modes()?,
begin: true,
+ transaction,
modifier,
})
}
| apache__datafusion-sqlparser-rs-1565 | 1,565 | [
"1553"
] | 0.52 | apache/datafusion-sqlparser-rs | 2024-11-28T01:15:56Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -7736,9 +7736,9 @@ fn parse_start_transaction() {
}
verified_stmt("START TRANSACTION");
- one_statement_parses_to("BEGIN", "BEGIN TRANSACTION");
- one_statement_parses_to("BEGIN WORK", "BEGIN TRANSACTION");
- one_statement_parses_to("BEGIN TRANSACTION", "BEGIN TRANSACTION");
+ verified_stmt("BEGIN");
+ verified_stmt("BEGIN WORK");
+ verified_stmt("BEGIN TRANSACTION");
verified_stmt("START TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
verified_stmt("START TRANSACTION ISOLATION LEVEL READ COMMITTED");
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -3031,3 +3031,8 @@ fn parse_longblob_type() {
mysql_and_generic().verified_stmt("CREATE TABLE foo (bar MEDIUMTEXT)");
mysql_and_generic().verified_stmt("CREATE TABLE foo (bar LONGTEXT)");
}
+
+#[test]
+fn parse_begin_without_transaction() {
+ mysql().verified_stmt("BEGIN");
+}
diff --git a/tests/sqlparser_sqlite.rs b/tests/sqlparser_sqlite.rs
--- a/tests/sqlparser_sqlite.rs
+++ b/tests/sqlparser_sqlite.rs
@@ -527,9 +527,9 @@ fn parse_start_transaction_with_modifier() {
sqlite_and_generic().verified_stmt("BEGIN DEFERRED TRANSACTION");
sqlite_and_generic().verified_stmt("BEGIN IMMEDIATE TRANSACTION");
sqlite_and_generic().verified_stmt("BEGIN EXCLUSIVE TRANSACTION");
- sqlite_and_generic().one_statement_parses_to("BEGIN DEFERRED", "BEGIN DEFERRED TRANSACTION");
- sqlite_and_generic().one_statement_parses_to("BEGIN IMMEDIATE", "BEGIN IMMEDIATE TRANSACTION");
- sqlite_and_generic().one_statement_parses_to("BEGIN EXCLUSIVE", "BEGIN EXCLUSIVE TRANSACTION");
+ sqlite_and_generic().verified_stmt("BEGIN DEFERRED");
+ sqlite_and_generic().verified_stmt("BEGIN IMMEDIATE");
+ sqlite_and_generic().verified_stmt("BEGIN EXCLUSIVE");
let unsupported_dialects = TestedDialects::new(
all_dialects()
| `BEGIN;` is formatted as `BEGIN TRANSACTION;`, which is invalid in MySQL
`BEGIN;` is valid in MySQL, but not `BEGIN TRANSACTION;`: https://dev.mysql.com/doc/refman/8.4/en/commit.html
But sqlparser does not preserve the exact syntax of the statement, and always formats it as `BEGIN TRANSACTION;`, causing an execution error in MySQL.
Found while investigating https://github.com/sqlpage/SQLPage/issues/711
| e16b24679a1e87dd54ce9565e87e818dce4d4a0a | [
"parse_start_transaction",
"parse_begin_without_transaction",
"parse_start_transaction_with_modifier"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::spans::tests::test_join",
"ast::spans::tests::test_cte",
"ast::tests::test_interval_display",
"ast::tests::test_one_or_many_with_parens_as_ref",
"ast::tests::... | [] | [] | |
3c8fd748043188957d2dfcadb4bfcfb0e1f70c82 | diff --git a/derive/README.md b/derive/README.md
--- a/derive/README.md
+++ b/derive/README.md
@@ -151,6 +151,55 @@ visitor.post_visit_expr(<is null operand>)
visitor.post_visit_expr(<is null expr>)
```
+If the field is a `Option` and add `#[with = "visit_xxx"]` to the field, the generated code
+will try to access the field only if it is `Some`:
+
+```rust
+#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
+pub struct ShowStatementIn {
+ pub clause: ShowStatementInClause,
+ pub parent_type: Option<ShowStatementInParentType>,
+ #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
+ pub parent_name: Option<ObjectName>,
+}
+```
+
+This will generate
+
+```rust
+impl sqlparser::ast::Visit for ShowStatementIn {
+ fn visit<V: sqlparser::ast::Visitor>(
+ &self,
+ visitor: &mut V,
+ ) -> ::std::ops::ControlFlow<V::Break> {
+ sqlparser::ast::Visit::visit(&self.clause, visitor)?;
+ sqlparser::ast::Visit::visit(&self.parent_type, visitor)?;
+ if let Some(value) = &self.parent_name {
+ visitor.pre_visit_relation(value)?;
+ sqlparser::ast::Visit::visit(value, visitor)?;
+ visitor.post_visit_relation(value)?;
+ }
+ ::std::ops::ControlFlow::Continue(())
+ }
+}
+
+impl sqlparser::ast::VisitMut for ShowStatementIn {
+ fn visit<V: sqlparser::ast::VisitorMut>(
+ &mut self,
+ visitor: &mut V,
+ ) -> ::std::ops::ControlFlow<V::Break> {
+ sqlparser::ast::VisitMut::visit(&mut self.clause, visitor)?;
+ sqlparser::ast::VisitMut::visit(&mut self.parent_type, visitor)?;
+ if let Some(value) = &mut self.parent_name {
+ visitor.pre_visit_relation(value)?;
+ sqlparser::ast::VisitMut::visit(value, visitor)?;
+ visitor.post_visit_relation(value)?;
+ }
+ ::std::ops::ControlFlow::Continue(())
+ }
+}
+```
+
## Releasing
This crate's release is not automated. Instead it is released manually as needed
diff --git a/derive/src/lib.rs b/derive/src/lib.rs
--- a/derive/src/lib.rs
+++ b/derive/src/lib.rs
@@ -18,11 +18,8 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned, ToTokens};
use syn::spanned::Spanned;
-use syn::{
- parse::{Parse, ParseStream},
- parse_macro_input, parse_quote, Attribute, Data, DeriveInput, Fields, GenericParam, Generics,
- Ident, Index, LitStr, Meta, Token,
-};
+use syn::{parse::{Parse, ParseStream}, parse_macro_input, parse_quote, Attribute, Data, DeriveInput, Fields, GenericParam, Generics, Ident, Index, LitStr, Meta, Token, Type, TypePath};
+use syn::{Path, PathArguments};
/// Implementation of `[#derive(Visit)]`
#[proc_macro_derive(VisitMut, attributes(visit))]
diff --git a/derive/src/lib.rs b/derive/src/lib.rs
--- a/derive/src/lib.rs
+++ b/derive/src/lib.rs
@@ -182,9 +179,21 @@ fn visit_children(
Fields::Named(fields) => {
let recurse = fields.named.iter().map(|f| {
let name = &f.ident;
+ let is_option = is_option(&f.ty);
let attributes = Attributes::parse(&f.attrs);
- let (pre_visit, post_visit) = attributes.visit(quote!(&#modifier self.#name));
- quote_spanned!(f.span() => #pre_visit sqlparser::ast::#visit_trait::visit(&#modifier self.#name, visitor)?; #post_visit)
+ if is_option && attributes.with.is_some() {
+ let (pre_visit, post_visit) = attributes.visit(quote!(value));
+ quote_spanned!(f.span() =>
+ if let Some(value) = &#modifier self.#name {
+ #pre_visit sqlparser::ast::#visit_trait::visit(value, visitor)?; #post_visit
+ }
+ )
+ } else {
+ let (pre_visit, post_visit) = attributes.visit(quote!(&#modifier self.#name));
+ quote_spanned!(f.span() =>
+ #pre_visit sqlparser::ast::#visit_trait::visit(&#modifier self.#name, visitor)?; #post_visit
+ )
+ }
});
quote! {
#(#recurse)*
diff --git a/derive/src/lib.rs b/derive/src/lib.rs
--- a/derive/src/lib.rs
+++ b/derive/src/lib.rs
@@ -256,3 +265,16 @@ fn visit_children(
Data::Union(_) => unimplemented!(),
}
}
+
+fn is_option(ty: &Type) -> bool {
+ if let Type::Path(TypePath { path: Path { segments, .. }, .. }) = ty {
+ if let Some(segment) = segments.last() {
+ if segment.ident == "Option" {
+ if let PathArguments::AngleBracketed(args) = &segment.arguments {
+ return args.args.len() == 1;
+ }
+ }
+ }
+ }
+ false
+}
diff --git a/src/ast/mod.rs b/src/ast/mod.rs
--- a/src/ast/mod.rs
+++ b/src/ast/mod.rs
@@ -7653,6 +7653,7 @@ impl fmt::Display for ShowStatementInParentType {
pub struct ShowStatementIn {
pub clause: ShowStatementInClause,
pub parent_type: Option<ShowStatementInParentType>,
+ #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
pub parent_name: Option<ObjectName>,
}
| apache__datafusion-sqlparser-rs-1556 | 1,556 | I think the reason is we changed the table name to `Option<ObjectName>` in https://github.com/apache/datafusion-sqlparser-rs/pull/1501 but the visitor can only recognize the `ObjectName`. ๐ค
https://github.com/apache/datafusion-sqlparser-rs/blob/525d1780e8f5c7ba6b7be327eaa788b6c8c47716/src/ast/mod.rs#L7587-L7590
Thank you for debugging this @goldmedal ๐
I was wondering why that test was failing on
- https://github.com/apache/datafusion/pull/13546
I suspect this was introduced by this PR from @yoavcloud
- https://github.com/apache/datafusion-sqlparser-rs/pull/1501
Any chance you can help us fix it @yoavcloud? | [
"1554"
] | 0.52 | apache/datafusion-sqlparser-rs | 2024-11-26T14:02:44Z | diff --git a/src/ast/visitor.rs b/src/ast/visitor.rs
--- a/src/ast/visitor.rs
+++ b/src/ast/visitor.rs
@@ -876,7 +876,16 @@ mod tests {
"POST: QUERY: SELECT * FROM monthly_sales PIVOT(SUM(a.amount) FOR a.MONTH IN ('JAN', 'FEB', 'MAR', 'APR')) AS p (c, d) ORDER BY EMPID",
"POST: STATEMENT: SELECT * FROM monthly_sales PIVOT(SUM(a.amount) FOR a.MONTH IN ('JAN', 'FEB', 'MAR', 'APR')) AS p (c, d) ORDER BY EMPID",
]
- )
+ ),
+ (
+ "SHOW COLUMNS FROM t1",
+ vec![
+ "PRE: STATEMENT: SHOW COLUMNS FROM t1",
+ "PRE: RELATION: t1",
+ "POST: RELATION: t1",
+ "POST: STATEMENT: SHOW COLUMNS FROM t1",
+ ],
+ ),
];
for (sql, expected) in tests {
let actual = do_visit(sql);
| Relation visitor fails to visit the `SHOW COLUMNS` statement in the latest commit of the main branch
# Description
This problem can be reproduced by adding a test case at
https://github.com/apache/datafusion-sqlparser-rs/blob/525d1780e8f5c7ba6b7be327eaa788b6c8c47716/src/ast/visitor.rs#L736-L738
Consider a case
```rust
(
"SHOW COLUMNS FROM t1",
vec![
"PRE: STATEMENT: SHOW COLUMNS FROM t1",
"PRE: RELATION: t1",
"POST: RELATION: t1",
"POST: STATEMENT: SHOW COLUMNS FROM t1",
],
),
```
The test case is passed in the previous release tag `v0.52.0-rc3`. However, in the latest commit of the main branch 525d1780e8f5c7ba6b7be327eaa788b6c8c47716 , the test fails and the result is
```rust
"PRE: STATEMENT: SHOW COLUMNS FROM t1",
"POST: STATEMENT: SHOW COLUMNS FROM t1",
```
It may cause the upstream project, DataFusion, to fail to execute the `SHOW COLUMNS FROM xxx` SQL.
https://github.com/apache/datafusion/blob/18fc103a403ab0efe5245dd4352f3f3b93c2a4fe/datafusion/core/src/execution/session_state.rs#L540
| e16b24679a1e87dd54ce9565e87e818dce4d4a0a | [
"ast::visitor::tests::test_sql"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::spans::tests::test_join",
"ast::spans::tests::test_snowflake_lateral_flatten",
"ast::spans::tests::test_subquery",
"ast::spans::tests::test_cte",
"ast::tests:... | [] | [] |
813f4a2eff8f091b643058ac1a46a4fbffd96806 | diff --git a/src/ast/value.rs b/src/ast/value.rs
--- a/src/ast/value.rs
+++ b/src/ast/value.rs
@@ -91,6 +91,8 @@ pub enum DateTimeField {
Millennium,
Millisecond,
Milliseconds,
+ Nanosecond,
+ Nanoseconds,
Quarter,
Timezone,
TimezoneHour,
diff --git a/src/ast/value.rs b/src/ast/value.rs
--- a/src/ast/value.rs
+++ b/src/ast/value.rs
@@ -123,6 +125,8 @@ impl fmt::Display for DateTimeField {
DateTimeField::Millennium => "MILLENNIUM",
DateTimeField::Millisecond => "MILLISECOND",
DateTimeField::Milliseconds => "MILLISECONDS",
+ DateTimeField::Nanosecond => "NANOSECOND",
+ DateTimeField::Nanoseconds => "NANOSECONDS",
DateTimeField::Quarter => "QUARTER",
DateTimeField::Timezone => "TIMEZONE",
DateTimeField::TimezoneHour => "TIMEZONE_HOUR",
diff --git a/src/keywords.rs b/src/keywords.rs
--- a/src/keywords.rs
+++ b/src/keywords.rs
@@ -361,6 +361,8 @@ define_keywords!(
MSCK,
MULTISET,
MUTATION,
+ NANOSECOND,
+ NANOSECONDS,
NATIONAL,
NATURAL,
NCHAR,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -1210,6 +1210,8 @@ impl<'a> Parser<'a> {
Keyword::MILLENNIUM => Ok(DateTimeField::Millennium),
Keyword::MILLISECOND => Ok(DateTimeField::Millisecond),
Keyword::MILLISECONDS => Ok(DateTimeField::Milliseconds),
+ Keyword::NANOSECOND => Ok(DateTimeField::Nanosecond),
+ Keyword::NANOSECONDS => Ok(DateTimeField::Nanoseconds),
Keyword::QUARTER => Ok(DateTimeField::Quarter),
Keyword::TIMEZONE => Ok(DateTimeField::Timezone),
Keyword::TIMEZONE_HOUR => Ok(DateTimeField::TimezoneHour),
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -1343,6 +1345,8 @@ impl<'a> Parser<'a> {
Keyword::MILLENNIUM,
Keyword::MILLISECOND,
Keyword::MILLISECONDS,
+ Keyword::NANOSECOND,
+ Keyword::NANOSECONDS,
Keyword::QUARTER,
Keyword::TIMEZONE,
Keyword::TIMEZONE_HOUR,
| apache__datafusion-sqlparser-rs-749 | 749 | [
"748"
] | 0.28 | apache/datafusion-sqlparser-rs | 2022-12-06T10:06:35Z | diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs
--- a/tests/sqlparser_common.rs
+++ b/tests/sqlparser_common.rs
@@ -1740,6 +1740,9 @@ fn parse_extract() {
verified_stmt("SELECT EXTRACT(HOUR FROM d)");
verified_stmt("SELECT EXTRACT(MINUTE FROM d)");
verified_stmt("SELECT EXTRACT(SECOND FROM d)");
+ verified_stmt("SELECT EXTRACT(MILLISECOND FROM d)");
+ verified_stmt("SELECT EXTRACT(MICROSECOND FROM d)");
+ verified_stmt("SELECT EXTRACT(NANOSECOND FROM d)");
verified_stmt("SELECT EXTRACT(CENTURY FROM d)");
verified_stmt("SELECT EXTRACT(DECADE FROM d)");
verified_stmt("SELECT EXTRACT(DOW FROM d)");
| support keyword `NANOSECOND`
i'd like to add a new keyword `NANOSECOND` so that we could parse something likes
`SELECT EXTRACT(NANOSECOND FROM d)`
| 0c9ec4008269dde77a4a5895b0a69a0a27c40ca3 | [
"parse_extract"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"parser::tests::test_parse_data_type::test_ansii_character_large_object_types",
"dialect::tests::test_is_dialect",
"ast::tests::test_cube_display",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"parser::tests::te... | [] | [] | |
6b2b3f1f6c903bddc87ba0858b5ccdb94c5e2242 | diff --git a/src/dialect/mysql.rs b/src/dialect/mysql.rs
--- a/src/dialect/mysql.rs
+++ b/src/dialect/mysql.rs
@@ -18,8 +18,8 @@ pub struct MySqlDialect {}
impl Dialect for MySqlDialect {
fn is_identifier_start(&self, ch: char) -> bool {
// See https://dev.mysql.com/doc/refman/8.0/en/identifiers.html.
- // We don't yet support identifiers beginning with numbers, as that
- // makes it hard to distinguish numeric literals.
+ // Identifiers which begin with a digit are recognized while tokenizing numbers,
+ // so they can be distinguished from exponent numeric literals.
ch.is_alphabetic()
|| ch == '_'
|| ch == '$'
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -673,10 +673,10 @@ impl<'a> Tokenizer<'a> {
return Ok(Some(Token::Period));
}
+ let mut exponent_part = String::new();
// Parse exponent as number
if chars.peek() == Some(&'e') || chars.peek() == Some(&'E') {
let mut char_clone = chars.peekable.clone();
- let mut exponent_part = String::new();
exponent_part.push(char_clone.next().unwrap());
// Optional sign
diff --git a/src/tokenizer.rs b/src/tokenizer.rs
--- a/src/tokenizer.rs
+++ b/src/tokenizer.rs
@@ -703,6 +703,18 @@ impl<'a> Tokenizer<'a> {
}
}
+ // mysql dialect supports identifiers that start with a numeric prefix,
+ // as long as they aren't an exponent number.
+ if dialect_of!(self is MySqlDialect) && exponent_part.is_empty() {
+ let word =
+ peeking_take_while(chars, |ch| self.dialect.is_identifier_part(ch));
+
+ if !word.is_empty() {
+ s += word.as_str();
+ return Ok(Some(Token::make_word(s.as_str(), None)));
+ }
+ }
+
let long = if chars.peek() == Some(&'L') {
chars.next();
true
| apache__datafusion-sqlparser-rs-856 | 856 | Althrough nodody would name their columns like `1col` `00column`, mysql does allow this.
```bash
CREATE DATABASE test;
use test;
CREATE TABLE my_table (
id int,
1col int,
2col int
);
INSERT INTO my_table VALUES (1,2,3);
INSERT INTO my_table VALUES (2,3,4);
INSERT INTO my_table VALUES (3,4,5);
SELECT * FROM my_table;
SELECT 1col FROM my_table
```
``` bash
MariaDB [(none)]> CREATE DATABASE test;
Query OK, 1 row affected (0.000 sec)
MariaDB [(none)]> use test;
INSERT INTO my_table VALUES (3,4,5);
SELECT * FROM my_table;
SELECT 1col FROM my_table
Database changed
MariaDB [test]> CREATE TABLE my_table (
-> id int,
-> 1col int,
-> 2col int
-> );
Query OK, 0 rows affected (0.029 sec)
MariaDB [test]>
MariaDB [test]> INSERT INTO my_table VALUES (1,2,3);
Query OK, 1 row affected (0.005 sec)
MariaDB [test]> INSERT INTO my_table VALUES (2,3,4);
Query OK, 1 row affected (0.003 sec)
MariaDB [test]> INSERT INTO my_table VALUES (3,4,5);
Query OK, 1 row affected (0.007 sec)
MariaDB [test]>
MariaDB [test]> SELECT * FROM my_table;
+------+------+------+
| id | 1col | 2col |
+------+------+------+
| 1 | 2 | 3 |
| 2 | 3 | 4 |
| 3 | 4 | 5 |
+------+------+------+
3 rows in set (0.000 sec)
MariaDB [test]> SELECT 1col FROM my_table
-> ;
+------+
| 1col |
+------+
| 2 |
| 3 |
| 4 |
+------+
3 rows in set (0.000 sec)
MariaDB [test]>
```

As you can see, `SELECT 1col FROM mytable` was treated as `SELECT 1 col FROM mytable`
Okay, I think it has nothing to do with if some dialect supports column name beginning with numbers. This is simply a bug about parsing word tokens incorrectly

I believe this is intended behaviour, at least for Generic/Postgres dialect. Relevant bit of discussion here:
https://github.com/sqlparser-rs/sqlparser-rs/pull/768#discussion_r1058345105
Though some dialects can support having their identifiers begin with a number, such as Hive:
https://github.com/sqlparser-rs/sqlparser-rs/blob/4955863bdf0e9d90e0fff72bca7912b3d20daac2/src/dialect/hive.rs#L23-L28
Though this does cause some issues with parsing numbers, for example exponent parsing does not work (related to above discussion)
Since Hive supports it, same could be enabled for MySql now which has an existing comment about it:
https://github.com/sqlparser-rs/sqlparser-rs/blob/4955863bdf0e9d90e0fff72bca7912b3d20daac2/src/dialect/mysql.rs#L19-L29
Any update about this issue? do this issue should be fixed in the near future for mysql?
thanks. | [
"804"
] | 0.33 | apache/datafusion-sqlparser-rs | 2023-04-24T10:14:20Z | diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -849,6 +849,106 @@ fn parse_insert_with_on_duplicate_update() {
}
}
+#[test]
+fn parse_select_with_numeric_prefix_column_name() {
+ let sql = "SELECT 123col_$@123abc FROM \"table\"";
+ match mysql().verified_stmt(sql) {
+ Statement::Query(q) => {
+ assert_eq!(
+ q.body,
+ Box::new(SetExpr::Select(Box::new(Select {
+ distinct: false,
+ top: None,
+ projection: vec![SelectItem::UnnamedExpr(Expr::Identifier(Ident::new(
+ "123col_$@123abc"
+ )))],
+ into: None,
+ from: vec![TableWithJoins {
+ relation: TableFactor::Table {
+ name: ObjectName(vec![Ident::with_quote('"', "table")]),
+ alias: None,
+ args: None,
+ with_hints: vec![],
+ },
+ joins: vec![]
+ }],
+ lateral_views: vec![],
+ selection: None,
+ group_by: vec![],
+ cluster_by: vec![],
+ distribute_by: vec![],
+ sort_by: vec![],
+ having: None,
+ qualify: None,
+ })))
+ );
+ }
+ _ => unreachable!(),
+ }
+}
+
+#[cfg(not(feature = "bigdecimal"))]
+#[test]
+fn parse_select_with_concatenation_of_exp_number_and_numeric_prefix_column() {
+ let sql = "SELECT 123e4, 123col_$@123abc FROM \"table\"";
+ match mysql().verified_stmt(sql) {
+ Statement::Query(q) => {
+ assert_eq!(
+ q.body,
+ Box::new(SetExpr::Select(Box::new(Select {
+ distinct: false,
+ top: None,
+ projection: vec![
+ SelectItem::UnnamedExpr(Expr::Value(Value::Number(
+ "123e4".to_string(),
+ false
+ ))),
+ SelectItem::UnnamedExpr(Expr::Identifier(Ident::new("123col_$@123abc")))
+ ],
+ into: None,
+ from: vec![TableWithJoins {
+ relation: TableFactor::Table {
+ name: ObjectName(vec![Ident::with_quote('"', "table")]),
+ alias: None,
+ args: None,
+ with_hints: vec![],
+ },
+ joins: vec![]
+ }],
+ lateral_views: vec![],
+ selection: None,
+ group_by: vec![],
+ cluster_by: vec![],
+ distribute_by: vec![],
+ sort_by: vec![],
+ having: None,
+ qualify: None,
+ })))
+ );
+ }
+ _ => unreachable!(),
+ }
+}
+
+#[test]
+fn parse_insert_with_numeric_prefix_column_name() {
+ let sql = "INSERT INTO s1.t1 (123col_$@length123) VALUES (67.654)";
+ match mysql().verified_stmt(sql) {
+ Statement::Insert {
+ table_name,
+ columns,
+ ..
+ } => {
+ assert_eq!(
+ ObjectName(vec![Ident::new("s1"), Ident::new("t1")]),
+ table_name
+ );
+ assert_eq!(vec![Ident::new("123col_$@length123")], columns);
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn parse_update_with_joins() {
let sql = "UPDATE orders AS o JOIN customers AS c ON o.customer_id = c.id SET o.completed = true WHERE c.firstname = 'Peter'";
| Incorrect parsing literals that consisting of digits and letters, beginning with digits
It seems when parsing a literal beginning with digits, the sql parser simply ends this token when meets a non-numeric character
see https://github.com/sqlparser-rs/sqlparser-rs/blob/main/src/tokenizer.rs#L547
For example, `123foobar` would be parsed into a number token `123` and a word token `foobar` instead of one word token `123foobar`.
And `123foobar456` would be parsed into `123` and `foobar456`
| 097e7ad56ed09e5757fbf0719d07194aa93521e8 | [
"parse_insert_with_numeric_prefix_column_name",
"parse_select_with_numeric_prefix_column_name"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_cube_display",
"dialect::tests::test_is_dialect",
"ast::tests::test_w... | [] | [] |
86d71f21097c0a44e67cc1513466c573ac1f763c | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -1433,7 +1433,7 @@ impl<'a> Parser<'a> {
///
/// [(1)]: Expr::MatchAgainst
pub fn parse_match_against(&mut self) -> Result<Expr, ParserError> {
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
self.expect_keyword(Keyword::AGAINST)?;
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -2419,7 +2419,7 @@ impl<'a> Parser<'a> {
// general that the arguments can be made to appear as column
// definitions in a traditional CREATE TABLE statement", but
// we don't implement that.
- let module_args = self.parse_parenthesized_column_list(Optional)?;
+ let module_args = self.parse_parenthesized_column_list(Optional, false)?;
Ok(Statement::CreateVirtualTable {
name: table_name,
if_not_exists,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -2698,12 +2698,12 @@ impl<'a> Parser<'a> {
// Many dialects support `OR ALTER` right after `CREATE`, but we don't (yet).
// ANSI SQL and Postgres support RECURSIVE here, but we don't support it either.
let name = self.parse_object_name()?;
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let columns = self.parse_parenthesized_column_list(Optional, false)?;
let with_options = self.parse_options(Keyword::WITH)?;
let cluster_by = if self.parse_keyword(Keyword::CLUSTER) {
self.expect_keyword(Keyword::BY)?;
- self.parse_parenthesized_column_list(Optional)?
+ self.parse_parenthesized_column_list(Optional, false)?
} else {
vec![]
};
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3441,7 +3441,7 @@ impl<'a> Parser<'a> {
let foreign_table = self.parse_object_name()?;
// PostgreSQL allows omitting the column list and
// uses the primary key column of the foreign table by default
- let referred_columns = self.parse_parenthesized_column_list(Optional)?;
+ let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
let mut on_delete = None;
let mut on_update = None;
loop {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3525,7 +3525,7 @@ impl<'a> Parser<'a> {
if is_primary {
self.expect_keyword(Keyword::KEY)?;
}
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
Ok(Some(TableConstraint::Unique {
name,
columns,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3534,10 +3534,10 @@ impl<'a> Parser<'a> {
}
Token::Word(w) if w.keyword == Keyword::FOREIGN => {
self.expect_keyword(Keyword::KEY)?;
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
self.expect_keyword(Keyword::REFERENCES)?;
let foreign_table = self.parse_object_name()?;
- let referred_columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let referred_columns = self.parse_parenthesized_column_list(Mandatory, false)?;
let mut on_delete = None;
let mut on_update = None;
loop {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3582,7 +3582,7 @@ impl<'a> Parser<'a> {
} else {
None
};
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
Ok(Some(TableConstraint::Index {
display_as_key,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3617,7 +3617,7 @@ impl<'a> Parser<'a> {
let opt_index_name = self.maybe_parse(|parser| parser.parse_identifier());
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
Ok(Some(TableConstraint::FulltextOrSpatial {
fulltext,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3864,7 +3864,7 @@ impl<'a> Parser<'a> {
/// Parse a copy statement
pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
let table_name = self.parse_object_name()?;
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let columns = self.parse_parenthesized_column_list(Optional, false)?;
let to = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::TO]) {
Some(Keyword::FROM) => false,
Some(Keyword::TO) => true,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -3950,13 +3950,13 @@ impl<'a> Parser<'a> {
Some(Keyword::QUOTE) => CopyOption::Quote(self.parse_literal_char()?),
Some(Keyword::ESCAPE) => CopyOption::Escape(self.parse_literal_char()?),
Some(Keyword::FORCE_QUOTE) => {
- CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory)?)
+ CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory, false)?)
}
Some(Keyword::FORCE_NOT_NULL) => {
- CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory)?)
+ CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory, false)?)
}
Some(Keyword::FORCE_NULL) => {
- CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory)?)
+ CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory, false)?)
}
Some(Keyword::ENCODING) => CopyOption::Encoding(self.parse_literal_string()?),
_ => self.expected("option", self.peek_token())?,
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4454,7 +4454,7 @@ impl<'a> Parser<'a> {
) -> Result<Option<TableAlias>, ParserError> {
match self.parse_optional_alias(reserved_kwds)? {
Some(name) => {
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let columns = self.parse_parenthesized_column_list(Optional, false)?;
Ok(Some(TableAlias { name, columns }))
}
None => Ok(None),
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4505,11 +4505,17 @@ impl<'a> Parser<'a> {
pub fn parse_parenthesized_column_list(
&mut self,
optional: IsOptional,
+ allow_empty: bool,
) -> Result<Vec<Ident>, ParserError> {
if self.consume_token(&Token::LParen) {
- let cols = self.parse_comma_separated(Parser::parse_identifier)?;
- self.expect_token(&Token::RParen)?;
- Ok(cols)
+ if allow_empty && self.peek_token().token == Token::RParen {
+ self.next_token();
+ Ok(vec![])
+ } else {
+ let cols = self.parse_comma_separated(Parser::parse_identifier)?;
+ self.expect_token(&Token::RParen)?;
+ Ok(cols)
+ }
} else if optional == Optional {
Ok(vec![])
} else {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4811,7 +4817,7 @@ impl<'a> Parser<'a> {
from: None,
}
} else {
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let columns = self.parse_parenthesized_column_list(Optional, false)?;
self.expect_keyword(Keyword::AS)?;
self.expect_token(&Token::LParen)?;
let query = Box::new(self.parse_query()?);
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4848,7 +4854,8 @@ impl<'a> Parser<'a> {
self.expect_token(&Token::RParen)?;
SetExpr::Query(Box::new(subquery))
} else if self.parse_keyword(Keyword::VALUES) {
- SetExpr::Values(self.parse_values()?)
+ let is_mysql = dialect_of!(self is MySqlDialect);
+ SetExpr::Values(self.parse_values(is_mysql)?)
} else if self.parse_keyword(Keyword::TABLE) {
SetExpr::Table(Box::new(self.parse_as_table()?))
} else {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5645,7 +5652,7 @@ impl<'a> Parser<'a> {
let constraint = self.parse_expr()?;
Ok(JoinConstraint::On(constraint))
} else if self.parse_keyword(Keyword::USING) {
- let columns = self.parse_parenthesized_column_list(Mandatory)?;
+ let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
Ok(JoinConstraint::Using(columns))
} else {
Ok(JoinConstraint::None)
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5770,7 +5777,7 @@ impl<'a> Parser<'a> {
]) {
let columns = match kw {
Keyword::INSERT | Keyword::REFERENCES | Keyword::SELECT | Keyword::UPDATE => {
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let columns = self.parse_parenthesized_column_list(Optional, false)?;
if columns.is_empty() {
None
} else {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5856,7 +5863,8 @@ impl<'a> Parser<'a> {
// Hive lets you put table here regardless
let table = self.parse_keyword(Keyword::TABLE);
let table_name = self.parse_object_name()?;
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let is_mysql = dialect_of!(self is MySqlDialect);
+ let columns = self.parse_parenthesized_column_list(Optional, is_mysql)?;
let partitioned = if self.parse_keyword(Keyword::PARTITION) {
self.expect_token(&Token::LParen)?;
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5868,7 +5876,7 @@ impl<'a> Parser<'a> {
};
// Hive allows you to specify columns after partitions as well if you want.
- let after_columns = self.parse_parenthesized_column_list(Optional)?;
+ let after_columns = self.parse_parenthesized_column_list(Optional, false)?;
let source = Box::new(self.parse_query()?);
let on = if self.parse_keyword(Keyword::ON) {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -5878,7 +5886,7 @@ impl<'a> Parser<'a> {
Some(ConflictTarget::OnConstraint(self.parse_object_name()?))
} else if self.peek_token() == Token::LParen {
Some(ConflictTarget::Columns(
- self.parse_parenthesized_column_list(IsOptional::Mandatory)?,
+ self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
))
} else {
None
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6091,7 +6099,7 @@ impl<'a> Parser<'a> {
&mut self,
) -> Result<Option<ExceptSelectItem>, ParserError> {
let opt_except = if self.parse_keyword(Keyword::EXCEPT) {
- let idents = self.parse_parenthesized_column_list(Mandatory)?;
+ let idents = self.parse_parenthesized_column_list(Mandatory, false)?;
match &idents[..] {
[] => {
return self.expected(
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6236,7 +6244,7 @@ impl<'a> Parser<'a> {
})
}
- pub fn parse_values(&mut self) -> Result<Values, ParserError> {
+ pub fn parse_values(&mut self, allow_empty: bool) -> Result<Values, ParserError> {
let mut explicit_row = false;
let rows = self.parse_comma_separated(|parser| {
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6245,9 +6253,14 @@ impl<'a> Parser<'a> {
}
parser.expect_token(&Token::LParen)?;
- let exprs = parser.parse_comma_separated(Parser::parse_expr)?;
- parser.expect_token(&Token::RParen)?;
- Ok(exprs)
+ if allow_empty && parser.peek_token().token == Token::RParen {
+ parser.next_token();
+ Ok(vec![])
+ } else {
+ let exprs = parser.parse_comma_separated(Parser::parse_expr)?;
+ parser.expect_token(&Token::RParen)?;
+ Ok(exprs)
+ }
})?;
Ok(Values { explicit_row, rows })
}
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -6413,9 +6426,10 @@ impl<'a> Parser<'a> {
"INSERT in MATCHED merge clause".to_string(),
));
}
- let columns = self.parse_parenthesized_column_list(Optional)?;
+ let is_mysql = dialect_of!(self is MySqlDialect);
+ let columns = self.parse_parenthesized_column_list(Optional, is_mysql)?;
self.expect_keyword(Keyword::VALUES)?;
- let values = self.parse_values()?;
+ let values = self.parse_values(is_mysql)?;
MergeClause::NotMatched {
predicate,
columns,
| apache__datafusion-sqlparser-rs-783 | 783 | [
"624"
] | 0.29 | apache/datafusion-sqlparser-rs | 2023-01-01T10:51:46Z | diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -692,6 +692,41 @@ fn parse_simple_insert() {
}
}
+#[test]
+fn parse_empty_row_insert() {
+ let sql = "INSERT INTO tb () VALUES (), ()";
+
+ match mysql().one_statement_parses_to(sql, "INSERT INTO tb VALUES (), ()") {
+ Statement::Insert {
+ table_name,
+ columns,
+ source,
+ on,
+ ..
+ } => {
+ assert_eq!(ObjectName(vec![Ident::new("tb")]), table_name);
+ assert!(columns.is_empty());
+ assert!(on.is_none());
+ assert_eq!(
+ Box::new(Query {
+ with: None,
+ body: Box::new(SetExpr::Values(Values {
+ explicit_row: false,
+ rows: vec![vec![], vec![]]
+ })),
+ order_by: vec![],
+ limit: None,
+ offset: None,
+ fetch: None,
+ locks: vec![],
+ }),
+ source
+ );
+ }
+ _ => unreachable!(),
+ }
+}
+
#[test]
fn parse_insert_with_on_duplicate_update() {
let sql = "INSERT INTO permission_groups (name, description, perm_create, perm_read, perm_update, perm_delete) VALUES ('accounting_manager', 'Some description about the group', true, true, true, true) ON DUPLICATE KEY UPDATE description = VALUES(description), perm_create = VALUES(perm_create), perm_read = VALUES(perm_read), perm_update = VALUES(perm_update), perm_delete = VALUES(perm_delete)";
| Support MySQL's empty row insert
MySQL supports default row inserts [1], which we don't, like:
```sql
INSERT INTO tb () VALUES ();
```
This returns: `ParserError("Expected identifier, found: )")`
Maybe the columns list could be an option, instead of a vector? This way we can differentiate between non-existent lists (`INSERT INTO tb VALUES ...`) and empty lists (`INSERT INTO tb () ...`).
[1]: https://dev.mysql.com/doc/refman/8.0/en/insert.html
| 86d71f21097c0a44e67cc1513466c573ac1f763c | [
"parse_empty_row_insert"
] | [
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_window_frame_default",
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"dialect::tes... | [] | [] | |
0c9ec4008269dde77a4a5895b0a69a0a27c40ca3 | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -4693,21 +4693,24 @@ impl<'a> Parser<'a> {
format = Some(self.parse_analyze_format()?);
}
- if let Some(statement) = self.maybe_parse(|parser| parser.parse_statement()) {
- Ok(Statement::Explain {
+ match self.maybe_parse(|parser| parser.parse_statement()) {
+ Some(Statement::Explain { .. }) | Some(Statement::ExplainTable { .. }) => Err(
+ ParserError::ParserError("Explain must be root of the plan".to_string()),
+ ),
+ Some(statement) => Ok(Statement::Explain {
describe_alias,
analyze,
verbose,
statement: Box::new(statement),
format,
- })
- } else {
- let table_name = self.parse_object_name()?;
-
- Ok(Statement::ExplainTable {
- describe_alias,
- table_name,
- })
+ }),
+ _ => {
+ let table_name = self.parse_object_name()?;
+ Ok(Statement::ExplainTable {
+ describe_alias,
+ table_name,
+ })
+ }
}
}
| apache__datafusion-sqlparser-rs-781 | 781 | [
"744"
] | 0.28 | apache/datafusion-sqlparser-rs | 2022-12-29T02:03:40Z | diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -7138,4 +7141,16 @@ mod tests {
))
);
}
+
+ #[test]
+ fn test_nested_explain_error() {
+ let sql = "EXPLAIN EXPLAIN SELECT 1";
+ let ast = Parser::parse_sql(&GenericDialect, sql);
+ assert_eq!(
+ ast,
+ Err(ParserError::ParserError(
+ "Explain must be root of the plan".to_string()
+ ))
+ );
+ }
}
| Return an error when the SQL query contains nested `Explain`
In datafusion, we met a bug (https://github.com/apache/arrow-datafusion/issues/4378) which the datafusion-CLI will panic when the query contains nested `EXPLAIN`.
We fixed this bug using a workaround way, and currently the datafusion will return an `Internal` error when meeting these invalid `explain` queries. However the error is generated when converting a logical plan to a physical plan, which is too late.
We'd like the sqlparser to return a parsing error when parsing these invalid query string.
An ideal example is:
```
> explain explain select 1;
ParseError ...
| 0c9ec4008269dde77a4a5895b0a69a0a27c40ca3 | [
"parser::tests::test_nested_explain_error"
] | [
"ast::helpers::stmt_create_table::tests::test_from_valid_statement",
"ast::helpers::stmt_create_table::tests::test_from_invalid_statement",
"ast::tests::test_cube_display",
"ast::tests::test_grouping_sets_display",
"ast::tests::test_rollup_display",
"ast::tests::test_window_frame_default",
"dialect::tes... | [] | [] | |
beb700f88974420d36cad494b1fac80de3e01093 | diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -1,5 +1,3 @@
-use lazy_static::lazy_static;
-use regex::Regex;
use std::io::Write;
use itertools::Itertools;
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -586,18 +584,26 @@ fn style_sections_contain_more_than_one_style(sections: &[(Style, &str)]) -> boo
}
}
-lazy_static! {
- static ref NON_WHITESPACE_REGEX: Regex = Regex::new(r"\S").unwrap();
-}
-
/// True iff the line represented by `sections` constitutes a whitespace error.
+// Note that a space is always present as the first character in the line (it was put there as a
+// replacement for the leading +/- marker; see paint::prepare()). A line is a whitespace error iff,
+// beyond the initial space character, (a) there are more characters and (b) they are all
+// whitespace characters.
// TODO: Git recognizes blank lines at end of file (blank-at-eof) as a whitespace error but delta
// does not yet.
// https://git-scm.com/docs/git-config#Documentation/git-config.txt-corewhitespace
fn is_whitespace_error(sections: &[(Style, &str)]) -> bool {
- !sections
- .iter()
- .any(|(_, s)| NON_WHITESPACE_REGEX.is_match(s))
+ let mut any_chars = false;
+ for c in sections.iter().flat_map(|(_, s)| s.chars()).skip(1) {
+ if c == '\n' {
+ return any_chars;
+ } else if c != ' ' && c != '\t' {
+ return false;
+ } else {
+ any_chars = true;
+ }
+ }
+ false
}
mod superimpose_style_sections {
| dandavison__delta-425 | 425 | I guess it *is* a whitespace ~error~ diff, since newlines are whitespace, no ?
It's very distracting having it highlighted in the middle of a block, and it's inconsistent with what `git` itself highlights as whitespace errors:


> It's very distracting having it highlighted in the middle of a block
Agreed, though one could also argue that it might be advantageous to have whitespace diffs highlighted esp. when working with languages as python where they are crucial
> it's inconsistent with what git itself highlights as whitespace errors
That depends on the configuration. Not sure though what the defaults are, to be honest, but IIRC git *does* highlight such a diff without any config.
**EDIT/** This was after removing all git config files :

Anyways, I agree it would be quite handy to have it configurable in delta, too.
Hi @Nemo157, thanks for this!
@Kr1ss-XD what @Nemo157 is pointing out is that completely normal, not-at-all-an-error blank lines are being styled with an error background color when using `keep-plus-minus-markers`. I would say this is definitely a bug!
<table><tr><td><img width=400px src="https://user-images.githubusercontent.com/52205/99154396-745dbd80-267d-11eb-9134-987a1e9d38ab.png" alt="image" /></td></tr></table>
Oh, I see. I've missed the point then I guess.
I think this is part of a bigger issue, as I reported in #345. | [
"388"
] | 0.4 | dandavison/delta | 2020-12-04T19:33:27Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1302,6 +1302,32 @@ impl<'a> Alignment<'a> { โ
);
}
+ #[test]
+ fn test_added_empty_line_is_not_whitespace_error() {
+ let plus_style = "bold yellow red ul";
+ let config = integration_test_utils::make_config_from_args(&[
+ "--light",
+ "--keep-plus-minus-markers",
+ "--plus-style",
+ plus_style,
+ ]);
+ let output = integration_test_utils::run_delta(DIFF_WITH_ADDED_EMPTY_LINE, &config);
+ ansi_test_utils::assert_line_has_style(&output, 6, "", plus_style, &config)
+ }
+
+ #[test]
+ fn test_single_character_line_is_not_whitespace_error() {
+ let plus_style = "bold yellow red ul";
+ let config = integration_test_utils::make_config_from_args(&[
+ "--light",
+ "--keep-plus-minus-markers",
+ "--plus-style",
+ plus_style,
+ ]);
+ let output = integration_test_utils::run_delta(DIFF_WITH_SINGLE_CHARACTER_LINE, &config);
+ ansi_test_utils::assert_line_has_style(&output, 12, "+}", plus_style, &config)
+ }
+
#[test]
fn test_color_only() {
let config = integration_test_utils::make_config_from_args(&["--color-only"]);
diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1848,6 +1874,22 @@ index e69de29..8b13789 100644
+++ w/a
@@ -0,0 +1 @@
+
+";
+
+ const DIFF_WITH_SINGLE_CHARACTER_LINE: &str = r"
+diff --git a/Person.java b/Person.java
+new file mode 100644
+index 0000000..c6c830c
+--- /dev/null
++++ b/Person.java
+@@ -0,0 +1,7 @@
++import lombok.Data;
++
++@Data
++public class Person {
++ private Long id;
++ private String name;
++}
";
const DIFF_WITH_WHITESPACE_ERROR: &str = r"
| ๐ Empty lines highlight plus-marker as whitespace-error
With a test file:
```
No Spaces
Spaces
```
(Note that there are spaces on the last line)
Running
```
delta --no-gitconfig --keep-plus-minus-markers <(echo -n) test-file
```
highlights the plus-marker on the empty line as a whitespace error

| 5e39a0e4dde2e010b13cb0d9cf01212e6910de4f | [
"tests::test_example_diffs::tests::test_added_empty_line_is_not_whitespace_error"
] | [
"align::tests::test_0",
"align::tests::test_0_nonascii",
"align::tests::test_1",
"align::tests::test_run_length_encode",
"align::tests::test_2",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"a... | [] | [] |
f52464c1af557a5759566a988d2478ccb6e86d3e | diff --git a/src/cli.rs b/src/cli.rs
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -437,6 +437,10 @@ pub struct Opt {
/// Text to display in front of a added file path.
pub file_added_label: String,
+ #[structopt(long = "file-copied-label", default_value = "copied:")]
+ /// Text to display in front of a copied file path.
+ pub file_copied_label: String,
+
#[structopt(long = "file-renamed-label", default_value = "renamed:")]
/// Text to display in front of a renamed file path.
pub file_renamed_label: String,
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -23,6 +23,7 @@ pub struct Config {
pub commit_style: Style,
pub decorations_width: cli::Width,
pub file_added_label: String,
+ pub file_copied_label: String,
pub file_modified_label: String,
pub file_removed_label: String,
pub file_renamed_label: String,
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -151,6 +152,7 @@ impl From<cli::Opt> for Config {
commit_style,
decorations_width: opt.computed.decorations_width,
file_added_label: opt.file_added_label,
+ file_copied_label: opt.file_copied_label,
file_modified_label: opt.file_modified_label,
file_removed_label: opt.file_removed_label,
file_renamed_label: opt.file_renamed_label,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -98,7 +98,9 @@ where
state = State::FileMeta;
handled_file_meta_header_line_file_pair = None;
} else if (state == State::FileMeta || source == Source::DiffUnified)
- && (line.starts_with("--- ") || line.starts_with("rename from "))
+ && (line.starts_with("--- ")
+ || line.starts_with("rename from ")
+ || line.starts_with("copy from "))
{
let parsed_file_meta_line =
parse::parse_file_meta_line(&line, source == Source::GitDiff);
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -114,7 +116,9 @@ where
));
}
} else if (state == State::FileMeta || source == Source::DiffUnified)
- && (line.starts_with("+++ ") || line.starts_with("rename to "))
+ && (line.starts_with("+++ ")
+ || line.starts_with("rename to ")
+ || line.starts_with("copy to "))
{
let parsed_file_meta_line =
parse::parse_file_meta_line(&line, source == Source::GitDiff);
diff --git a/src/options/set.rs b/src/options/set.rs
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -129,6 +129,7 @@ pub fn set_options(
commit_decoration_style,
commit_style,
file_added_label,
+ file_copied_label,
file_decoration_style,
file_modified_label,
file_removed_label,
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -22,6 +22,7 @@ pub fn get_file_extension_from_marker_line(line: &str) -> Option<&str> {
#[derive(Debug, PartialEq)]
pub enum FileEvent {
Change,
+ Copy,
Rename,
NoEvent,
}
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -47,6 +48,12 @@ pub fn parse_file_meta_line(line: &str, git_diff_name: bool) -> (String, FileEve
line if line.starts_with("rename to ") => {
(line[10..].to_string(), FileEvent::Rename) // "rename to ".len()
}
+ line if line.starts_with("copy from ") => {
+ (line[10..].to_string(), FileEvent::Copy) // "copy from ".len()
+ }
+ line if line.starts_with("copy to ") => {
+ (line[8..].to_string(), FileEvent::Copy) // "copy to ".len()
+ }
_ => ("".to_string(), FileEvent::NoEvent),
}
}
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -103,6 +110,7 @@ pub fn get_file_change_description_from_file_paths(
"{}{} โถ {}",
format_label(match file_event {
FileEvent::Rename => &config.file_renamed_label,
+ FileEvent::Copy => &config.file_copied_label,
_ => "",
}),
format_file(minus_file),
| dandavison__delta-403 | 403 | Hi @phil-blain, thanks for this, I didn't know about the feature. | [
"392"
] | 0.4 | dandavison/delta | 2020-11-23T01:30:11Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -46,6 +46,17 @@ mod tests {
));
}
+ #[test]
+ fn test_copied_file() {
+ let config = integration_test_utils::make_config_from_args(&[]);
+ let output = integration_test_utils::run_delta(GIT_DIFF_WITH_COPIED_FILE, &config);
+ let output = strip_ansi_codes(&output);
+ assert!(test_utils::contains_once(
+ &output,
+ "\ncopied: first_file โถ copied_file\n"
+ ));
+ }
+
#[test]
fn test_renamed_file_with_changes() {
let config = integration_test_utils::make_config_from_args(&[]);
diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1656,6 +1667,19 @@ diff --git a/foo b/foo
new file mode 100644
index 0000000..b572921
Binary files /dev/null and b/foo differ
+";
+
+ const GIT_DIFF_WITH_COPIED_FILE: &str = "
+commit f600ed5ced4d98295ffa97571ed240cd86c34ac6 (HEAD -> master)
+Author: Dan Davison <dandavison7@gmail.com>
+Date: Fri Nov 20 20:18:30 2020 -0500
+
+ copy
+
+diff --git a/first_file b/copied_file
+similarity index 100%
+copy from first_file
+copy to copied_file
";
// git --no-pager show -p --cc --format= --numstat --stat
| ๐ delta does not recognize Git's copy detection
Git has special flags and configuration variables for `git log`, `git show`, `git diff`, `git diff-tree`, `git diff-index`, `git diff-tree`, and `git format-patch` to detect copies as well as renames.
These add "copy from"/"copy to" lines in the diff header when Git detects a new file is in fact copied from an existing file. Currently delta shows these as renames, which is confusing. It would be nice if they would show up correctly as copies.
An example from the [same issue for diff-so-fancy](https://github.com/so-fancy/diff-so-fancy/issues/349#issuecomment-619029880):
> @ scottchiefbaker this setting tells git how to display renamed (same or similar content, new name, old file is missing) and copied (same or similar content, new name, old file present) files. By default git only detects renames, any copy is shown as new file. `diff.renames copies` works also for second case.
>
> To illustrate this one can create dummy repository as
>
> ```
> git init
> echo "hurr-durr" > first_file
> git add .
> git commit -m "first"
> ```
>
> After that copy and stage (or commit) some file:
>
> ```
> cp first_file copied_file
> git add .
> ```
>
> And inspect this change:
>
> ```
> โฏ git --no-pager diff --staged
> diff --git a/copied_file b/copied_file
> new file mode 100644
> index 0000000..d7b6a5e
> --- /dev/null
> +++ b/copied_file
> @@ -0,0 +1 @@
> +hurr-durr
>
> /tmp/copy-example master*
> โฏ git --no-pager diff -C --staged # -C has the same meaning
> diff --git a/first_file b/copied_file
> similarity index 100%
> copy from first_file
> copy to copied_file
> ```
>
> I hope this narrowed down example helps better than original ones.
> Looks like fancy just doesn't know how to parse `copy from/to` headers in diff.
Relevant parts of the Git documentation:
- [`-C` option for diff, show, log, etc.](https://git-scm.com/docs/git-diff#Documentation/git-diff.txt--Cltngt)
- [Doc for Git's extended diff header](https://git-scm.com/docs/git-diff#_generating_patch_text_with_p)
- [`diff.renames` configuration for diff, show, log](https://git-scm.com/docs/git-config#Documentation/git-config.txt-diffrenames)
| 5e39a0e4dde2e010b13cb0d9cf01212e6910de4f | [
"tests::test_example_diffs::tests::test_copied_file"
] | [
"align::tests::test_0",
"align::tests::test_1",
"align::tests::test_0_nonascii",
"align::tests::test_2",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::iterator::tests::test_iterator_1",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"ansi::it... | [] | [] |
759f484955f674bf000d1ae4bab8c7cb1f453ab2 | diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -380,9 +380,6 @@ fn handle_hunk_header_line(
plus_file: &str,
config: &Config,
) -> std::io::Result<()> {
- if config.hunk_header_style.is_omitted {
- return Ok(());
- }
let decoration_ansi_term_style;
let draw_fn = match config.hunk_header_style.decoration_style {
DecorationStyle::Box(style) => {
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -432,7 +429,7 @@ fn handle_hunk_header_line(
config.hunk_header_style,
decoration_ansi_term_style,
)?;
- } else {
+ } else if !config.hunk_header_style.is_omitted {
let line = match painter.prepare(&raw_code_fragment, false) {
s if s.len() > 0 => format!("{} ", s),
s => s,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -466,11 +463,10 @@ fn handle_hunk_header_line(
config.hunk_header_style,
decoration_ansi_term_style,
)?;
- if !config.hunk_header_style.is_raw {
- painter.output_buffer.clear()
- };
+ painter.output_buffer.clear();
}
};
+
// Emit a single line number, or prepare for full line-numbering
if config.line_numbers {
painter
diff --git a/src/options/set.rs b/src/options/set.rs
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -19,8 +19,8 @@ use crate::options::option_value::{OptionValue, ProvenancedOptionValue};
use crate::options::{self, theme};
macro_rules! set_options {
- ([$( $field_ident:ident ),* ],
- $opt:expr, $builtin_features:expr, $git_config:expr, $arg_matches:expr, $expected_option_name_map:expr, $check_names:expr) => {
+ ([$( $field_ident:ident ),* ],
+ $opt:expr, $builtin_features:expr, $git_config:expr, $arg_matches:expr, $expected_option_name_map:expr, $check_names:expr) => {
let mut option_names = HashSet::new();
$(
let kebab_case_field_name = stringify!($field_ident).replace("_", "-");
diff --git a/src/options/set.rs b/src/options/set.rs
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -59,7 +59,7 @@ macro_rules! set_options {
&option_names - &expected_option_names));
}
}
- }
+ }
}
pub fn set_options(
diff --git a/src/options/set.rs b/src/options/set.rs
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -192,6 +192,10 @@ pub fn set_options(
// there (does not emit lines in 1-1 correspondence with raw git output). See #274.
if opt.color_only {
opt.side_by_side = false;
+ opt.file_style = "raw".to_string();
+ opt.commit_style = "raw".to_string();
+ opt.hunk_header_style = "raw".to_string();
+ opt.hunk_header_decoration_style = "none".to_string();
}
}
| dandavison__delta-323 | 323 | Hi @Minnozz, thanks for this, very helpful. Clearly the test suite needs to be strengthened for `git add -p` also. I know `git add -p` is important, so this is probably the top priority for delta bugs right now.
Hi @dandavison, let me know if you need more information.
I looked for causes of this bug before, and
```
side-by-side = true
hunk-header-style = omit (only omit. I usually use this option except when git add -p)
file-style = (any option interestingly)
```
these options made it happened.
@Minnozz 's config can work if you remove file-style one.
I'd like to note that `git add -p` works here although I'm using `file-style`. Maybe it does not play well in combination with some other option(s) ?
For reference, my [delta --show-config](https://github.com/dandavison/delta/files/5214131/delta-conf.txt).
**EDIT** Oddly enough [this config](https://github.com/dandavison/delta/files/5214137/delta-conf2.txt) doesn't break `add -p` either in my environment. It contains _all_ of the options mentioned above by @ryuta69.
Thank you @Kr1ss-XD for looking. Hmm, I tried same config with you, however, it doesn't work. (core.pager = delta, and interactive.diffFilter = delta --color-only)
<img width="616" alt="ss 1" src="https://user-images.githubusercontent.com/41639488/93019396-aa48dc00-f611-11ea-848c-f040d4f78333.png">
As picture showing,
```
โฏ git --version
git version 2.28.0 (latest)
โฏ delta --version
delta 0.4.3 (latest)
OS is MacOS Catalina 10.15.6.
```
Additionally, with your config, if I delete
```
file-style = bold 232 bright-yellow
hunk-header-style = omit normal
side-by-side = true
```
now it works.
<img width="616" alt="ss 2" src="https://user-images.githubusercontent.com/41639488/93019541-9e114e80-f612-11ea-9ac8-ee9c6e9e83eb.png">
That's weird.
I'm trying @Minnozz 's configuration as I'm writing. It seems if the `file` option is deleted, it actually works, just as you suggested.
FWIW,
```
$ git --version; delta --version; uname -smro
git version 2.28.0
delta 0.4.3
Linux 5.7.19-1-ck x86_64 GNU/Linux
```
I hope this helps chasing that bug.
### I think I found something :
If I put the `file-style` option in a feature category, `git add -p` works with the @Minnozz configuration !
```
[delta]
features = files
<... other options ...>
[delta "files"]
file-style = blue
```
cc @dandavison
**EDIT** The same applies to `hunk-header-style = omit`.
@Kr1ss-XD
Oh!
Same as hunk-header-style, and side-by-side. Moving them to features, `git add -p` works while usual `git diff` work as those options enabled!
I think
```
src/options/set.rs
if config::user_supplied_option("color-only", arg_matches) {
builtin_features.remove("side-by-side");
}
```
this is the reason why side-by-side works. I look for file-style, hunk-header-style's reasons.
Thanks a lot @Kr1ss-XD and @ryuta69 for investigating here.
I think @Kr1ss-XD's suggestion of using features to work around these issues is an excellent one for now, until we fix all the `git app -p` bugs.
@Kr1ss-XD I'm finding that I have to move both the `file-style` and `hunk-header-style` to a feature to make @Minnozz's config work under `git add -p`.
So, to be completely explicit, here is a modification of @Minnozz's config that I am finding works.
```gitconfig
[delta]
features = meta
commit-style = raw
# file-style = blue
# hunk-header-style = syntax
minus-style = syntax 52
minus-emph-style = syntax 88
zero-style = syntax normal
plus-style = syntax black
plus-emph-style = syntax 22
keep-plus-minus-markers = true
line-numbers = true
line-numbers-minus-style = red
line-numbers-zero-style = brightgreen
line-numbers-plus-style = green
whitespace-error-style = reverse magenta
minus-empty-line-marker-style = normal 88
plus-empty-line-marker-style = normal 22
[delta "meta"]
file-style = blue
hunk-header-style = syntax
[delta "diff-filter"]
# Can leave empty, but optionally put diffFilter-only settings here
[interactive]
# I've added a --features override here to be explicit that we don't want diffFilter to use the
# features defined in the main [delta] section.
diffFilter = delta --color-only --features=diff-filter
```
> I look for file-style, hunk-header-style's reasons.
@ryuta69 It would be awesome if you can make progress here! I'm not certain but I think
https://github.com/dandavison/delta/pull/272#discussion_r474371089 may be relevant.
[WIP]
```
commit_style = omit
hunk-header-decoration-style = {any option}
```
also triggers this bug. (It's because it removes commit hash.)
I build test, then I realized only `commit-style=omit`, `file-style={any except raw}`, and `hunk-header-style={any except raw}` cause this bug.
It's still WIP, but gonna send PR in few days.
Hi @iyerusad, let's get to the bottom of this!
Can you post a plain text small example diff that is causing problems, and a screenshot of delta output when you pipe that diff to delta, using
```
cat example.diff | delta --no-gitconfig --line-numbers
```
For example (you can try this test diff to see if it works for you):
Here is the contents of `example.diff`
```
diff --git a/src/delta.rs b/src/delta.rs
index 33c205cf..d256e77a 100644
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -476,7 +476,7 @@ fn handle_hunk_header_line(
painter
.line_numbers_data
.initialize_hunk(line_numbers, plus_file.to_string());
- } else {
+ } else if !config.hunk_header_style.is_raw {
let plus_line_number = line_numbers[line_numbers.len() - 1].0;
let formatted_plus_line_number = if config.hyperlinks {
features::hyperlinks::format_osc8_file_hyperlink(
```
and that gives me
<table><tr><td><img width=300px src="https://user-images.githubusercontent.com/52205/90301101-cc610a00-de6b-11ea-900f-704dcc23a2e1.png" alt="image" /></td></tr></table>
What do you get if you use my example diff?
Powershell version: 5.1.19041.1
example.diff
--

example2.diff
--
```
diff --git a/vscode/settings.json b/vscode/settings.json
index a5346ba..38bdfb3 100644
--- a/vscode/settings.json
+++ b/vscode/settings.json
@@ -9,6 +9,11 @@
"workbench.tree.renderIndentGuides": "always",
"workbench.startupEditor": "newUntitledFile",
+ "files.insertFinalNewline": true, //POSIX-targeted tools want new lines
+ "files.trimFinalNewlines": true,
+ "files.trimTrailingWhitespace": true,
+
+ "diffEditor.ignoreTrimWhitespace": false,
"editor.renderWhitespace": "boundary",
"editor.tabSize": 2,
"editor.insertspaces": true,
@@ -33,6 +38,5 @@
"peacock.showColorInStatusBar": false,
"peacock.surpriseMeFromFavoritesOnly": true,
- "git.autofetch": true,
- "diffEditor.ignoreTrimWhitespace": false
+ "git.autofetch": true
}
\ No newline at end of file
```
Get-Content example2.diff | delta --no-gitconfig --line-numbers //Correct line numbers

git show //Incorrect

Hi @iyerusad, thanks.
1. Does the problem still occur when you do not use `side-by-side`?
2. Can you post the output of `git -c 'core.pager=less' show bc35635`? (That, in my understanding, should be showing exactly the characters that delta is receiving on standard input when invoked by git. So there _ought_ to be no difference in the effects of piping that output into delta, and showing it in delta natively, as long as delta config is the same in both cases.)
3. Is the problem occurring on every commit in your repo? What about other repos? (For example, something public like delta's repo?)
To state what you probably already know: Delta simply receives the standard input that git sends to `core.pager`. So our naive expectation at least, should be that the behavior of delta is the same when invoked by git, versus when sent data on standard input directly (e.g. via a pipe). Delta does use libgit2 to read the user's gitconfig, but that occurs in both cases. Delta doesn't do anything else magical that should cause it to behave differently when invoked by git automatically versus when invoked as a standard command-line application receiving standard input. So really, if you have a situation where you're seeing incorrect line numbers with delta invoked by git, we should be able to capture that diff and reproduce the problem by sending that same diff to delta on standard input.
It appears the setting `hunk-header-style = omit` reproduces this issue:

--
> 1. Does the problem still occur when you do not use side-by-side?
Yes, see below.
> 2. Can you post the output of git -c 'core.pager=less' show bc35635?
I pulled down https://github.com/dandavison/delta, using it to better illustrate. Using [b5f5ca572466dacfc7fada83d8e2f4e52f13f17e](https://github.com/dandavison/delta/commit/b5f5ca572466dacfc7fada83d8e2f4e52f13f17e). The problem persists:

> 3. Is the problem occurring on every commit in your repo? What about other repos? (For example, something public like delta's repo?)
Seems to be.
> It appears the setting hunk-header-style = omit reproduces this issue:
Hi @iyerusad, thanks for that diagnosis, that was very useful. Sorry this isn't fixed yet, but it is the top priority bug to fix. (looks like same issue as reported in #274 and #319).
There's good discussion in #320, which is the same bug. I'm going to close this one in favor of #320 to keep the discussion in one place. | [
"320",
"293"
] | 0.4 | dandavison/delta | 2020-09-16T23:05:16Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -831,6 +831,50 @@ src/align.rs
);
}
+ #[test]
+ fn test_color_only_output_is_in_one_to_one_correspondence_with_input() {
+ _do_test_output_is_in_one_to_one_correspondence_with_input(&["--color-only", "true"]);
+ _do_test_output_is_in_one_to_one_correspondence_with_input(&[
+ "--color-only",
+ "true",
+ "--file-style",
+ "blue",
+ "--commit-style",
+ "omit",
+ "--hunk-header-style",
+ "omit",
+ "--hunk-header-decoration-style",
+ "omit",
+ ]);
+ _do_test_output_is_in_one_to_one_correspondence_with_input(&[
+ "--color-only",
+ "true",
+ "--file-style",
+ "blue",
+ "--commit-style",
+ "red",
+ "--hunk-header-style",
+ "syntax",
+ "--hunk-header-decoration-style",
+ "box",
+ ]);
+ }
+
+ fn _do_test_output_is_in_one_to_one_correspondence_with_input(args: &[&str]) {
+ let config = integration_test_utils::make_config_from_args(args);
+ let output = integration_test_utils::run_delta(GIT_DIFF_SINGLE_HUNK, &config);
+
+ let output = strip_ansi_codes(&output);
+ let output_lines: Vec<&str> = output.split('\n').collect();
+ let input_lines: Vec<&str> = GIT_DIFF_SINGLE_HUNK.split('\n').collect();
+
+ assert_eq!(input_lines.len(), output_lines.len());
+
+ for n in 0..input_lines.len() {
+ assert_eq!(input_lines[n], output_lines[n]);
+ }
+ }
+
#[test]
fn test_hunk_header_style_colored_input_color_is_stripped_under_normal() {
let config = integration_test_utils::make_config_from_args(&[
| ๐ git add -p one-to-one correspondence errors
When I try to use `git add -p`, I get the following error:
```
$ git add -p
fatal: mismatched output from interactive.diffFilter
hint: Your filter must maintain a one-to-one correspondence
hint: between its input and output lines.
```
I'm using `delta` with the following config:
```
$ delta --version
delta 0.4.3
$ delta --show-config
commit-style = raw
file-style = blue
hunk-header-style = syntax
minus-style = syntax 52
minus-non-emph-style = syntax 52
minus-emph-style = syntax 88
minus-empty-line-marker-style = normal 88
zero-style = syntax
plus-style = syntax black
plus-non-emph-style = syntax black
plus-emph-style = syntax 22
plus-empty-line-marker-style = normal 22
whitespace-error-style = reverse magenta
24-bit-color = false
file-added-label = 'added:'
file-modified-label = ''
file-removed-label = 'removed:'
file-renamed-label = 'renamed:'
hyperlinks = false
inspect-raw-lines = true
keep-plus-minus-markers = true
line-numbers = true
line-numbers-minus-style = red
line-numbers-zero-style = brightgreen
line-numbers-plus-style = green
line-numbers-left-style = blue
line-numbers-right-style = blue
line-numbers-left-format = '{nm:^4}โฎ'
line-numbers-right-format = '{np:^4}โ'
max-line-distance = 0.6
max-line-length = 512
navigate = false
paging = auto
side-by-side = false
syntax-theme = Solarized (dark)
width = 145
tabs = 4
word-diff-regex = '\w+'
```
In my .gitconfig are the following relevant options:
```
[core]
pager = delta
[delta]
commit-style = raw
file-style = blue
hunk-header-style = syntax
minus-style = syntax 52
minus-emph-style = syntax 88
zero-style = syntax normal
plus-style = syntax black
plus-emph-style = syntax 22
keep-plus-minus-markers = true
line-numbers = true
line-numbers-minus-style = red
line-numbers-zero-style = brightgreen
line-numbers-plus-style = green
whitespace-error-style = reverse magenta
minus-empty-line-marker-style = normal 88
plus-empty-line-marker-style = normal 22
[interactive]
diffFilter = delta --color-only
[color]
ui = true
```
๐ Line numbers incorrect/relative - Windows/Delta 0.4.1
Line numbers seem to be incorrect/relative in delta output. I believe this a bug, but apologies if just expected behavior.
Examples:
---
**git diff** (line numbers should be like 500 or so)

**git show** (line numbers should be like at like 330 or so)

**git show --no-pager**

Configs:
--
Delta 0.4.1 - Windows, executable from github release added to PATH.
**delta --show-config:**

**git config --list**
```
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
core.autocrlf=input
core.fscache=true
core.symlinks=false
pull.rebase=false
core.editor="C:\Users\User\AppData\Local\Programs\Microsoft VS Code\Code.exe" --wait
core.autocrlf=false
core.eol=lf
winupdater.recentlyseenversion=2.25.0.windows.1
include.path=~/.dotfiles/git/git_tweaks
diff.mnemonicprefix=true
diff.algorithm=patience
push.default=simple
log.date=auto:format:%a %Y-%h-%d %I:%M %p %z %Z
include.path=~/.dotfiles/git/git_deltadiff
interactive.difffilter=delta --color-only
delta.features=side-by-side line-numbers decorations
delta.syntax-theme=Dracula
delta.plus-style=syntax #003800
delta.minus-style=syntax #3f0001
delta.hunk-header-style=omit
delta.decorations.commit-decoration-style=bold yellow box ul
delta.decorations.file-style=bold yellow ul
delta.decorations.file-decoration-style=none
delta.decorations.hunk-header-decoration-style=cyan box ul
delta.line-numbers.line-numbers-left-style=cyan
delta.line-numbers.line-numbers-right-style=cyan
delta.line-numbers.line-numbers-minus-style=124
delta.line-numbers.line-numbers-plus-style=28
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=<snipped>
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
user.name=<snipped>
user.email=<snipped>
```
| 5e39a0e4dde2e010b13cb0d9cf01212e6910de4f | [
"tests::test_example_diffs::tests::test_color_only_output_is_in_one_to_one_correspondence_with_input"
] | [
"align::tests::test_2",
"align::tests::test_0",
"align::tests::test_0_nonascii",
"align::tests::test_1",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::iterator::tests::test_iterator_1",
"ansi::console_te... | [] | [] |
218af1617f512b06bb1a7f52a15510fe56c5de80 | diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -374,7 +374,11 @@ fn remove_surrounding_quotes(path: &str) -> &str {
}
}
-fn _parse_file_path(s: &str, git_diff_name: bool) -> String {
+fn _parse_file_path(path: &str, git_diff_name: bool) -> String {
+ // When git config 'core.quotepath = true' (the default), and `path` contains
+ // non-ASCII characters, a backslash, or a quote; then it is quoted, so remove
+ // these quotes. Characters may also be escaped, but these are left as-is.
+ let path = remove_surrounding_quotes(path);
// It appears that, if the file name contains a space, git appends a tab
// character in the diff metadata lines, e.g.
// $ git diff --no-index "a b" "c d" | cat -A
diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -382,15 +386,13 @@ fn _parse_file_path(s: &str, git_diff_name: bool) -> String {
// indexยทd00491f..0cfbf08ยท100644โ
// ---ยทa/aยทbโโโโคโ
// +++ยทb/cยทdโโโโคโ
- let path = match s.strip_suffix('\t').unwrap_or(s) {
+ match path.strip_suffix('\t').unwrap_or(path) {
"/dev/null" => "/dev/null",
path if git_diff_name && DIFF_PREFIXES.iter().any(|s| path.starts_with(s)) => &path[2..],
path if git_diff_name => path,
path => path.split('\t').next().unwrap_or(""),
- };
- // When a path contains non-ASCII characters, a backslash, or a quote then it is quoted,
- // so remove these quotes. Characters may also be escaped, but these are left as-is.
- remove_surrounding_quotes(path).to_string()
+ }
+ .to_string()
}
pub fn get_file_change_description_from_file_paths(
| dandavison__delta-1840 | 1,840 | [
"1821"
] | 0.18 | dandavison/delta | 2024-09-02T21:16:56Z | diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -638,6 +640,10 @@ mod tests {
"diff --git a/.config/Code - Insiders/User/settings.json b/.config/Code - Insiders/User/settings.json"),
Some(".config/Code - Insiders/User/settings.json".to_string())
);
+ assert_eq!(
+ get_repeated_file_path_from_diff_line(r#"diff --git "a/quoted" "b/quoted""#),
+ Some("quoted".to_string())
+ );
}
pub const BIN_AND_TXT_FILE_ADDED: &str = "\
| ๐ Changes in files with non-Latin names incorrectly imply these files being renamed
When the name of a changed file contains non-Latin characters, `delta` shows it as renamed instead of just the contents being changed.
To reproduce:
```
$ git init
$ echo one > ะฟัะธะฒะตั.txt; echo three > hello.txt
$ git add .
$ echo two > ะฟัะธะฒะตั.txt; echo four > hello.txt
$ git diff
```
Delta output:
<img width="923" alt="image" src="https://github.com/user-attachments/assets/e11ebc9a-b032-4192-a846-d28a40a666ac">
Note the headers for the two files:
```
...
hello.txt
...
a/\320\277\321\200\320\270\320\262\320\265\321\202.txt โถ b/\320\277\321\200\320\270\320\262\320\265\321\202.txt
...
```
Raw `git diff` output:
```
$ git --no-pager diff
diff --git a/hello.txt b/hello.txt
index 2bdf67a..8510665 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-three
+four
diff --git "a/\320\277\321\200\320\270\320\262\320\265\321\202.txt" "b/\320\277\321\200\320\270\320\262\320\265\321\202.txt"
index 5626abf..f719efd 100644
--- "a/\320\277\321\200\320\270\320\262\320\265\321\202.txt"
+++ "b/\320\277\321\200\320\270\320\262\320\265\321\202.txt"
@@ -1 +1 @@
-one
+two
```
| 1dd28e7b51a913fc28eefc59d01f3b78f1146850 | [
"handlers::diff_header::tests::test_get_repeated_file_path_from_diff_line"
] | [
"align::tests::test_0",
"align::tests::test_2",
"align::tests::test_1",
"align::tests::test_3",
"align::tests::test_0_nonascii",
"align::tests::test_5",
"align::tests::test_4",
"align::tests::test_6",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::c... | [] | [] | |
738c5a141bf86d3e05aa348eb87df78c36a72337 | diff --git a/manual/src/full---help-output.md b/manual/src/full---help-output.md
--- a/manual/src/full---help-output.md
+++ b/manual/src/full---help-output.md
@@ -1,7 +1,7 @@
# Full --help output
```
-delta 0.12.1
+delta 0.13.0
A viewer for git and diff output
USAGE:
diff --git a/manual/src/full---help-output.md b/manual/src/full---help-output.md
--- a/manual/src/full---help-output.md
+++ b/manual/src/full---help-output.md
@@ -103,7 +110,7 @@ OPTIONS:
--features <FEATURES>
Names of delta features to activate (space-separated).
- A feature is a named collection of delta options in ~/.gitconfig. See FEATURES section. The environment variable DELTA_FEATURES can be set to a space-separated list of feature names. If this is preceded with a space, the features from the environment variable will be added to those specified in git config. E.g. DELTA_FEATURES=+side-by-side can be used to activate side-by-side temporarily.
+ A feature is a named collection of delta options in ~/.gitconfig. See FEATURES section. The environment variable DELTA_FEATURES can be set to a space-separated list of feature names. If this is preceded with a + character, the features from the environment variable will be added to those specified in git config. E.g. DELTA_FEATURES=+side-by-side can be used to activate side-by-side temporarily (use DELTA_FEATURES=+ to go back to just the features from git config).
--file-added-label <STRING>
Text to display before an added file path.
diff --git a/manual/src/full---help-output.md b/manual/src/full---help-output.md
--- a/manual/src/full---help-output.md
+++ b/manual/src/full---help-output.md
@@ -228,7 +235,7 @@ OPTIONS:
Following the hyperlink spec for terminal emulators: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda. By default, file names and line numbers link to the local file using a file URL, whereas commit hashes link to the commit in GitHub, if the remote repository is hosted by GitHub. See --hyperlinks-file-link-format for full control over the file URLs emitted. Hyperlinks are supported by several common terminal emulators. To make them work, you must use less version >= 581 with the -R flag (or use -r with older less versions, but this will break e.g. --navigate). If you use tmux, then you will also need a patched fork of tmux (see https://github.com/dandavison/tmux).
--hyperlinks-commit-link-format <FMT>
- Format string for commit hyperlinks (requiraes --hyperlinks).
+ Format string for commit hyperlinks (requires --hyperlinks).
The placeholder "{commit}" will be replaced by the commit hash. For example: --hyperlinks-commit-link-format='https://mygitrepo/{commit}/'
diff --git a/manual/src/full---help-output.md b/manual/src/full---help-output.md
--- a/manual/src/full---help-output.md
+++ b/manual/src/full---help-output.md
@@ -570,7 +577,7 @@ OPTIONS:
--wrap-max-lines <N>
How often a line should be wrapped if it does not fit.
- Zero means to never wrap. Any content which does not fit will be truncated. A value of "unlimited" means a line will be wrapped as many times as required.
+ Zero means to never wrap. Any content which does not fit after wrapping will be truncated. A value of "unlimited" means a line will be wrapped as many times as required.
[default: 2]
diff --git a/src/align.rs b/src/align.rs
--- a/src/align.rs
+++ b/src/align.rs
@@ -5,7 +5,7 @@ const SUBSTITUTION_COST: usize = 1;
const DELETION_COST: usize = 1;
const INSERTION_COST: usize = 1;
-#[derive(Clone, Copy, Debug, PartialEq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Operation {
NoOp,
Substitution,
diff --git a/src/ansi/iterator.rs b/src/ansi/iterator.rs
--- a/src/ansi/iterator.rs
+++ b/src/ansi/iterator.rs
@@ -129,7 +129,7 @@ impl vte::Perform for Performer {
return;
}
- if let ('m', None) = (c, intermediates.get(0)) {
+ if let ('m', None) = (c, intermediates.first()) {
if params.is_empty() {
// Attr::Reset
// Probably doesn't need to be handled: https://github.com/dandavison/delta/pull/431#discussion_r536883568
diff --git a/src/cli.rs b/src/cli.rs
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1092,7 +1102,7 @@ pub struct ComputedValues {
pub true_color: bool,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Width {
Fixed(usize),
Variable,
diff --git a/src/cli.rs b/src/cli.rs
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -1104,7 +1114,7 @@ impl Default for Width {
}
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InspectRawLines {
True,
False,
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -40,6 +40,7 @@ pub struct Config {
pub blame_palette: Vec<String>,
pub blame_separator_style: Option<Style>,
pub blame_timestamp_format: String,
+ pub blame_timestamp_output_format: Option<String>,
pub color_only: bool,
pub commit_regex: Regex,
pub commit_style: Style,
diff --git a/src/config.rs b/src/config.rs
--- a/src/config.rs
+++ b/src/config.rs
@@ -240,6 +241,7 @@ impl From<cli::Opt> for Config {
blame_separator_format: parse_blame_line_numbers(&opt.blame_separator_format),
blame_separator_style: styles.remove("blame-separator-style"),
blame_timestamp_format: opt.blame_timestamp_format,
+ blame_timestamp_output_format: opt.blame_timestamp_output_format,
commit_style: styles["commit-style"],
color_only: opt.color_only,
commit_regex,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -15,7 +15,7 @@ use crate::paint::Painter;
use crate::style::DecorationStyle;
use crate::utils;
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum State {
CommitMeta, // In commit metadata section
DiffHeader(DiffType), // In diff metadata section, between (possible) commit metadata and first hunk
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -36,21 +36,21 @@ pub enum State {
HunkPlusWrapped, // Wrapped added line
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DiffType {
Unified,
// https://git-scm.com/docs/git-diff#_combined_diff_format
Combined(MergeParents, InMergeConflict),
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MergeParents {
Number(usize), // Number of parent commits == (number of @s in hunk header) - 1
Prefix(String), // Hunk line prefix, length == number of parent commits
Unknown,
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InMergeConflict {
Yes,
No,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -69,7 +69,7 @@ impl DiffType {
}
}
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Eq)]
pub enum Source {
GitDiff, // Coming from a `git diff` command
DiffUnified, // Coming from a `diff -u` command
diff --git a/src/features/side_by_side.rs b/src/features/side_by_side.rs
--- a/src/features/side_by_side.rs
+++ b/src/features/side_by_side.rs
@@ -526,6 +526,7 @@ fn pad_panel_line_to_width<'a>(
}
Some(BgFillMethod::Spaces) if text_width >= panel_width => (),
Some(BgFillMethod::Spaces) => panel_line.push_str(
+ #[allow(clippy::unnecessary_to_owned)]
&fill_style
.paint(" ".repeat(panel_width - text_width))
.to_string(),
diff --git a/src/format.rs b/src/format.rs
--- a/src/format.rs
+++ b/src/format.rs
@@ -6,7 +6,7 @@ use unicode_segmentation::UnicodeSegmentation;
use crate::features::side_by_side::ansifill::ODD_PAD_CHAR;
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Eq)]
pub enum Placeholder<'a> {
NumberMinus,
NumberPlus,
diff --git a/src/format.rs b/src/format.rs
--- a/src/format.rs
+++ b/src/format.rs
@@ -25,7 +25,7 @@ impl<'a> TryFrom<Option<&'a str>> for Placeholder<'a> {
}
}
-#[derive(Debug, Copy, Clone, PartialEq)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Align {
Left,
Center,
diff --git a/src/format.rs b/src/format.rs
--- a/src/format.rs
+++ b/src/format.rs
@@ -48,7 +48,7 @@ impl TryFrom<Option<&str>> for Align {
}
}
-#[derive(Debug, PartialEq, Clone)]
+#[derive(Debug, PartialEq, Eq, Clone)]
pub struct FormatStringPlaceholderDataAnyPlaceholder<T> {
pub prefix: SmolStr,
pub prefix_len: usize,
diff --git a/src/git_config/git_config_entry.rs b/src/git_config/git_config_entry.rs
--- a/src/git_config/git_config_entry.rs
+++ b/src/git_config/git_config_entry.rs
@@ -12,7 +12,7 @@ pub enum GitConfigEntry {
GitRemote(GitRemoteRepo),
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GitRemoteRepo {
GitHubRepo { repo_slug: String },
GitLabRepo { repo_slug: String },
diff --git a/src/handlers/blame.rs b/src/handlers/blame.rs
--- a/src/handlers/blame.rs
+++ b/src/handlers/blame.rs
@@ -269,9 +269,12 @@ pub fn format_blame_metadata(
let width = placeholder.width.unwrap_or(15);
let field = match placeholder.placeholder {
- Some(Placeholder::Str("timestamp")) => Some(Cow::from(
- chrono_humanize::HumanTime::from(blame.time).to_string(),
- )),
+ Some(Placeholder::Str("timestamp")) => {
+ Some(Cow::from(match &config.blame_timestamp_output_format {
+ Some(time_format) => blame.time.format(time_format).to_string(),
+ None => chrono_humanize::HumanTime::from(blame.time).to_string(),
+ }))
+ }
Some(Placeholder::Str("author")) => Some(Cow::from(blame.author)),
Some(Placeholder::Str("commit")) => Some(delta::format_raw_line(blame.commit, config)),
None => None,
diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -12,7 +12,7 @@ use crate::{features, utils};
// https://git-scm.com/docs/git-config#Documentation/git-config.txt-diffmnemonicPrefix
const DIFF_PREFIXES: [&str; 6] = ["a/", "b/", "c/", "i/", "o/", "w/"];
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Eq)]
pub enum FileEvent {
Added,
Change,
diff --git a/src/handlers/draw.rs b/src/handlers/draw.rs
--- a/src/handlers/draw.rs
+++ b/src/handlers/draw.rs
@@ -223,12 +223,11 @@ fn _write_under_or_over_lined(
Width::Fixed(n) => max(n, text_width),
Width::Variable => text_width,
};
- let mut write_line: Box<dyn FnMut(&mut dyn Write) -> std::io::Result<()>> =
- Box::new(|writer| {
- write_horizontal_line(writer, line_width, text_style, decoration_style)?;
- writeln!(writer)?;
- Ok(())
- });
+ let write_line = |writer: &mut dyn Write| -> std::io::Result<()> {
+ write_horizontal_line(writer, line_width, text_style, decoration_style)?;
+ writeln!(writer)?;
+ Ok(())
+ };
match underoverline {
UnderOverline::Under => {}
_ => write_line(writer)?,
diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -12,7 +12,7 @@ use crate::paint::{self, expand_tabs, BgShouldFill, StyleSectionSpecifier};
use crate::style::Style;
use crate::utils::process;
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Eq)]
pub struct GrepLine<'b> {
pub path: Cow<'b, str>,
pub line_number: Option<usize>,
diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -21,7 +21,7 @@ pub struct GrepLine<'b> {
pub submatches: Option<Vec<(usize, usize)>>,
}
-#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineType {
ContextHeader,
diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -30,7 +30,7 @@ use crate::delta::{self, DiffType, InMergeConflict, MergeParents, State, StateMa
use crate::paint::{self, BgShouldFill, Painter, StyleSectionSpecifier};
use crate::style::DecorationStyle;
-#[derive(Clone, Default, Debug, PartialEq)]
+#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct ParsedHunkHeader {
code_fragment: String,
line_numbers_and_hunk_lengths: Vec<(usize, usize)>,
diff --git a/src/handlers/merge_conflict.rs b/src/handlers/merge_conflict.rs
--- a/src/handlers/merge_conflict.rs
+++ b/src/handlers/merge_conflict.rs
@@ -11,7 +11,7 @@ use crate::minusplus::MinusPlus;
use crate::paint::{self, prepare};
use crate::style::Style;
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MergeConflictCommit {
Ours,
Ancestral,
diff --git a/src/options/set.rs b/src/options/set.rs
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -132,6 +132,7 @@ pub fn set_options(
blame_palette,
blame_separator_style,
blame_timestamp_format,
+ blame_timestamp_output_format,
color_only,
commit_decoration_style,
commit_regex,
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -41,7 +41,7 @@ pub struct Painter<'p> {
}
// How the background of a line is filled up to the end
-#[derive(Debug, PartialEq, Clone, Copy)]
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BgFillMethod {
// Fill the background with ANSI spaces if possible,
// but might fallback to Spaces (e.g. in the left side-by-side panel),
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -51,7 +51,7 @@ pub enum BgFillMethod {
}
// If the background of a line extends to the end, and if configured to do so, how.
-#[derive(Debug, PartialEq, Clone, Copy)]
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BgShouldFill {
With(BgFillMethod),
No,
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -230,6 +230,7 @@ impl<'p> Painter<'p> {
} else if let Some(BgFillMethod::Spaces) = bg_fill_mode {
let text_width = ansi::measure_text_width(&line);
line.push_str(
+ #[allow(clippy::unnecessary_to_owned)]
&fill_style
.paint(" ".repeat(config.available_terminal_width - text_width))
.to_string(),
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -363,6 +364,7 @@ impl<'p> Painter<'p> {
/// current buffer position.
pub fn mark_empty_line(empty_line_style: &Style, line: &mut String, marker: Option<&str>) {
line.push_str(
+ #[allow(clippy::unnecessary_to_owned)]
&empty_line_style
.paint(marker.unwrap_or(ansi::ANSI_CSI_CLEAR_TO_BOL))
.to_string(),
diff --git a/src/utils/bat/output.rs b/src/utils/bat/output.rs
--- a/src/utils/bat/output.rs
+++ b/src/utils/bat/output.rs
@@ -13,7 +13,7 @@ use crate::env::DeltaEnv;
use crate::fatal;
use crate::features::navigate;
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub enum PagingMode {
Always,
diff --git a/src/utils/process.rs b/src/utils/process.rs
--- a/src/utils/process.rs
+++ b/src/utils/process.rs
@@ -7,7 +7,7 @@ use sysinfo::{Pid, PidExt, Process, ProcessExt, ProcessRefreshKind, SystemExt};
pub type DeltaPid = u32;
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CallingProcess {
GitDiff(CommandLine),
GitShow(CommandLine, Option<String>), // element 2 is file extension
diff --git a/src/utils/process.rs b/src/utils/process.rs
--- a/src/utils/process.rs
+++ b/src/utils/process.rs
@@ -32,7 +32,7 @@ impl CallingProcess {
}
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandLine {
pub long_options: HashSet<String>,
pub short_options: HashSet<String>,
diff --git a/src/utils/process.rs b/src/utils/process.rs
--- a/src/utils/process.rs
+++ b/src/utils/process.rs
@@ -100,7 +100,7 @@ fn determine_calling_process() -> CallingProcess {
// Return value of `extract_args(args: &[String]) -> ProcessArgs<T>` function which is
// passed to `calling_process_cmdline()`.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Eq)]
pub enum ProcessArgs<T> {
// A result has been successfully extracted from args.
Args(T),
| dandavison__delta-1158 | 1,158 | Hi @mliszcz, thanks! I agree with the feature proposal and I think that your proposed API is spot-on. Please do go ahead and make a PR if you have time, and let me know if anything's unclear about the development workflow. | [
"1157"
] | 0.13 | dandavison/delta | 2022-08-11T23:11:31Z | diff --git a/manual/src/full---help-output.md b/manual/src/full---help-output.md
--- a/manual/src/full---help-output.md
+++ b/manual/src/full---help-output.md
@@ -49,6 +49,13 @@ OPTIONS:
[default: "%Y-%m-%d %H:%M:%S %z"]
+ --blame-timestamp-output-format <FMT>
+ Format string for git blame timestamp output.
+
+ This string is used for formatting the timestamps in git blame output. It must follow the `strftime` format syntax specification. If it is not present, the timestamps will be formatted in a human-friendly but possibly less accurate form.
+
+ See: (https://docs.rs/chrono/latest/chrono/format/strftime/index.html)
+
--color-only
Do not alter the input structurally in any way.
diff --git a/src/cli.rs b/src/cli.rs
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -260,6 +260,16 @@ pub struct Opt {
/// Format of `git blame` timestamp in raw git output received by delta.
pub blame_timestamp_format: String,
+ #[clap(long = "blame-timestamp-output-format", value_name = "FMT")]
+ /// Format string for git blame timestamp output.
+ ///
+ /// This string is used for formatting the timestamps in git blame output. It must follow
+ /// the `strftime` format syntax specification. If it is not present, the timestamps will
+ /// be formatted in a human-friendly but possibly less accurate form.
+ ///
+ /// See: (https://docs.rs/chrono/latest/chrono/format/strftime/index.html)
+ pub blame_timestamp_output_format: Option<String>,
+
#[clap(long = "color-only")]
/// Do not alter the input structurally in any way.
///
diff --git a/src/handlers/blame.rs b/src/handlers/blame.rs
--- a/src/handlers/blame.rs
+++ b/src/handlers/blame.rs
@@ -408,6 +411,33 @@ mod tests {
assert_eq!(caps.get(2).unwrap().as_str(), "Kangwook Lee (์ด๊ฐ์ฑ)");
}
+ #[test]
+ fn test_format_blame_metadata_with_default_timestamp_output_format() {
+ let format_data = format::FormatStringPlaceholderData {
+ placeholder: Some(Placeholder::Str("timestamp")),
+ ..Default::default()
+ };
+ let blame = make_blame_line_with_time("1996-12-19T16:39:57-08:00");
+ let config = integration_test_utils::make_config_from_args(&[]);
+ let regex = Regex::new(r"^\d+ years ago$").unwrap();
+ let result = format_blame_metadata(&[format_data], &blame, &config);
+ assert!(regex.is_match(result.trim()));
+ }
+
+ #[test]
+ fn test_format_blame_metadata_with_custom_timestamp_output_format() {
+ let format_data = format::FormatStringPlaceholderData {
+ placeholder: Some(Placeholder::Str("timestamp")),
+ ..Default::default()
+ };
+ let blame = make_blame_line_with_time("1996-12-19T16:39:57-08:00");
+ let config = integration_test_utils::make_config_from_args(&[
+ "--blame-timestamp-output-format=%Y-%m-%d %H:%M",
+ ]);
+ let result = format_blame_metadata(&[format_data], &blame, &config);
+ assert_eq!(result.trim(), "1996-12-19 16:39");
+ }
+
#[test]
fn test_color_assignment() {
let mut writer = Cursor::new(vec![0; 512]);
diff --git a/src/handlers/blame.rs b/src/handlers/blame.rs
--- a/src/handlers/blame.rs
+++ b/src/handlers/blame.rs
@@ -497,4 +527,15 @@ mod tests {
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect()
}
+
+ fn make_blame_line_with_time(timestamp: &str) -> BlameLine {
+ let time = chrono::DateTime::parse_from_rfc3339(×tamp).unwrap();
+ return BlameLine {
+ commit: "",
+ author: "",
+ time: time,
+ line_number: 0,
+ code: "",
+ };
+ }
}
| ๐ Configurable timestamp output format in git blame
In git blame I noticed this:

It would be helpful to know e.g. which change was applied first but this can not be figured out from the humanized timestamp.
https://github.com/dandavison/delta/blob/738c5a141bf86d3e05aa348eb87df78c36a72337/src/handlers/blame.rs#L273
I changed it locally to: `blame.time.format("%H:%M %Y-%m-%d").to_string(),`.
Would it be possible to make this configurable? Perhaps a new option *--blame-**output**-timestamp-format* could be added. If present (and not empty) it would be used as a format string. If not, we will fall back to HumanTime formatting. What do you think?
I can work on a PR if this could be accepted.
| 738c5a141bf86d3e05aa348eb87df78c36a72337 | [
"config::tests::test_get_computed_values_from_config",
"features::diff_so_fancy::tests::test_diff_so_fancy_respects_git_config",
"features::hyperlinks::tests::test_paths_and_hyperlinks_user_in_repo_root_dir",
"features::diff_highlight::test_utils::test_diff_highlight_respects_gitconfig",
"features::diff_so_... | [
"align::tests::test_0_nonascii",
"align::tests::test_0",
"align::tests::test_2",
"align::tests::test_1",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"a... | [] | [] |
3f527e0d9c6100119c86a5cd4adb21f3c51651c6 | diff --git a/src/handlers/commit_meta.rs b/src/handlers/commit_meta.rs
--- a/src/handlers/commit_meta.rs
+++ b/src/handlers/commit_meta.rs
@@ -16,6 +16,7 @@ impl<'a> StateMachine<'a> {
}
let mut handled_line = false;
self.painter.paint_buffered_minus_and_plus_lines();
+ self.handle_pending_line_with_diff_name()?;
self.state = State::CommitMeta;
if self.should_handle() {
self.painter.emit()?;
| dandavison__delta-1111 | 1,111 | Thanks very much @dotdash, this looks like a rather bad bug. (Sorry to be slow replying, I was on holiday, and a bit consumed by the day job).
I believe I'm observing likely the same issue but after mode modification. It appears to affect last file only.
Note that without `-p` all files are correctly placed:
```
commit 4aba2e850e2790d0ff2adf450c134a68605bcc09 (HEAD -> master)
Author: Jan Palus <jpalus@fastmail.com>
Date: Tue Jun 21 14:44:00 2022
no exec
file1.txt | 0
file2.txt | 0
file3.txt | 0
3 files changed, 0 insertions(+), 0 deletions(-)
commit 145500a7bde15e51c19bfb09f4942a3d1337e5a2
Author: Jan Palus <jpalus@fastmail.com>
Date: Tue Jun 21 14:43:44 2022
new
file1.txt | 1 +
file2.txt | 1 +
file3.txt | 1 +
3 files changed, 3 insertions(+)
```
While with `-p` last file in latest commit is misplaced:
```
commit 4aba2e850e2790d0ff2adf450c134a68605bcc09 (HEAD -> master)
Author: Jan Palus <jpalus@fastmail.com>
Date: Tue Jun 21 14:44:00 2022
no exec
---
file1.txt | 0
file2.txt | 0
file3.txt | 0
3 files changed, 0 insertions(+), 0 deletions(-)
file1.txt (mode -x)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
file2.txt (mode -x)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
commit 145500a7bde15e51c19bfb09f4942a3d1337e5a2
Author: Jan Palus <jpalus@fastmail.com>
Date: Tue Jun 21 14:43:44 2022
new
---
file1.txt | 1 +
file2.txt | 1 +
file3.txt | 1 +
3 files changed, 3 insertions(+)
file3.txt (mode -x)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
added: file1.txt
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโ
1: โ
โโโโ
test
``` | [
"1089"
] | 0.13 | dandavison/delta | 2022-06-21T18:07:24Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1626,6 +1626,13 @@ src/align.rs:71: impl<'a> Alignment<'a> { โ
.expect_contains("a b โถ c d\n");
}
+ #[test]
+ fn test_file_removal_in_log_output() {
+ DeltaTest::with_args(&[])
+ .with_input(GIT_LOG_FILE_REMOVAL_IN_FIRST_COMMIT)
+ .expect_after_header("#partial\n\nremoved: a");
+ }
+
const GIT_DIFF_SINGLE_HUNK: &str = "\
commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e
Author: Dan Davison <dandavison7@gmail.com>
diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -2385,5 +2392,27 @@ index d00491f..0cfbf08 100644
@@ -1 +1 @@
-1
+2
+";
+
+ const GIT_LOG_FILE_REMOVAL_IN_FIRST_COMMIT: &str = "
+commit 4117f616160180c0c57ea64840eadd08b7fa32a4
+Author: Bjรถrn Steinbrink <bsteinbr@gmail.com>
+Date: Tue Jun 21 14:51:59 2022 +0200
+
+ remove file
+
+diff --git a a
+deleted file mode 100644
+index e69de29..0000000
+
+commit 190cce5dffeb9050fd6a27780f16d84b19c07dc0
+Author: Bjรถrn Steinbrink <bsteinbr@gmail.com>
+Date: Tue Jun 21 14:48:20 2022 +0200
+
+ add file
+
+diff --git a a
+new file mode 100644
+index 0000000..e69de29
";
}
diff --git a/src/utils/process.rs b/src/utils/process.rs
--- a/src/utils/process.rs
+++ b/src/utils/process.rs
@@ -1195,7 +1195,7 @@ pub mod tests {
}
// Tests that caller is something like "cargo test" or "cargo tarpaulin"
- let find_test = |args: &[String]| find_calling_process(args, &["test", "tarpaulin"]);
+ let find_test = |args: &[String]| find_calling_process(args, &["t", "test", "tarpaulin"]);
assert_eq!(calling_process_cmdline(info, find_test), Some(()));
let nonsense = ppid_distance
| ๐ File removal attributed to wrong commit in `git log`
When viewing more than one commit, file removals are shown on the wrong commit.
Raw log from `git log -p | "cat"`:
```
commit 166ed1d1c00715eb111a7d5938f2efc43f2f7c08
Author: Bjรถrn Steinbrink <b.steinbrink@demv.de>
Date: Mon May 30 12:19:21 2022 +0200
Remove bar
diff --git bar bar
deleted file mode 100644
index e69de29..0000000
commit 9c05c365c81da9248e08a33599e038cb3a2d43ee
Author: Bjรถrn Steinbrink <b.steinbrink@demv.de>
Date: Mon May 30 12:19:14 2022 +0200
Add files
diff --git bar bar
new file mode 100644
index 0000000..e69de29
diff --git foo foo
new file mode 100644
index 0000000..e69de29
```
Output with `delta`:
```
commit 166ed1d1c00715eb111a7d5938f2efc43f2f7c08 (HEAD -> master)
Author: Bjรถrn Steinbrink <b.steinbrink@demv.de>
Date: Mon May 30 12:19:21 2022 +0200
Remove bar
commit 9c05c365c81da9248e08a33599e038cb3a2d43ee
Author: Bjรถrn Steinbrink <b.steinbrink@demv.de>
Date: Mon May 30 12:19:14 2022 +0200
Add files
removed: bar
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
added: bar
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
added: foo
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
| 738c5a141bf86d3e05aa348eb87df78c36a72337 | [
"tests::test_example_diffs::tests::test_file_removal_in_log_output"
] | [
"align::tests::test_0_nonascii",
"align::tests::test_0",
"align::tests::test_1",
"align::tests::test_2",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"a... | [] | [] |
f556db8d4edac47c6b053191f02568969a14f06a | diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -222,17 +222,19 @@ fn get_code_style_sections<'b>(
non_match_style: Style,
grep: &GrepLine,
) -> Option<StyleSectionSpecifier<'b>> {
- if let Some(raw_code_start) = ansi::ansi_preserving_index(
+ if let Some(prefix_end) = ansi::ansi_preserving_index(
raw_line,
match grep.line_number {
- Some(n) => format!("{}:{}:", grep.path, n).len(),
- None => grep.path.len() + 1,
+ Some(n) => format!("{}:{}:", grep.path, n).len() - 1,
+ None => grep.path.len(),
},
) {
- let match_style_sections = ansi::parse_style_sections(&raw_line[raw_code_start..])
+ let match_style_sections = ansi::parse_style_sections(&raw_line[(prefix_end + 1)..])
.iter()
.map(|(ansi_term_style, s)| {
- if ansi_term_style.foreground.is_some() {
+ if ansi_term_style.is_bold
+ && ansi_term_style.foreground == Some(ansi_term::Colour::Red)
+ {
(match_style, *s)
} else {
(non_match_style, *s)
| dandavison__delta-1057 | 1,057 | [
"1056"
] | 0.13 | dandavison/delta | 2022-04-25T23:55:59Z | diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -900,4 +902,60 @@ mod tests {
let apparently_grep_output = "src/co-7-fig.rs:xxx";
assert_eq!(parse_grep_line(apparently_grep_output), None);
}
+
+ #[test]
+ fn test_get_code_style_sections() {
+ use crate::ansi::strip_ansi_codes;
+ use crate::handlers::grep::get_code_style_sections;
+ use crate::paint::StyleSectionSpecifier;
+ use crate::style::Style;
+
+ let fake_parent_grep_command = "git --doesnt-matter grep --nor-this nor_this -- nor_this";
+ let _args = FakeParentArgs::for_scope(fake_parent_grep_command);
+
+ let miss = Style::new();
+ let hit = Style {
+ is_emph: true,
+ ..miss
+ };
+
+ let escape = "\x1B";
+ let working_example = format!("foo/bar/baz.yaml{escape}[36m:{escape}[m1090{escape}[36m:{escape}[m - {escape}[1;31mkind: Service{escape}[mAccount");
+ let stripped = strip_ansi_codes(&working_example);
+ let grep = parse_grep_line(&stripped).unwrap();
+
+ assert_eq!(
+ get_code_style_sections(&working_example, hit, miss, &grep),
+ Some(StyleSectionSpecifier::StyleSections(vec![
+ (miss, " - "),
+ (hit, "kind: Service"),
+ (miss, "Account")
+ ]))
+ );
+
+ let broken_example = format!("foo/bar/baz.yaml{escape}[36m:{escape}[m2{escape}[36m:{escape}[m{escape}[1;31mkind: Service{escape}[m");
+ let broken_stripped = strip_ansi_codes(&broken_example);
+ let broken_grep = parse_grep_line(&broken_stripped).unwrap();
+
+ assert_eq!(
+ get_code_style_sections(&broken_example, hit, miss, &broken_grep),
+ Some(StyleSectionSpecifier::StyleSections(vec![(
+ hit,
+ "kind: Service"
+ )]))
+ );
+
+ let plus_example = format!("etc/examples/189-merge-conflict.2.diff{escape}[36m:{escape}[m10{escape}[36m:{escape}[m{escape}[32m + let (style, non_emph_style) = {escape}[1;31mmatch{escape}[m state {{{escape}[m");
+ let plus_stripped = strip_ansi_codes(&plus_example);
+ let plus_grep = parse_grep_line(&plus_stripped).unwrap();
+
+ assert_eq!(
+ get_code_style_sections(&plus_example, hit, miss, &plus_grep),
+ Some(StyleSectionSpecifier::StyleSections(vec![
+ (miss, " + let (style, non_emph_style) = "),
+ (hit, "match"),
+ (miss, " state {")
+ ]))
+ );
+ }
}
| ๐ `git grep` handler doesn't highlight matches that start in column 0
Hi! It looks like the `git grep` handler can't highlight the grep-match if the grep-match starts at the beginning of the line of code. I'm not sure if this is always the case or if it's specific to my type of terminal in some way (I'm using Terminal.app on macOS).
To repro,
```
mkdir /tmp/delta-test
cd /tmp/delta-test
echo 'foo' > broken.md
echo '...foo' > working.md
git init
git add .
git commit -m 'Add files to repro bug'
git grep 'foo'
```
On my machine, that leaves us with one line where foo is highlighted (`working.md`) and another line where it is not (`broken.md`):
<img width="225" alt="Screen Shot 2022-04-25 at 7 49 27 PM" src="https://user-images.githubusercontent.com/3980541/165192571-37b42097-d718-4325-8e8f-a942a610b0d1.png">
Not a big deal for a trivial case like this (where the entire line matches the query exactly), but with a more complicated regex it can be annoying.
I have a fix for this. It's a little bit weird, but I _think_ it should be okay.
- [x] Please include the raw text output from git, so that we can reproduce the problem.
The problem is in handling of ANSI color codes, which I suspect cannot be pasted here? But here's a `cat -v` representation of what `GIT_PAGER=less git color.grep=always grep 'foo'` does here:
```
broken.md^[[36m:^[[m1^[[36m:^[[m^[[1;31mfoo^[[m
working.md^[[36m:^[[m1^[[36m:^[[m...^[[1;31mfoo^[[m
```
(Pretty hard to visually parse this, but: it highlights "foo" correctly on both lines.)
- [x] A screenshot of Delta's output is often helpful also.
Thanks for filing a Delta bug report!
| 738c5a141bf86d3e05aa348eb87df78c36a72337 | [
"handlers::grep::tests::test_get_code_style_sections"
] | [
"align::tests::test_0",
"align::tests::test_0_nonascii",
"align::tests::test_1",
"align::tests::test_2",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::iterator::tests::test_iterator_1",
"ansi::iterator::... | [] | [] | |
32138d031ec2bc42bc856f7a9b3367729256781c | diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -29,7 +29,7 @@ use crate::config::Config;
use crate::delta::{self, State, StateMachine};
use crate::features;
use crate::paint::Painter;
-use crate::style::{DecorationStyle, Style};
+use crate::style::DecorationStyle;
impl<'a> StateMachine<'a> {
#[inline]
diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -170,12 +170,7 @@ fn write_hunk_header(
let file_with_line_number = get_painted_file_with_line_number(line_numbers, plus_file, config);
if !line.is_empty() || !file_with_line_number.is_empty() {
- write_to_output_buffer(
- &file_with_line_number,
- line,
- config.hunk_header_style,
- painter,
- );
+ write_to_output_buffer(&file_with_line_number, line, painter, config);
draw_fn(
painter.writer,
&painter.output_buffer,
diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -196,11 +191,6 @@ fn get_painted_file_with_line_number(
config: &Config,
) -> String {
let mut file_with_line_number = Vec::new();
- let hunk_label;
- if config.navigate {
- hunk_label = format!("{} ", config.hunk_label);
- file_with_line_number.push(config.hunk_header_file_style.paint(&hunk_label));
- }
let plus_line_number = line_numbers[line_numbers.len() - 1].0;
if config.hunk_header_style_include_file_path {
file_with_line_number.push(config.hunk_header_file_style.paint(plus_file))
diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -235,16 +225,23 @@ fn get_painted_file_with_line_number(
fn write_to_output_buffer(
file_with_line_number: &str,
line: String,
- style: Style,
painter: &mut Painter,
+ config: &Config,
) {
+ if config.navigate {
+ let _ = write!(
+ &mut painter.output_buffer,
+ "{} ",
+ config.hunk_header_file_style.paint(&config.hunk_label)
+ );
+ }
if !file_with_line_number.is_empty() {
let _ = write!(&mut painter.output_buffer, "{}: ", file_with_line_number);
}
if !line.is_empty() {
painter.syntax_highlight_and_paint_line(
&line,
- style,
+ config.hunk_header_style,
delta::State::HunkHeader("".to_owned(), "".to_owned()),
false,
);
| dandavison__delta-710 | 710 | Hi @ynavott, thanks for this. Can you post the delta config that produces this behavior please?
I am currently on vacation in the highlands of Iceland at the moment and don't have very good reception most of the time, will try to send you the exact config as soon as possible.
> Hi @ynavott, thanks for this. Can you post the delta config that produces this behavior please?
This is the delta section in my `.gitconfig`
```
[delta]
line-numbers = true
navigate = true
```
Thanks @ynavott, are you sure that's your entire config? I'm only able to reproduce this by setting `hunk-header-style` to a value that does not include `line-number`. e.g.
```gitconfig
[delta]
hunk-header-style = syntax
navigate = true
```
For example, using the woolly-mammoth theme would have this effect, and it looks like you might be using that in your first screenshot?
My apologies, I am indeed using that theme.
Ok, great. Shouldn't be too hard to fix. | [
"672"
] | 0.8 | dandavison/delta | 2021-09-02T14:22:42Z | diff --git a/src/handlers/hunk_header.rs b/src/handlers/hunk_header.rs
--- a/src/handlers/hunk_header.rs
+++ b/src/handlers/hunk_header.rs
@@ -354,4 +351,19 @@ pub mod tests {
assert_eq!(result, "");
}
+
+ #[test]
+ fn test_get_painted_file_with_line_number_empty_navigate() {
+ let cfg = integration_test_utils::make_config_from_args(&[
+ "--hunk-header-style",
+ "syntax bold",
+ "--hunk-header-decoration-style",
+ "omit",
+ "--navigate",
+ ]);
+
+ let result = get_painted_file_with_line_number(&vec![(3, 4)], "ฮด some-file", &cfg);
+
+ assert_eq!(result, "");
+ }
}
| ๐ Hunk header prints ":" with no file or line number, even when hyperlinks are off
This issue relates to the bug already discussed in #650. Since then. It was probably broken again by some newer commits. To demonstrate:

As you can see, both `file-modified-label` (it is set to ` [M] ` in this theme) and a `:` are printed before the hunk header, even though hyperlinks are off. The issue persists when hyperlinks are turned on, even though this bug was supposed to be fixed by #650.
| 80691898cd4cae02f40ed5ad6986e517a938d14f | [
"handlers::hunk_header::tests::test_get_painted_file_with_line_number_empty_navigate"
] | [
"align::tests::test_0_nonascii",
"align::tests::test_0",
"align::tests::test_1",
"align::tests::test_2",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"ansi::console_tests::tests::test_truncate_str",
"a... | [] | [] |
fd3770875be43b28aed72adc7b3fec44d5a7a80d | diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -83,6 +83,7 @@ impl<'a> StateMachine<'a> {
));
}
+ self.painter.paint_buffered_minus_and_plus_lines();
// In color_only mode, raw_line's structure shouldn't be changed.
// So it needs to avoid fn _handle_diff_header_header_line
// (it connects the plus_file and minus_file),
diff --git a/src/handlers/diff_header.rs b/src/handlers/diff_header.rs
--- a/src/handlers/diff_header.rs
+++ b/src/handlers/diff_header.rs
@@ -127,6 +128,7 @@ impl<'a> StateMachine<'a> {
));
self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
+ self.painter.paint_buffered_minus_and_plus_lines();
// In color_only mode, raw_line's structure shouldn't be changed.
// So it needs to avoid fn _handle_diff_header_header_line
// (it connects the plus_file and minus_file),
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -126,6 +126,9 @@ impl<'p> Painter<'p> {
}
pub fn paint_buffered_minus_and_plus_lines(&mut self) {
+ if self.minus_lines.is_empty() && self.plus_lines.is_empty() {
+ return;
+ }
paint_minus_and_plus_lines(
MinusPlus::new(&self.minus_lines, &self.plus_lines),
&mut self.line_numbers_data,
| dandavison__delta-1003 | 1,003 | [
"1002"
] | 0.12 | dandavison/delta | 2022-03-07T13:24:46Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -135,6 +135,15 @@ mod tests {
);
}
+ #[test]
+ fn test_diff_unified_concatenated() {
+ // See #1002. Line buffers were not being flushed correctly, leading to material from first
+ // file last hunk appearing at beginning of second file first hunk.
+ DeltaTest::with_args(&[])
+ .with_input(DIFF_UNIFIED_CONCATENATED)
+ .expect_contains("\nLINES.\n\n1/y 2022-03-06");
+ }
+
#[test]
#[ignore] // Ideally, delta would make this test pass. See #121.
fn test_delta_ignores_non_diff_input() {
diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1875,6 +1884,27 @@ Only in b/: just_b
+This is different from a
";
+ const DIFF_UNIFIED_CONCATENATED: &str = "\
+--- 1/x 2022-03-06 11:16:06.313403500 -0800
++++ 2/x 2022-03-06 11:18:14.083403500 -0800
+@@ -1,5 +1,5 @@
+ This
+-is
++IS
+ a
+ few
+-lines.
++LINES.
+--- 1/y 2022-03-06 11:16:44.483403500 -0800
++++ 2/y 2022-03-06 11:16:55.213403500 -0800
+@@ -1,4 +1,4 @@
+ This
+ is
+-another
++ANOTHER
+ test.
+";
+
const NOT_A_DIFF_OUTPUT: &str = "\
Hello world
This is a regular file that contains:
| ๐ Misplaced diff output
I had occasion to concatenate the `diff -u` output for several files into a single file and noticed that using delta to page the input stream misplaced a trailing chunk from one file into the start of the next file. A simple example input that reproduces the issue:
```text
--- 1/x 2022-03-06 11:16:06.313403500 -0800
+++ 2/x 2022-03-06 11:18:14.083403500 -0800
@@ -1,5 +1,5 @@
This
-is
+IS
a
few
-lines.
+LINES.
--- 1/y 2022-03-06 11:16:44.483403500 -0800
+++ 2/y 2022-03-06 11:16:55.213403500 -0800
@@ -1,4 +1,4 @@
This
is
-another
+ANOTHER
test.
```
Running that text through delta on stdin displays the `-lines.` `+LINES.` chunk after the header for the "y" file. If a "diff" line was prior to the "---" line in the input then delta would have flushed the dangling diff lines.
| fd3770875be43b28aed72adc7b3fec44d5a7a80d | [
"tests::test_example_diffs::tests::test_diff_unified_concatenated"
] | [
"align::tests::test_0",
"ansi::console_tests::tests::test_truncate_str",
"ansi::console_tests::tests::test_text_width",
"align::tests::test_1",
"align::tests::test_2",
"align::tests::test_0_nonascii",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"ansi::iterator::tests::test_iterator_2",
... | [] | [] | |
32e15ce6fb3cbc9648f189f197206ab29aa329c4 | diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -345,7 +345,7 @@ fn make_grep_line_regex(regex_variant: GrepLineRegex) -> Regex {
( # 1. file name (colons not allowed)
[^:|\ ] # try to be strict about what a file path can start with
[^:]* # anything
- [^\ ]\.[^.\ :=-]{1,6} # extension
+ [^\ ]\.[^.\ :=-]{1,10} # extension
)
"
}
| dandavison__delta-975 | 975 | [
"974"
] | 0.12 | dandavison/delta | 2022-02-19T16:26:25Z | diff --git a/src/handlers/grep.rs b/src/handlers/grep.rs
--- a/src/handlers/grep.rs
+++ b/src/handlers/grep.rs
@@ -655,6 +655,24 @@ mod tests {
);
}
+ #[test]
+ fn test_parse_grep_n_match_directory_name_with_dashes() {
+ let fake_parent_grep_command =
+ "/usr/local/bin/git --doesnt-matter grep --nor-this nor_this -- nor_this";
+ let _args = FakeParentArgs::once(fake_parent_grep_command);
+
+ assert_eq!(
+ parse_grep_line("etc/META-INF/foo.properties:4:value=hi-there"),
+ Some(GrepLine {
+ path: "etc/META-INF/foo.properties".into(),
+ line_number: Some(4),
+ line_type: LineType::Match,
+ code: "value=hi-there".into(),
+ submatches: None,
+ })
+ );
+ }
+
#[test]
fn test_parse_grep_no_match() {
let fake_parent_grep_command =
| ๐ `git grep` output parsed, printed incorrectly for .properties files with hyphen in path
When I `git grep` for something that's found in a `.properties` file whose directory name contains a hyphen, I get bad results. The highlighting is wrong on the matching line, and the filename itself is incorrect - the hyphen within the path gets replaced with a colon.
To repro:
```
mkdir /tmp/delta-test
cd /tmp/delta-test
mkdir src
mkdir src-ext
echo 'foo' > src{,-ext}/bar.properties
git init
git add .
git commit -m 'Add properties files'
git grep 'oo'
```
Here's what I get:
<img width="335" alt="Screen Shot 2022-02-19 at 11 02 15 AM" src="https://user-images.githubusercontent.com/3980541/154808961-086722df-8cd7-4dde-a5ef-479a87e053f2.png">
Note that the first line has incorrect highlighting (the filename-highlighting cuts off where the `-` should be and the match isn't highlighted at all) and the hyphen in `src-ext` is actually replaced by a `:`.
`git --no-pager grep 'oo'` results:
```
src-ext/bar.properties:1:foo
src/bar.properties:1:foo
```
I looked into this and I have a fix (sort of). I'll post a PR soon.
--
- [X] Please include the raw text output from git, so that we can reproduce the problem.
(You can use `git --no-pager` to produce the raw text output.)
- [X] A screenshot of Delta's output is often helpful also.
Thanks for filing a Delta bug report!
| fd3770875be43b28aed72adc7b3fec44d5a7a80d | [
"handlers::grep::tests::test_parse_grep_n_match_directory_name_with_dashes"
] | [
"align::tests::test_0_nonascii",
"align::tests::test_0",
"align::tests::test_2",
"align::tests::test_1",
"ansi::console_tests::tests::test_text_width",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_truncate_str",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"a... | [] | [] | |
5ece1944f1a7df30d342452d7a85d4871c16a42c | diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -62,7 +62,9 @@ struct StateMachine<'a> {
source: Source,
minus_file: String,
plus_file: String,
- file_event: parse::FileEvent,
+ minus_file_event: parse::FileEvent,
+ plus_file_event: parse::FileEvent,
+ file_paths_from_diff_line: (Option<String>, Option<String>),
painter: Painter<'a>,
config: &'a Config,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -91,7 +93,9 @@ impl<'a> StateMachine<'a> {
source: Source::Unknown,
minus_file: "".to_string(),
plus_file: "".to_string(),
- file_event: parse::FileEvent::NoEvent,
+ minus_file_event: parse::FileEvent::NoEvent,
+ plus_file_event: parse::FileEvent::NoEvent,
+ file_paths_from_diff_line: (None, None),
current_file_pair: None,
handled_file_meta_header_line_file_pair: None,
painter: Painter::new(writer, config),
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -122,13 +126,15 @@ impl<'a> StateMachine<'a> {
} else if (self.state == State::FileMeta || self.source == Source::DiffUnified)
&& (line.starts_with("--- ")
|| line.starts_with("rename from ")
- || line.starts_with("copy from "))
+ || line.starts_with("copy from ")
+ || line.starts_with("old mode "))
{
self.handle_file_meta_minus_line()?
} else if (self.state == State::FileMeta || self.source == Source::DiffUnified)
&& (line.starts_with("+++ ")
|| line.starts_with("rename to ")
- || line.starts_with("copy to "))
+ || line.starts_with("copy to ")
+ || line.starts_with("new mode "))
{
self.handle_file_meta_plus_line()?
} else if line.starts_with("@@") {
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -253,13 +259,14 @@ impl<'a> StateMachine<'a> {
self.painter.paint_buffered_minus_and_plus_lines();
self.state = State::FileMeta;
self.handled_file_meta_header_line_file_pair = None;
+ self.file_paths_from_diff_line = parse::get_file_paths_from_diff_line(&self.line);
Ok(false)
}
fn handle_file_meta_minus_line(&mut self) -> std::io::Result<bool> {
let mut handled_line = false;
- let parsed_file_meta_line = parse::parse_file_meta_line(
+ let (path_or_mode, file_event) = parse::parse_file_meta_line(
&self.line,
self.source == Source::GitDiff,
if self.config.relative_paths {
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -268,8 +275,14 @@ impl<'a> StateMachine<'a> {
None
},
);
- self.minus_file = parsed_file_meta_line.0;
- self.file_event = parsed_file_meta_line.1;
+ // In the case of ModeChange only, the file path is taken from the diff
+ // --git line (since that is the only place the file path occurs);
+ // otherwise it is taken from the --- / +++ line.
+ self.minus_file = match (&file_event, &self.file_paths_from_diff_line) {
+ (parse::FileEvent::ModeChange(_), (Some(file), _)) => file.clone(),
+ _ => path_or_mode,
+ };
+ self.minus_file_event = file_event;
if self.source == Source::DiffUnified {
self.state = State::FileMeta;
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -300,7 +313,7 @@ impl<'a> StateMachine<'a> {
fn handle_file_meta_plus_line(&mut self) -> std::io::Result<bool> {
let mut handled_line = false;
- let parsed_file_meta_line = parse::parse_file_meta_line(
+ let (path_or_mode, file_event) = parse::parse_file_meta_line(
&self.line,
self.source == Source::GitDiff,
if self.config.relative_paths {
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -309,7 +322,14 @@ impl<'a> StateMachine<'a> {
None
},
);
- self.plus_file = parsed_file_meta_line.0;
+ // In the case of ModeChange only, the file path is taken from the diff
+ // --git line (since that is the only place the file path occurs);
+ // otherwise it is taken from the --- / +++ line.
+ self.plus_file = match (&file_event, &self.file_paths_from_diff_line) {
+ (parse::FileEvent::ModeChange(_), (_, Some(file))) => file.clone(),
+ _ => path_or_mode,
+ };
+ self.plus_file_event = file_event;
self.painter
.set_syntax(parse::get_file_extension_from_file_meta_line_file_path(
&self.plus_file,
diff --git a/src/delta.rs b/src/delta.rs
--- a/src/delta.rs
+++ b/src/delta.rs
@@ -344,7 +364,8 @@ impl<'a> StateMachine<'a> {
&self.minus_file,
&self.plus_file,
comparing,
- &self.file_event,
+ &self.minus_file_event,
+ &self.plus_file_event,
self.config,
);
// FIXME: no support for 'raw'
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -25,6 +25,7 @@ pub enum FileEvent {
Change,
Copy,
Rename,
+ ModeChange(String),
NoEvent,
}
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -33,7 +34,7 @@ pub fn parse_file_meta_line(
git_diff_name: bool,
relative_path_base: Option<&str>,
) -> (String, FileEvent) {
- let (mut path, file_event) = match line {
+ let (mut path_or_mode, file_event) = match line {
line if line.starts_with("--- ") || line.starts_with("+++ ") => {
let offset = 4;
let file = _parse_file_path(&line[offset..], git_diff_name);
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -51,18 +52,35 @@ pub fn parse_file_meta_line(
line if line.starts_with("copy to ") => {
(line[8..].to_string(), FileEvent::Copy) // "copy to ".len()
}
+ line if line.starts_with("old mode ") => {
+ ("".to_string(), FileEvent::ModeChange(line[9..].to_string())) // "old mode ".len()
+ }
+ line if line.starts_with("new mode ") => {
+ ("".to_string(), FileEvent::ModeChange(line[9..].to_string())) // "new mode ".len()
+ }
_ => ("".to_string(), FileEvent::NoEvent),
};
if let Some(base) = relative_path_base {
- if let Some(relative_path) = pathdiff::diff_paths(&path, base) {
+ if let FileEvent::ModeChange(_) = file_event {
+ } else if let Some(relative_path) = pathdiff::diff_paths(&path_or_mode, base) {
if let Some(relative_path) = relative_path.to_str() {
- path = relative_path.to_owned();
+ path_or_mode = relative_path.to_owned();
}
}
}
- (path, file_event)
+ (path_or_mode, file_event)
+}
+
+/// Given input like "diff --git a/src/main.rs b/src/main.rs"
+/// return (Some("src/main.rs"), Some("src/main.rs"))
+pub fn get_file_paths_from_diff_line(line: &str) -> (Option<String>, Option<String>) {
+ let mut iter = line.split(' ').skip(2);
+ (
+ iter.next().map(|s| _parse_file_path(&s[2..], true)),
+ iter.next().map(|s| _parse_file_path(&s[2..], true)),
+ )
}
fn _parse_file_path(s: &str, git_diff_name: bool) -> String {
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -117,7 +135,8 @@ pub fn get_file_change_description_from_file_paths(
minus_file: &str,
plus_file: &str,
comparing: bool,
- file_event: &FileEvent,
+ minus_file_event: &FileEvent,
+ plus_file_event: &FileEvent,
config: &Config,
) -> String {
if comparing {
diff --git a/src/parse.rs b/src/parse.rs
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -137,23 +156,33 @@ pub fn get_file_change_description_from_file_paths(
Cow::from(file)
}
};
- match (minus_file, plus_file) {
- (minus_file, plus_file) if minus_file == plus_file => format!(
+ match (minus_file, plus_file, minus_file_event, plus_file_event) {
+ (
+ minus_file,
+ plus_file,
+ FileEvent::ModeChange(old_mode),
+ FileEvent::ModeChange(new_mode),
+ ) if minus_file == plus_file => {
+ format!("{}: {} โถ {}", plus_file, old_mode, new_mode)
+ }
+ (minus_file, plus_file, _, _) if minus_file == plus_file => format!(
"{}{}",
format_label(&config.file_modified_label),
format_file(minus_file)
),
- (minus_file, "/dev/null") => format!(
+ (minus_file, "/dev/null", _, _) => format!(
"{}{}",
format_label(&config.file_removed_label),
format_file(minus_file)
),
- ("/dev/null", plus_file) => format!(
+ ("/dev/null", plus_file, _, _) => format!(
"{}{}",
format_label(&config.file_added_label),
format_file(plus_file)
),
- (minus_file, plus_file) => format!(
+ // minus_file_event == plus_file_event, except in the ModeChange
+ // case above.
+ (minus_file, plus_file, file_event, _) => format!(
"{}{} โถ {}",
format_label(match file_event {
FileEvent::Rename => &config.file_renamed_label,
| dandavison__delta-605 | 605 | I am running into the same problem. Forwarding the plaintext would be sufficient, I would personally prefer a more human readable option of
```
old mode rw-r--r--
new mode rwxr-xr-x
```
similar to `ls -l` (or colored like `exa -l` ), and finally I expect people would like only a diff variant similar to `chmod u+x` syntax
```
mode change a+x
```
Thanks @mrjoel , @HarHarLinks -- agree this needs fixing, and it should be an easy enough fix. | [
"583"
] | 0.7 | dandavison/delta | 2021-05-20T02:23:34Z | diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -1569,6 +1569,14 @@ src/align.rs:71: impl<'a> Alignment<'a> { โ
));
}
+ #[test]
+ fn test_file_mode_change() {
+ let config = integration_test_utils::make_config_from_args(&[]);
+ let output = integration_test_utils::run_delta(GIT_DIFF_FILE_MODE_CHANGE, &config);
+ let output = strip_ansi_codes(&output);
+ assert!(output.contains(r"src/delta.rs: 100644 โถ 100755"));
+ }
+
const GIT_DIFF_SINGLE_HUNK: &str = "\
commit 94907c0f136f46dc46ffae2dc92dca9af7eb7c2e
Author: Dan Davison <dandavison7@gmail.com>
diff --git a/src/tests/test_example_diffs.rs b/src/tests/test_example_diffs.rs
--- a/src/tests/test_example_diffs.rs
+++ b/src/tests/test_example_diffs.rs
@@ -2172,4 +2180,10 @@ Date: Sun Nov 1 15:28:53 2020 -0500
\ No newline at end of file[m
[32m+[m[32m][m
"#;
+
+ const GIT_DIFF_FILE_MODE_CHANGE: &str = "
+diff --git a/src/delta.rs b/src/delta.rs
+old mode 100644
+new mode 100755
+";
}
| ๐ No output for chmod file mode change
There is no output shown for file mode change (add/remove execute bit). I've tested using delta 0.7.1, with my custom style configuration as well as the default style (empty delta section in effective `.gitconfig`). Examples of raw git output is shown below, for both for both a mode only change, as well as mode changes and content changes
I don't offhand have any thrilling recommendation as to an alternate display (compact single line `+x` or `-x`?), but even just allowing the plaintext through delta would be very beneficial. Otherwise what can be a noteworthy change is hidden entirely.
```
diff --git i/foo w/foo
old mode 100644
new mode 100755
```
```
diff --git i/foo w/foo
old mode 100644
new mode 100755
index 25160a3..57d50cf
--- i/foo
+++ w/foo
@@ -1 +1,2 @@
line1
+line2
```
| 6be96be6b9af9ababc67835a35d8685d2fc6867d | [
"tests::test_example_diffs::tests::test_file_mode_change"
] | [
"align::tests::test_0",
"align::tests::test_1",
"align::tests::test_0_nonascii",
"align::tests::test_2",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str",
"ansi::iterator::tests::test_iterator_2",
... | [] | [] |
656a1f939d4854fc16295b472bb8d10a044aae47 | diff --git a/src/bat_utils/terminal.rs b/src/bat_utils/terminal.rs
--- a/src/bat_utils/terminal.rs
+++ b/src/bat_utils/terminal.rs
@@ -1,21 +1,48 @@
-extern crate ansi_colours;
-
-use ansi_term::Colour::{Fixed, RGB};
+use ansi_term::Color::{self, Fixed, RGB};
use ansi_term::{self, Style};
use syntect::highlighting::{self, FontStyle};
-pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> ansi_term::Colour {
+pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> Option<ansi_term::Color> {
if color.a == 0 {
// Themes can specify one of the user-configurable terminal colors by
// encoding them as #RRGGBBAA with AA set to 00 (transparent) and RR set
- // to the color palette number. The built-in themes ansi-light,
- // ansi-dark, and base16 use this.
- Fixed(color.r)
+ // to the 8-bit color palette number. The built-in themes ansi, base16,
+ // and base16-256 use this.
+ Some(match color.r {
+ // For the first 8 colors, use the Color enum to produce ANSI escape
+ // sequences using codes 30-37 (foreground) and 40-47 (background).
+ // For example, red foreground is \x1b[31m. This works on terminals
+ // without 256-color support.
+ 0x00 => Color::Black,
+ 0x01 => Color::Red,
+ 0x02 => Color::Green,
+ 0x03 => Color::Yellow,
+ 0x04 => Color::Blue,
+ 0x05 => Color::Purple,
+ 0x06 => Color::Cyan,
+ 0x07 => Color::White,
+ // For all other colors, use Fixed to produce escape sequences using
+ // codes 38;5 (foreground) and 48;5 (background). For example,
+ // bright red foreground is \x1b[38;5;9m. This only works on
+ // terminals with 256-color support.
+ //
+ // TODO: When ansi_term adds support for bright variants using codes
+ // 90-97 (foreground) and 100-107 (background), we should use those
+ // for values 0x08 to 0x0f and only use Fixed for 0x10 to 0xff.
+ n => Fixed(n),
+ })
+ } else if color.a == 1 {
+ // Themes can specify the terminal's default foreground/background color
+ // (i.e. no escape sequence) using the encoding #RRGGBBAA with AA set to
+ // 01. The built-in theme ansi uses this.
+ None
} else if true_color {
- RGB(color.r, color.g, color.b)
+ Some(RGB(color.r, color.g, color.b))
} else {
- Fixed(ansi_colours::ansi256_from_rgb((color.r, color.g, color.b)))
+ Some(Fixed(ansi_colours::ansi256_from_rgb((
+ color.r, color.g, color.b,
+ ))))
}
}
diff --git a/src/bat_utils/terminal.rs b/src/bat_utils/terminal.rs
--- a/src/bat_utils/terminal.rs
+++ b/src/bat_utils/terminal.rs
@@ -35,19 +62,22 @@ pub fn as_terminal_escaped(
let mut style = if !colored {
Style::default()
} else {
- let color = to_ansi_color(style.foreground, true_color);
-
+ let mut color = Style {
+ foreground: to_ansi_color(style.foreground, true_color),
+ ..Style::default()
+ };
if style.font_style.contains(FontStyle::BOLD) {
- color.bold()
- } else if style.font_style.contains(FontStyle::UNDERLINE) {
- color.underline()
- } else if italics && style.font_style.contains(FontStyle::ITALIC) {
- color.italic()
- } else {
- color.normal()
+ color = color.bold();
+ }
+ if style.font_style.contains(FontStyle::UNDERLINE) {
+ color = color.underline();
+ }
+ if italics && style.font_style.contains(FontStyle::ITALIC) {
+ color = color.italic();
}
+ color
};
- style.background = background_color.map(|c| to_ansi_color(c, true_color));
+ style.background = background_color.and_then(|c| to_ansi_color(c, true_color));
style.paint(text).to_string()
}
diff --git a/src/color.rs b/src/color.rs
--- a/src/color.rs
+++ b/src/color.rs
@@ -26,7 +26,7 @@ pub fn parse_color(s: &str, true_color: bool) -> Option<Color> {
.or_else(|| syntect_color::syntect_color_from_ansi_name(s))
.unwrap_or_else(die)
};
- Some(to_ansi_color(syntect_color, true_color))
+ to_ansi_color(syntect_color, true_color)
}
pub fn color_to_string(color: Color) -> String {
diff --git a/src/options/theme.rs b/src/options/theme.rs
--- a/src/options/theme.rs
+++ b/src/options/theme.rs
@@ -38,13 +38,12 @@ pub fn is_light_syntax_theme(theme: &str) -> bool {
LIGHT_SYNTAX_THEMES.contains(&theme)
}
-const LIGHT_SYNTAX_THEMES: [&str; 7] = [
+const LIGHT_SYNTAX_THEMES: [&str; 6] = [
"GitHub",
"gruvbox-light",
"gruvbox-white",
"Monokai Extended Light",
"OneHalfLight",
- "ansi-light",
"Solarized (light)",
];
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -667,7 +667,7 @@ mod superimpose_style_sections {
if style.is_syntax_highlighted && syntect_style != null_syntect_style {
Style {
ansi_term_style: ansi_term::Style {
- foreground: Some(to_ansi_color(syntect_style.foreground, true_color)),
+ foreground: to_ansi_color(syntect_style.foreground, true_color),
..style.ansi_term_style
},
..style
diff --git a/src/paint.rs b/src/paint.rs
--- a/src/paint.rs
+++ b/src/paint.rs
@@ -755,7 +755,7 @@ mod superimpose_style_sections {
lazy_static! {
static ref SUPERIMPOSED_STYLE: Style = Style {
ansi_term_style: ansi_term::Style {
- foreground: Some(to_ansi_color(SyntectColor::BLACK, true)),
+ foreground: to_ansi_color(SyntectColor::BLACK, true),
background: Some(Color::White),
is_underline: true,
..ansi_term::Style::new()
| dandavison__delta-581 | 581 | I second that. I'm struggling with the same issue.
I don't care about the `delta` theme at all, I wish `delta` could just alternate between `--light` and `--dark` colors according to the terminal colors automatically.
Out of the curiosity, what terminal emulator are you using @tshu-w? Does it support this out-of-the-box?
Thank you.
@lourenci Hi, I'm using iTerm2 on macOS, unlike the terminal that comes with the system, it requires a [script](https://gist.github.com/jamesmacfie/2061023e5365e8b6bfbbc20792ac90f8) to make the automatic switch possible.
Hi @tshu-w and @lourenci, yes let's figure out a good way to do this. What do you think of this proposal:
- There are two parts to this: (1) detecting the relevant system state (e.g. OS dark mode, or current terminal color theme etc) and (2) getting delta to respond to the relevant system state.
- I suggest we address those separately. Specifically, I suggest that we say that (1) is not Delta's responsibility. Instead, Delta will expose an environment variable named `DELTA_FEATURES`. This environment variable does exactly the same thing as the existing `--features` flag. (see [custom features](https://github.com/dandavison/delta#custom-features) and [`--help` output](https://github.com/dandavison/delta#full---help-output))
- Thus it is the user's responsibility to populate the `DELTA_FEATURES` environment variable with the names of the custom features they want to be active, in response to changes in their system state. One way to do this might be to use shell prompt code (i.e. shell code that is executed every time the prompt is displayed).
- So, for example, one might define custom features something like below, and then arrange for `DELTA_FEATURES` to contain either `"my-light-mode"` or `"my-dark-mode"` as appropriate.
```gitconfig
[delta "my-light-mode"]
light = true
file-style = magenta # or whatever other settings you want; this is just an example
[delta "my-dark-mode"]
dark = true
file-style = green # or whatever other settings you want; this is just an example
```
If you're able to [build delta from source](https://github.com/dandavison/delta#build-delta-from-source) then you can play around with this now as I've added support for the `DELTA_FEATURES` env var. cc @ulwlu ref https://github.com/dandavison/delta/pull/340#issuecomment-744257639
If this seems like a good way forward then let's put together a concrete example of doing this with a particular OS/terminal emulator/shell combination.
@tshu-w @lourenci here's a proof-of-principle that uses [iTerm2 proprietary escape codes](https://iterm2.com/documentation-escape-codes.html) and zsh's preexec hook. Unfortunately the iterm2 escape codes do not work in tmux. The `DELTA_FEATURES` env var is available in master but not yet released.
Instructions:
1. Set up Delta features for your light and dark modes:
```gitconfig
[delta "my-light-mode"]
light = true
syntax-theme = GitHub
[delta "my-dark-mode"]
dark = true
syntax-theme = Dracula
```
2. Arrange for the `DELTA_FEATURES` env var to be populated correctly according to the current terminal background color, before running any command (This is for `zsh`; in bash one can use `PROMPT_COMMAND` which runs before displaying the prompt).
```zsh
__dan_preexec_function () {
export DELTA_FEATURES="my-$(iterm2-get-light-or-dark-bg)-mode"
}
typeset -ag preexec_functions;
preexec_functions=( __dan_preexec_function ${preexec_functions[@]} )
```
3. Put the python script below on your `$PATH` with the name `iterm2-get-light-or-dark-bg` and make it executable.
```python
#!/usr/bin/env python
import subprocess
import sys
def gamma_correct(rgb: int) -> float:
rgb = rgb / 255
return rgb / 12.92 if rgb <= 0.03928 else ((rgb + 0.055) / 1.055) ** 2.4
def luminance(r: int, g: int, b: int) -> float:
"""
https://www.w3.org/TR/WCAG20/#relativeluminancedef
"""
r, g, b = map(gamma_correct, [r, g, b])
return 0.2126 * r + 0.7152 * g + 0.0722 * b
# https://iterm2.com/documentation-escape-codes.html
cmd = "read -s -N 26 -p $'\x1b]4;-2;?\x07' RESPONSE; echo \"$RESPONSE\""
response = subprocess.check_output(["bash", "-c", cmd]).strip().decode('utf-8')
r, g, b = map(lambda hex: int(hex[:2], 16), response.split(":")[1].split('/'))
sys.stdout.write("light\n" if luminance(r, g, b) > 0.5 else "dark\n")
```
Now run `exec zsh` to reload `zsh` config and Delta will automatically switch between your light/dark modes according to the relative luminance value of the background color used by your iTerm2 color theme.
Hi, I agree with dandavison that this is not delta's responsibility, but I feel not a few people want this.
I knew this library can solve this issue.
https://github.com/dalance/termbg
If we'll approach as delta side will solve this, I will fix.
@ulwlu oh, that library looks perfect. I am absolutely happy for us to build in background color detection to Delta. You're right: that would be a much better solution. Terminal color detection is important enough for delta to do it. And I see it has some tmux support... the code I posted above doesn't work in tmux.
Yes it works in tmux. There are many informations about this library in Japanese articles, so I'm going to give it a try in a few days!
> Yes it works in tmux. There are many informations about this library in Japanese articles, so I'm going to give it a try in a few days!
Ok, sounds great -- I'll leave this one for you to work on.
I've been trying to think about how we want this to work ultimately. Basically, `termbg` (if it works as we hope) is going to give us two states: light mode and dark mode. Initially, I think we can just have that switch between delta's existing `--light` and `--dark` settings.
Ultimately, I think it would be nice if users could have two features defined in their gitconfig, one for their light mode settings, and one for their dark mode settings. These would contain the `syntax-theme` and colors, etc. I'm not sure whether those feature names should be fixed, e.g. `[delta "light"]` and `[delta "dark"]` or whether users should be able to specify the name of the custom feature that holds their light-mode and dark-mode settings.
A related issue is that the code for `--light` and `--dark` should probably be refactored to use the "builtin feature" pattern (`src/features/*`).
@dandavison @ulwlu Thank you for your efforts, I've been a bit busy recently. Although the solution provided by @dandavison is sufficient, I agree that it would be great for delta to have built-in color detection, so I will leave this issue open.
> Basically, `termbg` (if it works as we hope) is going to give us two states: light mode and dark mode.
I have a custom script to set/get/toggle darkmode states on different OSโ. Maybe delta could expose an environment variable (e.g., `DELTA_TERMBG_CMD="dm get"`) that can be used if/when `termbg` is not available/does not work as expected?
@sscherfke
oh sorry for repling late. As my status said I'm currently quite busy with my job until March.
If you can create PR, it would be better.
bat "solved" this by providing an "ansi" theme, replacing ansi-dark and ansi-light, which automatically switches colors to work in either a dark or light theme. https://github.com/sharkdp/bat/issues/1104
Could delta do the same?
Hi @skyfaller I'm sorry, I was on the verge of replying to this 3 weeks ago when you said it and then somehow didn't! What I was going to say is thanks, and you prompted me to update delta to bat's latest themes, so `ansi` will be available in delta (and ansi-light and ansi-dark will be gone), since delta follows bat here. However, delta users also (mostly) specify background colors for the different sorts of highlighting of plus and minus lines, and this is typically done with 256 colors or 24-bit colors, and so the question of automated choice between two modes of those colors would still be unsolved, as I'm understanding things.
@dandavison Thank you! It doesn't solve the problem for people who want more advanced themes, no, but for people who just want legible text for now, the "ansi" theme is a fine workaround. I look forward to the next release!
Here's what I did to "solve" the problem for myself in the meantime, on Gnome with [fish shell](https://fishshell.com/) using [sd](https://github.com/chmln/sd).
I made a fish function that detects my Gnome theme and uses that to change my .gitconfig to my desired delta theme:
```fish
function theme-delta --description 'Set delta theme based on gtk-theme'
switch (gsettings get org.gnome.desktop.interface gtk-theme)
case "'Pop'"
sd '^\tsyntax-theme = .*$' '\tsyntax-theme = gruvbox' ~/.gitconfig
case "'Adwaita'"
sd '^\tsyntax-theme = .*$' '\tsyntax-theme = GitHub' ~/.gitconfig
case "'Pop-dark'"
sd '^\tsyntax-theme = .*$' '\tsyntax-theme = Monokai Extended' ~/.gitconfig
case '*'
echo "error: unidentified GTK theme"
end
end
```
Then I use the [Night Theme Switcher GNOME Shell extension](https://gitlab.com/rmnvgr/nightthemeswitcher-gnome-shell-extension/) to run that fish function (and similar functions for Alacritty and bat) at the same time as it changes my theme between light and dark, like so:
`/usr/bin/fish -c 'theme-bat; theme-alacritty; theme-delta'`
I'm very interested to see how you finally solve this, termbg looks cool!
Cool, thanks, that's a lot of helpful links and example code! (And I hadn't come across `sd`, I'll definitely look into that.)
I just tried out the `ansi` theme in the latest master (1b3bd2877a3ba97a2fa10a328610edc945e993f4) and it doesn't behave as expected. Works on light themes, but not dark themes. I think the default text colour is set to black, when it actually should be left uncolored. | [
"447"
] | 0.7 | dandavison/delta | 2021-04-29T21:12:25Z | diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -334,8 +334,6 @@ mod tests {
use ansi_term;
- use crate::color::ansi_16_color_name_to_number;
-
#[test]
fn test_parse_ansi_term_style() {
assert_eq!(
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -346,9 +344,7 @@ mod tests {
parse_ansi_term_style("red", None, false),
(
ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("red").unwrap()
- )),
+ foreground: Some(ansi_term::Color::Red),
..ansi_term::Style::new()
},
false,
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -360,12 +356,8 @@ mod tests {
parse_ansi_term_style("red green", None, false),
(
ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("red").unwrap()
- )),
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("green").unwrap()
- )),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
..ansi_term::Style::new()
},
false,
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -377,12 +369,8 @@ mod tests {
parse_ansi_term_style("bold red underline green blink", None, false),
(
ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("red").unwrap()
- )),
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("green").unwrap()
- )),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_blink: true,
is_bold: true,
is_underline: true,
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -405,9 +393,7 @@ mod tests {
parse_ansi_term_style("syntax italic white hidden", None, false),
(
ansi_term::Style {
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("white").unwrap()
- )),
+ background: Some(ansi_term::Color::White),
is_italic: true,
is_hidden: true,
..ansi_term::Style::new()
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -421,9 +407,7 @@ mod tests {
parse_ansi_term_style("bold syntax italic white hidden", None, false),
(
ansi_term::Style {
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("white").unwrap()
- )),
+ background: Some(ansi_term::Color::White),
is_bold: true,
is_italic: true,
is_hidden: true,
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -447,9 +431,7 @@ mod tests {
parse_ansi_term_style("omit syntax italic white hidden", None, false),
(
ansi_term::Style {
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("white").unwrap()
- )),
+ background: Some(ansi_term::Color::White),
is_italic: true,
is_hidden: true,
..ansi_term::Style::new()
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -472,9 +454,7 @@ mod tests {
parse_ansi_term_style("raw syntax italic white hidden", None, false),
(
ansi_term::Style {
- background: Some(ansi_term::Color::Fixed(
- ansi_16_color_name_to_number("white").unwrap()
- )),
+ background: Some(ansi_term::Color::White),
is_italic: true,
is_hidden: true,
..ansi_term::Style::new()
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -542,8 +522,8 @@ mod tests {
assert_eq!(
DecorationStyle::from_str("ol red box bold green ul", true),
DecorationStyle::BoxWithUnderOverline(ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(1)),
- background: Some(ansi_term::Color::Fixed(2)),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_bold: true,
..ansi_term::Style::new()
})
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -560,8 +540,8 @@ mod tests {
false,
);
let red_green_bold = ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(1)),
- background: Some(ansi_term::Color::Fixed(2)),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_bold: true,
..ansi_term::Style::new()
};
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -594,8 +574,8 @@ mod tests {
fn test_style_from_str_decoration_style_only() {
let actual_style = Style::from_str("", None, Some("ol red box bold green ul"), true, false);
let red_green_bold = ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(1)),
- background: Some(ansi_term::Color::Fixed(2)),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_bold: true,
..ansi_term::Style::new()
};
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -618,8 +598,8 @@ mod tests {
false,
);
let expected_decoration_style = DecorationStyle::BoxWithUnderOverline(ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(1)),
- background: Some(ansi_term::Color::Fixed(2)),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_bold: true,
..ansi_term::Style::new()
});
diff --git a/src/parse_style.rs b/src/parse_style.rs
--- a/src/parse_style.rs
+++ b/src/parse_style.rs
@@ -657,8 +637,8 @@ mod tests {
fn test_style_from_str_with_handling_of_special_decoration_attributes_and_respecting_deprecated_foreground_color_arg(
) {
let expected_decoration_style = DecorationStyle::BoxWithUnderOverline(ansi_term::Style {
- foreground: Some(ansi_term::Color::Fixed(1)),
- background: Some(ansi_term::Color::Fixed(2)),
+ foreground: Some(ansi_term::Color::Red),
+ background: Some(ansi_term::Color::Green),
is_bold: true,
..ansi_term::Style::new()
});
| ๐ Use light/dark theme base on terminal theme or system variable.
Hi, I have set my terminal to auto change themes based on macOS appearance. It would be much appreciated if delta can use light/dark theme base on terminal theme or system variable.
| 6be96be6b9af9ababc67835a35d8685d2fc6867d | [
"parse_style::tests::test_decoration_style_from_str",
"parse_style::tests::test_parse_ansi_term_style",
"parse_style::tests::test_parse_ansi_term_style_with_special_omit_attribute",
"parse_style::tests::test_parse_ansi_term_style_with_special_raw_attribute",
"parse_style::tests::test_parse_ansi_term_style_w... | [
"align::tests::test_0_nonascii",
"align::tests::test_0",
"align::tests::test_2",
"align::tests::test_1",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::iterator::tests::test_iterator_2",
"ansi::iterator::tests::test_iterator_osc_hyperlinks_styled_non_asci... | [] | [] |
63fdebbf68878fa52fe178f0e5d2a89478345878 | diff --git a/src/git_config/git_config_entry.rs b/src/git_config/git_config_entry.rs
--- a/src/git_config/git_config_entry.rs
+++ b/src/git_config/git_config_entry.rs
@@ -23,7 +23,7 @@ lazy_static! {
static ref GITHUB_REMOTE_URL: Regex = Regex::new(
r"(?x)
^
- (?:https://|git@) # Support both HTTPS and SSH URLs
+ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@
github\.com
[:/] # This separator differs between SSH and HTTPS URLs
([^/]+) # Capture the user/org name
| dandavison__delta-668 | 668 | (Fwiw, if you deem this to a feature you want included in the first place, I'd be happy to submit a PR adding it if that's useful :)
Hi @spaarmann, we recently added this option:
```
--hyperlinks-commit-link-format <hyperlinks-commit-link-format>
Format string for commit hyperlinks (requires --hyperlinks). The placeholder "{commit}" will be replaced by
the commit hash. For example: --hyperlinks-commit-link-format='https://mygitrepo/{commit}/'
```
Am I right in thinking that that can be used to solve this? (It takes precedence over the auto-recognizing of github URLs)
That could be used to make hyperlinks work but unless I'm missing something, I believe that would have to be configured for every repository / clone separately, because the custom format would have to include the `user/repo` part. The main advantage of tweaking the Regex is that it would work for every repository automatically.
Yes, you're right. Ok, sure, it would be great if you're able to improve this regex!
Great! I'm about to go to bed, but I'll look at sending a PR tomorrow. | [
"667"
] | 0.8 | dandavison/delta | 2021-07-26T11:43:15Z | diff --git a/src/git_config/git_config_entry.rs b/src/git_config/git_config_entry.rs
--- a/src/git_config/git_config_entry.rs
+++ b/src/git_config/git_config_entry.rs
@@ -62,6 +62,8 @@ mod tests {
"https://github.com/dandavison/delta",
"git@github.com:dandavison/delta.git",
"git@github.com:dandavison/delta",
+ "github.com:dandavison/delta.git",
+ "github.com:dandavison/delta",
];
for url in urls {
let parsed = GitRemoteRepo::from_str(url);
| ๐ Show Github commit hyperlinks even if remote URL does not contain `git@`
Hi! I was recently a bit confused why hyperlinks for commits were working in some of my local clones but not others.
After a bit of investigation I've figured out that it's caused by the remote URL being simply `github.com:user/repo` instead of `git@github.com:user/repo`, which is not matched by the current regex.
Now, this remote URL only works in the first place because of a custom SSH config containing something like this:
```
Host github.com
HostName github.com
User git
IdentityFile <some key>
```
Considering that I fully understand if you'd prefer to not support such configs out-of-the-box. (You can also put anything into the `Host` portion there and have it still end up going to GitHub with configs like this and I imagine that parsing the SSH config or anything similar to make everything here work is definitely out of scope ๐ ).
Still, I figured specifically allowing omitting the `git@` is a pretty small change so I might as well ask (and I suspect this is at least a *somewhat* common config; I don't remember where I stole it, but I definitely got the idea from someone else).
| 80691898cd4cae02f40ed5ad6986e517a938d14f | [
"git_config::git_config_entry::tests::test_parse_github_urls"
] | [
"align::tests::test_0_nonascii",
"align::tests::test_1",
"align::tests::test_2",
"align::tests::test_0",
"align::tests::test_run_length_encode",
"ansi::console_tests::tests::test_text_width",
"ansi::console_tests::tests::test_truncate_str_no_ansi",
"ansi::console_tests::tests::test_truncate_str",
"a... | [] | [] |
faa743a6f1055705aa923911003cef6b1807e93e | diff --git a/crates/core/src/kernel/arrow/json.rs b/crates/core/src/kernel/arrow/json.rs
--- a/crates/core/src/kernel/arrow/json.rs
+++ b/crates/core/src/kernel/arrow/json.rs
@@ -62,9 +62,10 @@ pub(crate) fn parse_json(
for it in 0..json_strings.len() {
if json_strings.is_null(it) {
if value_count > 0 {
- let slice = json_strings.slice(value_start, value_count);
- let batch = decode_reader(&mut decoder, get_reader(slice.value_data()))
- .collect::<Result<Vec<_>, _>>()?;
+ let slice_data = get_nonnull_slice_data(json_strings, value_start, value_count);
+ let batch =
+ decode_reader(&mut decoder, get_reader(&slice_data))
+ .collect::<Result<Vec<_>, _>>()?;
batches.extend(batch);
value_count = 0;
}
diff --git a/crates/core/src/kernel/arrow/json.rs b/crates/core/src/kernel/arrow/json.rs
--- a/crates/core/src/kernel/arrow/json.rs
+++ b/crates/core/src/kernel/arrow/json.rs
@@ -86,15 +87,28 @@ pub(crate) fn parse_json(
}
if value_count > 0 {
- let slice = json_strings.slice(value_start, value_count);
- let batch = decode_reader(&mut decoder, get_reader(slice.value_data()))
- .collect::<Result<Vec<_>, _>>()?;
+ let slice_data = get_nonnull_slice_data(json_strings, value_start, value_count);
+ let batch =
+ decode_reader(&mut decoder, get_reader(&slice_data)).collect::<Result<Vec<_>, _>>()?;
batches.extend(batch);
}
Ok(concat_batches(&output_schema, &batches)?)
}
+/// Get the data of a slice of non-null JSON strings.
+fn get_nonnull_slice_data(
+ json_strings: &StringArray,
+ value_start: usize,
+ value_count: usize,
+) -> Vec<u8> {
+ let slice = json_strings.slice(value_start, value_count);
+ slice.iter().fold(Vec::new(), |mut acc, s| {
+ acc.extend_from_slice(s.unwrap().as_bytes());
+ acc
+ })
+}
+
/// Decode a stream of bytes into a stream of record batches.
pub(crate) fn decode_stream<S: Stream<Item = ObjectStoreResult<Bytes>> + Unpin>(
mut decoder: Decoder,
diff --git a/crates/core/src/kernel/snapshot/replay.rs b/crates/core/src/kernel/snapshot/replay.rs
--- a/crates/core/src/kernel/snapshot/replay.rs
+++ b/crates/core/src/kernel/snapshot/replay.rs
@@ -79,7 +79,7 @@ fn map_batch(
config: &DeltaTableConfig,
) -> DeltaResult<RecordBatch> {
let stats_col = ex::extract_and_cast_opt::<StringArray>(&batch, "add.stats");
- let stats_parsed_col = ex::extract_and_cast_opt::<StringArray>(&batch, "add.stats_parsed");
+ let stats_parsed_col = ex::extract_and_cast_opt::<StructArray>(&batch, "add.stats_parsed");
if stats_parsed_col.is_some() {
return Ok(batch);
}
| delta-io__delta-rs-2405 | 2,405 | @yjshen can you add some reproducible code?
I've seen this error when trying to read an old table with 10s of thousands of partitions. I started removing old partitions and vacuum/compact and the error went away. Maybe the schema changed at some point or something wrong with the old data. I'm not sure. | [
"2312"
] | 1.0 | delta-io/delta-rs | 2024-04-10T02:48:43Z | diff --git a/crates/core/src/kernel/arrow/json.rs b/crates/core/src/kernel/arrow/json.rs
--- a/crates/core/src/kernel/arrow/json.rs
+++ b/crates/core/src/kernel/arrow/json.rs
@@ -148,3 +162,42 @@ pub(crate) fn decode_reader<'a, R: BufRead + 'a>(
};
std::iter::from_fn(move || next().map_err(DeltaTableError::from).transpose())
}
+
+#[cfg(test)]
+mod tests {
+ use crate::kernel::arrow::json::parse_json;
+ use crate::DeltaTableConfig;
+ use arrow_array::{Int32Array, RecordBatch, StringArray};
+ use arrow_schema::{DataType, Field, Schema};
+ use std::sync::Arc;
+
+ #[test]
+ fn json_to_struct() {
+ let json_strings = StringArray::from(vec![
+ Some(r#"{"a": 1, "b": "foo"}"#),
+ Some(r#"{"a": 2, "b": "bar"}"#),
+ None,
+ Some(r#"{"a": 3, "b": "baz"}"#),
+ ]);
+ let struct_schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, true),
+ Field::new("b", DataType::Utf8, true),
+ ]));
+ let config = DeltaTableConfig::default();
+ let result = parse_json(&json_strings, struct_schema.clone(), &config).unwrap();
+ let expected = RecordBatch::try_new(
+ struct_schema,
+ vec![
+ Arc::new(Int32Array::from(vec![Some(1), Some(2), None, Some(3)])),
+ Arc::new(StringArray::from(vec![
+ Some("foo"),
+ Some("bar"),
+ None,
+ Some("baz"),
+ ])),
+ ],
+ )
+ .unwrap();
+ assert_eq!(result, expected);
+ }
+}
| Extract `add.stats_parsed` with wrong type
# Bug
During delta log reading, extracting `add.stats_parsed` with the wrong `StringArray` type (on line 82) results in a double `stats_parsed` column in the result batch.
https://github.com/delta-io/delta-rs/blob/eb8c19c404bc53e1e74ddbeb55f182c9e6804b74/crates/core/src/kernel/snapshot/replay.rs#L76-L89
Also, the newly generated `stats_parsed` from `stats` has a different array length than other columns.
```
source: Arrow { source: InvalidArgumentError("Incorrect array length for StructArray field \"stats_parsed\", expected 10 got 14")
```
**What you expected to happen**:
1. extract `add.stats_parsed` with `StructArray` type
2. generated `stats_parsed` should have a same number of rows as other cols.
**How to reproduce it**:
**More details**:
| f2e30a0bbf58a3b56b2f912a02e10e7af0835301 | [
"kernel::arrow::json::tests::json_to_struct"
] | [
"data_catalog::client::backoff::tests::test_backoff",
"data_catalog::storage::tests::test_normalize_table_name",
"data_catalog::unity::models::tests::test_response_errors",
"data_catalog::unity::models::tests::test_responses",
"kernel::arrow::tests::test_arrow_from_delta_decimal_type_invalid_precision",
"... | [] | [] |
9d3ecbeb628db3d046d86429315aaf4765f6a41b | diff --git a/crates/core/src/operations/constraints.rs b/crates/core/src/operations/constraints.rs
--- a/crates/core/src/operations/constraints.rs
+++ b/crates/core/src/operations/constraints.rs
@@ -198,9 +198,10 @@ impl std::future::IntoFuture for ConstraintBuilder {
.build(Some(&this.snapshot), this.log_store.clone(), operation)?
.await?;
- this.snapshot
- .merge(commit.data.actions, &commit.data.operation, commit.version)?;
- Ok(DeltaTable::new_with_state(this.log_store, this.snapshot))
+ Ok(DeltaTable::new_with_state(
+ this.log_store,
+ commit.snapshot(),
+ ))
})
}
}
diff --git a/crates/core/src/operations/delete.rs b/crates/core/src/operations/delete.rs
--- a/crates/core/src/operations/delete.rs
+++ b/crates/core/src/operations/delete.rs
@@ -186,16 +186,16 @@ async fn excute_non_empty_expr(
async fn execute(
predicate: Option<Expr>,
log_store: LogStoreRef,
- snapshot: &DeltaTableState,
+ snapshot: DeltaTableState,
state: SessionState,
writer_properties: Option<WriterProperties>,
mut commit_properties: CommitProperties,
-) -> DeltaResult<((Vec<Action>, i64, Option<DeltaOperation>), DeleteMetrics)> {
+) -> DeltaResult<(DeltaTableState, DeleteMetrics)> {
let exec_start = Instant::now();
let mut metrics = DeleteMetrics::default();
let scan_start = Instant::now();
- let candidates = find_files(snapshot, log_store.clone(), &state, predicate.clone()).await?;
+ let candidates = find_files(&snapshot, log_store.clone(), &state, predicate.clone()).await?;
metrics.scan_time_ms = Instant::now().duration_since(scan_start).as_millis();
let predicate = predicate.unwrap_or(Expr::Literal(ScalarValue::Boolean(Some(true))));
diff --git a/crates/core/src/operations/delete.rs b/crates/core/src/operations/delete.rs
--- a/crates/core/src/operations/delete.rs
+++ b/crates/core/src/operations/delete.rs
@@ -205,7 +205,7 @@ async fn execute(
} else {
let write_start = Instant::now();
let add = excute_non_empty_expr(
- snapshot,
+ &snapshot,
log_store.clone(),
&state,
&predicate,
diff --git a/crates/core/src/operations/delete.rs b/crates/core/src/operations/delete.rs
--- a/crates/core/src/operations/delete.rs
+++ b/crates/core/src/operations/delete.rs
@@ -258,21 +258,14 @@ async fn execute(
predicate: Some(fmt_expr_to_sql(&predicate)?),
};
if actions.is_empty() {
- return Ok(((actions, snapshot.version(), None), metrics));
+ return Ok((snapshot.clone(), metrics));
}
let commit = CommitBuilder::from(commit_properties)
.with_actions(actions)
- .build(Some(snapshot), log_store, operation)?
+ .build(Some(&snapshot), log_store, operation)?
.await?;
- Ok((
- (
- commit.data.actions,
- commit.version,
- Some(commit.data.operation),
- ),
- metrics,
- ))
+ Ok((commit.snapshot(), metrics))
}
impl std::future::IntoFuture for DeleteBuilder {
diff --git a/crates/core/src/operations/delete.rs b/crates/core/src/operations/delete.rs
--- a/crates/core/src/operations/delete.rs
+++ b/crates/core/src/operations/delete.rs
@@ -305,22 +298,20 @@ impl std::future::IntoFuture for DeleteBuilder {
None => None,
};
- let ((actions, version, operation), metrics) = execute(
+ let (new_snapshot, metrics) = execute(
predicate,
this.log_store.clone(),
- &this.snapshot,
+ this.snapshot,
state,
this.writer_properties,
this.commit_properties,
)
.await?;
- if let Some(op) = &operation {
- this.snapshot.merge(actions, op, version)?;
- }
-
- let table = DeltaTable::new_with_state(this.log_store, this.snapshot);
- Ok((table, metrics))
+ Ok((
+ DeltaTable::new_with_state(this.log_store, new_snapshot),
+ metrics,
+ ))
})
}
}
diff --git a/crates/core/src/operations/drop_constraints.rs b/crates/core/src/operations/drop_constraints.rs
--- a/crates/core/src/operations/drop_constraints.rs
+++ b/crates/core/src/operations/drop_constraints.rs
@@ -91,9 +91,10 @@ impl std::future::IntoFuture for DropConstraintBuilder {
.build(Some(&this.snapshot), this.log_store.clone(), operation)?
.await?;
- this.snapshot
- .merge(commit.data.actions, &commit.data.operation, commit.version)?;
- Ok(DeltaTable::new_with_state(this.log_store, this.snapshot))
+ Ok(DeltaTable::new_with_state(
+ this.log_store,
+ commit.snapshot(),
+ ))
})
}
}
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -932,7 +932,7 @@ async fn execute(
predicate: Expression,
source: DataFrame,
log_store: LogStoreRef,
- snapshot: &DeltaTableState,
+ snapshot: DeltaTableState,
state: SessionState,
writer_properties: Option<WriterProperties>,
mut commit_properties: CommitProperties,
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -942,7 +942,7 @@ async fn execute(
match_operations: Vec<MergeOperationConfig>,
not_match_target_operations: Vec<MergeOperationConfig>,
not_match_source_operations: Vec<MergeOperationConfig>,
-) -> DeltaResult<((Vec<Action>, i64, Option<DeltaOperation>), MergeMetrics)> {
+) -> DeltaResult<(DeltaTableState, MergeMetrics)> {
let mut metrics = MergeMetrics::default();
let exec_start = Instant::now();
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -987,7 +987,7 @@ async fn execute(
let scan_config = DeltaScanConfigBuilder::default()
.with_file_column(true)
.with_parquet_pushdown(false)
- .build(snapshot)?;
+ .build(&snapshot)?;
let target_provider = Arc::new(DeltaTableProvider::try_new(
snapshot.clone(),
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -1017,7 +1017,7 @@ async fn execute(
} else {
try_construct_early_filter(
predicate.clone(),
- snapshot,
+ &snapshot,
&state,
&source,
&source_name,
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -1370,7 +1370,7 @@ async fn execute(
let rewrite_start = Instant::now();
let add_actions = write_execution_plan(
- Some(snapshot),
+ Some(&snapshot),
state.clone(),
write,
table_partition_cols.clone(),
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -1449,21 +1449,14 @@ async fn execute(
};
if actions.is_empty() {
- return Ok(((actions, snapshot.version(), None), metrics));
+ return Ok((snapshot, metrics));
}
let commit = CommitBuilder::from(commit_properties)
.with_actions(actions)
- .build(Some(snapshot), log_store.clone(), operation)?
+ .build(Some(&snapshot), log_store.clone(), operation)?
.await?;
- Ok((
- (
- commit.data.actions,
- commit.version,
- Some(commit.data.operation),
- ),
- metrics,
- ))
+ Ok((commit.snapshot(), metrics))
}
fn remove_table_alias(expr: Expr, table_alias: &str) -> Expr {
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -1521,11 +1514,11 @@ impl std::future::IntoFuture for MergeBuilder {
session.state()
});
- let ((actions, version, operation), metrics) = execute(
+ let (snapshot, metrics) = execute(
this.predicate,
this.source,
this.log_store.clone(),
- &this.snapshot,
+ this.snapshot,
state,
this.writer_properties,
this.commit_properties,
diff --git a/crates/core/src/operations/merge/mod.rs b/crates/core/src/operations/merge/mod.rs
--- a/crates/core/src/operations/merge/mod.rs
+++ b/crates/core/src/operations/merge/mod.rs
@@ -1538,12 +1531,10 @@ impl std::future::IntoFuture for MergeBuilder {
)
.await?;
- if let Some(op) = &operation {
- this.snapshot.merge(actions, op, version)?;
- }
- let table = DeltaTable::new_with_state(this.log_store, this.snapshot);
-
- Ok((table, metrics))
+ Ok((
+ DeltaTable::new_with_state(this.log_store, snapshot),
+ metrics,
+ ))
})
}
}
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -207,7 +207,7 @@ pub trait TableReference: Send + Sync {
fn metadata(&self) -> &Metadata;
/// Try to cast this table reference to a `EagerSnapshot`
- fn eager_snapshot(&self) -> Option<&EagerSnapshot>;
+ fn eager_snapshot(&self) -> &EagerSnapshot;
}
impl TableReference for EagerSnapshot {
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -223,8 +223,8 @@ impl TableReference for EagerSnapshot {
self.table_config()
}
- fn eager_snapshot(&self) -> Option<&EagerSnapshot> {
- Some(self)
+ fn eager_snapshot(&self) -> &EagerSnapshot {
+ self
}
}
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -241,8 +241,8 @@ impl TableReference for DeltaTableState {
self.snapshot.metadata()
}
- fn eager_snapshot(&self) -> Option<&EagerSnapshot> {
- Some(&self.snapshot)
+ fn eager_snapshot(&self) -> &EagerSnapshot {
+ &self.snapshot
}
}
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -512,13 +512,7 @@ impl<'a> std::future::IntoFuture for PreparedCommit<'a> {
// unwrap() is safe here due to the above check
// TODO: refactor to only depend on TableReference Trait
- let read_snapshot =
- this.table_data
- .unwrap()
- .eager_snapshot()
- .ok_or(DeltaTableError::Generic(
- "Expected an instance of EagerSnapshot".to_owned(),
- ))?;
+ let read_snapshot = this.table_data.unwrap().eager_snapshot();
let mut attempt_number = 1;
while attempt_number <= this.max_retries {
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -595,36 +589,49 @@ pub struct PostCommit<'a> {
impl<'a> PostCommit<'a> {
/// Runs the post commit activities
- async fn run_post_commit_hook(
- &self,
- version: i64,
- commit_data: &CommitData,
- ) -> DeltaResult<()> {
- if self.create_checkpoint {
- self.create_checkpoint(&self.table_data, &self.log_store, version, commit_data)
- .await?
+ async fn run_post_commit_hook(&self) -> DeltaResult<DeltaTableState> {
+ if let Some(table) = self.table_data {
+ let mut snapshot = table.eager_snapshot().clone();
+ if self.version - snapshot.version() > 1 {
+ // This may only occur during concurrent write actions. We need to update the state first to - 1
+ // then we can advance.
+ snapshot
+ .update(self.log_store.clone(), Some(self.version - 1))
+ .await?;
+ snapshot.advance(vec![&self.data])?;
+ } else {
+ snapshot.advance(vec![&self.data])?;
+ }
+ let state = DeltaTableState {
+ app_transaction_version: HashMap::new(),
+ snapshot,
+ };
+ // Execute each hook
+ if self.create_checkpoint {
+ self.create_checkpoint(&state, &self.log_store, self.version)
+ .await?;
+ }
+ Ok(state)
+ } else {
+ let state = DeltaTableState::try_new(
+ &Path::default(),
+ self.log_store.object_store(),
+ Default::default(),
+ Some(self.version),
+ )
+ .await?;
+ Ok(state)
}
- Ok(())
}
async fn create_checkpoint(
&self,
- table: &Option<&'a dyn TableReference>,
+ table_state: &DeltaTableState,
log_store: &LogStoreRef,
version: i64,
- commit_data: &CommitData,
) -> DeltaResult<()> {
- if let Some(table) = table {
- let checkpoint_interval = table.config().checkpoint_interval() as i64;
- if ((version + 1) % checkpoint_interval) == 0 {
- // We have to advance the snapshot otherwise we can't create a checkpoint
- let mut snapshot = table.eager_snapshot().unwrap().clone();
- snapshot.advance(vec![commit_data])?;
- let state = DeltaTableState {
- app_transaction_version: HashMap::new(),
- snapshot,
- };
- create_checkpoint_for(version, &state, log_store.as_ref()).await?
- }
+ let checkpoint_interval = table_state.config().checkpoint_interval() as i64;
+ if ((version + 1) % checkpoint_interval) == 0 {
+ create_checkpoint_for(version, table_state, log_store.as_ref()).await?
}
Ok(())
}
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -632,22 +639,22 @@ impl<'a> PostCommit<'a> {
/// A commit that successfully completed
pub struct FinalizedCommit {
- /// The winning version number of the commit
+ /// The new table state after a commmit
+ pub snapshot: DeltaTableState,
+
+ /// Version of the finalized commit
pub version: i64,
- /// The data that was comitted to the log store
- pub data: CommitData,
}
impl FinalizedCommit {
- /// The materialized version of the commit
+ /// The new table state after a commmit
+ pub fn snapshot(&self) -> DeltaTableState {
+ self.snapshot.clone()
+ }
+ /// Version of the finalized commit
pub fn version(&self) -> i64 {
self.version
}
-
- /// Data used to write the commit
- pub fn data(&self) -> &CommitData {
- &self.data
- }
}
impl<'a> std::future::IntoFuture for PostCommit<'a> {
diff --git a/crates/core/src/operations/transaction/mod.rs b/crates/core/src/operations/transaction/mod.rs
--- a/crates/core/src/operations/transaction/mod.rs
+++ b/crates/core/src/operations/transaction/mod.rs
@@ -658,15 +665,13 @@ impl<'a> std::future::IntoFuture for PostCommit<'a> {
let this = self;
Box::pin(async move {
- match this.run_post_commit_hook(this.version, &this.data).await {
- Ok(_) => {
- return Ok(FinalizedCommit {
- version: this.version,
- data: this.data,
- })
- }
- Err(err) => return Err(err),
- };
+ match this.run_post_commit_hook().await {
+ Ok(snapshot) => Ok(FinalizedCommit {
+ snapshot,
+ version: this.version,
+ }),
+ Err(err) => Err(err),
+ }
})
}
}
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -41,7 +41,7 @@ use futures::future::BoxFuture;
use parquet::file::properties::WriterProperties;
use serde::Serialize;
-use super::transaction::PROTOCOL;
+use super::transaction::{FinalizedCommit, PROTOCOL};
use super::write::write_execution_plan;
use super::{
datafusion_utils::Expression,
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -168,12 +168,12 @@ async fn execute(
predicate: Option<Expression>,
updates: HashMap<Column, Expression>,
log_store: LogStoreRef,
- snapshot: &DeltaTableState,
+ snapshot: DeltaTableState,
state: SessionState,
writer_properties: Option<WriterProperties>,
mut commit_properties: CommitProperties,
safe_cast: bool,
-) -> DeltaResult<((Vec<Action>, i64, Option<DeltaOperation>), UpdateMetrics)> {
+) -> DeltaResult<(DeltaTableState, UpdateMetrics)> {
// Validate the predicate and update expressions.
//
// If the predicate is not set, then all files need to be updated.
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -189,7 +189,7 @@ async fn execute(
let version = snapshot.version();
if updates.is_empty() {
- return Ok(((Vec::new(), version, None), metrics));
+ return Ok((snapshot, metrics));
}
let predicate = match predicate {
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -214,11 +214,11 @@ async fn execute(
let table_partition_cols = current_metadata.partition_columns.clone();
let scan_start = Instant::now();
- let candidates = find_files(snapshot, log_store.clone(), &state, predicate.clone()).await?;
+ let candidates = find_files(&snapshot, log_store.clone(), &state, predicate.clone()).await?;
metrics.scan_time_ms = Instant::now().duration_since(scan_start).as_millis() as u64;
if candidates.candidates.is_empty() {
- return Ok(((Vec::new(), version, None), metrics));
+ return Ok((snapshot, metrics));
}
let predicate = predicate.unwrap_or(Expr::Literal(ScalarValue::Boolean(Some(true))));
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -226,7 +226,7 @@ async fn execute(
let execution_props = state.execution_props();
// For each rewrite evaluate the predicate and then modify each expression
// to either compute the new value or obtain the old one then write these batches
- let scan = DeltaScanBuilder::new(snapshot, log_store.clone(), &state)
+ let scan = DeltaScanBuilder::new(&snapshot, log_store.clone(), &state)
.with_files(&candidates.candidates)
.build()
.await?;
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -350,7 +350,7 @@ async fn execute(
)?);
let add_actions = write_execution_plan(
- Some(snapshot),
+ Some(&snapshot),
state.clone(),
projection.clone(),
table_partition_cols.clone(),
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -416,17 +416,10 @@ async fn execute(
let commit = CommitBuilder::from(commit_properties)
.with_actions(actions)
- .build(Some(snapshot), log_store, operation)?
+ .build(Some(&snapshot), log_store, operation)?
.await?;
- Ok((
- (
- commit.data.actions,
- commit.version,
- Some(commit.data.operation),
- ),
- metrics,
- ))
+ Ok((commit.snapshot(), metrics))
}
impl std::future::IntoFuture for UpdateBuilder {
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -449,11 +442,11 @@ impl std::future::IntoFuture for UpdateBuilder {
session.state()
});
- let ((actions, version, operation), metrics) = execute(
+ let (snapshot, metrics) = execute(
this.predicate,
this.updates,
this.log_store.clone(),
- &this.snapshot,
+ this.snapshot,
state,
this.writer_properties,
this.commit_properties,
diff --git a/crates/core/src/operations/update.rs b/crates/core/src/operations/update.rs
--- a/crates/core/src/operations/update.rs
+++ b/crates/core/src/operations/update.rs
@@ -461,12 +454,10 @@ impl std::future::IntoFuture for UpdateBuilder {
)
.await?;
- if let Some(op) = &operation {
- this.snapshot.merge(actions, op, version)?;
- }
-
- let table = DeltaTable::new_with_state(this.log_store, this.snapshot);
- Ok((table, metrics))
+ Ok((
+ DeltaTable::new_with_state(this.log_store, snapshot),
+ metrics,
+ ))
})
}
}
diff --git a/crates/core/src/operations/write.rs b/crates/core/src/operations/write.rs
--- a/crates/core/src/operations/write.rs
+++ b/crates/core/src/operations/write.rs
@@ -808,17 +808,7 @@ impl std::future::IntoFuture for WriteBuilder {
)?
.await?;
- // TODO we do not have the table config available, but since we are merging only our newly
- // created actions, it may be safe to assume, that we want to include all actions.
- // then again, having only some tombstones may be misleading.
- if let Some(mut snapshot) = this.snapshot {
- snapshot.merge(commit.data.actions, &commit.data.operation, commit.version)?;
- Ok(DeltaTable::new_with_state(this.log_store, snapshot))
- } else {
- let mut table = DeltaTable::new(this.log_store, Default::default());
- table.update().await?;
- Ok(table)
- }
+ Ok(DeltaTable::new_with_state(this.log_store, commit.snapshot))
})
}
}
| delta-io__delta-rs-2396 | 2,396 | Does this only manifest with the schema evolution? Or are you able to see errors with append or merge writes as well?
> Does this only manifest with the schema evolution? Or are you able to see errors with append or merge writes as well?
It happens at any operation when there is concurrency and the state gets updated at the end | [
"2262"
] | 1.0 | delta-io/delta-rs | 2024-04-07T18:57:01Z | diff --git a/crates/core/tests/command_merge.rs b/crates/core/tests/command_merge.rs
--- a/crates/core/tests/command_merge.rs
+++ b/crates/core/tests/command_merge.rs
@@ -177,17 +177,7 @@ async fn test_merge_concurrent_different_partition() {
// TODO: Currently it throws a Version mismatch error, but the merge commit was successfully
// This bug needs to be fixed, see pull request #2280
- assert!(!matches!(
- result.as_ref().unwrap_err(),
- DeltaTableError::Transaction { .. }
- ));
- assert!(matches!(
- result.as_ref().unwrap_err(),
- DeltaTableError::Generic(_)
- ));
- if let DeltaTableError::Generic(msg) = result.unwrap_err() {
- assert_eq!(msg, "Version mismatch");
- }
+ assert!(matches!(result.as_ref().is_ok(), true));
}
#[tokio::test]
| Generic DeltaTable error: Version mismatch with new schema merge functionality in AWS S3
# Environment
**Delta-rs version**: python v0.16
**Binding**: ^^
**Environment**:
- **Cloud provider**: AWS s3 with dynamo
***
# Bug
**What happened**:
To test the rust engine, we cleared out any existing delta tables in our nonprod environment and switched from pyarrow over to the rust engine with schema merging, with this `write_deltalake` call:
```
write_deltalake(s3_path, table, schema=pyarrow_schema, mode="append", engine="rust", partition_by=["Uid","date","hour"], schema_mode="merge", configuration={"delta.logRetentionDuration": "interval 7 day"})
```
Despite it being a brand new Delta table and after some successful writes, eventually the lambdas started erroring with `Generic DeltaTable error: Version mismatch`. I believe the error is coming from here: https://github.com/delta-io/delta-rs/blob/3e6a4d61923602d189f559636b3e3e3f61b6a924/crates/core/src/table/state.rs#L192
**What you expected to happen**:
Especially since we are testing with a fresh table, I'd expect all writes to work (and not just some) even with the new schema merge flag set.
**How to reproduce it**:
I was not able to reproduce with a randomly generated dataset locally, so my guess is its something more to do with the dynamo locking on S3 If you have thoughts on how I could test this better, please let me know.
Note that we have roughly 10 concurrent lambdas that could potentially write to Lambda. However, before this change we had 50 writing with pyarrow and all was well.
| f2e30a0bbf58a3b56b2f912a02e10e7af0835301 | [
"test_merge_concurrent_different_partition"
] | [
"test_merge_concurrent_with_overlapping_files",
"test_merge_concurrent_conflict"
] | [] | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.