ProductPromotion
Logo

Rust

made by https://0x3d.site

GitHub - sagiegurari/duckscript: Simple, extendable and embeddable scripting language.
Simple, extendable and embeddable scripting language. - sagiegurari/duckscript
Visit Site

GitHub - sagiegurari/duckscript: Simple, extendable and embeddable scripting language.

GitHub - sagiegurari/duckscript: Simple, extendable and embeddable scripting language.

duckscript

duckscript SDK CLI
crates.io crates.io crates.io

downloads CI codecov license Built with cargo-make

Simple, extendable and embeddable scripting language.

Overview

Duckscript is a simple, extendable and embeddable scripting language. The language itself has only few rules and most common language features are implemented as commands rather than part of the language itself.

Language Goals

Duckscript scripting language goals are:

  • Simple - This is probably the simplest language you will ever see.
  • Extendable - Instead of having common features such as functions and conditional blocks be a part of the language, they are actually part of the API. So they can easily be replaced/modified or you can add more 'feature' like commands on your own.
  • Embeddable - One of the main purposes of this language is to allow other libraries/executables/apps have scripting capability by embedding duckscript. Embedding is easy (for rust) and requires only few lines of code.

Installation

If you have rust, just run the following command

cargo install --force duckscript_cli

This will install duckscript script runner, the standard duckscript SDK and the duckscript CLI. You should then have a duck executable in your ~/.cargo/bin directory. Make sure to add ~/.cargo/bin directory to your PATH variable.

Homebrew

brew install duckscript

More details in the brew page

Binary Release

Binary releases are available in the github releases page. The following binaries are available for each release:

  • x86_64-unknown-linux-musl
  • x86_64-apple-darwin
  • x86_64-pc-windows-msvc

Duckscript Tutorial

The following sections will teach you how to write and run duck scripts.

Hello World Example

Let's take a really simple example (all examples are located in the examples directory:

# print the text "Hello World"
echo Hello World

Running this script is done using the duck executable as follows:

duck ./examples/hello_world.ds

We will understand more and break this down in the following sections.

Running the duck command without any arguments will open up the repl mode.

Commands

Commands are the basis of everything in duckscript. Commands may execute some action (like printing "Hello World" to the console) or serve as flow control (such as functions or if/else conditions). In order to invoke an action, simply write the action name:

echo

The basic syntax of a command line is:

[:label] [output variable =] [command [arguments]]

Passing Arguments

Commands may accept arguments, for example the command echo may accept any number of arguments and it will print all of them. Arguments are separated with the space character. So in the example:

# print the text "Hello World"
echo Hello World

The echo command got 2 arguments: "Hello" and "World". If your argument contains a space, you can wrap the entire argument with the " character as follows:

# print the text "Hello World"
echo "Hello World"

In which case the echo command got only one argument: "Hello World" and prints it. You can escape the " character using the "\" character, for example:

# print the text 'hello "world"'
echo "hello \"world\""

In the above example, the echo command got one argument: 'hello "world"' and prints it. The "\" is also used to escape the following:

  • \n - End of line
  • \r - Carriage return
  • \t - Tab character

Storing Output

Commands may return an output which can be stored in a variable. Variables in duckscript have no strict type. In the following example, the set command takes one argument and stores it in the out variable.

out = set "Hello World"

Duckscript has only global scope, so once you have stored a value in a variable, you may use it anywhere in your script.

Using Variables - Binding

Stored variables can be later on used as arguments for other commands. In order to use a variable, we need to wrap it as follows: ${variable}. The following example uses the set command to store a value in the out variable and then prints it:

out = set "Hello World"

# This will print: "The out variable holds the value: Hello World"
echo The out variable holds the value: ${out}

# This will print: "To use the out variable just write: ${out}"
echo To use the out variable just write: \${out}

In this example, although out holds the value Hello World which contains a space, it is still considered as a single input argument to the echo command. In the second echo command we prevented the variable name from being replaced by escaping it using the \ character.

Using Variables - Spread Binding

Spread binding provides a way to convert a variable value into multiple command arguments. For example:

out = set "Hello World"

The out variable holds the value "Hello World". If we were to create an array from it using the array command as follows:

list = array ${out}

The array would be of size 1 and its only entry value would be "Hello World". So it is the same as if we wrote:

