Skip to content

Add array(), first(), indexOf() functions #1041

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Aug 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
380 changes: 224 additions & 156 deletions dsc/tests/dsc_functions.tests.ps1

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions dsc_lib/locales/en-us.toml
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,10 @@ invoked = "add function"
description = "Evaluates if all arguments are true"
invoked = "and function"

[functions.array]
description = "Convert the value to an array"
invoked = "array function"

[functions.base64]
description = "Encodes a string to Base64 format"

Expand Down Expand Up @@ -280,6 +284,13 @@ description = "Evaluates if the two values are the same"
description = "Returns the boolean value false"
invoked = "false function"

[functions.first]
description = "Returns the first element of an array or first character of a string"
invoked = "first function"
emptyArray = "Cannot get first element of empty array"
emptyString = "Cannot get first character of empty string"
invalidArgType = "Invalid argument type, argument must be an array or string"

[functions.greater]
description = "Evaluates if the first value is greater than the second value"
invoked = "greater function"
Expand Down Expand Up @@ -307,6 +318,11 @@ parseStringError = "unable to parse string to int"
castError = "unable to cast to int"
parseNumError = "unable to parse number to int"

[functions.indexOf]
description = "Returns the index of the first occurrence of an item in an array"
invoked = "indexOf function"
invalidArrayArg = "First argument must be an array"

[functions.length]
description = "Returns the length of a string, array, or object"
invoked = "length function"
Expand Down
97 changes: 97 additions & 0 deletions dsc_lib/src/functions/array.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct Array {}

impl Function for Array {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "array".to_string(),
description: t!("functions.array.description").to_string(),
category: FunctionCategory::Array,
min_args: 1,
max_args: 1,
accepted_arg_ordered_types: vec![
vec![FunctionArgKind::String, FunctionArgKind::Number, FunctionArgKind::Object, FunctionArgKind::Array],
],
remaining_arg_accepted_types: None,
return_types: vec![FunctionArgKind::Array],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.array.invoked"));

Ok(Value::Array(vec![args[0].clone()]))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn single_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array('hello')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"["hello"]"#);
}

#[test]
fn single_number() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(42)]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "[42]");
}

#[test]
fn single_object() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(createObject('key', 'value'))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"[{"key":"value"}]"#);
}

#[test]
fn single_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(createArray('a','b'))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"[["a","b"]]"#);
}

#[test]
fn empty_array_not_allowed() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array()]", &Context::new());
assert!(result.is_err());
}

#[test]
fn multiple_args_not_allowed() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array('hello', 42)]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_boolean() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(true)]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_null() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(null())]", &Context::new());
assert!(result.is_err());
}
}
116 changes: 116 additions & 0 deletions dsc_lib/src/functions/first.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct First {}

impl Function for First {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "first".to_string(),
description: t!("functions.first.description").to_string(),
category: FunctionCategory::Array,
min_args: 1,
max_args: 1,
accepted_arg_ordered_types: vec![vec![FunctionArgKind::Array, FunctionArgKind::String]],
remaining_arg_accepted_types: None,
return_types: vec![FunctionArgKind::String, FunctionArgKind::Number, FunctionArgKind::Array, FunctionArgKind::Object],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.first.invoked"));

if let Some(array) = args[0].as_array() {
if array.is_empty() {
return Err(DscError::Parser(t!("functions.first.emptyArray").to_string()));
}
return Ok(array[0].clone());
}

if let Some(string) = args[0].as_str() {
if string.is_empty() {
return Err(DscError::Parser(t!("functions.first.emptyString").to_string()));
}
return Ok(Value::String(string.chars().next().unwrap().to_string()));
}

Err(DscError::Parser(t!("functions.first.invalidArgType").to_string()))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn array_of_strings() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray('hello', 'world'))]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("hello"));
}

#[test]
fn array_of_numbers() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray(1, 2, 3))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn array_of_single_element() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(array('hello'))]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("hello"));
}

#[test]
fn string_input() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('hello')]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("h"));
}

#[test]
fn single_character_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('a')]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("a"));
}

#[test]
fn empty_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray())]", &Context::new());
assert!(result.is_err());
}

#[test]
fn empty_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('')]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_object() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createObject('key', 'value'))]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_number() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(42)]", &Context::new());
assert!(result.is_err());
}
}
121 changes: 121 additions & 0 deletions dsc_lib/src/functions/index_of.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct IndexOf {}

impl Function for IndexOf {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "indexOf".to_string(),
description: t!("functions.indexOf.description").to_string(),
category: FunctionCategory::Array,
min_args: 2,
max_args: 2,
accepted_arg_ordered_types: vec![
vec![FunctionArgKind::Array],
vec![FunctionArgKind::String, FunctionArgKind::Number, FunctionArgKind::Array, FunctionArgKind::Object],
],
remaining_arg_accepted_types: None,
return_types: vec![FunctionArgKind::Number],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.indexOf.invoked"));

let Some(array) = args[0].as_array() else {
return Err(DscError::Parser(t!("functions.indexOf.invalidArrayArg").to_string()));
};

let item_to_find = &args[1];

for (index, item) in array.iter().enumerate() {
if item == item_to_find {
let index_i64 = i64::try_from(index).map_err(|_| {
DscError::Parser("Array index too large to represent as integer".to_string())
})?;
return Ok(Value::Number(index_i64.into()));
}
}

// Not found is -1
Ok(Value::Number((-1i64).into()))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn find_string_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('apple', 'banana', 'cherry'), 'banana')]", &Context::new()).unwrap();
assert_eq!(result, 1);
}

#[test]
fn find_number_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(10, 20, 30), 20)]", &Context::new()).unwrap();
assert_eq!(result, 1);
}

#[test]
fn find_first_occurrence() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('a', 'b', 'a', 'c'), 'a')]", &Context::new()).unwrap();
assert_eq!(result, 0);
}

#[test]
fn item_not_found() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('apple', 'banana'), 'orange')]", &Context::new()).unwrap();
assert_eq!(result, -1);
}

#[test]
fn case_sensitive_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('Apple', 'Banana'), 'apple')]", &Context::new()).unwrap();
assert_eq!(result, -1);
}

#[test]
fn find_array_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(createArray('a', 'b'), createArray('c', 'd')), createArray('c', 'd'))]", &Context::new()).unwrap();
assert_eq!(result, 1);
}

#[test]
fn find_object_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(createObject('name', 'John'), createObject('name', 'Jane')), createObject('name', 'Jane'))]", &Context::new()).unwrap();
assert_eq!(result, 1);
}

#[test]
fn empty_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(), 'test')]", &Context::new()).unwrap();
assert_eq!(result, -1);
}

#[test]
fn invalid_array_arg() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf('not_an_array', 'test')]", &Context::new());
assert!(result.is_err());
}
}
Loading
Loading