Create Record type (#10103)

# Description
This PR creates a new `Record` type to reduce duplicate code and
possibly bugs as well. (This is an edited version of #9648.)
- `Record` implements `FromIterator` and `IntoIterator` and so can be
iterated over or collected into. For example, this helps with
conversions to and from (hash)maps. (Also, no more
`cols.iter().zip(vals)`!)
- `Record` has a `push(col, val)` function to help insure that the
number of columns is equal to the number of values. I caught a few
potential bugs thanks to this (e.g. in the `ls` command).
- Finally, this PR also adds a `record!` macro that helps simplify
record creation. It is used like so:
   ```rust
   record! {
       "key1" => some_value,
       "key2" => Value::string("text", span),
       "key3" => Value::int(optional_int.unwrap_or(0), span),
       "key4" => Value::bool(config.setting, span),
   }
   ```
Since macros hinder formatting, etc., the right hand side values should
be relatively short and sweet like the examples above.

Where possible, prefer `record!` or `.collect()` on an iterator instead
of multiple `Record::push`s, since the first two automatically set the
record capacity and do less work overall.

# User-Facing Changes
Besides the changes in `nu-protocol` the only other breaking changes are
to `nu-table::{ExpandedTable::build_map, JustTable::kv_table}`.
This commit is contained in:
Ian Manske
2023-08-24 19:50:29 +00:00
committed by GitHub
parent 030e749fe7
commit 8da27a1a09
195 changed files with 4211 additions and 6245 deletions

View File

@ -4,11 +4,11 @@ use std::collections::HashSet;
pub fn get_columns(input: &[Value]) -> Vec<String> {
let mut columns = vec![];
for item in input {
let Value::Record { cols, .. } = item else {
let Value::Record { val, .. } = item else {
return vec![];
};
for col in cols {
for col in &val.cols {
if !columns.contains(col) {
columns.push(col.to_string());
}

View File

@ -1,7 +1,7 @@
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack},
Category, Example, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Value,
record, Category, Example, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Value,
};
use std::{collections::HashMap, fmt::Write};
@ -210,14 +210,13 @@ fn get_documentation(
let span = Span::unknown();
let mut vals = vec![];
for (input, output) in &sig.input_output_types {
vals.push(Value::Record {
cols: vec!["input".into(), "output".into()],
vals: vec![
Value::string(input.to_string(), span),
Value::string(output.to_string(), span),
],
vals.push(Value::record(
record! {
"input" => Value::string(input.to_string(), span),
"output" => Value::string(output.to_string(), span),
},
span,
});
));
}
let mut caller_stack = Stack::new();

View File

@ -6,8 +6,9 @@ use nu_protocol::{
Operator, PathMember, PipelineElement, Redirection,
},
engine::{EngineState, ProfilingConfig, Stack},
DataSource, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, PipelineMetadata,
Range, ShellError, Span, Spanned, Unit, Value, VarId, ENV_VARIABLE_ID,
record, DataSource, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
PipelineMetadata, Range, Record, ShellError, Span, Spanned, Unit, Value, VarId,
ENV_VARIABLE_ID,
};
use std::time::Instant;
use std::{collections::HashMap, path::PathBuf};
@ -588,12 +589,12 @@ pub fn eval_expression(
})
}
Expr::Record(fields) => {
let mut cols = vec![];
let mut vals = vec![];
let mut record = Record::new();
for (col, val) in fields {
// avoid duplicate cols.
let col_name = eval_expression(engine_state, stack, col)?.as_string()?;
let pos = cols.iter().position(|c| c == &col_name);
let pos = record.cols.iter().position(|c| c == &col_name);
match pos {
Some(index) => {
return Err(ShellError::ColumnDefinedTwice {
@ -602,17 +603,12 @@ pub fn eval_expression(
})
}
None => {
cols.push(col_name);
vals.push(eval_expression(engine_state, stack, val)?);
record.push(col_name, eval_expression(engine_state, stack, val)?);
}
}
}
Ok(Value::Record {
cols,
vals,
span: expr.span,
})
Ok(Value::record(record, expr.span))
}
Expr::Table(headers, vals) => {
let mut output_headers = vec![];
@ -626,11 +622,13 @@ pub fn eval_expression(
for expr in val {
row.push(eval_expression(engine_state, stack, expr)?);
}
output_rows.push(Value::Record {
cols: output_headers.clone(),
vals: row,
span: expr.span,
});
output_rows.push(Value::record(
Record {
cols: output_headers.clone(),
vals: row,
},
expr.span,
));
}
Ok(Value::List {
vals: output_rows,
@ -1241,201 +1239,154 @@ pub fn eval_nu_variable(engine_state: &EngineState, span: Span) -> Result<Value,
}
}
let mut cols = vec![];
let mut vals = vec![];
let mut record = Record::new();
cols.push("default-config-dir".to_string());
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
vals.push(Value::String {
val: path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError("Could not get config directory".into())),
})
}
record.push(
"default-config-dir",
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
Value::string(path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError("Could not get config directory".into()))
},
);
cols.push("config-path".to_string());
if let Some(path) = engine_state.get_config_path("config-path") {
let canon_config_path = canonicalize_path(engine_state, path);
vals.push(Value::String {
val: canon_config_path.to_string_lossy().to_string(),
span,
})
} else if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("config.nu");
vals.push(Value::String {
val: path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError("Could not get config directory".into())),
})
}
record.push(
"config-path",
if let Some(path) = engine_state.get_config_path("config-path") {
let canon_config_path = canonicalize_path(engine_state, path);
Value::string(canon_config_path.to_string_lossy(), span)
} else if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("config.nu");
Value::string(path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError("Could not get config directory".into()))
},
);
cols.push("env-path".to_string());
if let Some(path) = engine_state.get_config_path("env-path") {
let canon_env_path = canonicalize_path(engine_state, path);
vals.push(Value::String {
val: canon_env_path.to_string_lossy().to_string(),
span,
})
} else if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("env.nu");
vals.push(Value::String {
val: path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError(
record.push(
"env-path",
if let Some(path) = engine_state.get_config_path("env-path") {
let canon_env_path = canonicalize_path(engine_state, path);
Value::string(canon_env_path.to_string_lossy(), span)
} else if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("env.nu");
Value::string(path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError(
"Could not find environment path".into(),
)),
})
}
))
},
);
cols.push("history-path".to_string());
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
match engine_state.config.history_file_format {
nu_protocol::HistoryFileFormat::Sqlite => {
path.push("history.sqlite3");
record.push(
"history-path",
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
match engine_state.config.history_file_format {
nu_protocol::HistoryFileFormat::Sqlite => {
path.push("history.sqlite3");
}
nu_protocol::HistoryFileFormat::PlainText => {
path.push("history.txt");
}
}
nu_protocol::HistoryFileFormat::PlainText => {
path.push("history.txt");
}
}
let canon_hist_path = canonicalize_path(engine_state, &path);
vals.push(Value::String {
val: canon_hist_path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError("Could not find history path".into())),
})
}
let canon_hist_path = canonicalize_path(engine_state, &path);
Value::string(canon_hist_path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError("Could not find history path".into()))
},
);
cols.push("loginshell-path".to_string());
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("login.nu");
let canon_login_path = canonicalize_path(engine_state, &path);
vals.push(Value::String {
val: canon_login_path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError(
record.push(
"loginshell-path",
if let Some(mut path) = nu_path::config_dir() {
path.push("nushell");
path.push("login.nu");
let canon_login_path = canonicalize_path(engine_state, &path);
Value::string(canon_login_path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError(
"Could not find login shell path".into(),
)),
})
}
))
},
);
#[cfg(feature = "plugin")]
{
cols.push("plugin-path".to_string());
if let Some(path) = &engine_state.plugin_signatures {
let canon_plugin_path = canonicalize_path(engine_state, path);
vals.push(Value::String {
val: canon_plugin_path.to_string_lossy().to_string(),
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError(
record.push(
"plugin-path",
if let Some(path) = &engine_state.plugin_signatures {
let canon_plugin_path = canonicalize_path(engine_state, path);
Value::string(canon_plugin_path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError(
"Could not get plugin signature location".into(),
)),
})
}
))
},
);
}
cols.push("home-path".to_string());
if let Some(path) = nu_path::home_dir() {
let canon_home_path = canonicalize_path(engine_state, &path);
vals.push(Value::String {
val: canon_home_path.to_string_lossy().into(),
record.push(
"home-path",
if let Some(path) = nu_path::home_dir() {
let canon_home_path = canonicalize_path(engine_state, &path);
Value::string(canon_home_path.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError("Could not get home path".into()))
},
);
record.push("temp-path", {
let canon_temp_path = canonicalize_path(engine_state, &std::env::temp_dir());
Value::string(canon_temp_path.to_string_lossy(), span)
});
record.push("pid", Value::int(std::process::id().into(), span));
record.push("os-info", {
let sys = sysinfo::System::new();
let ver = match sys.kernel_version() {
Some(v) => v,
None => "unknown".into(),
};
Value::record(
record! {
"name" => Value::string(std::env::consts::OS, span),
"arch" => Value::string(std::env::consts::ARCH, span),
"family" => Value::string(std::env::consts::FAMILY, span),
"kernel_version" => Value::string(ver, span),
},
span,
})
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError("Could not get home path".into())),
})
}
cols.push("temp-path".to_string());
let canon_temp_path = canonicalize_path(engine_state, &std::env::temp_dir());
vals.push(Value::String {
val: canon_temp_path.to_string_lossy().into(),
span,
)
});
cols.push("pid".to_string());
vals.push(Value::int(std::process::id().into(), span));
record.push(
"startup-time",
Value::duration(engine_state.get_startup_time(), span),
);
cols.push("os-info".to_string());
let sys = sysinfo::System::new();
let ver = match sys.kernel_version() {
Some(v) => v,
None => "unknown".into(),
};
let os_record = Value::Record {
cols: vec![
"name".into(),
"arch".into(),
"family".into(),
"kernel_version".into(),
],
vals: vec![
Value::string(std::env::consts::OS, span),
Value::string(std::env::consts::ARCH, span),
Value::string(std::env::consts::FAMILY, span),
Value::string(ver, span),
],
span,
};
vals.push(os_record);
record.push(
"is-interactive",
Value::bool(engine_state.is_interactive, span),
);
cols.push("startup-time".to_string());
vals.push(Value::Duration {
val: engine_state.get_startup_time(),
span,
});
record.push("is-login", Value::bool(engine_state.is_login, span));
cols.push("is-interactive".to_string());
vals.push(Value::Bool {
val: engine_state.is_interactive,
span,
});
cols.push("is-login".to_string());
vals.push(Value::Bool {
val: engine_state.is_login,
span,
});
cols.push("current-exe".to_string());
if let Ok(current_exe) = std::env::current_exe() {
vals.push(Value::String {
val: current_exe.to_string_lossy().into(),
span,
});
} else {
vals.push(Value::Error {
error: Box::new(ShellError::IOError(
record.push(
"current-exe",
if let Ok(current_exe) = std::env::current_exe() {
Value::string(current_exe.to_string_lossy(), span)
} else {
Value::error(ShellError::IOError(
"Could not get current executable path".to_string(),
)),
})
}
))
},
);
Ok(Value::Record { cols, vals, span })
Ok(Value::record(record, span))
}
pub fn eval_variable(
@ -1459,13 +1410,7 @@ pub fn eval_variable(
pairs.sort_by(|a, b| a.0.cmp(&b.0));
let (env_columns, env_values) = pairs.into_iter().unzip();
Ok(Value::Record {
cols: env_columns,
vals: env_values,
span,
})
Ok(Value::record(pairs.into_iter().collect(), span))
}
var_id => stack.get_var(var_id, span),
}
@ -1490,30 +1435,20 @@ fn collect_profiling_metadata(
let element_str = Value::string(element_str, element_span);
let time_ns = (end_time - start_time).as_nanos() as i64;
let mut cols = vec![
"pipeline_idx".to_string(),
"element_idx".to_string(),
"depth".to_string(),
"span".to_string(),
];
let span_record = record! {
"start" => Value::int(element_span.start as i64, element_span),
"end" => Value::int(element_span.end as i64, element_span),
};
let mut vals = vec![
Value::int(pipeline_idx as i64, element_span),
Value::int(element_idx as i64, element_span),
Value::int(profiling_config.depth, element_span),
Value::record(
vec!["start".to_string(), "end".to_string()],
vec![
Value::int(element_span.start as i64, element_span),
Value::int(element_span.end as i64, element_span),
],
element_span,
),
];
let mut record = record! {
"pipeline_idx" => Value::int(pipeline_idx as i64, element_span),
"element_idx" => Value::int(element_idx as i64, element_span),
"depth" => Value::int(profiling_config.depth, element_span),
"span" => Value::record(span_record, element_span),
};
if profiling_config.collect_source {
cols.push("source".to_string());
vals.push(element_str);
record.push("source", element_str);
}
if profiling_config.collect_values {
@ -1529,21 +1464,12 @@ fn collect_profiling_metadata(
},
};
cols.push("value".to_string());
vals.push(value);
record.push("value", value);
}
cols.push("time".to_string());
vals.push(Value::Duration {
val: time_ns,
span: element_span,
});
record.push("time", Value::duration(time_ns, element_span));
let record = Value::Record {
cols,
vals,
span: element_span,
};
let record = Value::record(record, element_span);
let element_metadata = if let Ok((pipeline_data, ..)) = &eval_result {
pipeline_data.metadata()

View File

@ -1,7 +1,7 @@
use nu_protocol::{
ast::Expr,
engine::{Command, EngineState, Stack, Visibility},
ModuleId, Signature, Span, SyntaxShape, Type, Value,
record, ModuleId, Record, Signature, Span, SyntaxShape, Type, Value,
};
use std::cmp::Ordering;
use std::collections::HashMap;
@ -65,17 +65,16 @@ impl<'e, 's> ScopeData<'e, 's> {
let var_id_val = Value::int(**var_id as i64, span);
vars.push(Value::Record {
cols: vec![
"name".to_string(),
"type".to_string(),
"value".to_string(),
"is_const".to_string(),
"var_id".to_string(),
],
vals: vec![var_name, var_type, var_value, is_const, var_id_val],
vars.push(Value::record(
record! {
"name" => var_name,
"type" => var_type,
"value" => var_value,
"is_const" => is_const,
"var_id" => var_id_val,
},
span,
})
));
}
sort_rows(&mut vars);
@ -89,121 +88,44 @@ impl<'e, 's> ScopeData<'e, 's> {
if self.visibility.is_decl_id_visible(decl_id)
&& !self.engine_state.get_decl(**decl_id).is_alias()
{
let mut cols = vec![];
let mut vals = vec![];
cols.push("name".into());
vals.push(Value::String {
val: String::from_utf8_lossy(command_name).to_string(),
span,
});
let decl = self.engine_state.get_decl(**decl_id);
let signature = decl.signature();
cols.push("category".to_string());
vals.push(Value::String {
val: signature.category.to_string(),
span,
});
cols.push("signatures".to_string());
vals.push(self.collect_signatures(&signature, span));
cols.push("usage".to_string());
vals.push(Value::String {
val: decl.usage().into(),
span,
});
cols.push("examples".to_string());
vals.push(Value::List {
vals: decl
.examples()
.into_iter()
.map(|x| Value::Record {
cols: vec!["description".into(), "example".into(), "result".into()],
vals: vec![
Value::String {
val: x.description.to_string(),
span,
},
Value::String {
val: x.example.to_string(),
span,
},
if let Some(result) = x.result {
result
} else {
Value::Nothing { span }
},
],
let examples = decl
.examples()
.into_iter()
.map(|x| {
Value::record(
record! {
"description" => Value::string(x.description, span),
"example" => Value::string(x.example, span),
"result" => x.result.unwrap_or(Value::nothing(span)),
},
span,
})
.collect(),
span,
});
)
})
.collect();
cols.push("is_builtin".to_string());
// we can only be a is_builtin or is_custom, not both
vals.push(Value::Bool {
val: !decl.is_custom_command(),
span,
});
let record = record! {
"name" => Value::string(String::from_utf8_lossy(command_name), span),
"category" => Value::string(signature.category.to_string(), span),
"signatures" => self.collect_signatures(&signature, span),
"usage" => Value::string(decl.usage(), span),
"examples" => Value::list(examples, span),
// we can only be a is_builtin or is_custom, not both
"is_builtin" => Value::bool(!decl.is_custom_command(), span),
"is_sub" => Value::bool(decl.is_sub(), span),
"is_plugin" => Value::bool(decl.is_plugin().is_some(), span),
"is_custom" => Value::bool(decl.is_custom_command(), span),
"is_keyword" => Value::bool(decl.is_parser_keyword(), span),
"is_extern" => Value::bool(decl.is_known_external(), span),
"creates_scope" => Value::bool(signature.creates_scope, span),
"extra_usage" => Value::string(decl.extra_usage(), span),
"search_terms" => Value::string(decl.search_terms().join(", "), span),
"decl_id" => Value::int(**decl_id as i64, span),
};
cols.push("is_sub".to_string());
vals.push(Value::Bool {
val: decl.is_sub(),
span,
});
cols.push("is_plugin".to_string());
vals.push(Value::Bool {
val: decl.is_plugin().is_some(),
span,
});
cols.push("is_custom".to_string());
vals.push(Value::Bool {
val: decl.is_custom_command(),
span,
});
cols.push("is_keyword".into());
vals.push(Value::Bool {
val: decl.is_parser_keyword(),
span,
});
cols.push("is_extern".to_string());
vals.push(Value::Bool {
val: decl.is_known_external(),
span,
});
cols.push("creates_scope".to_string());
vals.push(Value::Bool {
val: signature.creates_scope,
span,
});
cols.push("extra_usage".to_string());
vals.push(Value::String {
val: decl.extra_usage().into(),
span,
});
let search_terms = decl.search_terms();
cols.push("search_terms".to_string());
vals.push(Value::String {
val: search_terms.join(", "),
span,
});
cols.push("decl_id".into());
vals.push(Value::int(**decl_id as i64, span));
commands.push(Value::Record { cols, vals, span })
commands.push(Value::record(record, span))
}
}
@ -256,8 +178,7 @@ impl<'e, 's> ScopeData<'e, 's> {
// signature usually comes later in the input_output_types, so this will
// remove them from the record.
sigs.dedup_by(|(k1, _), (k2, _)| k1 == k2);
let (cols, vals) = sigs.into_iter().unzip();
Value::Record { cols, vals, span }
Value::record(sigs.into_iter().collect(), span)
}
fn collect_signature_entries(
@ -281,20 +202,22 @@ impl<'e, 's> ScopeData<'e, 's> {
];
// input
sig_records.push(Value::Record {
cols: sig_cols.clone(),
vals: vec![
Value::nothing(span),
Value::string("input", span),
Value::string(input_type.to_shape().to_string(), span),
Value::bool(false, span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
],
sig_records.push(Value::record(
Record {
cols: sig_cols.clone(),
vals: vec![
Value::nothing(span),
Value::string("input", span),
Value::string(input_type.to_shape().to_string(), span),
Value::bool(false, span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
],
},
span,
});
));
// required_positional
for req in &signature.required_positional {
@ -312,11 +235,13 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::nothing(span),
];
sig_records.push(Value::Record {
cols: sig_cols.clone(),
vals: sig_vals,
sig_records.push(Value::record(
Record {
cols: sig_cols.clone(),
vals: sig_vals,
},
span,
});
));
}
// optional_positional
@ -339,11 +264,13 @@ impl<'e, 's> ScopeData<'e, 's> {
},
];
sig_records.push(Value::Record {
cols: sig_cols.clone(),
vals: sig_vals,
sig_records.push(Value::record(
Record {
cols: sig_cols.clone(),
vals: sig_vals,
},
span,
});
));
}
// rest_positional
@ -362,11 +289,13 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::nothing(span), // rest_positional does have default, but parser prohibits specifying it?!
];
sig_records.push(Value::Record {
cols: sig_cols.clone(),
vals: sig_vals,
sig_records.push(Value::record(
Record {
cols: sig_cols.clone(),
vals: sig_vals,
},
span,
});
));
}
// named flags
@ -410,28 +339,32 @@ impl<'e, 's> ScopeData<'e, 's> {
},
];
sig_records.push(Value::Record {
cols: sig_cols.clone(),
vals: sig_vals,
sig_records.push(Value::record(
Record {
cols: sig_cols.clone(),
vals: sig_vals,
},
span,
});
));
}
// output
sig_records.push(Value::Record {
cols: sig_cols,
vals: vec![
Value::nothing(span),
Value::string("output", span),
Value::string(output_type.to_shape().to_string(), span),
Value::bool(false, span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
],
sig_records.push(Value::record(
Record {
cols: sig_cols,
vals: vec![
Value::nothing(span),
Value::string("output", span),
Value::string(output_type.to_shape().to_string(), span),
Value::bool(false, span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
Value::nothing(span),
],
},
span,
});
));
sig_records
}
@ -443,25 +376,13 @@ impl<'e, 's> ScopeData<'e, 's> {
let decl = self.engine_state.get_decl(**decl_id);
if decl.is_known_external() {
let mut cols = vec![];
let mut vals = vec![];
let record = record! {
"name" => Value::string(String::from_utf8_lossy(command_name), span),
"usage" => Value::string(decl.usage(), span),
"decl_id" => Value::int(**decl_id as i64, span),
};
cols.push("name".into());
vals.push(Value::String {
val: String::from_utf8_lossy(command_name).to_string(),
span,
});
cols.push("usage".to_string());
vals.push(Value::String {
val: decl.usage().into(),
span,
});
cols.push("decl_id".into());
vals.push(Value::int(**decl_id as i64, span));
externals.push(Value::Record { cols, vals, span })
externals.push(Value::record(record, span))
}
}
@ -483,38 +404,20 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::nothing(span)
};
aliases.push(Value::Record {
cols: vec![
"name".into(),
"expansion".into(),
"usage".into(),
"decl_id".into(),
"aliased_decl_id".into(),
],
vals: vec![
Value::String {
val: String::from_utf8_lossy(&decl_name).to_string(),
span,
},
Value::String {
val: String::from_utf8_lossy(
self.engine_state.get_span_contents(alias.wrapped_call.span),
)
.to_string(),
span,
},
Value::String {
val: alias.usage().to_string(),
span,
},
Value::Int {
val: decl_id as i64,
span,
},
aliased_decl_id,
],
let expansion = String::from_utf8_lossy(
self.engine_state.get_span_contents(alias.wrapped_call.span),
);
aliases.push(Value::record(
record! {
"name" => Value::string(String::from_utf8_lossy(&decl_name), span),
"expansion" => Value::string(expansion, span),
"usage" => Value::string(alias.usage(), span),
"decl_id" => Value::int(decl_id as i64, span),
"aliased_decl_id" => aliased_decl_id,
},
span,
});
));
}
}
}
@ -536,11 +439,10 @@ impl<'e, 's> ScopeData<'e, 's> {
if !decl.is_alias() && !decl.is_known_external() {
Some(Value::record(
vec!["name".into(), "decl_id".into()],
vec![
Value::string(String::from_utf8_lossy(name_bytes), span),
Value::int(*decl_id as i64, span),
],
record! {
"name" => Value::string(String::from_utf8_lossy(name_bytes), span),
"decl_id" => Value::int(*decl_id as i64, span),
},
span,
))
} else {
@ -556,11 +458,10 @@ impl<'e, 's> ScopeData<'e, 's> {
if decl.is_alias() {
Some(Value::record(
vec!["name".into(), "decl_id".into()],
vec![
Value::string(String::from_utf8_lossy(name_bytes), span),
Value::int(*decl_id as i64, span),
],
record! {
"name" => Value::string(String::from_utf8_lossy(name_bytes), span),
"decl_id" => Value::int(*decl_id as i64, span),
},
span,
))
} else {
@ -576,11 +477,10 @@ impl<'e, 's> ScopeData<'e, 's> {
if decl.is_known_external() {
Some(Value::record(
vec!["name".into(), "decl_id".into()],
vec![
Value::string(String::from_utf8_lossy(name_bytes), span),
Value::int(*decl_id as i64, span),
],
record! {
"name" => Value::string(String::from_utf8_lossy(name_bytes), span),
"decl_id" => Value::int(*decl_id as i64, span),
},
span,
))
} else {
@ -600,12 +500,11 @@ impl<'e, 's> ScopeData<'e, 's> {
.iter()
.map(|(name_bytes, var_id)| {
Value::record(
vec!["name".into(), "type".into(), "var_id".into()],
vec![
Value::string(String::from_utf8_lossy(name_bytes), span),
Value::string(self.engine_state.get_var(*var_id).ty.to_string(), span),
Value::int(*var_id as i64, span),
],
record! {
"name" => Value::string(String::from_utf8_lossy(name_bytes), span),
"type" => Value::string(self.engine_state.get_var(*var_id).ty.to_string(), span),
"var_id" => Value::int(*var_id as i64, span),
},
span,
)
})
@ -631,46 +530,20 @@ impl<'e, 's> ScopeData<'e, 's> {
.map(|(usage, _)| usage)
.unwrap_or_default();
Value::Record {
cols: vec![
"name".into(),
"commands".into(),
"aliases".into(),
"externs".into(),
"submodules".into(),
"constants".into(),
"env_block".into(),
"usage".into(),
"module_id".into(),
],
vals: vec![
Value::string(String::from_utf8_lossy(module_name), span),
Value::List {
vals: export_commands,
span,
},
Value::List {
vals: export_aliases,
span,
},
Value::List {
vals: export_externs,
span,
},
Value::List {
vals: export_submodules,
span,
},
Value::List {
vals: export_consts,
span,
},
export_env_block,
Value::string(module_usage, span),
Value::int(*module_id as i64, span),
],
Value::record(
record! {
"name" => Value::string(String::from_utf8_lossy(module_name), span),
"commands" => Value::list(export_commands, span),
"aliases" => Value::list(export_aliases, span),
"externs" => Value::list(export_externs, span),
"submodules" => Value::list(export_submodules, span),
"constants" => Value::list(export_consts, span),
"env_block" => export_env_block,
"usage" => Value::string(module_usage, span),
"module_id" => Value::int(*module_id as i64, span),
},
span,
}
)
}
pub fn collect_modules(&self, span: Span) -> Vec<Value> {
@ -685,36 +558,24 @@ impl<'e, 's> ScopeData<'e, 's> {
}
pub fn collect_engine_state(&self, span: Span) -> Value {
let engine_state_cols = vec![
"source_bytes".to_string(),
"num_vars".to_string(),
"num_decls".to_string(),
"num_blocks".to_string(),
"num_modules".to_string(),
"num_env_vars".to_string(),
];
let num_env_vars = self
.engine_state
.env_vars
.values()
.map(|overlay| overlay.len() as i64)
.sum();
let engine_state_vals = vec![
Value::int(self.engine_state.next_span_start() as i64, span),
Value::int(self.engine_state.num_vars() as i64, span),
Value::int(self.engine_state.num_decls() as i64, span),
Value::int(self.engine_state.num_blocks() as i64, span),
Value::int(self.engine_state.num_modules() as i64, span),
Value::int(
self.engine_state
.env_vars
.values()
.map(|overlay| overlay.len() as i64)
.sum(),
span,
),
];
Value::Record {
cols: engine_state_cols,
vals: engine_state_vals,
Value::record(
record! {
"source_bytes" => Value::int(self.engine_state.next_span_start() as i64, span),
"num_vars" => Value::int(self.engine_state.num_vars() as i64, span),
"num_decls" => Value::int(self.engine_state.num_decls() as i64, span),
"num_blocks" => Value::int(self.engine_state.num_blocks() as i64, span),
"num_modules" => Value::int(self.engine_state.num_modules() as i64, span),
"num_env_vars" => Value::int(num_env_vars, span),
},
span,
}
)
}
}
@ -731,10 +592,10 @@ fn extract_custom_completion_from_arg(engine_state: &EngineState, shape: &Syntax
fn sort_rows(decls: &mut [Value]) {
decls.sort_by(|a, b| match (a, b) {
(Value::Record { vals: rec_a, .. }, Value::Record { vals: rec_b, .. }) => {
(Value::Record { val: rec_a, .. }, Value::Record { val: rec_b, .. }) => {
// Comparing the first value from the record
// It is expected that the first value is the name of the entry (command, module, alias, etc.)
match (rec_a.get(0), rec_b.get(0)) {
match (rec_a.vals.get(0), rec_b.vals.get(0)) {
(Some(val_a), Some(val_b)) => match (val_a, val_b) {
(Value::String { val: str_a, .. }, Value::String { val: str_b, .. }) => {
str_a.cmp(str_b)