E08120: mutating variables is not allowed when scope is marked as 'pure'

Category: E08xxx Pre-IR checks (flow analysis) · Reported in phase: FULL_RESOLUTION · Classification: NO_MUTATION_IN_PURE_CONTEXT · All error codes

What went wrong

You're calling a MUTATING operation (like +=, :=:, ++, --) inside a PURE context where mutations are forbidden.

Worked examples

Compilable examples demonstrating this error and the correct fix:

  • ek9 -q 54 (What are pure functions and what is the difference betwee...)
  • ek9 -q 273 (How does purity create security boundaries?)
  • ek9 -q 52 (What are dynamic functions and how do they differ from la...)
  • ek9 -q 53 (How do closures and variable capture work in EK9?)
  • ek9 -q 268 (How does EK9 prevent common security vulnerabilities?)

Mutating operators

'++', '--', '+=', '-=', '*=', '/=', ':=:', ':~:', ':^:'

How to fix it

  1. Use non-mutating alternatives (+ instead of +=)
  2. Create new values instead of mutating
  3. If mutation needed, remove 'pure' modifier

Common causes

  • Using compound assignment in pure function
  • Calling mutating method in pure scope

See also

  • E08120: mutating operation in pure context (this error)
  • E08130: non-pure call in pure context

Examples

Every example is compiled by the EK9 compiler: the first fails exactly as captioned, the others fix it.

Fails with E08120: mutating variables is not allowed when scope is marked as 'pure'

#!ek9
defines module error.e08120.bad

  defines function

    withReviewedTag() as pure
      -> tags as List of String
      <- tagged as List of String: tags
      tags += "reviewed"

Fixed: Return a new value instead of changing one

#!ek9
defines module error.e08120.good

  defines function

    withReviewedTag() as pure
      -> tags as List of String
      <- tagged as List of String: tags + "reviewed"

Questions and answers

These Q&A entries show E08120 and its fix:

Found a problem?

If EK9 reported E08120 for a program you think is valid, or did not report it where it should have, use the compiler form with the smallest program that shows it. If this page is wrong or unclear, use the documentation form. Both are at github.com/ek9lang/ek9-issues.