Shortcuty Studio
Shortcuty Studio

Documentation

Learn Shortcuty Script, from your first shortcut to the full language syntax.

Interpreters and complex projects

Shortcuty Script can express stateful algorithms using dictionaries, lists, mutable variables, helpers, conditions, and bounded repeats. This is a basis for implementing a small interpreter; it is not a built-in Python runtime or proof that a complete Python implementation works in Apple Shortcuts. A source parser, runtime values, scopes, control flow, errors, and tests must be implemented explicitly.

Agree on the language being implemented

Define the supported syntax and semantics before generating a large project. Distinguish an arithmetic evaluator, a Python-like subset, and Python compatibility. State which literals, operators, assignments, functions, loops, and built-ins are supported. Treat unimplemented syntax as an explicit language error, not an ignored statement or a claim that the program ran.

Do not quietly replace a native interpreter with a remote evaluation service, an external Python app, shell execution, or browser simulation. Those choices change dependencies, privacy, and runtime requirements. If a native implementation cannot meet the requested scope, explain the exact gap. Offer a smaller milestone only when the user has not already ruled that out.

Shortcuts has no built-in Python runtime. A few Python-like commands can be useful, but document the supported syntax and don’t call it full Python. If the project requires full compatibility, agree on any narrower scope before building it.

Build layers, with explicit state

  1. Lexer: turn source text into tokens with kinds, values, and source positions. text.match can help with a deliberately defined token grammar; use actual capture groups and verify them with text.match_group. A single regex is not a parser for arbitrary nested Python syntax. See regex capture groups.
  2. Parser: consume tokens with an index and explicit stack or state machine. Shortcuty def recursion is unsupported; do not invent recursive helper calls. Specify precedence and associativity for the target language explicitly; Shortcuty arithmetic binds before comparisons.
  3. Runtime: represent environments, instructions, and values as dictionaries/lists. Keep program counter, accumulator or operand stack, status, error text, and instruction count explicit. Choose supported catalog operations for stack/list changes instead of inventing push, pop, or array methods.
  4. Dispatcher: run a fixed instruction budget using repeat, with if running == true: inside it and switch on the opcode. Update the program counter deliberately. Record halted or error state, then skip later dispatches. This avoids needing a loop-only break.
  5. Results and errors: report your interpreter's own status and source location. Native action failures are not generally catchable. A compiler pass or a blank result is not a successful interpreted program.

Python-style mutable identity, aliasing, and closures need explicit heap or environment identities; do not assume native dictionary reassignment gives Python reference semantics. Implement target-language Boolean short-circuiting with dispatcher branches: Shortcuty compound-condition operands are evaluated before the native If.

Target-language function calls need an explicit call stack: define frame locals, return address, arguments, and a return-value convention. Target-language loops can be modeled as jumps. These are implementation designs, not built-in Python features or tested compatibility claims.

Use cohesive helper files for reusable lexer, parser, runtime, and diagnostic operations. Imports are quoted relative paths, not Python imports or packages. Helpers need a value return on every continuing path. Multi-file projects still compile into one shortcut, and helper expansion adds native actions. See Functions and imports.

Whole-program validation and source positions

These rules also apply to CPU emulators, assembly runners, and virtual machines. Separate parsing and validation from dispatch. If the grammar describes the whole program, validate every instruction and opcode-specific operand before executing any instruction. A check inside the execution loop misses malformed code after a halt and instructions skipped by a jump. Runtime-only validation is a different contract; state it explicitly rather than advertising whole-program validation.

Preserve source positions and instruction addresses. Normalize only line-ending differences the grammar allows. Do not trim the whole source, discard empty lines, or renumber instructions when blank lines are invalid or address-significant. Decide whether spaces, tabs, lowercase opcodes, comments, and a final newline are allowed, then make the parser and help text agree. Validate jump destinations against the loaded instruction count as well as the machine's address range. A non-taken jump does not excuse an invalid operand under a whole-program contract.

This standalone preflight example accepts only SET 0 through SET 9, EMIT, and STOP, one instruction per line, using LF or CRLF. It deliberately rejects all blank lines, a final newline, surrounding whitespace, lowercase opcodes, and lone CR. It validates the complete source before splitting, so native split behavior cannot hide empty lines. The final negative lookahead requires the actual end of input; $ can accept a final newline. This is input validation, not an interpreter or CPU implementation.

