Remove some macros (#12742)

# Description
Replaces some macros with regular functions or other code.
This commit is contained in:
Ian Manske 2024-05-03 08:35:37 +00:00 committed by GitHub
parent eff2f1b3b0
commit f32ecc641f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 220 additions and 302 deletions

View File

@ -1,6 +1,7 @@
use crate::{menus::NuMenuCompleter, NuHelpCompleter}; use crate::{menus::NuMenuCompleter, NuHelpCompleter};
use crossterm::event::{KeyCode, KeyModifiers}; use crossterm::event::{KeyCode, KeyModifiers};
use log::trace; use log::trace;
use nu_ansi_term::Style;
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style}; use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_engine::eval_block; use nu_engine::eval_block;
use nu_parser::parse; use nu_parser::parse;
@ -158,21 +159,14 @@ fn add_menu(
} }
} }
macro_rules! add_style { fn get_style(record: &Record, name: &str, span: Span) -> Option<Style> {
// first arm match add!(1,2), add!(2,3) etc extract_value(name, record, span)
($name:expr, $record: expr, $span:expr, $config: expr, $menu:expr, $f:expr) => { .ok()
$menu = match extract_value($name, $record, $span) { .map(|text| match text {
Ok(text) => { Value::String { val, .. } => lookup_ansi_color_style(val),
let style = match text { Value::Record { .. } => color_record_to_nustyle(text),
Value::String { val, .. } => lookup_ansi_color_style(&val), _ => lookup_ansi_color_style("green"),
Value::Record { .. } => color_record_to_nustyle(&text), })
_ => lookup_ansi_color_style("green"),
};
$f($menu, style)
}
Err(_) => $menu,
};
};
} }
// Adds a columnar menu to the editor engine // Adds a columnar menu to the editor engine
@ -215,46 +209,21 @@ pub(crate) fn add_columnar_menu(
let span = menu.style.span(); let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style { if let Value::Record { val, .. } = &menu.style {
add_style!( if let Some(style) = get_style(val, "text", span) {
"text", columnar_menu = columnar_menu.with_text_style(style);
val, }
span, if let Some(style) = get_style(val, "selected_text", span) {
config, columnar_menu = columnar_menu.with_selected_text_style(style);
columnar_menu, }
ColumnarMenu::with_text_style if let Some(style) = get_style(val, "description_text", span) {
); columnar_menu = columnar_menu.with_description_text_style(style);
add_style!( }
"selected_text", if let Some(style) = get_style(val, "match_text", span) {
val, columnar_menu = columnar_menu.with_match_text_style(style);
span, }
config, if let Some(style) = get_style(val, "selected_match_text", span) {
columnar_menu, columnar_menu = columnar_menu.with_selected_match_text_style(style);
ColumnarMenu::with_selected_text_style }
);
add_style!(
"description_text",
val,
span,
config,
columnar_menu,
ColumnarMenu::with_description_text_style
);
add_style!(
"match_text",
val,
span,
config,
columnar_menu,
ColumnarMenu::with_match_text_style
);
add_style!(
"selected_match_text",
val,
span,
config,
columnar_menu,
ColumnarMenu::with_selected_match_text_style
);
} }
let marker = menu.marker.to_expanded_string("", config); let marker = menu.marker.to_expanded_string("", config);
@ -313,30 +282,15 @@ pub(crate) fn add_list_menu(
let span = menu.style.span(); let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style { if let Value::Record { val, .. } = &menu.style {
add_style!( if let Some(style) = get_style(val, "text", span) {
"text", list_menu = list_menu.with_text_style(style);
val, }
span, if let Some(style) = get_style(val, "selected_text", span) {
config, list_menu = list_menu.with_selected_text_style(style);
list_menu, }
ListMenu::with_text_style if let Some(style) = get_style(val, "description_text", span) {
); list_menu = list_menu.with_description_text_style(style);
add_style!( }
"selected_text",
val,
span,
config,
list_menu,
ListMenu::with_selected_text_style
);
add_style!(
"description_text",
val,
span,
config,
list_menu,
ListMenu::with_description_text_style
);
} }
let marker = menu.marker.to_expanded_string("", config); let marker = menu.marker.to_expanded_string("", config);
@ -520,46 +474,21 @@ pub(crate) fn add_ide_menu(
let span = menu.style.span(); let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style { if let Value::Record { val, .. } = &menu.style {
add_style!( if let Some(style) = get_style(val, "text", span) {
"text", ide_menu = ide_menu.with_text_style(style);
val, }
span, if let Some(style) = get_style(val, "selected_text", span) {
config, ide_menu = ide_menu.with_selected_text_style(style);
ide_menu, }
IdeMenu::with_text_style if let Some(style) = get_style(val, "description_text", span) {
); ide_menu = ide_menu.with_description_text_style(style);
add_style!( }
"selected_text", if let Some(style) = get_style(val, "match_text", span) {
val, ide_menu = ide_menu.with_match_text_style(style);
span, }
config, if let Some(style) = get_style(val, "selected_match_text", span) {
ide_menu, ide_menu = ide_menu.with_selected_match_text_style(style);
IdeMenu::with_selected_text_style }
);
add_style!(
"description_text",
val,
span,
config,
ide_menu,
IdeMenu::with_description_text_style
);
add_style!(
"match_text",
val,
span,
config,
ide_menu,
IdeMenu::with_match_text_style
);
add_style!(
"selected_match_text",
val,
span,
config,
ide_menu,
IdeMenu::with_selected_match_text_style
);
} }
let marker = menu.marker.to_expanded_string("", config); let marker = menu.marker.to_expanded_string("", config);
@ -650,30 +579,15 @@ pub(crate) fn add_description_menu(
let span = menu.style.span(); let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style { if let Value::Record { val, .. } = &menu.style {
add_style!( if let Some(style) = get_style(val, "text", span) {
"text", description_menu = description_menu.with_text_style(style);
val, }
span, if let Some(style) = get_style(val, "selected_text", span) {
config, description_menu = description_menu.with_selected_text_style(style);
description_menu, }
DescriptionMenu::with_text_style if let Some(style) = get_style(val, "description_text", span) {
); description_menu = description_menu.with_description_text_style(style);
add_style!( }
"selected_text",
val,
span,
config,
description_menu,
DescriptionMenu::with_selected_text_style
);
add_style!(
"description_text",
val,
span,
config,
description_menu,
DescriptionMenu::with_description_text_style
);
} }
let marker = menu.marker.to_expanded_string("", config); let marker = menu.marker.to_expanded_string("", config);

View File

@ -4,7 +4,7 @@ use nu_color_config::{get_matching_brackets_style, get_shape_color};
use nu_engine::env; use nu_engine::env;
use nu_parser::{flatten_block, parse, FlatShape}; use nu_parser::{flatten_block, parse, FlatShape};
use nu_protocol::{ use nu_protocol::{
ast::{Argument, Block, Expr, Expression, PipelineRedirection, RecordItem}, ast::{Block, Expr, Expression, PipelineRedirection, RecordItem},
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
Config, Span, Config, Span,
}; };
@ -86,27 +86,6 @@ impl Highlighter for NuHighlighter {
[(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)] [(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)]
.to_string(); .to_string();
macro_rules! add_colored_token_with_bracket_highlight {
($shape:expr, $span:expr, $text:expr) => {{
let spans = split_span_by_highlight_positions(
line,
$span,
&matching_brackets_pos,
global_span_offset,
);
spans.iter().for_each(|(part, highlight)| {
let start = part.start - $span.start;
let end = part.end - $span.start;
let text = (&next_token[start..end]).to_string();
let mut style = get_shape_color($shape.to_string(), &self.config);
if *highlight {
style = get_matching_brackets_style(style, &self.config);
}
output.push((style, text));
});
}};
}
let mut add_colored_token = |shape: &FlatShape, text: String| { let mut add_colored_token = |shape: &FlatShape, text: String| {
output.push((get_shape_color(shape.to_string(), &self.config), text)); output.push((get_shape_color(shape.to_string(), &self.config), text));
}; };
@ -131,21 +110,29 @@ impl Highlighter for NuHighlighter {
FlatShape::RawString => add_colored_token(&shape.1, next_token), FlatShape::RawString => add_colored_token(&shape.1, next_token),
FlatShape::StringInterpolation => add_colored_token(&shape.1, next_token), FlatShape::StringInterpolation => add_colored_token(&shape.1, next_token),
FlatShape::DateTime => add_colored_token(&shape.1, next_token), FlatShape::DateTime => add_colored_token(&shape.1, next_token),
FlatShape::List => { FlatShape::List
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token) | FlatShape::Table
} | FlatShape::Record
FlatShape::Table => { | FlatShape::Block
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token) | FlatShape::Closure => {
} let span = shape.0;
FlatShape::Record => { let shape = &shape.1;
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token) let spans = split_span_by_highlight_positions(
} line,
span,
FlatShape::Block => { &matching_brackets_pos,
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token) global_span_offset,
} );
FlatShape::Closure => { for (part, highlight) in spans {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token) let start = part.start - span.start;
let end = part.end - span.start;
let text = next_token[start..end].to_string();
let mut style = get_shape_color(shape.to_string(), &self.config);
if highlight {
style = get_matching_brackets_style(style, &self.config);
}
output.push((style, text));
}
} }
FlatShape::Filepath => add_colored_token(&shape.1, next_token), FlatShape::Filepath => add_colored_token(&shape.1, next_token),
@ -311,20 +298,6 @@ fn find_matching_block_end_in_expr(
global_span_offset: usize, global_span_offset: usize,
global_cursor_offset: usize, global_cursor_offset: usize,
) -> Option<usize> { ) -> Option<usize> {
macro_rules! find_in_expr_or_continue {
($inner_expr:ident) => {
if let Some(pos) = find_matching_block_end_in_expr(
line,
working_set,
$inner_expr,
global_span_offset,
global_cursor_offset,
) {
return Some(pos);
}
};
}
if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset
{ {
let expr_first = expression.span.start; let expr_first = expression.span.start;
@ -372,15 +345,19 @@ fn find_matching_block_end_in_expr(
Some(expr_last) Some(expr_last)
} else { } else {
// cursor is inside table // cursor is inside table
for inner_expr in table.columns.as_ref() { table
find_in_expr_or_continue!(inner_expr); .columns
} .iter()
for row in table.rows.as_ref() { .chain(table.rows.iter().flat_map(AsRef::as_ref))
for inner_expr in row.as_ref() { .find_map(|expr| {
find_in_expr_or_continue!(inner_expr); find_matching_block_end_in_expr(
} line,
} working_set,
None expr,
global_span_offset,
global_cursor_offset,
)
})
} }
} }
@ -393,36 +370,45 @@ fn find_matching_block_end_in_expr(
Some(expr_last) Some(expr_last)
} else { } else {
// cursor is inside record // cursor is inside record
for expr in exprs { exprs.iter().find_map(|expr| match expr {
match expr { RecordItem::Pair(k, v) => find_matching_block_end_in_expr(
RecordItem::Pair(k, v) => { line,
find_in_expr_or_continue!(k); working_set,
find_in_expr_or_continue!(v); k,
} global_span_offset,
RecordItem::Spread(_, record) => { global_cursor_offset,
find_in_expr_or_continue!(record); )
} .or_else(|| {
} find_matching_block_end_in_expr(
} line,
None working_set,
v,
global_span_offset,
global_cursor_offset,
)
}),
RecordItem::Spread(_, record) => find_matching_block_end_in_expr(
line,
working_set,
record,
global_span_offset,
global_cursor_offset,
),
})
} }
} }
Expr::Call(call) => { Expr::Call(call) => call.arguments.iter().find_map(|arg| {
for arg in &call.arguments { arg.expr().and_then(|expr| {
let opt_expr = match arg { find_matching_block_end_in_expr(
Argument::Named((_, _, opt_expr)) => opt_expr.as_ref(), line,
Argument::Positional(inner_expr) => Some(inner_expr), working_set,
Argument::Unknown(inner_expr) => Some(inner_expr), expr,
Argument::Spread(inner_expr) => Some(inner_expr), global_span_offset,
}; global_cursor_offset,
)
if let Some(inner_expr) = opt_expr { })
find_in_expr_or_continue!(inner_expr); }),
}
}
None
}
Expr::FullCellPath(b) => find_matching_block_end_in_expr( Expr::FullCellPath(b) => find_matching_block_end_in_expr(
line, line,
@ -432,12 +418,15 @@ fn find_matching_block_end_in_expr(
global_cursor_offset, global_cursor_offset,
), ),
Expr::BinaryOp(lhs, op, rhs) => { Expr::BinaryOp(lhs, op, rhs) => [lhs, op, rhs].into_iter().find_map(|expr| {
find_in_expr_or_continue!(lhs); find_matching_block_end_in_expr(
find_in_expr_or_continue!(op); line,
find_in_expr_or_continue!(rhs); working_set,
None expr,
} global_span_offset,
global_cursor_offset,
)
}),
Expr::Block(block_id) Expr::Block(block_id)
| Expr::Closure(block_id) | Expr::Closure(block_id)
@ -462,12 +451,15 @@ fn find_matching_block_end_in_expr(
} }
} }
Expr::StringInterpolation(inner_expr) => { Expr::StringInterpolation(exprs) => exprs.iter().find_map(|expr| {
for inner_expr in inner_expr { find_matching_block_end_in_expr(
find_in_expr_or_continue!(inner_expr); line,
} working_set,
None expr,
} global_span_offset,
global_cursor_offset,
)
}),
Expr::List(list) => { Expr::List(list) => {
if expr_last == global_cursor_offset { if expr_last == global_cursor_offset {
@ -477,12 +469,15 @@ fn find_matching_block_end_in_expr(
// cursor is at list start // cursor is at list start
Some(expr_last) Some(expr_last)
} else { } else {
// cursor is inside list list.iter().find_map(|item| {
for item in list { find_matching_block_end_in_expr(
let expr = item.expr(); line,
find_in_expr_or_continue!(expr); working_set,
} item.expr(),
None global_span_offset,
global_cursor_offset,
)
})
} }
} }
}; };

