Custom Functions

CS-MIC is designed to let host applications define their own functions.

Implement ICodedFunction, register the function on an InputInterpreter, and then call it from user expressions.

Example

using CSMic;

public sealed class Square : ICodedFunction
{
    public string Name => "square";

    public IEnumerable<FunctionArgument> ExpectedArguments =>
        new[] { new FunctionArgument("value", FunctionValue.NUMBER) };

    public FunctionValue ReturnValue => FunctionValue.NUMBER;

    public FunctionValue Execute(params FunctionArgument[] args)
    {
        var value = (decimal)args[0].Value.Value!;
        return new FunctionValue(FunctionValueType.Numeric, value * value);
    }
}

var interpreter = new InputInterpreter();
interpreter.RegisterFunction(new Square());

decimal result = interpreter.Interpret("square(12)");
// result == 144

Function Shape

An ICodedFunction describes:

  • Name: the function name users call in expressions.
  • ExpectedArguments: the ordered argument list and expected argument types.
  • ReturnValue: the function return type.
  • Execute: the host code that evaluates the function.

Numeric And String Arguments

Functions can accept numeric or string arguments.

Numeric arguments are normal expression values:

square(12)

String arguments are useful when host code needs keys, labels, modes, or identifiers:

price("sku-1234")

String literals are only valid in function argument positions. CS-MIC remains a numeric-first expression interpreter.

Registration

Register custom functions before evaluating expressions that need them:

var interpreter = new InputInterpreter();

interpreter.RegisterFunction(new Square());
interpreter.RegisterFunction(new HostLookupFunction());

decimal result = interpreter.Interpret("square(price(\"sku-1234\"))");

Use a new interpreter when the registered function set should be isolated. Reuse an interpreter when the registered functions and variables should persist.

Design Guidance

Keep custom functions small and domain-specific.

Good candidates:

  • Host lookups such as price("sku") or score("metric").
  • Business rules such as discount(amount, tier).
  • Safe math helpers specific to your application.
  • Conversions that should be explicit in user expressions.

Avoid using custom functions to expose broad application internals. CS-MIC works best when the host application deliberately chooses the small surface area users are allowed to call.