shortcut:
  source = "SET 3\nEMIT\nSTOP"
  normalized = replace(source, "\r\n", with: "\n")
  valid_program = text.match(input: normalized, pattern: "\\A(?:SET [0-9]|EMIT|STOP)(?:\\n(?:SET [0-9]|EMIT|STOP))*(?![\\s\\S])")
  guard valid_program has value else return "Invalid program: expected SET 0-9, EMIT, or STOP on each line; no blank lines."
  program = text.split(input: normalized, separator: "New Lines")
  size = count(program)
  guard size <= 256 else return "Program exceeds 256 instruction lines."
  result(program)

For a richer grammar, use a separate bounded parsing pass with explicit opcode, operand-count, integer/range, and jump-target checks. Only enter dispatch after that pass succeeds. This recipe's nonempty full-source match avoids the empty-match presence trap below; it does not validate arbitrary assembly languages.

Test valid programs, empty lines, different line endings, unknown commands, missing operands, out-of-range jump targets, and the step limit. Test those same cases in Apple Shortcuts.

Source indentation and empty matches

Treat a source line at column zero as valid. Do not test an empty prefix against ^( )*$ and then infer regex failure from has no value: the successful match itself is empty. This width check first separates blank lines, then requires a nonempty match containing the first source character. Here the target language uses two spaces per indentation level; that is a subset policy, not a Python requirement.

shortcut:
  line_text = "print(1)"
  content = text.match(input: line_text, pattern: "[^ \\t\\r\\n]")
  if content has value:
    indentation = text.match(input: line_text, pattern: "^(?: {2})*[^ \\t\\r\\n]")
    if indentation has no value:
      result("Use pairs of spaces for indentation, without leading tabs")
    else:
      result("Indentation width is valid")
  else:
    result("Blank line")

Each successful regex match here contains at least one character. Test zero, two, and four leading spaces; odd widths; leading and mixed tabs; empty and whitespace-only lines; and a line beginning with t. This checks indentation width only. The parser must separately track allowed block depths, required block bodies, dedents, comments, and the target language's blank-line policy. Do not reject a tab inside a string or comment merely because leading tabs are disallowed. These patterns are compiler/export tested; real Shortcuts action behavior still needs native tests.

Structured interpreter results

Represent success and failure explicitly. A successful record can deliberately contain "error": "". Do not use record["error"] ?? "Evaluation error" as a success test: ?? checks native presence, not status or text length, and a blank Text item may still be present. A missing key, a blank error message, and an error status are distinct schema states. Validate status first; for known Text, use is empty or is not empty when checking message content.

Use a separate, validated status field. This complete example consumes a known helper contract with "ok" or "error" status; only the error branch supplies a nonempty error-message default.

def checked_divide(left: Number, right: Number) -> Dictionary:
  if right == 0:
    return {"status": "error", "error": "Division by zero", "value": 0}
  return {"status": "ok", "error": "", "value": left / right}
shortcut:
  answer = checked_divide(12, 3)
  status = text(value(answer, key: "status") ?? "invalid")
  if status == "ok":
    raw = value(answer, key: "value")
    guard raw has value else return "Missing result value"
    result(number(raw))
  else:
    if status == "error":
      message = text(value(answer, key: "error") ?? "Unknown runtime error")
      result(message)
    else:
      result("Malformed result record")

The status is text, so neither Boolean truthiness nor an empty error string decides success. Zero is a valid numeric result. This demonstrates a helper-owned schema, not validation of arbitrary external records: untrusted values also need type and structure checks before conversion. Test successful zero/nonzero results, real errors, missing/unknown status, and malformed values. Compilation verifies wiring and types, not native execution.

Dynamic environments

Dictionary keys are text variable names. Read a dynamic key with value(environment, key: name), not environment[name]. data.set_value returns an updated dictionary: assign it back when updating runtime state. A lookup may be missing; presence does not establish a numeric type. A fallback after a lookup cannot catch a native action failure. If missing-key behavior has not been verified for the target action, check the dictionary keys or initialize the declared address space before looking up a value; do not claim sparse memory is safe from a compiler pass alone.

shortcut:
  environment = {}
  name = "counter"
  environment = data.set_value(dictionary: environment, key: name, value: 4)
  raw = value(environment, key: name)
  guard raw has value else exit()
  counter = number(raw)
  result(counter + 1)

This example supplies a numeric literal and explicitly converts the retrieved value. The setter has a native Text value contract, so native dictionary conversions still need device checks. For an actual language runtime, design explicit value tags and conversion/error rules. number() is not a substitute for Python's type system, and require() is not a runtime validation or error handler. List access is one-based through item(items, at: index); validate bounds before reading.

