reek-rs 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/Cargo.lock +614 -0
- data/Cargo.toml +24 -0
- data/DIVERGENCES.md +15 -0
- data/LICENSE +22 -0
- data/README.md +125 -0
- data/THIRD_PARTY_NOTICES.md +57 -0
- data/crates/reek-cli/Cargo.toml +22 -0
- data/crates/reek-cli/src/main.rs +277 -0
- data/crates/reek-core/Cargo.toml +21 -0
- data/crates/reek-core/src/ast.rs +449 -0
- data/crates/reek-core/src/code_comment.rs +245 -0
- data/crates/reek-core/src/comments.rs +179 -0
- data/crates/reek-core/src/config.rs +803 -0
- data/crates/reek-core/src/context.rs +891 -0
- data/crates/reek-core/src/detectors/attribute.rs +13 -0
- data/crates/reek-core/src/detectors/boolean_parameter.rs +20 -0
- data/crates/reek-core/src/detectors/class_variable.rs +25 -0
- data/crates/reek-core/src/detectors/control_parameter.rs +110 -0
- data/crates/reek-core/src/detectors/data_clump.rs +114 -0
- data/crates/reek-core/src/detectors/duplicate_method_call.rs +63 -0
- data/crates/reek-core/src/detectors/feature_envy.rs +32 -0
- data/crates/reek-core/src/detectors/instance_variable_assumption.rs +39 -0
- data/crates/reek-core/src/detectors/irresponsible_module.rs +12 -0
- data/crates/reek-core/src/detectors/long_parameter_list.rs +16 -0
- data/crates/reek-core/src/detectors/long_yield_list.rs +20 -0
- data/crates/reek-core/src/detectors/manual_dispatch.rs +18 -0
- data/crates/reek-core/src/detectors/missing_safe_method.rs +34 -0
- data/crates/reek-core/src/detectors/mod.rs +479 -0
- data/crates/reek-core/src/detectors/module_initialize.rs +15 -0
- data/crates/reek-core/src/detectors/nested_iterators.rs +82 -0
- data/crates/reek-core/src/detectors/nil_check.rs +40 -0
- data/crates/reek-core/src/detectors/repeated_conditional.rs +51 -0
- data/crates/reek-core/src/detectors/subclassed_from_core_class.rs +22 -0
- data/crates/reek-core/src/detectors/too_many_constants.rs +18 -0
- data/crates/reek-core/src/detectors/too_many_instance_variables.rs +25 -0
- data/crates/reek-core/src/detectors/too_many_methods.rs +15 -0
- data/crates/reek-core/src/detectors/too_many_statements.rs +16 -0
- data/crates/reek-core/src/detectors/uncommunicative_method_name.rs +32 -0
- data/crates/reek-core/src/detectors/uncommunicative_module_name.rs +33 -0
- data/crates/reek-core/src/detectors/uncommunicative_parameter_name.rs +49 -0
- data/crates/reek-core/src/detectors/uncommunicative_variable_name.rs +138 -0
- data/crates/reek-core/src/detectors/unused_parameters.rs +21 -0
- data/crates/reek-core/src/detectors/unused_private_method.rs +59 -0
- data/crates/reek-core/src/detectors/utility_function.rs +27 -0
- data/crates/reek-core/src/encodings.rs +180 -0
- data/crates/reek-core/src/examiner.rs +165 -0
- data/crates/reek-core/src/lib.rs +21 -0
- data/crates/reek-core/src/node.rs +423 -0
- data/crates/reek-core/src/ruby_format.rs +60 -0
- data/crates/reek-core/src/ruby_inspect.rs +172 -0
- data/crates/reek-core/src/ruby_regexp.rs +243 -0
- data/crates/reek-core/src/single_byte_encodings.rs +6007 -0
- data/crates/reek-core/src/source.rs +280 -0
- data/crates/reek-core/src/translate.rs +3112 -0
- data/crates/reek-core/src/yaml.rs +520 -0
- data/ext/reek_rs/Cargo.toml +18 -0
- data/ext/reek_rs/extconf.rb +6 -0
- data/ext/reek_rs/src/lib.rs +155 -0
- data/lib/reek_rs/version.rb +8 -0
- data/lib/reek_rs.rb +390 -0
- metadata +123 -0
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
//! YAML loading with Psych's results (`YAML.safe_load`, Psych 5.1): plain
|
|
2
|
+
//! scalars are resolved by `Psych::ScalarScanner#tokenize`, quoted scalars
|
|
3
|
+
//! are strings, and classes `safe_load` does not permit raise.
|
|
4
|
+
//!
|
|
5
|
+
//! Reek loads `.reek.yml` with `YAML.load_file` (safe, no aliases) and
|
|
6
|
+
//! source-comment options with `YAML.safe_load(options,
|
|
7
|
+
//! permitted_classes: [Regexp])`.
|
|
8
|
+
|
|
9
|
+
use indexmap::IndexMap;
|
|
10
|
+
use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser, Tag};
|
|
11
|
+
use yaml_rust2::scanner::{Marker, TScalarStyle};
|
|
12
|
+
|
|
13
|
+
use crate::ruby_regexp::RubyRegexp;
|
|
14
|
+
|
|
15
|
+
/// A value loaded from YAML.
|
|
16
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
17
|
+
pub enum Value {
|
|
18
|
+
Nil,
|
|
19
|
+
Bool(bool),
|
|
20
|
+
Int(i64),
|
|
21
|
+
Float(f64),
|
|
22
|
+
Str(String),
|
|
23
|
+
Regexp(RubyRegexp),
|
|
24
|
+
Array(Vec<Value>),
|
|
25
|
+
/// Keys are strings: Reek's configuration keys always are.
|
|
26
|
+
Hash(IndexMap<String, Value>),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl Value {
|
|
30
|
+
/// Ruby truthiness: everything but `nil` and `false`.
|
|
31
|
+
pub fn is_truthy(&self) -> bool {
|
|
32
|
+
!matches!(self, Value::Nil | Value::Bool(false))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
pub fn as_hash(&self) -> Option<&IndexMap<String, Value>> {
|
|
36
|
+
match self {
|
|
37
|
+
Value::Hash(hash) => Some(hash),
|
|
38
|
+
_ => None,
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// The Ruby class name, for error messages.
|
|
43
|
+
pub fn class_name(&self) -> &'static str {
|
|
44
|
+
match self {
|
|
45
|
+
Value::Nil => "NilClass",
|
|
46
|
+
Value::Bool(true) => "TrueClass",
|
|
47
|
+
Value::Bool(false) => "FalseClass",
|
|
48
|
+
Value::Int(_) => "Integer",
|
|
49
|
+
Value::Float(_) => "Float",
|
|
50
|
+
Value::Str(_) => "String",
|
|
51
|
+
Value::Regexp(_) => "Regexp",
|
|
52
|
+
Value::Array(_) => "Array",
|
|
53
|
+
Value::Hash(_) => "Hash",
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// `to_s`, as string interpolation (`"#{value}"`) uses it.
|
|
58
|
+
pub fn to_s(&self) -> String {
|
|
59
|
+
match self {
|
|
60
|
+
Value::Nil => String::new(),
|
|
61
|
+
Value::Bool(value) => value.to_string(),
|
|
62
|
+
Value::Int(value) => value.to_string(),
|
|
63
|
+
Value::Float(value) => crate::ruby_format::float_to_s(*value),
|
|
64
|
+
Value::Str(value) => value.clone(),
|
|
65
|
+
Value::Regexp(regexp) => regexp.to_embedded(),
|
|
66
|
+
Value::Array(_) | Value::Hash(_) => self.inspect(),
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// `inspect` (Ruby 3.3: `{"key"=>value}`).
|
|
71
|
+
pub fn inspect(&self) -> String {
|
|
72
|
+
match self {
|
|
73
|
+
Value::Nil => "nil".to_string(),
|
|
74
|
+
Value::Str(value) => crate::ruby_inspect::string_inspect(value.as_bytes()),
|
|
75
|
+
Value::Regexp(regexp) => regexp.inspect(),
|
|
76
|
+
Value::Array(items) => format!("[{}]", items.iter().map(Value::inspect).collect::<Vec<_>>().join(", ")),
|
|
77
|
+
Value::Hash(hash) => {
|
|
78
|
+
if hash.is_empty() {
|
|
79
|
+
return "{}".to_string();
|
|
80
|
+
}
|
|
81
|
+
let pairs: Vec<String> = hash
|
|
82
|
+
.iter()
|
|
83
|
+
.map(|(key, value)| format!("{}=>{}", crate::ruby_inspect::string_inspect(key.as_bytes()), value.inspect()))
|
|
84
|
+
.collect();
|
|
85
|
+
format!("{{{}}}", pairs.join(", "))
|
|
86
|
+
}
|
|
87
|
+
other => other.to_s(),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/// Why loading failed.
|
|
93
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
94
|
+
pub enum YamlError {
|
|
95
|
+
/// `Psych::SyntaxError`.
|
|
96
|
+
Syntax(String),
|
|
97
|
+
/// `Psych::DisallowedClass`: a Symbol, Date, Time, or a tagged object.
|
|
98
|
+
DisallowedClass(String),
|
|
99
|
+
/// `Psych::AliasesNotEnabled`.
|
|
100
|
+
AliasesNotEnabled,
|
|
101
|
+
/// A mapping key that is not a string. Reek calls `to_sym` on keys,
|
|
102
|
+
/// which only strings (and symbols) have.
|
|
103
|
+
NonStringKey(String),
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
impl std::fmt::Display for YamlError {
|
|
107
|
+
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
108
|
+
match self {
|
|
109
|
+
YamlError::Syntax(message) => write!(formatter, "{message}"),
|
|
110
|
+
YamlError::DisallowedClass(class) => write!(formatter, "Tried to load unspecified class: {class}"),
|
|
111
|
+
YamlError::AliasesNotEnabled => write!(formatter, "Alias parsing was not enabled. To enable it, pass `aliases: true` to `Psych::load` or `Psych::safe_load`."),
|
|
112
|
+
YamlError::NonStringKey(key) => write!(formatter, "undefined method 'to_sym' for {key}"),
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// Loads the first document; `None` for an empty stream (Psych returns
|
|
118
|
+
/// `false` for `safe_load('')` and `nil` documents load as `nil`).
|
|
119
|
+
pub fn load(text: &str, permit_regexp: bool) -> Result<Option<Value>, YamlError> {
|
|
120
|
+
load_with(text, permit_regexp, false)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/// Like [`load`], but a mapping key that is not a string becomes its `to_s`
|
|
124
|
+
/// (Reek's configuration file validation only reads keys as text).
|
|
125
|
+
pub fn load_with_key_text(text: &str, permit_regexp: bool) -> Result<Option<Value>, YamlError> {
|
|
126
|
+
load_with(text, permit_regexp, true)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
fn load_with(text: &str, permit_regexp: bool, keys_as_text: bool) -> Result<Option<Value>, YamlError> {
|
|
130
|
+
let mut collector = Collector { events: Vec::new(), markers: Vec::new() };
|
|
131
|
+
let mut parser = Parser::new_from_str(text);
|
|
132
|
+
parser.load(&mut collector, false).map_err(|error| YamlError::Syntax(error.to_string()))?;
|
|
133
|
+
let chars: Vec<char> = text.chars().collect();
|
|
134
|
+
let first_chars = collector.markers.iter().map(|marker| chars.get(marker.index()).copied()).collect();
|
|
135
|
+
let mut builder =
|
|
136
|
+
Builder { events: collector.events, first_chars, position: 0, flow_depth: 0, permit_regexp, keys_as_text };
|
|
137
|
+
while let Some(event) = builder.next_event() {
|
|
138
|
+
if let Event::DocumentStart = event {
|
|
139
|
+
return builder.build().map(Some);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
Ok(None)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
struct Collector {
|
|
146
|
+
events: Vec<Event>,
|
|
147
|
+
markers: Vec<Marker>,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
impl MarkedEventReceiver for Collector {
|
|
151
|
+
fn on_event(&mut self, event: Event, mark: Marker) {
|
|
152
|
+
self.events.push(event);
|
|
153
|
+
self.markers.push(mark);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
struct Builder {
|
|
158
|
+
events: Vec<Event>,
|
|
159
|
+
/// Per event: the source character it starts at.
|
|
160
|
+
first_chars: Vec<Option<char>>,
|
|
161
|
+
position: usize,
|
|
162
|
+
/// How many flow collections enclose the current event.
|
|
163
|
+
flow_depth: usize,
|
|
164
|
+
permit_regexp: bool,
|
|
165
|
+
/// Mapping keys that are not strings become their `to_s`.
|
|
166
|
+
keys_as_text: bool,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
impl Builder {
|
|
170
|
+
fn next_event(&mut self) -> Option<Event> {
|
|
171
|
+
let event = self.events.get(self.position).cloned();
|
|
172
|
+
self.position += 1;
|
|
173
|
+
event
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
fn build(&mut self) -> Result<Value, YamlError> {
|
|
177
|
+
// Block collections cannot be nested in flow collections.
|
|
178
|
+
let is_flow = self.flow_depth > 0 || matches!(self.first_chars.get(self.position), Some(Some('{' | '[')));
|
|
179
|
+
match self.next_event() {
|
|
180
|
+
Some(Event::Scalar(text, style, _anchor, tag)) => {
|
|
181
|
+
// libyaml reads `:` in a flow collection as the value
|
|
182
|
+
// indicator, so a plain scalar cannot start with it there.
|
|
183
|
+
if self.flow_depth > 0 && style == TScalarStyle::Plain && text.starts_with(':') {
|
|
184
|
+
return Err(YamlError::Syntax("did not find expected node content while parsing a flow node".to_string()));
|
|
185
|
+
}
|
|
186
|
+
self.scalar(&text, style, tag.as_ref())
|
|
187
|
+
}
|
|
188
|
+
Some(Event::SequenceStart(_anchor, tag)) => {
|
|
189
|
+
self.check_collection_tag(tag.as_ref(), "seq")?;
|
|
190
|
+
self.flow_depth += usize::from(is_flow);
|
|
191
|
+
let mut items = Vec::new();
|
|
192
|
+
while !self.at(&Event::SequenceEnd) {
|
|
193
|
+
if self.flow_depth > 0 && self.take_explicit_key_indicator() {
|
|
194
|
+
// `[ ?b ]`: a single-pair mapping with a `nil` value.
|
|
195
|
+
let key = self.build()?;
|
|
196
|
+
items.push(Value::Hash(IndexMap::from([(self.hash_key(key)?, Value::Nil)])));
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
items.push(self.build()?);
|
|
200
|
+
}
|
|
201
|
+
self.position += 1;
|
|
202
|
+
self.flow_depth -= usize::from(is_flow);
|
|
203
|
+
Ok(Value::Array(items))
|
|
204
|
+
}
|
|
205
|
+
Some(Event::MappingStart(_anchor, tag)) => {
|
|
206
|
+
self.check_collection_tag(tag.as_ref(), "map")?;
|
|
207
|
+
self.flow_depth += usize::from(is_flow);
|
|
208
|
+
let mut hash = IndexMap::new();
|
|
209
|
+
while !self.at(&Event::MappingEnd) {
|
|
210
|
+
if self.flow_depth > 0 {
|
|
211
|
+
self.take_explicit_key_indicator();
|
|
212
|
+
if self.at_empty_node() {
|
|
213
|
+
return Err(YamlError::Syntax("did not find expected node content while parsing a flow node".to_string()));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
let key = self.build()?;
|
|
217
|
+
if self.flow_depth > 0 && self.take_explicit_key_indicator() {
|
|
218
|
+
return Err(YamlError::Syntax("did not find expected node content while parsing a flow node".to_string()));
|
|
219
|
+
}
|
|
220
|
+
let value = self.build()?;
|
|
221
|
+
hash.insert(self.hash_key(key)?, value);
|
|
222
|
+
}
|
|
223
|
+
self.position += 1;
|
|
224
|
+
self.flow_depth -= usize::from(is_flow);
|
|
225
|
+
Ok(Value::Hash(hash))
|
|
226
|
+
}
|
|
227
|
+
Some(Event::Alias(_)) => Err(YamlError::AliasesNotEnabled),
|
|
228
|
+
Some(Event::DocumentEnd) | None => Ok(Value::Nil),
|
|
229
|
+
Some(other) => Err(YamlError::Syntax(format!("unexpected event {other:?}"))),
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// libyaml reads `?` in a flow collection as the explicit key indicator
|
|
234
|
+
/// even when a non-blank follows, where yaml-rust2 reads a plain scalar
|
|
235
|
+
/// starting with `?`. When the next event is such a scalar, removes the
|
|
236
|
+
/// `?` from it and returns `true`.
|
|
237
|
+
fn take_explicit_key_indicator(&mut self) -> bool {
|
|
238
|
+
match self.events.get_mut(self.position) {
|
|
239
|
+
Some(Event::Scalar(text, TScalarStyle::Plain, _, None)) if text.len() > 1 && text.starts_with('?') => {
|
|
240
|
+
text.remove(0);
|
|
241
|
+
true
|
|
242
|
+
}
|
|
243
|
+
_ => false,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/// A mapping key: Reek calls `to_sym` on comment option keys, which only
|
|
248
|
+
/// strings have.
|
|
249
|
+
fn hash_key(&self, key: Value) -> Result<String, YamlError> {
|
|
250
|
+
match key {
|
|
251
|
+
Value::Str(key) => Ok(key),
|
|
252
|
+
other if self.keys_as_text => Ok(other.to_s()),
|
|
253
|
+
other => Err(YamlError::NonStringKey(other.inspect())),
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/// Whether the next event is an empty node, which yaml-rust2 emits as an
|
|
258
|
+
/// empty plain scalar. libyaml does not allow empty keys in flow
|
|
259
|
+
/// collections.
|
|
260
|
+
fn at_empty_node(&self) -> bool {
|
|
261
|
+
matches!(self.events.get(self.position), Some(Event::Scalar(text, TScalarStyle::Plain, _, None)) if text.is_empty())
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/// Whether the next event is `event` (the end of a collection).
|
|
265
|
+
fn at(&self, event: &Event) -> bool {
|
|
266
|
+
self.events.get(self.position).is_none_or(|next| next == event)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
fn check_collection_tag(&self, tag: Option<&Tag>, kind: &str) -> Result<(), YamlError> {
|
|
270
|
+
match tag {
|
|
271
|
+
None => Ok(()),
|
|
272
|
+
Some(tag) if tag.handle == "tag:yaml.org,2002:" && tag.suffix == kind => Ok(()),
|
|
273
|
+
Some(tag) if tag.handle == "!!" && tag.suffix == kind => Ok(()),
|
|
274
|
+
Some(tag) => Err(YamlError::DisallowedClass(format!("{}{}", tag.handle, tag.suffix))),
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
fn scalar(&self, text: &str, style: TScalarStyle, tag: Option<&Tag>) -> Result<Value, YamlError> {
|
|
279
|
+
if let Some(tag) = tag {
|
|
280
|
+
let name = format!("{}{}", tag.handle, tag.suffix);
|
|
281
|
+
return match name.as_str() {
|
|
282
|
+
"!ruby/regexp" if self.permit_regexp => regexp_from_tag(text),
|
|
283
|
+
"!ruby/regexp" => Err(YamlError::DisallowedClass("Regexp".to_string())),
|
|
284
|
+
"!!str" | "tag:yaml.org,2002:str" | "!" => Ok(Value::Str(text.to_string())),
|
|
285
|
+
"!!int" | "tag:yaml.org,2002:int" => match tokenize(text)? {
|
|
286
|
+
Value::Int(value) => Ok(Value::Int(value)),
|
|
287
|
+
_ => Ok(Value::Str(text.to_string())),
|
|
288
|
+
},
|
|
289
|
+
"!!float" | "tag:yaml.org,2002:float" => Ok(match tokenize(text)? {
|
|
290
|
+
Value::Int(value) => Value::Float(value as f64),
|
|
291
|
+
other => other,
|
|
292
|
+
}),
|
|
293
|
+
_ => Err(YamlError::DisallowedClass(name)),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
match style {
|
|
297
|
+
TScalarStyle::Plain => tokenize(text),
|
|
298
|
+
_ => Ok(Value::Str(text.to_string())),
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
/// `!ruby/regexp /source/options`.
|
|
305
|
+
fn regexp_from_tag(text: &str) -> Result<Value, YamlError> {
|
|
306
|
+
let pattern = RubyRegexp::new(r"\A/(.*)/([mixn]*)\z", "m").expect("tag pattern");
|
|
307
|
+
let Some(groups) = pattern.captures(text.as_bytes()) else {
|
|
308
|
+
return Err(YamlError::Syntax(format!("invalid regexp tag {text}")));
|
|
309
|
+
};
|
|
310
|
+
let slice = |group: Option<(usize, usize)>| group.map_or("", |(start, end)| &text[start..end]);
|
|
311
|
+
let source = slice(groups[1]);
|
|
312
|
+
let options: String = slice(groups[2]).chars().filter(|option| "mix".contains(*option)).collect();
|
|
313
|
+
RubyRegexp::new(source, &options).map(Value::Regexp).map_err(YamlError::Syntax)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
fn matches(pattern: &str, options: &str, text: &str) -> bool {
|
|
317
|
+
RubyRegexp::new(pattern, options).expect("Psych pattern").is_match(text.as_bytes())
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/// `Psych::ScalarScanner#tokenize` for a plain scalar, with the safe class
|
|
321
|
+
/// loader (Symbols, Dates and Times are disallowed).
|
|
322
|
+
pub fn tokenize(string: &str) -> Result<Value, YamlError> {
|
|
323
|
+
const TIME: &str = r"^-?\d{4}-\d{1,2}-\d{1,2}(?:[Tt]|\s+)\d{1,2}:\d\d:\d\d(?:\.\d*)?(?:\s*(?:Z|[-+]\d{1,2}:?(?:\d\d)?))?$";
|
|
324
|
+
const FLOAT: &str = r"^(?:[-+]?([0-9][0-9_,]*)?\.[0-9]*([eE][-+][0-9]+)?)$";
|
|
325
|
+
const INTEGER_LEGACY: &str =
|
|
326
|
+
r"^(?:[-+]?0b[0-1_,]+|[-+]?0[0-7_,]+|[-+]?(?:0|[1-9](?:[0-9]|,[0-9]|_[0-9])*)|[-+]?0x[0-9a-fA-F_,]+)$";
|
|
327
|
+
if string.is_empty() {
|
|
328
|
+
return Ok(Value::Nil);
|
|
329
|
+
}
|
|
330
|
+
if matches(r"^[^\d.:-]?[[:alpha:]_\s!@#$%\^&*(){}<>|/\\~;=]+", "", string) || string.contains('\n') {
|
|
331
|
+
if string.chars().count() > 5 {
|
|
332
|
+
return Ok(Value::Str(string.to_string()));
|
|
333
|
+
}
|
|
334
|
+
return Ok(if matches(r"^[^ytonf~]", "i", string) {
|
|
335
|
+
Value::Str(string.to_string())
|
|
336
|
+
} else if string == "~" || matches(r"^null$", "i", string) {
|
|
337
|
+
Value::Nil
|
|
338
|
+
} else if matches(r"^(yes|true|on)$", "i", string) {
|
|
339
|
+
Value::Bool(true)
|
|
340
|
+
} else if matches(r"^(no|false|off)$", "i", string) {
|
|
341
|
+
Value::Bool(false)
|
|
342
|
+
} else {
|
|
343
|
+
Value::Str(string.to_string())
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
if matches(TIME, "", string) {
|
|
347
|
+
return Err(YamlError::DisallowedClass("Time".to_string()));
|
|
348
|
+
}
|
|
349
|
+
if matches(r"^\d{4}-(?:1[012]|0\d|\d)-(?:[12]\d|3[01]|0\d|\d)$", "", string) {
|
|
350
|
+
return Err(YamlError::DisallowedClass("Date".to_string()));
|
|
351
|
+
}
|
|
352
|
+
if matches(r"^\+?\.inf$", "i", string) {
|
|
353
|
+
return Ok(Value::Float(f64::INFINITY));
|
|
354
|
+
}
|
|
355
|
+
if matches(r"^-\.inf$", "i", string) {
|
|
356
|
+
return Ok(Value::Float(f64::NEG_INFINITY));
|
|
357
|
+
}
|
|
358
|
+
if matches(r"^\.nan$", "i", string) {
|
|
359
|
+
return Ok(Value::Float(f64::NAN));
|
|
360
|
+
}
|
|
361
|
+
if matches(r"^:.", "", string) {
|
|
362
|
+
return Err(YamlError::DisallowedClass("Symbol".to_string()));
|
|
363
|
+
}
|
|
364
|
+
if matches(r"^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}$", "", string) {
|
|
365
|
+
return Ok(Value::Int(sexagesimal(string) as i64));
|
|
366
|
+
}
|
|
367
|
+
if matches(r"^[-+]?[0-9][0-9_]*(:[0-5]?[0-9]){1,2}\.[0-9_]*$", "", string) {
|
|
368
|
+
return Ok(Value::Float(sexagesimal(string)));
|
|
369
|
+
}
|
|
370
|
+
if matches(FLOAT, "", string) {
|
|
371
|
+
if matches(r"\A[-+]?\.\Z", "", string) {
|
|
372
|
+
return Ok(Value::Str(string.to_string()));
|
|
373
|
+
}
|
|
374
|
+
let cleaned: String = string.chars().filter(|character| !matches!(character, ',' | '_')).collect();
|
|
375
|
+
// `.gsub(/\.([Ee]|$)/, '\1')`
|
|
376
|
+
let cleaned = cleaned.replace(".e", "e").replace(".E", "E");
|
|
377
|
+
let cleaned = cleaned.strip_suffix('.').unwrap_or(&cleaned);
|
|
378
|
+
return cleaned.parse::<f64>().map(Value::Float).map_err(|_| YamlError::Syntax(format!("invalid value for Float(): {string:?}")));
|
|
379
|
+
}
|
|
380
|
+
if matches(INTEGER_LEGACY, "", string) {
|
|
381
|
+
return parse_int(string);
|
|
382
|
+
}
|
|
383
|
+
Ok(Value::Str(string.to_string()))
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/// `n.to_i * 60 ** (e - 2).abs` summed over the `:`-separated parts.
|
|
387
|
+
fn sexagesimal(string: &str) -> f64 {
|
|
388
|
+
let parts: Vec<&str> = string.split(':').collect();
|
|
389
|
+
parts
|
|
390
|
+
.iter()
|
|
391
|
+
.enumerate()
|
|
392
|
+
.map(|(index, part)| {
|
|
393
|
+
let digits: String = part.chars().filter(|character| *character != '_').collect();
|
|
394
|
+
let value: f64 = leading_number(&digits);
|
|
395
|
+
value * 60f64.powi((index as i32 - 2).abs())
|
|
396
|
+
})
|
|
397
|
+
.sum()
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/// `String#to_f` (and `to_i`) of a leading number.
|
|
401
|
+
fn leading_number(text: &str) -> f64 {
|
|
402
|
+
let end = text
|
|
403
|
+
.char_indices()
|
|
404
|
+
.find(|(index, character)| !(character.is_ascii_digit() || *character == '.' || (*index == 0 && "+-".contains(*character))))
|
|
405
|
+
.map_or(text.len(), |(index, _)| index);
|
|
406
|
+
text[..end].parse().unwrap_or(0.0)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/// `Integer(string.delete(',_'))`: decimal, `0b`, `0x`, or octal with a
|
|
410
|
+
/// leading `0`.
|
|
411
|
+
fn parse_int(string: &str) -> Result<Value, YamlError> {
|
|
412
|
+
let cleaned: String = string.chars().filter(|character| !matches!(character, ',' | '_')).collect();
|
|
413
|
+
let (negative, digits) = match cleaned.strip_prefix('-') {
|
|
414
|
+
Some(rest) => (true, rest),
|
|
415
|
+
None => (false, cleaned.strip_prefix('+').unwrap_or(&cleaned)),
|
|
416
|
+
};
|
|
417
|
+
let parsed = if let Some(binary) = digits.strip_prefix("0b") {
|
|
418
|
+
i64::from_str_radix(binary, 2)
|
|
419
|
+
} else if let Some(hex) = digits.strip_prefix("0x") {
|
|
420
|
+
i64::from_str_radix(hex, 16)
|
|
421
|
+
} else if digits.len() > 1 && digits.starts_with('0') {
|
|
422
|
+
i64::from_str_radix(&digits[1..], 8)
|
|
423
|
+
} else {
|
|
424
|
+
digits.parse()
|
|
425
|
+
};
|
|
426
|
+
match parsed {
|
|
427
|
+
Ok(value) => Ok(Value::Int(if negative { -value } else { value })),
|
|
428
|
+
Err(_) => Err(YamlError::Syntax(format!("invalid value for Integer(): {string:?}"))),
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
#[cfg(test)]
|
|
433
|
+
mod tests {
|
|
434
|
+
use super::*;
|
|
435
|
+
|
|
436
|
+
fn token(text: &str) -> String {
|
|
437
|
+
match tokenize(text) {
|
|
438
|
+
Ok(value) => format!("{}:{}", value.class_name(), value.inspect()),
|
|
439
|
+
Err(error) => format!("error:{error}"),
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
#[test]
|
|
444
|
+
fn scalars_resolve_as_psych_does() {
|
|
445
|
+
let cases = [
|
|
446
|
+
("yes", "TrueClass:true"),
|
|
447
|
+
("NO", "FalseClass:false"),
|
|
448
|
+
("Off", "FalseClass:false"),
|
|
449
|
+
("y", "String:\"y\""),
|
|
450
|
+
("~", "NilClass:nil"),
|
|
451
|
+
("Null", "NilClass:nil"),
|
|
452
|
+
("0x1f", "Integer:31"),
|
|
453
|
+
("0o17", "String:\"0o17\""),
|
|
454
|
+
("017", "Integer:15"),
|
|
455
|
+
("0b101", "Integer:5"),
|
|
456
|
+
("1_000", "Integer:1000"),
|
|
457
|
+
("1,000", "Integer:1000"),
|
|
458
|
+
("+5", "Integer:5"),
|
|
459
|
+
("1.5", "Float:1.5"),
|
|
460
|
+
(".5", "Float:0.5"),
|
|
461
|
+
("1e3", "String:\"1e3\""),
|
|
462
|
+
("12:30:45", "Integer:45045"),
|
|
463
|
+
("08", "String:\"08\""),
|
|
464
|
+
("/foo/", "String:\"/foo/\""),
|
|
465
|
+
("enabled", "String:\"enabled\""),
|
|
466
|
+
(":sym", "error:Tried to load unspecified class: Symbol"),
|
|
467
|
+
("2020-01-01", "error:Tried to load unspecified class: Date"),
|
|
468
|
+
];
|
|
469
|
+
for (text, expected) in cases {
|
|
470
|
+
assert_eq!(token(text), expected, "{text}");
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
#[test]
|
|
475
|
+
fn loads_flow_mappings() {
|
|
476
|
+
let value = load("{ max_statements: 6, exclude: [foo, '/bar/'] }", true).unwrap().unwrap();
|
|
477
|
+
assert_eq!(value.inspect(), "{\"max_statements\"=>6, \"exclude\"=>[\"foo\", \"/bar/\"]}");
|
|
478
|
+
let value = load("{ accept: !ruby/regexp /^x/i }", true).unwrap().unwrap();
|
|
479
|
+
assert_eq!(value.inspect(), "{\"accept\"=>/^x/i}");
|
|
480
|
+
assert!(load("{ a: [", true).is_err());
|
|
481
|
+
assert!(load("", true).unwrap().is_none());
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
#[test]
|
|
485
|
+
fn flow_collections_load_as_psych_does() {
|
|
486
|
+
let cases: [(&str, &str); 23] = [
|
|
487
|
+
("{ :a }", "SyntaxError"),
|
|
488
|
+
("{ :a: 1 }", "SyntaxError"),
|
|
489
|
+
("[ :a ]", "SyntaxError"),
|
|
490
|
+
("{ a: [:b, c] }", "SyntaxError"),
|
|
491
|
+
("{ ?a: 1 }", "{\"a\"=>1}"),
|
|
492
|
+
("{ a: ?b }", "SyntaxError"),
|
|
493
|
+
("[ ?b ]", "[{\"b\"=>nil}]"),
|
|
494
|
+
("[ ?b: c ]", "[{\"b\"=>\"c\"}]"),
|
|
495
|
+
("{ : b }", "SyntaxError"),
|
|
496
|
+
("[ : b ]", "SyntaxError"),
|
|
497
|
+
("{ a: }", "{\"a\"=>nil}"),
|
|
498
|
+
("{ a, ~: 1 }", "NonStringKey(\"nil\")"),
|
|
499
|
+
("{ a: b, :c }", "SyntaxError"),
|
|
500
|
+
("{ a: :}", "SyntaxError"),
|
|
501
|
+
("[a, :]", "SyntaxError"),
|
|
502
|
+
("{ a: 1, ? b : c }", "{\"a\"=>1, \"b\"=>\"c\"}"),
|
|
503
|
+
("{ a: x:y }", "{\"a\"=>\"x:y\"}"),
|
|
504
|
+
("{a: b :c}", "{\"a\"=>\"b :c\"}"),
|
|
505
|
+
("{ a: -:x }", "{\"a\"=>\"-:x\"}"),
|
|
506
|
+
("{ enabled: false }", "{\"enabled\"=>false}"),
|
|
507
|
+
("{ max: 0x1f, b: 1_000, c: 1.5, d: .inf, e: ~, f: yes, g: no, h: 012 }", "{\"max\"=>31, \"b\"=>1000, \"c\"=>1.5, \"d\"=>Infinity, \"e\"=>nil, \"f\"=>true, \"g\"=>false, \"h\"=>10}"),
|
|
508
|
+
("{ a: \"x\" }", "{\"a\"=>\"x\"}"),
|
|
509
|
+
("{ a: [1, [2, 3]] }", "{\"a\"=>[1, [2, 3]]}"),
|
|
510
|
+
];
|
|
511
|
+
for (text, expected) in cases {
|
|
512
|
+
let actual = match load(text, true) {
|
|
513
|
+
Ok(value) => value.map_or("nil".to_string(), |value| value.inspect()),
|
|
514
|
+
Err(YamlError::Syntax(_)) => "SyntaxError".to_string(),
|
|
515
|
+
Err(error) => format!("{error:?}"),
|
|
516
|
+
};
|
|
517
|
+
assert_eq!(actual, expected, "{text}");
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "reek_rs"
|
|
3
|
+
version.workspace = true
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
authors.workspace = true
|
|
8
|
+
homepage.workspace = true
|
|
9
|
+
repository.workspace = true
|
|
10
|
+
publish = false
|
|
11
|
+
|
|
12
|
+
[lib]
|
|
13
|
+
crate-type = ["cdylib"]
|
|
14
|
+
|
|
15
|
+
[dependencies]
|
|
16
|
+
reek-core = { path = "../../crates/reek-core" }
|
|
17
|
+
magnus = "0.9"
|
|
18
|
+
rayon.workspace = true
|