View File

@ -36,6 +36,15 @@ impl Argument {
Argument::Spread(e) => e.span, Argument::Spread(e) => e.span,
} }
} }
pub fn expr(&self) -> Option<&Expression> {
match self {
Argument::Named((_, _, expr)) => expr.as_ref(),
Argument::Positional(expr) | Argument::Unknown(expr) | Argument::Spread(expr) => {
Some(expr)
}
}
}
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]

View File

@ -72,24 +72,29 @@ fn get_filesize_format(
) -> Option<byte_unit::Unit> { ) -> Option<byte_unit::Unit> {
// filesize_metric always overrides the unit of filesize_format. // filesize_metric always overrides the unit of filesize_format.
let metric = filesize_metric.unwrap_or(!format_value.ends_with("ib")); let metric = filesize_metric.unwrap_or(!format_value.ends_with("ib"));
macro_rules! either {
($metric:ident, $binary:ident) => { if metric {
Some(if metric { match format_value {
byte_unit::Unit::$metric "b" => Some(byte_unit::Unit::B),
} else { "kb" | "kib" => Some(byte_unit::Unit::KB),
byte_unit::Unit::$binary "mb" | "mib" => Some(byte_unit::Unit::MB),
}) "gb" | "gib" => Some(byte_unit::Unit::GB),
}; "tb" | "tib" => Some(byte_unit::Unit::TB),
} "pb" | "pib" => Some(byte_unit::Unit::TB),
match format_value { "eb" | "eib" => Some(byte_unit::Unit::EB),
"b" => Some(byte_unit::Unit::B), _ => None,
"kb" | "kib" => either!(KB, KiB), }
"mb" | "mib" => either!(MB, MiB), } else {
"gb" | "gib" => either!(GB, GiB), match format_value {
"tb" | "tib" => either!(TB, TiB), "b" => Some(byte_unit::Unit::B),
"pb" | "pib" => either!(TB, TiB), "kb" | "kib" => Some(byte_unit::Unit::KiB),
"eb" | "eib" => either!(EB, EiB), "mb" | "mib" => Some(byte_unit::Unit::MiB),
_ => None, "gb" | "gib" => Some(byte_unit::Unit::GiB),
"tb" | "tib" => Some(byte_unit::Unit::TiB),
"pb" | "pib" => Some(byte_unit::Unit::TiB),
"eb" | "eib" => Some(byte_unit::Unit::EiB),
_ => None,
}
} }
} }