An explicit operand stack

variables.append appends to the named variable. Read the last item only after checking the stack depth, then replace the stack with the remaining range. Handle a one-item stack separately instead of asking for an invalid range.

shortcut:
  stack = [10, 20]
  variables.append(name: "stack", value: 30)
  depth = count(stack)
  guard depth > 0 else return "Empty stack"
  top = item(stack, at: depth)
  if depth > 1:
    end_index = depth - 1
    stack = lists.item(items: stack, specifier: "Items in Range", item_range_start: 1, item_range_end: end_index)
  else:
    stack = []
  result({"top": top, "stack": stack})

This is a numeric stack example. A dynamically typed interpreter needs value tags, consistent list element representation, and explicit underflow/type errors.

Bounded bytecode dispatch

This example runs a small program supplied as instruction dictionaries. It is not Python and does not parse source text. It counts down using load, add, jnz, and halt, with a 100-step limit.

shortcut:
  program = [{"op": "load", "arg": 3}, {"op": "add", "arg": -1}, {"op": "jnz", "arg": 2}, {"op": "halt", "arg": 0}]
  pc = 1
  accumulator = 0
  running = true
  error = ""
  steps = 0
  size = count(program)
  repeat 100 times:
    if running == true:
      steps = steps + 1
      if pc >= 1 and pc <= size:
        instruction = item(program, at: pc)
        raw_op = value(instruction, key: "op")
        raw_arg = value(instruction, key: "arg")
        guard raw_op has value else return "Missing opcode"
        guard raw_arg has value else return "Missing operand"
        opcode = text(raw_op)
        operand = number(raw_arg)
        pc = pc + 1
        switch opcode:
          case "load":
            accumulator = operand
          case "add":
            accumulator = accumulator + operand
          case "jnz":
            if accumulator != 0:
              pc = operand
          case "halt":
            running = false
          default:
            error = "Unknown opcode"
            running = false
      else:
        error = "Program counter out of range"
        running = false
  if running == true:
    error = "Instruction budget exceeded"
  result({"value": accumulator, "steps": steps, "error": error})

For user-supplied bytecode, check each instruction’s inputs and ensure jump targets are whole numbers within the program. A call such as number(raw) can fail when the shortcut runs.

The instruction cap is intentional. Halting skips further authored dispatch work, but the native repeat may still advance through its remaining iterations. Do not promise an immediate native break or unbounded execution.

Current boundaries

These constrain Shortcuty implementation code. An interpreter may emulate a target-language feature through explicit state and instructions, with separate tests; unsupported Shortcuty syntax must not appear in the implementation.

  • There is no supported while, break, continue, Python try/except, or recursive def authoring. Use explicit state and bounded dispatch; exit() stops the entire shortcut, not just a loop.
  • Arithmetic source operators are +, -, *, /, % (native Modulus), and ** (native power). ** associates right and binds above unary minus. // and bitwise operators are unsupported. Use # for comments. All arithmetic operands require known, present Number types. Do not assume Python division, remainder, overflow, or exception semantics; verify the target behavior separately. Boolean and/or are eager, unlike Python, so use explicit control flow for target-language short-circuiting.
  • Dynamic bracket lookup, zero-based list indexing, and Python-style collection methods are not available. Use the exact dictionary/list calls and preserve their returned state.
  • Shortcuty objects are nominal typed dictionaries declared inside the shortcut body. They are not Python classes, and helper signatures cannot name locally declared object types.
  • Native content types, conversions, numeric ranges, and action behavior are not Python semantics. Large integers, text escapes, Unicode, missing values, and evaluation order need explicit compatibility tests.
  • Source import is not access to arbitrary local files, packages, or an asset root. Choosing a runtime file does not parse or execute its contents.

Validate milestones instead of claiming completeness

Start with a small grammar and known programs. Test token boundaries and captures, malformed input, missing names, precedence, jumps, loop termination, instruction-budget exhaustion, and unsupported syntax. Preserve file/line locations in the interpreter's own diagnostics. Compare results with the intended language specification using a trusted test corpus.

Compiler checks and export validate Shortcuty source and generated structure; manual Check/Build controls are deployment-dependent. Browser simulation and native framework deserialization are different checks; neither proves every generated action runs correctly on a device. Before claiming compatibility, run representative and adversarial programs in the intended Apple environment and report the tested subset and remaining gaps.