list = array "Hello World"

But what if we want to split the value to multiple parts separated by spaces? For that we have the spread binding which is defined as follows: %{variable}. For example:

list = array %{out}

Which would act the same as:

list = array Hello World

And now our array is of size 2 with first entry "Hello" and second entry "World".

Labels

Labels are simple textual names you can give to a specific line. Commands like goto can then be used to make the script execution jump from its current position to the label position. For example:

goto :good

echo error!!!!

:good echo yay!!!!

Comments

Comments are not executed and are simply in the code for documentation purposes. A document line must start with the # character. You can also have a comment after the command and the command will ignore it. For example:

# This is just a comment

echo This will print # But this will not

Pre Processing

Pre processing is the phase that duckscript is parsing the script content. It is possible to run specific commands at that phase to modify the script during the parsing phase.

The basic syntax of a pre processing command line is:

!command [arguments]

!include_files

The include_files command enables you to load script files into the position of the pre processor command. Basically it enables you to include many scripts and generate one bigger script for runtime. The include files command accepts any number of files and all will be loaded by the order they are defined. For example:

# load the hello_world.ds script here
!include_files ./hello_world.ds

# load 2 scripts here. The hello_world.ds is loaded again.
!include_files ./hello_world.ds ./use_variable.ds

Important to note that the script paths included are relative to the script file including them and not to the current working directory.

!print

The print pre processing command allows to print any number of arguments, which could be useful for debugging. In the following example, although the print command comes after the echo command, it will execute first as it is invoked in the parsing phase and not in the script execution phase which comes later:

# this will print "Hello World during script execution"
echo Hello World during script execution

# this will print "Hello World during parsing"
!print Hello World during parsing

Standard API

Duckscript is split to several modules and while the script runner does not require it, by default it will come with the standard duckscript API called the duckscript SDK. This SDK holds the most common commands, some which execute actions (such as echo) and some which serve as flow control (such as function). The SDK enables users to develop their scripts and have a good starting point without the need to develop the commands on their own (as that is a bit more complex).

Commands Instead Of Language Features

As mentioned before, duckscript is really simple and only has few basic rules. In order to provide a more richer development experience, common language features such as functions and conditional blocks have been implemented as commands. This is an example of the function command:

fn print_first_and_second_argument
    echo ${1} ${2}
    return printed
end

fn run_flow
    status = print_first_and_second_argument Hello World
    echo The printout status is: ${status}
end

run_flow

This example demonstrates how functions as a concept do not need to be part of the language and can be implemented by anyone as a command. This also means that other developers can replace the function command with their implementation to provide additional/different functionality.

Below an example of loops using the for/in command:

values = range 1 10

for i in ${values}
    for j in ${values}
        echo i: ${i} j: ${j}
    end
end

release ${values}

Below an example of if/else command:

echo Enter Full Name:
name = read

if is_empty ${name}
    echo You did not enter any value
else
    echo Your name is: ${name}
end

value = set false
if ${value}
    echo should not be here
elseif true or false
    echo in else if but not done yet

    value = set true

    if not true and false
        echo nested if

        value = set "some text"

        if starts_with ${value} "some"
            echo after command
        else
            echo should not be here
        end
    end
else
    echo should not be here
end

Full SDK Docs

The full SDK docs can be found here

Keep in mind that the command names (such as std::Echo) can be used to invoke the commands, however for simplicity, the documentation examples uses the alias form of the commands (for example: echo). Each command may have multiple aliases which can be used to invoke it.

Final Notes

That's It!!!! That is all the language. Short, simple, only few rules to follow and you mastered duckscript.

If you want to know what more you can do with it, look at the SDK docs. If you want to know how to write your own commands or embed the duckscript runtime in your application, continue reading.

Duckscript Command Implementation Tutorial

Want to write new custom commands so you can use them in your duckscripts? great! Hopefully the following sections will help you gain the basic knowledge on how to write them.

Commands

Commands are structs that must implement the Command trait.

  • They must have a name, which is used to invoke the command.
  • They optionally may have aliases which can also be used to invoke the command.
  • They should return help documentation in markdown format in order to generate SDK documentation (must for PRs to duckscript official SDK).
  • They must implement the run function which holds the command logic.

