-
Notifications
You must be signed in to change notification settings - Fork 55
Add lambda expression and map() + filter() functions with ARM syntax
#1238
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
Open
Gijsreyn
wants to merge
23
commits into
PowerShell:main
Choose a base branch
from
Gijsreyn:gh-57/main/add-map-lambda-function
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
dd9d3d3
Initial setup
Gijsreyn fed30d4
Fix comments
Gijsreyn 9b05728
Re-add localization
Gijsreyn 97cf256
Merge branch 'main' of https://github.com/Gijsreyn/operation-methods …
Gijsreyn acc8181
Remove dead code and add instructions
Gijsreyn 3e019fe
Initial setup
Gijsreyn a81882c
Fix comments
Gijsreyn b180986
Re-add localization
Gijsreyn fc04a3b
Merge branch 'gh-57/main/add-map-lambda-function' of https://github.c…
Gijsreyn 00f9701
Merge branch 'main' into gh-57/main/add-map-lambda-function
Gijsreyn 3176d5b
Remove conflict
Gijsreyn a93f9e2
Fix test to look at output
Gijsreyn 3139835
Merge branch 'main' into gh-57/main/add-map-lambda-function
Gijsreyn 0869cf0
Add lambda expression support for DSC function expressions
Gijsreyn 4d831b1
Merge branch 'main' into gh-57/main/add-map-lambda-function
Gijsreyn fb353f4
Add support for Lambda function arguments in the function dispatcher
Gijsreyn e9df293
Merge branch 'main' into gh-57/main/add-map-lambda-function
Gijsreyn af25cc2
Refactor argument handling
Gijsreyn 7a1de83
Remove test
Gijsreyn 9057146
Remove unused localization strings
Gijsreyn 7c3c6b6
Add Lambda process mode and update function invocation logic
Gijsreyn f5a902d
Merge branch 'main' into gh-57/main/add-map-lambda-function
Gijsreyn c3d6d77
Implement filter function with lambda support and update related meta…
Gijsreyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
| Describe 'map() function with lambda tests' { | ||
| It 'map with simple lambda multiplies each element by 2' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| parameters: | ||
| numbers: | ||
| type: array | ||
| defaultValue: [1, 2, 3] | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[map(parameters('numbers'), lambda('x', mul(lambdaVariables('x'), 2)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(2,4,6) | ||
| } | ||
|
|
||
| It 'map with lambda using index parameter' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| parameters: | ||
| items: | ||
| type: array | ||
| defaultValue: [10, 20, 30] | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[map(parameters('items'), lambda('val', 'i', add(lambdaVariables('val'), lambdaVariables('i'))))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(10,21,32) | ||
| } | ||
|
|
||
| It 'map with range generates array' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[map(range(0, 3), lambda('x', mul(lambdaVariables('x'), 3)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(0,3,6) | ||
| } | ||
|
|
||
| It 'map returns empty array for empty input' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[map(createArray(), lambda('x', mul(lambdaVariables('x'), 2)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output.Count | Should -Be 0 | ||
| } | ||
| } | ||
|
|
||
| Describe 'filter() function with lambda tests' { | ||
| It 'filter with simple lambda filters elements greater than 2' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| parameters: | ||
| numbers: | ||
| type: array | ||
| defaultValue: [1, 2, 3, 4, 5] | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[filter(parameters('numbers'), lambda('x', greater(lambdaVariables('x'), 2)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(3,4,5) | ||
| } | ||
|
|
||
| It 'filter with lambda using index parameter' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| parameters: | ||
| items: | ||
| type: array | ||
| defaultValue: [10, 20, 30, 40] | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[filter(parameters('items'), lambda('val', 'i', less(lambdaVariables('i'), 2)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(10,20) | ||
| } | ||
|
|
||
| It 'filter returns empty array when no elements match' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[filter(createArray(1, 2, 3), lambda('x', greater(lambdaVariables('x'), 10)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output.Count | Should -Be 0 | ||
| } | ||
|
|
||
| It 'filter returns all elements when all match' { | ||
| $config_yaml = @' | ||
| $schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json | ||
| resources: | ||
| - name: Echo | ||
| type: Microsoft.DSC.Debug/Echo | ||
| properties: | ||
| output: "[filter(createArray(5, 6, 7), lambda('x', greater(lambdaVariables('x'), 2)))]" | ||
| '@ | ||
| $out = $config_yaml | dsc config get -f - | ConvertFrom-Json | ||
| $LASTEXITCODE | Should -Be 0 | ||
| $out.results[0].result.actualState.output | Should -Be @(5,6,7) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // 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 crate::functions::lambda_helpers::{get_lambda, apply_lambda_to_array}; | ||
| use rust_i18n::t; | ||
| use serde_json::Value; | ||
| use tracing::debug; | ||
|
|
||
| #[derive(Debug, Default)] | ||
| pub struct Filter {} | ||
|
|
||
| impl Function for Filter { | ||
| fn get_metadata(&self) -> FunctionMetadata { | ||
| FunctionMetadata { | ||
| name: "filter".to_string(), | ||
| description: t!("functions.filter.description").to_string(), | ||
| category: vec![FunctionCategory::Array, FunctionCategory::Lambda], | ||
| min_args: 2, | ||
| max_args: 2, | ||
| accepted_arg_ordered_types: vec![ | ||
| vec![FunctionArgKind::Array], | ||
| vec![FunctionArgKind::Lambda], | ||
| ], | ||
| remaining_arg_accepted_types: None, | ||
| return_types: vec![FunctionArgKind::Array], | ||
| } | ||
| } | ||
|
|
||
| fn invoke(&self, args: &[Value], context: &Context) -> Result<Value, DscError> { | ||
| debug!("{}", t!("functions.filter.invoked")); | ||
|
|
||
| let array = args[0].as_array().unwrap(); | ||
| let lambda_id = args[1].as_str().unwrap(); | ||
|
|
||
| let lambdas = get_lambda(context, lambda_id, "filter")?; | ||
| let lambda = lambdas.get(lambda_id).unwrap(); | ||
|
|
||
| let result_array = apply_lambda_to_array(array, lambda, context, |result, element| { | ||
| let Some(include) = result.as_bool() else { | ||
| return Err(DscError::Parser(t!("functions.filter.lambdaMustReturnBool").to_string())); | ||
| }; | ||
| if include { | ||
| Ok(Some(element.clone())) | ||
| } else { | ||
| Ok(None) | ||
| } | ||
| })?; | ||
|
|
||
| Ok(Value::Array(result_array)) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| // 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 crate::parser::functions::{FunctionArg, Lambda}; | ||
| use rust_i18n::t; | ||
| use serde_json::Value; | ||
| use tracing::debug; | ||
| use uuid::Uuid; | ||
|
|
||
| #[derive(Debug, Default)] | ||
| pub struct LambdaFn {} | ||
|
|
||
| impl Function for LambdaFn { | ||
| fn get_metadata(&self) -> FunctionMetadata { | ||
| FunctionMetadata { | ||
| name: "lambda".to_string(), | ||
| description: t!("functions.lambda.description").to_string(), | ||
| category: vec![FunctionCategory::Lambda], | ||
| min_args: 0, // Args come through context.lambda_raw_args | ||
| max_args: 0, | ||
| accepted_arg_ordered_types: vec![], | ||
| remaining_arg_accepted_types: None, | ||
| return_types: vec![FunctionArgKind::Lambda], | ||
| } | ||
| } | ||
|
|
||
| fn invoke(&self, _args: &[Value], context: &Context) -> Result<Value, DscError> { | ||
| debug!("{}", t!("functions.lambda.invoked")); | ||
|
|
||
| let raw_args = context.lambda_raw_args.borrow(); | ||
| let args = raw_args.as_ref() | ||
| .filter(|a| a.len() >= 2) | ||
| .ok_or_else(|| DscError::Parser(t!("functions.lambda.requiresParamAndBody").to_string()))?; | ||
|
|
||
| let (body_arg, param_args) = args.split_last().unwrap(); // safe: len >= 2 | ||
|
|
||
| let parameters: Vec<String> = param_args.iter() | ||
| .map(|arg| match arg { | ||
| FunctionArg::Value(Value::String(s)) => Ok(s.clone()), | ||
| _ => Err(DscError::Parser(t!("functions.lambda.paramsMustBeStrings").to_string())), | ||
| }) | ||
| .collect::<Result<_, _>>()?; | ||
|
|
||
| // Extract body expression | ||
| let body = match body_arg { | ||
| FunctionArg::Expression(expr) => expr.clone(), | ||
| _ => return Err(DscError::Parser(t!("functions.lambda.bodyMustBeExpression").to_string())), | ||
| }; | ||
|
|
||
| // Create Lambda and store in Context with unique ID | ||
| let lambda = Lambda { parameters, body }; | ||
| let lambda_id = format!("__lambda_{}", Uuid::new_v4()); | ||
| context.lambdas.borrow_mut().insert(lambda_id.clone(), lambda); | ||
|
|
||
| Ok(Value::String(lambda_id)) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.