View File

@ -1065,63 +1065,58 @@ mod tilde_expansion {
mod variable_scoping { mod variable_scoping {
use nu_test_support::nu; use nu_test_support::nu;
macro_rules! test_variable_scope { fn test_variable_scope(code: &str, expected: &str) {
($func:literal == $res:literal $(,)*) => { let actual = nu!(code);
let actual = nu!($func); assert_eq!(actual.out, expected);
assert_eq!(actual.out, $res);
};
} }
macro_rules! test_variable_scope_list {
($func:literal == $res:expr $(,)*) => {
let actual = nu!($func);
let result: Vec<&str> = actual.out.matches("ZZZ").collect(); fn test_variable_scope_list(code: &str, expected: &[&str]) {
assert_eq!(result, $res); let actual = nu!(code);
}; let result: Vec<&str> = actual.out.matches("ZZZ").collect();
assert_eq!(result, expected);
} }
#[test] #[test]
fn access_variables_in_scopes() { fn access_variables_in_scopes() {
test_variable_scope!( test_variable_scope(
" def test [input] { echo [0 1 2] | do { do { echo $input } } } " def test [input] { echo [0 1 2] | do { do { echo $input } } }
test ZZZ " test ZZZ ",
== "ZZZ" "ZZZ",
); );
test_variable_scope!( test_variable_scope(
r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } } r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } }
test ZZZ "# test ZZZ "#,
== "ZZZ" "ZZZ",
); );
test_variable_scope!( test_variable_scope(
r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } } r#" def test [input] { echo [0 1 2] | do { do { if $input == "ZZZ" { echo $input } else { echo $input } } } }
test ZZZ "# test ZZZ "#,
== "ZZZ" "ZZZ",
); );
test_variable_scope!( test_variable_scope(
" def test [input] { echo [0 1 2] | do { echo $input } } " def test [input] { echo [0 1 2] | do { echo $input } }
test ZZZ " test ZZZ ",
== "ZZZ" "ZZZ",
); );
test_variable_scope!( test_variable_scope(
" def test [input] { echo [0 1 2] | do { if $input == $input { echo $input } else { echo $input } } } " def test [input] { echo [0 1 2] | do { if $input == $input { echo $input } else { echo $input } } }
test ZZZ " test ZZZ ",
== "ZZZ" "ZZZ"
); );
test_variable_scope_list!( test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |_| echo $input } } " def test [input] { echo [0 1 2] | each { |_| echo $input } }
test ZZZ " test ZZZ ",
== ["ZZZ", "ZZZ", "ZZZ"] &["ZZZ", "ZZZ", "ZZZ"],
); );
test_variable_scope_list!( test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |it| if $it > 0 {echo $input} else {echo $input}} } " def test [input] { echo [0 1 2] | each { |it| if $it > 0 {echo $input} else {echo $input}} }
test ZZZ " test ZZZ ",
== ["ZZZ", "ZZZ", "ZZZ"] &["ZZZ", "ZZZ", "ZZZ"],
); );
test_variable_scope_list!( test_variable_scope_list(
" def test [input] { echo [0 1 2] | each { |_| if $input == $input {echo $input} else {echo $input}} } " def test [input] { echo [0 1 2] | each { |_| if $input == $input {echo $input} else {echo $input}} }
test ZZZ " test ZZZ ",
== ["ZZZ", "ZZZ", "ZZZ"] &["ZZZ", "ZZZ", "ZZZ"],
); );
} }
} }