Warning: Work in progress! Leave feedback on Zulip or Github if you'd like this doc to be updated.

Block Literals

Procs are shell like-functions, but they can have declared parameters, and lack dynamic scope.

proc p(name, age) {
  echo "$name is $age years old"
}

p alice 42  # => alice is 42 years old

Blocks are fragments of code within { } that can be passed to builtins (and eventually procs):

cd /tmp {
  echo $PWD  # prints /tmp
}
echo $PWD  # prints original dir
Table of Contents
Syntax
Semantics
Use eval to evaluate a block
Hay Config Blocks
Errors
Control Flow
16 Use Cases for Blocks

Syntax

These forms work:

cd / {
  echo $PWD
}
cd / { echo $PWD }
cd / { echo $PWD }; cd / { echo $PWD }

These are syntax errors:

a=1 { echo bad };        # assignments can't take blocks
>out.txt { echo bad };   # bare redirects can't take blocks
break { echo bad };      # control flow can't take blocks

Runtime error:

local a=1 { echo bad };  # assignment builtins can't take blocks

Caveat: Blocks Are Space Sensitive

cd {a,b}  # brace substitution
cd { a,b }  # tries to run command 'a,b', which probably doesn't exist

Quoting of { } obeys the normal rules:

echo 'literal braces not a block' \{ \}
echo 'literal braces not a block' '{' '}'

Semantics

TODO: This section has to be implemented and tested.

Use eval to evaluate a block

TODO: use eval

proc p(&block) {
  echo '>'
  $block    # call it?
            # or maybe just 'block' -- it's a new word in the "proc" namespace?
  echo '<'
}

# Invoke it
p {
  echo 'hello'
}
# Output:
# >
# hello
# <

Hay Config Blocks

TODO

Errors

Generally, errors occur inside blocks, not outside:

cd /tmp {
   cp myfile /bad   # error happens here
   echo 'done'
}                   # not here

Control Flow

16 Use Cases for Blocks

See 16 use cases on the blog: Sketches of YSH Features.

Generated on Sun, 10 Nov 2024 13:11:50 -0500