The run function accepts the command invocation context (args array contains actual values and not original variables) and returns the command result. The command result can be one of the following:

  • Continue(Option) - Tells the runner to continue to the next command and optionally set the output variable the given value.
  • GoTo(Option, GoToValue) - Tells the runner to jump to the requested line or label and optionally set the output variable the given value.
  • Error(String) - Returns the value 'false' and invokes the 'on_error' command if exists with the error message and instruction information.
  • Crash(String) - Tells the runner to stop the execution and return the error message.
  • Exit(Option) - Tells the runner to stop the execution and optionally set the output variable the given value.

Let's implement a simple set command which accepts a single argument and sets the output variable to that value. And if no argument was provided, return a None which will tell the runner to delete the output variable. Afterwards the runner should continue to the next line. So we need to use a Continue(Option) result. Full example:

struct SetCommand {}

impl Command for SetCommand {
    fn name(&self) -> String {
        "set".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn run(&self, context: CommandInvocationContext) -> CommandResult {
        let output = if context.arguments.is_empty() {
            None
        } else {
            Some(context.arguments[0].clone())
        };

        CommandResult::Continue(output)
    }
}

Let's implement a get_env command which pulls an environment variable value and sets the output variable with that value. In case no input was provided we will throw an error, otherwise we will use the first input as the environment variable key. We will return the value if exists or nothing if it does not. Full example:

struct GetEnvCommand {
    package: String,
}

impl Command for GetEnvCommand {
    fn name(&self) -> String {
        "get_env".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn run(&self, context: CommandInvocationContext) -> CommandResult {
        if context.arguments.is_empty() {
            CommandResult::Error("Missing environment variable name.".to_string())
        } else {
            match env::var(&context.arguments[0]) {
                Ok(value) => CommandResult::Continue(Some(value)),
                Err(_) => CommandResult::Continue(None),
            }
        }
    }
}

You can look at more examples in the duckscript_sdk folder.

Access The Context

The duckscript runtime context is available in the CommandInvocationContext struc.

/// Run the instruction with access to the runtime context.
///
/// The CommandInvocationContext has the following members:
/// * `arguments` - The command arguments array
/// * `state` - Internal state which is only used by commands to store/pull data
/// * `variables` - All script variables
/// * `output_variable` - The output variable name (if defined)
/// * `instructions` - The entire list of instructions which make up the currently running script
/// * `commands` - The currently known commands
/// * `line` - The current instruction line number (global line number after including all scripts into one global script)
/// * `env` - The current runtime env with access to out/err writers, etc...
fn run(&self, context: CommandInvocationContext) -> CommandResult;

With access to this context you can add/remove/switch commands in runtime, store/pull internal state, add/remove/change variables and so on...

Duckscript Embedding Tutorial

Embedding duckscript is really simple and this is one of the language main goals. The duckscript cli basically embeds duckscript so you can look at it as a reference, but basically it boils down to really few lines of code:

let mut context = Context::new();
duckscriptsdk::load(&mut context.commands)?;
runner::run_script_file(file, context, None)?;

That's it! Unless you want to provide your own custom SDK, pre populate the runtime context with custom variables/state or pull information out of the context after invocation than those 3 lines of code is all you need to do. Let's go over it line by line.

Setting Up The Context

The context holds the initial known commands, variables and state (internal objects used by commands). Running the Context::new() simply creates a new empty context. You can add to it any command, variable or state object you want before running the scripts. In our example we load all default standard API commands into the new context via: duckscriptsdk::load(&mut context.commands)?;

Running The Script

After we have a context setup, we will run the script. The runner enables to run a script text or a script file. The following public functions are available:

/// Executes the provided script with the given context
pub fn run_script(text: &str, context: Context, env: Option<Env>) -> Result<Context, ScriptError>;

/// Executes the provided script file with the given context
pub fn run_script_file(file: &str, context: Context, env: Option<Env>) -> Result<Context, ScriptError>;

Editor Support

Contributing

There are many ways to contribute to duckscript, including:

  • Writing more commands and adding them to the standard SDK
  • Improving existing commands by adding more features
  • Improving the documentation
  • Opening issues with new feature requests or bugs found
  • Spreading the word :)

As for expanding the language, I personally prefer not to make it complex. Let's try to add more language feature using commands and not changing the language itself.

See contributing guide

Release History

See Changelog

License

Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license.

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory