import {
  collectReferencedIdentifiers,
  createArrowFn,
  createIIFE,
  createMethodCall,
  extractReturnExpr,
  inferTypeConstructor
} from "./chunk-RZHX2YRY.js";
import {
  getFlatMapMethodNames,
  getParCombineBuilderFromRegistry,
  hasFlatMapInstance,
  hasParCombineInstance,
  registerInstanceWithMeta,
  registerTypeclassDef
} from "./chunk-4QIJY5PM.js";

// src/macros/let-yield.ts
import * as ts from "typescript";
import { defineLabeledBlockMacro, globalRegistry } from "@typesugar/core";
var letYieldMacro = defineLabeledBlockMacro({
  name: "letYield",
  label: "let",
  continuationLabels: ["yield", "pure", "return"],
  expand(ctx, mainBlock, continuation) {
    const { factory, typeChecker } = ctx;
    if (!ts.isBlock(mainBlock.statement)) {
      ctx.reportError(mainBlock, "let: must be followed by a block { ... }");
      return mainBlock;
    }
    const steps = extractSteps(ctx, mainBlock.statement);
    if (!steps || steps.length === 0) {
      ctx.reportError(mainBlock, "let: block must contain at least one binding or guard");
      return mainBlock;
    }
    const hasBindStep = steps.some((s) => s.kind === "bind");
    if (!hasBindStep) {
      ctx.reportError(mainBlock, "let: block must contain at least one `name << expression` binding");
      return mainBlock;
    }
    const firstBind = steps.find((s) => s.kind === "bind");
    const typeConstructorName = inferTypeConstructor(firstBind.effect, typeChecker);
    if (!typeConstructorName) {
      ctx.reportError(firstBind.effect, "Could not infer type constructor from expression. Make sure the expression has a known type (Array, Promise, Option, etc.)");
      return mainBlock;
    }
    if (!hasFlatMapInstance(typeConstructorName)) {
      ctx.reportError(firstBind.effect, `No FlatMap instance registered for '${typeConstructorName}'. Use @instance decorator or registerFlatMap() to register an instance.`);
      return mainBlock;
    }
    const methods = getFlatMapMethodNames(typeConstructorName);
    let returnExpr;
    if (continuation) {
      if (!ts.isBlock(continuation.statement)) {
        ctx.reportError(continuation, `${continuation.label.text}: must be followed by a block { ... }`);
        return mainBlock;
      }
      const extracted = extractReturnExpr(ctx, continuation.statement);
      if (!extracted) {
        return mainBlock;
      }
      returnExpr = extracted;
    } else {
      const lastBind = [...steps].reverse().find((s) => s.kind === "bind");
      if (!lastBind) {
        ctx.reportError(mainBlock, "No bind step found for implicit return");
        return mainBlock;
      }
      const stepsWithoutLast = steps.slice(0, steps.lastIndexOf(lastBind));
      if (stepsWithoutLast.length === 0) {
        return factory.createExpressionStatement(lastBind.effect);
      }
      const chain = buildChain(ctx, stepsWithoutLast, lastBind.effect, methods, typeConstructorName);
      return factory.createExpressionStatement(chain);
    }
    const result = buildChain(ctx, steps, returnExpr, methods, typeConstructorName);
    return factory.createExpressionStatement(result);
  }
});
function extractSteps(ctx, block) {
  const steps = [];
  for (const stmt of block.statements) {
    if (ts.isIfStatement(stmt)) {
      steps.push({
        kind: "guard",
        condition: stmt.expression,
        node: stmt
      });
      continue;
    }
    if (!ts.isExpressionStatement(stmt)) {
      ctx.reportError(stmt, "let: block statements must be `name << expr`, `name = expr`, or `if (cond) {}`");
      return void 0;
    }
    const expr = stmt.expression;
    if (!ts.isBinaryExpression(expr)) {
      ctx.reportError(stmt, "Expected `name << expression` or `name = expression`");
      return void 0;
    }
    const opKind = expr.operatorToken.kind;
    if (opKind === ts.SyntaxKind.FirstAssignment) {
      if (!ts.isIdentifier(expr.left)) {
        ctx.reportError(expr.left, "Left side of = must be an identifier");
        return void 0;
      }
      steps.push({
        kind: "map",
        name: expr.left.text,
        expression: expr.right,
        node: stmt
      });
      continue;
    }
    if (opKind === ts.SyntaxKind.BarBarToken) {
      const lhs = expr.left;
      if (ts.isBinaryExpression(lhs) && lhs.operatorToken.kind === ts.SyntaxKind.LessThanLessThanToken && ts.isIdentifier(lhs.left)) {
        steps.push({
          kind: "bind",
          name: lhs.left.text,
          effect: lhs.right,
          orElse: expr.right,
          node: stmt
        });
        continue;
      }
    }
    if (opKind === ts.SyntaxKind.QuestionQuestionToken) {
      const lhs = expr.left;
      if (ts.isBinaryExpression(lhs) && lhs.operatorToken.kind === ts.SyntaxKind.LessThanLessThanToken && ts.isIdentifier(lhs.left)) {
        steps.push({
          kind: "bind",
          name: lhs.left.text,
          effect: lhs.right,
          orElse: expr.right,
          node: stmt
        });
        continue;
      }
    }
    if (opKind === ts.SyntaxKind.LessThanLessThanToken) {
      if (!ts.isIdentifier(expr.left)) {
        ctx.reportError(expr.left, "Left side of << must be an identifier (variable name or _)");
        return void 0;
      }
      steps.push({
        kind: "bind",
        name: expr.left.text,
        effect: expr.right,
        node: stmt
      });
      continue;
    }
    ctx.reportError(stmt, "Expected `name << expression`, `name = expression`, or `if (cond) {}`");
    return void 0;
  }
  return steps;
}
function buildChain(ctx, steps, returnExpr, methods, typeConstructor) {
  const { factory } = ctx;
  if (steps.length === 0) {
    return returnExpr;
  }
  let inner = returnExpr;
  for (let i = steps.length - 1; i >= 0; i--) {
    const step = steps[i];
    switch (step.kind) {
      case "bind": {
        const remainingBinds = steps.slice(i + 1).filter((s) => s.kind === "bind");
        const isLastBind = remainingBinds.length === 0;
        const methodName = isLastBind ? methods.map : methods.bind;
        let effectExpr = step.effect;
        if (step.orElse && methods.orElse) {
          effectExpr = createMethodCall(factory, effectExpr, methods.orElse, createArrowFn(factory, "_", step.orElse));
        }
        inner = generateMethodCall(factory, effectExpr, methodName, step.name, inner, typeConstructor);
        break;
      }
      case "map": {
        inner = createIIFE(factory, step.name, inner, step.expression);
        break;
      }
      case "guard": {
        inner = factory.createConditionalExpression(step.condition, factory.createToken(ts.SyntaxKind.QuestionToken), inner, factory.createToken(ts.SyntaxKind.ColonToken), factory.createIdentifier("undefined"));
        break;
      }
    }
  }
  return inner;
}
function generateMethodCall(factory, expr, methodName, paramName, body, typeConstructor) {
  if (typeConstructor === "Array" || typeConstructor === "Promise") {
    return createMethodCall(factory, expr, methodName, createArrowFn(factory, paramName, body));
  }
  if (typeConstructor === "Effect") {
    return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Effect"), factory.createIdentifier(methodName)), void 0, [expr, createArrowFn(factory, paramName, body)]);
  }
  return createMethodCall(factory, expr, methodName, createArrowFn(factory, paramName, body));
}
function registerLetYield() {
  globalRegistry.register(letYieldMacro);
}
registerLetYield();

// src/macros/par-yield.ts
import * as ts2 from "typescript";
import { defineLabeledBlockMacro as defineLabeledBlockMacro2, globalRegistry as globalRegistry2 } from "@typesugar/core";
var parYieldMacro = defineLabeledBlockMacro2({
  name: "parYield",
  label: "par",
  continuationLabels: ["yield", "pure"],
  expand(ctx, mainBlock, continuation) {
    const { factory, typeChecker } = ctx;
    if (!ts2.isBlock(mainBlock.statement)) {
      ctx.reportError(mainBlock, "par: must be followed by a block { ... }");
      return mainBlock;
    }
    const steps = extractParSteps(ctx, mainBlock.statement);
    if (!steps || steps.length === 0) {
      ctx.reportError(mainBlock, "par: block must contain at least one binding");
      return mainBlock;
    }
    const hasBindStep = steps.some((s) => s.kind === "bind");
    if (!hasBindStep) {
      ctx.reportError(mainBlock, "par: block must contain at least one `name << expression` binding");
      return mainBlock;
    }
    if (!validateIndependence(ctx, steps)) {
      return mainBlock;
    }
    if (!continuation) {
      ctx.reportError(mainBlock, "par: requires a yield: or pure: block (applicative must have an explicit combining expression)");
      return mainBlock;
    }
    if (!ts2.isBlock(continuation.statement)) {
      ctx.reportError(continuation, `${continuation.label.text}: must be followed by a block { ... }`);
      return mainBlock;
    }
    const returnExpr = extractReturnExpr(ctx, continuation.statement);
    if (!returnExpr) {
      return mainBlock;
    }
    const firstBind = steps.find((s) => s.kind === "bind");
    const typeConstructorName = inferTypeConstructor(firstBind.effect, typeChecker);
    if (!typeConstructorName) {
      ctx.reportError(firstBind.effect, "Could not infer type constructor from expression. Make sure the expression has a known type (Array, Promise, Option, etc.)");
      return mainBlock;
    }
    if (!hasParCombineInstance(typeConstructorName)) {
      const result2 = buildApplicativeChain(ctx, steps, returnExpr);
      return factory.createExpressionStatement(result2);
    }
    const parCombineBuilder = getParCombineBuilderFromRegistry(typeConstructorName);
    const result = parCombineBuilder ? parCombineBuilder(ctx, steps, returnExpr) : buildApplicativeChain(ctx, steps, returnExpr);
    return factory.createExpressionStatement(result);
  }
});
function extractParSteps(ctx, block) {
  const steps = [];
  for (const stmt of block.statements) {
    if (ts2.isIfStatement(stmt)) {
      ctx.reportError(stmt, "par: blocks do not support guards (if). Use let: for monadic comprehensions with guards.");
      return void 0;
    }
    if (!ts2.isExpressionStatement(stmt)) {
      ctx.reportError(stmt, "par: block statements must be `name << expr` or `name = expr`");
      return void 0;
    }
    const expr = stmt.expression;
    if (!ts2.isBinaryExpression(expr)) {
      ctx.reportError(stmt, "Expected `name << expression` or `name = expression`");
      return void 0;
    }
    const opKind = expr.operatorToken.kind;
    if (opKind === ts2.SyntaxKind.FirstAssignment) {
      if (!ts2.isIdentifier(expr.left)) {
        ctx.reportError(expr.left, "Left side of = must be an identifier");
        return void 0;
      }
      steps.push({
        kind: "map",
        name: expr.left.text,
        expression: expr.right,
        node: stmt
      });
      continue;
    }
    if (opKind === ts2.SyntaxKind.BarBarToken || opKind === ts2.SyntaxKind.QuestionQuestionToken) {
      const lhs = expr.left;
      if (ts2.isBinaryExpression(lhs) && lhs.operatorToken.kind === ts2.SyntaxKind.LessThanLessThanToken) {
        ctx.reportError(stmt, "par: blocks do not support orElse (||/??). Use let: for monadic comprehensions with fallbacks.");
        return void 0;
      }
    }
    if (opKind === ts2.SyntaxKind.LessThanLessThanToken) {
      if (!ts2.isIdentifier(expr.left)) {
        ctx.reportError(expr.left, "Left side of << must be an identifier (variable name)");
        return void 0;
      }
      steps.push({
        kind: "bind",
        name: expr.left.text,
        effect: expr.right,
        node: stmt
      });
      continue;
    }
    ctx.reportError(stmt, "Expected `name << expression` or `name = expression`");
    return void 0;
  }
  return steps;
}
function validateIndependence(ctx, steps) {
  const boundNames = /* @__PURE__ */ new Set();
  let valid = true;
  for (const step of steps) {
    const refs = collectReferencedIdentifiers(step.kind === "bind" ? step.effect : step.expression);
    for (const ref of refs) {
      if (boundNames.has(ref)) {
        ctx.reportError(step.node, `par: bindings must be independent, but '${step.name}' references '${ref}' from a previous binding. Use let: for sequential/dependent bindings.`);
        valid = false;
      }
    }
    boundNames.add(step.name);
  }
  return valid;
}
function buildApplicativeChain(ctx, steps, returnExpr) {
  const { factory } = ctx;
  const bindSteps = steps.filter((s) => s.kind === "bind");
  const mapSteps = steps.filter((s) => s.kind === "map");
  let yieldExpr = returnExpr;
  for (let i = mapSteps.length - 1; i >= 0; i--) {
    const step = mapSteps[i];
    yieldExpr = createIIFE(factory, step.name, yieldExpr, step.expression);
  }
  if (bindSteps.length === 0) {
    return yieldExpr;
  }
  if (bindSteps.length === 1) {
    return createMethodCall(factory, bindSteps[0].effect, "map", createArrowFn(factory, bindSteps[0].name, yieldExpr));
  }
  let curriedBody = yieldExpr;
  for (let i = bindSteps.length - 1; i >= 1; i--) {
    curriedBody = createArrowFn(factory, bindSteps[i].name, curriedBody);
  }
  let chain = createMethodCall(factory, bindSteps[0].effect, "map", createArrowFn(factory, bindSteps[0].name, curriedBody));
  for (let i = 1; i < bindSteps.length; i++) {
    chain = createMethodCall(factory, chain, "ap", bindSteps[i].effect);
  }
  return chain;
}
function registerParYield() {
  globalRegistry2.register(parYieldMacro);
}
registerParYield();

// src/macros/match.ts
import * as ts3 from "typescript";
import { defineExpressionMacro, globalRegistry as globalRegistry3 } from "@typesugar/core";
function when(predicate, handler) {
  return { predicate, handler };
}
function otherwise(handler) {
  return { predicate: () => true, handler };
}
function isType(typeOrCtor) {
  if (typeof typeOrCtor === "string") {
    if (typeOrCtor === "null")
      return (v) => v === null;
    return (v) => typeof v === typeOrCtor;
  }
  return (v) => v instanceof typeOrCtor;
}
var P = {
  /**
   * Matches empty arrays: `arr.length === 0`
   *
   * Note: This also works on strings since strings have a `.length` property.
   * Using `P.empty` on a string will return true for empty strings `""`.
   * This is intentional - any value with `length === 0` matches.
   * See Finding #6 in FINDINGS.md.
   */
  empty: (arr) => arr.length === 0,
  /** Matches null or undefined */
  nil: (value) => value == null,
  /** Matches non-null, non-undefined */
  defined: (value) => value != null,
  /** Matches arrays of exactly n elements */
  length(n) {
    return (arr) => arr.length === n;
  },
  /** Matches arrays with at least n elements */
  minLength(n) {
    return (arr) => arr.length >= n;
  },
  /** Matches arrays whose first element satisfies a predicate */
  head(pred) {
    return (arr) => arr.length > 0 && pred(arr[0]);
  },
  /** Matches values in a set of allowed values */
  oneOf(...values) {
    const set = new Set(values);
    return (v) => set.has(v);
  },
  /** Matches values within a numeric range [lo, hi] inclusive */
  between(lo, hi) {
    return (v) => v >= lo && v <= hi;
  },
  /** Matches values satisfying all predicates */
  allOf(...preds) {
    return (v) => preds.every((p) => p(v));
  },
  /** Matches values satisfying any predicate (OR combinator for guards) */
  anyOf(...preds) {
    return (v) => preds.some((p) => p(v));
  },
  /** Matches objects that have a given property */
  has(key) {
    return (v) => typeof v === "object" && v !== null && key in v;
  },
  /** Matches strings against a regex */
  regex(pattern) {
    return (v) => pattern.test(v);
  }
};
function match(value, handlersOrArms, discriminant) {
  if (Array.isArray(handlersOrArms)) {
    for (const arm of handlersOrArms) {
      const result = arm.predicate(value);
      if (result && typeof result === "object" && typeof result.then === "function") {
        throw new Error("match() guard predicates must be synchronous. Use await before match() for async logic.");
      }
      if (result)
        return arm.handler(value);
    }
    throw new Error("Non-exhaustive match: no guard matched");
  }
  if (typeof value === "object" && value !== null) {
    const key = discriminant ?? inferDiscriminant(value, handlersOrArms);
    const tag = value[key];
    const handler2 = handlersOrArms[tag] ?? handlersOrArms._;
    if (!handler2)
      throw new Error(`Non-exhaustive match: no handler for '${String(tag)}'`);
    return handler2(value);
  }
  const handler = handlersOrArms[value] ?? handlersOrArms._;
  if (!handler)
    throw new Error(`Non-exhaustive match: no handler for '${String(value)}'`);
  return handler(value);
}
function inferDiscriminant(value, handlers) {
  const commonNames = [
    "kind",
    // FP-TS, typesugar conventions
    "_tag",
    // FP-TS convention
    "type",
    // Redux actions, DOM events
    "ok",
    // Result/Either patterns
    "status",
    // HTTP responses, state machines
    "tag",
    // Generic discriminant
    "discriminant",
    // Explicit discriminant
    "variant",
    // Rust-style enums
    "action",
    // Redux-style actions
    "event",
    // Event systems
    "case",
    // Pattern matching
    "state",
    // State machines
    "name",
    // AST nodes, enums
    "nodeType",
    // DOM nodes
    "message"
    // Message systems
  ];
  for (const name of commonNames) {
    if (name in value) {
      const tag = value[name];
      if (typeof tag === "string" || typeof tag === "number" || typeof tag === "boolean") {
        const tagKey = String(tag);
        if (tagKey in handlers || "_" in handlers) {
          return name;
        }
      }
    }
  }
  const handlerKeys = Object.keys(handlers).filter((k) => k !== "_");
  if (handlerKeys.length === 2 && handlerKeys.includes("true") && handlerKeys.includes("false")) {
    for (const [propName, propValue] of Object.entries(value)) {
      if (typeof propValue === "boolean") {
        return propName;
      }
    }
  }
  return "kind";
}
function matchLiteral(value, handlers) {
  const handler = handlers[value];
  if (handler)
    return handler(value);
  const wildcard = handlers["_"];
  if (wildcard)
    return wildcard(value);
  throw new Error(`Non-exhaustive match: no handler for '${value}'`);
}
function matchGuard(value, arms) {
  for (const [pred, handler] of arms) {
    if (pred(value))
      return handler(value);
  }
  throw new Error("Non-exhaustive match: no guard matched");
}
var KNOWN_DISCRIMINANTS = ["kind", "_tag", "type", "tag", "__typename", "ok", "status"];
function detectDiscriminant(type, checker) {
  if (!type.isUnion())
    return null;
  for (const candidate of KNOWN_DISCRIMINANTS) {
    let allHave = true;
    let allLiteral = true;
    for (const member of type.types) {
      const prop = member.getProperty(candidate);
      if (!prop) {
        allHave = false;
        break;
      }
      const propType = checker.getTypeOfSymbol(prop);
      if (!propType.isStringLiteral() && !propType.isNumberLiteral() && !(propType.flags & ts3.TypeFlags.BooleanLiteral)) {
        allLiteral = false;
        break;
      }
    }
    if (allHave && allLiteral)
      return candidate;
  }
  return null;
}
function getUnionVariantTags(type, discriminant, checker) {
  const tags = /* @__PURE__ */ new Set();
  if (!type.isUnion())
    return tags;
  for (const member of type.types) {
    const prop = member.getProperty(discriminant);
    if (!prop)
      continue;
    const propType = checker.getTypeOfSymbol(prop);
    if (propType.isStringLiteral()) {
      tags.add(propType.value);
    } else if (propType.isNumberLiteral()) {
      tags.add(String(propType.value));
    } else if (propType.flags & ts3.TypeFlags.BooleanLiteral) {
      const boolName = propType.intrinsicName;
      tags.add(boolName === "true" ? "true" : "false");
    }
  }
  return tags;
}
function getLiteralTypeValues(type) {
  const values = /* @__PURE__ */ new Set();
  if (type.isUnion()) {
    for (const member of type.types) {
      if (member.isStringLiteral())
        values.add(member.value);
      else if (member.isNumberLiteral())
        values.add(String(member.value));
      else
        return null;
    }
    return values.size > 0 ? values : null;
  }
  if (type.isStringLiteral()) {
    values.add(type.value);
    return values;
  }
  if (type.isNumberLiteral()) {
    values.add(String(type.value));
    return values;
  }
  return null;
}
function checkExhaustiveness(expectedVariants, providedKeys, hasWildcard) {
  const providedSet = new Set(providedKeys);
  const missing = [...expectedVariants].filter((v) => !providedSet.has(v));
  const extra = [...providedSet].filter((v) => !expectedVariants.has(v));
  return {
    isExhaustive: hasWildcard || missing.length === 0,
    missingVariants: missing,
    extraVariants: extra
  };
}
function performExhaustivenessCheck(ctx, callExpr, value, analysis) {
  const checker = ctx.typeChecker;
  const valueType = ctx.getTypeOf(value);
  let expectedVariants = null;
  if (analysis.form === 0 /* Discriminant */ && analysis.discriminant) {
    expectedVariants = getUnionVariantTags(valueType, analysis.discriminant, checker);
  } else if (analysis.form === 1 /* StringLiteral */ || analysis.form === 2 /* IntegerLiteral */) {
    expectedVariants = getLiteralTypeValues(valueType);
  }
  if (!expectedVariants || expectedVariants.size === 0)
    return;
  const result = checkExhaustiveness(expectedVariants, analysis.keys, analysis.hasWildcard);
  if (!result.isExhaustive && result.missingVariants.length > 0) {
    const label = result.missingVariants.length === 1 ? "case" : "cases";
    ctx.reportError(callExpr, `Non-exhaustive match: missing ${label} for ` + result.missingVariants.map((v) => `'${v}'`).join(", "));
  }
  for (const extra of result.extraVariants) {
    ctx.reportWarning(callExpr, `match() has handler for unknown variant '${extra}'`);
  }
}
var SWITCH_THRESHOLD = 6;
function generateTernaryChain(factory, entries, fallback) {
  let result = fallback;
  for (let i = entries.length - 1; i >= 0; i--) {
    result = factory.createConditionalExpression(entries[i].condition, factory.createToken(ts3.SyntaxKind.QuestionToken), entries[i].result, factory.createToken(ts3.SyntaxKind.ColonToken), result);
  }
  return result;
}
function generateBinarySearch(factory, scrutinee, entries, fallback) {
  const sorted = [...entries].sort((a, b) => a.value - b.value);
  return binarySearchHelper(factory, scrutinee, sorted, fallback, 0, sorted.length - 1);
}
function binarySearchHelper(factory, scrutinee, entries, fallback, lo, hi) {
  if (lo > hi)
    return fallback;
  if (lo === hi) {
    return factory.createConditionalExpression(factory.createBinaryExpression(scrutinee, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNumericLiteral(entries[lo].value)), factory.createToken(ts3.SyntaxKind.QuestionToken), entries[lo].result, factory.createToken(ts3.SyntaxKind.ColonToken), fallback);
  }
  const mid = lo + hi >>> 1;
  const midValue = entries[mid].value;
  return factory.createConditionalExpression(factory.createBinaryExpression(scrutinee, factory.createToken(ts3.SyntaxKind.LessThanToken), factory.createNumericLiteral(midValue)), factory.createToken(ts3.SyntaxKind.QuestionToken), binarySearchHelper(factory, scrutinee, entries, fallback, lo, mid - 1), factory.createToken(ts3.SyntaxKind.ColonToken), factory.createConditionalExpression(factory.createBinaryExpression(scrutinee, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNumericLiteral(midValue)), factory.createToken(ts3.SyntaxKind.QuestionToken), entries[mid].result, factory.createToken(ts3.SyntaxKind.ColonToken), binarySearchHelper(factory, scrutinee, entries, fallback, mid + 1, hi)));
}
function isDenseIntegerRange(values) {
  if (values.length < 2)
    return true;
  const sorted = [...values].sort((a, b) => a - b);
  const range = sorted[sorted.length - 1] - sorted[0] + 1;
  return range <= values.length * 2;
}
function generateThrowIIFE(factory, message) {
  return factory.createCallExpression(factory.createParenthesizedExpression(factory.createArrowFunction(void 0, void 0, [], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), factory.createBlock([
    factory.createThrowStatement(factory.createNewExpression(factory.createIdentifier("Error"), void 0, [
      factory.createStringLiteral(message)
    ]))
  ]))), void 0, []);
}
function extractHandlers(factory, obj) {
  const entries = [];
  let wildcardHandler;
  for (const prop of obj.properties) {
    if (!ts3.isPropertyAssignment(prop) && !ts3.isMethodDeclaration(prop))
      continue;
    const rawName = ts3.isIdentifier(prop.name) ? prop.name.text : ts3.isStringLiteral(prop.name) ? prop.name.text : ts3.isNumericLiteral(prop.name) ? prop.name.text : null;
    if (!rawName)
      continue;
    let handler;
    if (ts3.isPropertyAssignment(prop)) {
      handler = prop.initializer;
    } else {
      handler = factory.createArrowFunction(void 0, void 0, prop.parameters, void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), prop.body ?? factory.createBlock([]));
    }
    if (rawName === "_") {
      wildcardHandler = handler;
    } else {
      const names = rawName.includes("|") ? rawName.split("|").map((s) => s.trim()).filter(Boolean) : [rawName];
      entries.push({ names, handler });
    }
  }
  return { entries, wildcardHandler };
}
function analyzeMatchForm(ctx, value, handlers, explicitDiscriminant) {
  const factory = ctx.factory;
  const checker = ctx.typeChecker;
  const valueType = ctx.getTypeOf(value);
  const { entries, wildcardHandler } = extractHandlers(factory, handlers);
  const keys = entries.flatMap((e) => e.names);
  const hasWildcard = wildcardHandler !== void 0;
  if (explicitDiscriminant) {
    return {
      form: 0 /* Discriminant */,
      discriminant: explicitDiscriminant,
      keys,
      handlers: entries,
      wildcardHandler,
      hasWildcard
    };
  }
  if (keys.length > 0 && keys.every((k) => !isNaN(Number(k)) && k.trim() !== "")) {
    return {
      form: 2 /* IntegerLiteral */,
      keys,
      handlers: entries,
      wildcardHandler,
      hasWildcard
    };
  }
  const disc = detectDiscriminant(valueType, checker);
  if (disc) {
    return {
      form: 0 /* Discriminant */,
      discriminant: disc,
      keys,
      handlers: entries,
      wildcardHandler,
      hasWildcard
    };
  }
  const literalValues = getLiteralTypeValues(valueType);
  if (literalValues) {
    return {
      form: 1 /* StringLiteral */,
      keys,
      handlers: entries,
      wildcardHandler,
      hasWildcard
    };
  }
  return {
    form: 4 /* Mixed */,
    keys,
    handlers: entries,
    wildcardHandler,
    hasWildcard
  };
}
function buildDiscriminantCondition(factory, scrutinee, disc, names) {
  const conditions = names.map((name) => factory.createBinaryExpression(factory.createPropertyAccessExpression(scrutinee, disc), factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral(name)));
  if (conditions.length === 1)
    return conditions[0];
  return factory.createParenthesizedExpression(conditions.reduce((left, right) => factory.createBinaryExpression(left, factory.createToken(ts3.SyntaxKind.BarBarToken), right)));
}
function expandDiscriminantMatch(ctx, value, analysis) {
  const factory = ctx.factory;
  const disc = analysis.discriminant;
  const fallback = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [value]) : generateThrowIIFE(factory, "Non-exhaustive match");
  const totalKeys = analysis.keys.length;
  if (totalKeys > SWITCH_THRESHOLD) {
    const paramId = factory.createIdentifier("__v");
    const switchCases = [];
    for (const h of analysis.handlers) {
      for (let i = 0; i < h.names.length; i++) {
        if (i < h.names.length - 1) {
          switchCases.push(factory.createCaseClause(factory.createStringLiteral(h.names[i]), []));
        } else {
          switchCases.push(factory.createCaseClause(factory.createStringLiteral(h.names[i]), [
            factory.createReturnStatement(factory.createCallExpression(h.handler, void 0, [paramId]))
          ]));
        }
      }
    }
    const defaultBody = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [paramId]) : generateThrowIIFE(factory, "Non-exhaustive match");
    switchCases.push(factory.createDefaultClause([factory.createReturnStatement(defaultBody)]));
    const param = factory.createParameterDeclaration(void 0, void 0, paramId);
    const switchStmt = factory.createSwitchStatement(factory.createPropertyAccessExpression(paramId, disc), factory.createCaseBlock(switchCases));
    const fn = factory.createArrowFunction(void 0, void 0, [param], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), factory.createBlock([switchStmt], true));
    return factory.createCallExpression(factory.createParenthesizedExpression(fn), void 0, [
      value
    ]);
  }
  const entries = analysis.handlers.map((h) => ({
    condition: buildDiscriminantCondition(factory, value, disc, h.names),
    result: factory.createCallExpression(h.handler, void 0, [value])
  }));
  return generateTernaryChain(factory, entries, fallback);
}
function expandIntegerMatch(ctx, value, analysis) {
  const factory = ctx.factory;
  const fallback = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [value]) : generateThrowIIFE(factory, "Non-exhaustive match");
  const flatEntries = [];
  for (const h of analysis.handlers) {
    for (const name of h.names) {
      flatEntries.push({ value: Number(name), handler: h.handler });
    }
  }
  const values = flatEntries.map((e) => e.value);
  if (flatEntries.length > SWITCH_THRESHOLD && isDenseIntegerRange(values)) {
    const paramId = factory.createIdentifier("__v");
    const switchCases = [];
    for (const h of analysis.handlers) {
      const nums = h.names.map(Number);
      for (let i = 0; i < nums.length; i++) {
        if (i < nums.length - 1) {
          switchCases.push(factory.createCaseClause(factory.createNumericLiteral(nums[i]), []));
        } else {
          switchCases.push(factory.createCaseClause(factory.createNumericLiteral(nums[i]), [
            factory.createReturnStatement(factory.createCallExpression(h.handler, void 0, [paramId]))
          ]));
        }
      }
    }
    const defaultBody = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [paramId]) : generateThrowIIFE(factory, "Non-exhaustive match");
    switchCases.push(factory.createDefaultClause([factory.createReturnStatement(defaultBody)]));
    const param = factory.createParameterDeclaration(void 0, void 0, paramId);
    const switchStmt = factory.createSwitchStatement(paramId, factory.createCaseBlock(switchCases));
    const fn = factory.createArrowFunction(void 0, void 0, [param], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), factory.createBlock([switchStmt], true));
    return factory.createCallExpression(factory.createParenthesizedExpression(fn), void 0, [
      value
    ]);
  }
  if (flatEntries.length > SWITCH_THRESHOLD) {
    const bsEntries = flatEntries.map((e) => ({
      value: e.value,
      result: factory.createCallExpression(e.handler, void 0, [value])
    }));
    return generateBinarySearch(factory, value, bsEntries, fallback);
  }
  const entries = analysis.handlers.map((h) => {
    const nums = h.names.map(Number);
    const condition = nums.length === 1 ? factory.createBinaryExpression(value, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNumericLiteral(nums[0])) : factory.createParenthesizedExpression(nums.map((n) => factory.createBinaryExpression(value, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNumericLiteral(n))).reduce((left, right) => factory.createBinaryExpression(left, factory.createToken(ts3.SyntaxKind.BarBarToken), right)));
    return {
      condition,
      result: factory.createCallExpression(h.handler, void 0, [value])
    };
  });
  return generateTernaryChain(factory, entries, fallback);
}
function expandLiteralMatch(ctx, value, analysis) {
  const factory = ctx.factory;
  const fallback = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [value]) : generateThrowIIFE(factory, "Non-exhaustive match");
  const totalKeys = analysis.keys.length;
  if (totalKeys > SWITCH_THRESHOLD) {
    const paramId = factory.createIdentifier("__v");
    const switchCases = [];
    for (const h of analysis.handlers) {
      for (let i = 0; i < h.names.length; i++) {
        if (i < h.names.length - 1) {
          switchCases.push(factory.createCaseClause(factory.createStringLiteral(h.names[i]), []));
        } else {
          switchCases.push(factory.createCaseClause(factory.createStringLiteral(h.names[i]), [
            factory.createReturnStatement(factory.createCallExpression(h.handler, void 0, [paramId]))
          ]));
        }
      }
    }
    const defaultBody = analysis.wildcardHandler ? factory.createCallExpression(analysis.wildcardHandler, void 0, [paramId]) : generateThrowIIFE(factory, "Non-exhaustive match");
    switchCases.push(factory.createDefaultClause([factory.createReturnStatement(defaultBody)]));
    const param = factory.createParameterDeclaration(void 0, void 0, paramId);
    const switchStmt = factory.createSwitchStatement(paramId, factory.createCaseBlock(switchCases));
    const fn = factory.createArrowFunction(void 0, void 0, [param], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), factory.createBlock([switchStmt], true));
    return factory.createCallExpression(factory.createParenthesizedExpression(fn), void 0, [
      value
    ]);
  }
  const entries = analysis.handlers.map((h) => {
    const condition = h.names.length === 1 ? factory.createBinaryExpression(value, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral(h.names[0])) : factory.createParenthesizedExpression(h.names.map((name) => factory.createBinaryExpression(value, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral(name))).reduce((left, right) => factory.createBinaryExpression(left, factory.createToken(ts3.SyntaxKind.BarBarToken), right)));
    return {
      condition,
      result: factory.createCallExpression(h.handler, void 0, [value])
    };
  });
  return generateTernaryChain(factory, entries, fallback);
}
function tryOptimizeGuardPredicate(factory, node) {
  const paramId = factory.createIdentifier("__x");
  const param = factory.createParameterDeclaration(void 0, void 0, paramId);
  const makeArrow = (body) => factory.createArrowFunction(void 0, void 0, [param], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), body);
  if (ts3.isCallExpression(node) && ts3.isIdentifier(node.expression) && node.expression.text === "isType" && node.arguments.length === 1) {
    const arg = node.arguments[0];
    if (ts3.isStringLiteral(arg)) {
      const typeName = arg.text;
      if (typeName === "null") {
        return makeArrow(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNull()));
      }
      return makeArrow(factory.createBinaryExpression(factory.createTypeOfExpression(paramId), factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral(typeName)));
    }
    return makeArrow(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.InstanceOfKeyword), arg));
  }
  if (ts3.isPropertyAccessExpression(node) && ts3.isIdentifier(node.expression) && node.expression.text === "P") {
    const prop = node.name.text;
    if (prop === "empty") {
      return makeArrow(factory.createBinaryExpression(factory.createPropertyAccessExpression(paramId, "length"), factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createNumericLiteral(0)));
    }
    if (prop === "nil") {
      return makeArrow(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.EqualsEqualsToken), factory.createNull()));
    }
    if (prop === "defined") {
      return makeArrow(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.ExclamationEqualsToken), factory.createNull()));
    }
  }
  if (ts3.isCallExpression(node) && ts3.isPropertyAccessExpression(node.expression) && ts3.isIdentifier(node.expression.expression) && node.expression.expression.text === "P") {
    const method = node.expression.name.text;
    const args = node.arguments;
    if (method === "length" && args.length === 1) {
      return makeArrow(factory.createBinaryExpression(factory.createPropertyAccessExpression(paramId, "length"), factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), args[0]));
    }
    if (method === "minLength" && args.length === 1) {
      return makeArrow(factory.createBinaryExpression(factory.createPropertyAccessExpression(paramId, "length"), factory.createToken(ts3.SyntaxKind.GreaterThanEqualsToken), args[0]));
    }
    if (method === "between" && args.length === 2) {
      return makeArrow(factory.createBinaryExpression(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.GreaterThanEqualsToken), args[0]), factory.createToken(ts3.SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.LessThanEqualsToken), args[1])));
    }
    if (method === "oneOf" && args.length > 0) {
      const checks = Array.from(args).map((arg) => factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), arg));
      const combined = checks.reduce((left, right) => factory.createBinaryExpression(left, factory.createToken(ts3.SyntaxKind.BarBarToken), right));
      return makeArrow(args.length > 1 ? factory.createParenthesizedExpression(combined) : combined);
    }
    if (method === "head" && args.length === 1) {
      return makeArrow(factory.createBinaryExpression(factory.createBinaryExpression(factory.createPropertyAccessExpression(paramId, "length"), factory.createToken(ts3.SyntaxKind.GreaterThanToken), factory.createNumericLiteral(0)), factory.createToken(ts3.SyntaxKind.AmpersandAmpersandToken), factory.createCallExpression(args[0], void 0, [
        factory.createElementAccessExpression(paramId, factory.createNumericLiteral(0))
      ])));
    }
    if (method === "has" && args.length === 1) {
      return makeArrow(factory.createBinaryExpression(factory.createBinaryExpression(factory.createTypeOfExpression(paramId), factory.createToken(ts3.SyntaxKind.EqualsEqualsEqualsToken), factory.createStringLiteral("object")), factory.createToken(ts3.SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(factory.createBinaryExpression(paramId, factory.createToken(ts3.SyntaxKind.ExclamationEqualsEqualsToken), factory.createNull()), factory.createToken(ts3.SyntaxKind.AmpersandAmpersandToken), factory.createBinaryExpression(args[0], factory.createToken(ts3.SyntaxKind.InKeyword), paramId))));
    }
    if (method === "regex" && args.length === 1) {
      return makeArrow(factory.createCallExpression(factory.createPropertyAccessExpression(args[0], "test"), void 0, [paramId]));
    }
  }
  return void 0;
}
function expandGuardMatch(ctx, callExpr, value, arms) {
  const factory = ctx.factory;
  const guardArms = [];
  for (const element of arms.elements) {
    if (ts3.isCallExpression(element) && ts3.isIdentifier(element.expression)) {
      const fnName = element.expression.text;
      if (fnName === "when" && element.arguments.length === 2) {
        const rawPred = element.arguments[0];
        const predicate = tryOptimizeGuardPredicate(factory, rawPred) ?? rawPred;
        guardArms.push({
          predicate,
          handler: element.arguments[1]
        });
        continue;
      }
      if (fnName === "otherwise" && element.arguments.length === 1) {
        guardArms.push({
          predicate: factory.createArrowFunction(void 0, void 0, [], void 0, factory.createToken(ts3.SyntaxKind.EqualsGreaterThanToken), factory.createTrue()),
          handler: element.arguments[0]
        });
        continue;
      }
    }
    if (ts3.isArrayLiteralExpression(element) && element.elements.length === 2) {
      guardArms.push({
        predicate: element.elements[0],
        handler: element.elements[1]
      });
      continue;
    }
    ctx.reportError(element, "Invalid match arm: expected when(pred, handler), otherwise(handler), or [pred, handler]");
  }
  if (guardArms.length === 0) {
    ctx.reportError(callExpr, "match() requires at least one arm");
    return callExpr;
  }
  const fallback = generateThrowIIFE(factory, "Non-exhaustive match: no guard matched");
  const entries = guardArms.map((arm) => ({
    condition: factory.createCallExpression(arm.predicate, void 0, [value]),
    result: factory.createCallExpression(arm.handler, void 0, [value])
  }));
  return generateTernaryChain(factory, entries, fallback);
}
function expandMatch(ctx, callExpr, args) {
  if (args.length < 2) {
    ctx.reportError(callExpr, "match() requires at least 2 arguments: value and handlers/arms");
    return callExpr;
  }
  const value = args[0];
  const handlersOrArms = args[1];
  if (ts3.isArrayLiteralExpression(handlersOrArms)) {
    return expandGuardMatch(ctx, callExpr, value, handlersOrArms);
  }
  if (!ts3.isObjectLiteralExpression(handlersOrArms)) {
    ctx.reportError(handlersOrArms, "match() second argument must be an object literal or array of guard arms");
    return callExpr;
  }
  let explicitDiscriminant;
  if (args.length >= 3 && ts3.isStringLiteral(args[2])) {
    explicitDiscriminant = args[2].text;
  }
  const analysis = analyzeMatchForm(ctx, value, handlersOrArms, explicitDiscriminant);
  performExhaustivenessCheck(ctx, callExpr, value, analysis);
  switch (analysis.form) {
    case 0 /* Discriminant */:
      return expandDiscriminantMatch(ctx, value, analysis);
    case 2 /* IntegerLiteral */:
      return expandIntegerMatch(ctx, value, analysis);
    case 1 /* StringLiteral */:
    case 4 /* Mixed */:
      return expandLiteralMatch(ctx, value, analysis);
    default:
      return callExpr;
  }
}
var matchMacro = defineExpressionMacro({
  name: "match",
  module: "@typesugar/std",
  description: "Zero-cost exhaustive pattern matching with compile-time optimization",
  expand: expandMatch
});
var matchLiteralMacro = defineExpressionMacro({
  name: "matchLiteral",
  module: "@typesugar/std",
  description: "Zero-cost literal matching (deprecated \u2014 use match())",
  expand: expandMatch
});
var matchGuardMacro = defineExpressionMacro({
  name: "matchGuard",
  module: "@typesugar/std",
  description: "Zero-cost guard matching (deprecated \u2014 use match())",
  expand: expandMatch
});
globalRegistry3.register(matchMacro);
globalRegistry3.register(matchLiteralMacro);
globalRegistry3.register(matchGuardMacro);

// src/macros/register-instances.ts
import { defineExpressionMacro as defineExpressionMacro2, globalRegistry as globalRegistry4 } from "@typesugar/core";
var TYPECLASS_DEFS = [
  {
    name: "Eq",
    typeParam: "A",
    methods: [
      {
        name: "equals",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: "==="
      },
      {
        name: "notEquals",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: "!=="
      }
    ],
    canDeriveProduct: true,
    canDeriveSum: true,
    syntax: /* @__PURE__ */ new Map([
      ["===", "equals"],
      ["!==", "notEquals"]
    ])
  },
  {
    name: "Ord",
    typeParam: "A",
    methods: [
      {
        name: "compare",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "Ordering",
        isSelfMethod: true
      },
      {
        name: "lessThan",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: "<"
      },
      {
        name: "lessThanOrEqual",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: "<="
      },
      {
        name: "greaterThan",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: ">"
      },
      {
        name: "greaterThanOrEqual",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "boolean",
        isSelfMethod: true,
        operatorSymbol: ">="
      }
    ],
    canDeriveProduct: true,
    canDeriveSum: true,
    syntax: /* @__PURE__ */ new Map([
      ["<", "lessThan"],
      ["<=", "lessThanOrEqual"],
      [">", "greaterThan"],
      [">=", "greaterThanOrEqual"]
    ])
  },
  {
    name: "Semigroup",
    typeParam: "A",
    methods: [
      {
        name: "combine",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "+"
      }
    ],
    canDeriveProduct: true,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([["+", "combine"]])
  },
  {
    name: "Monoid",
    typeParam: "A",
    methods: [
      {
        name: "empty",
        params: [],
        returnType: "A",
        isSelfMethod: false
      },
      {
        name: "combine",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "+"
      }
    ],
    canDeriveProduct: true,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([["+", "combine"]])
  },
  {
    name: "Group",
    typeParam: "A",
    methods: [
      {
        name: "empty",
        params: [],
        returnType: "A",
        isSelfMethod: false
      },
      {
        name: "combine",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "+"
      },
      {
        name: "invert",
        params: [{ name: "a", typeString: "A" }],
        returnType: "A",
        isSelfMethod: true
      }
    ],
    canDeriveProduct: false,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([["+", "combine"]])
  },
  {
    name: "Numeric",
    typeParam: "A",
    methods: [
      {
        name: "add",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "+"
      },
      {
        name: "sub",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "-"
      },
      {
        name: "mul",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "*"
      }
    ],
    canDeriveProduct: false,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([
      ["+", "add"],
      ["-", "sub"],
      ["*", "mul"]
    ])
  },
  {
    name: "Integral",
    typeParam: "A",
    methods: [
      {
        name: "div",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "/"
      },
      {
        name: "mod",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "%"
      }
    ],
    canDeriveProduct: false,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([
      ["/", "div"],
      ["%", "mod"]
    ])
  },
  {
    name: "Fractional",
    typeParam: "A",
    methods: [
      {
        name: "div",
        params: [
          { name: "a", typeString: "A" },
          { name: "b", typeString: "A" }
        ],
        returnType: "A",
        isSelfMethod: true,
        operatorSymbol: "/"
      }
    ],
    canDeriveProduct: false,
    canDeriveSum: false,
    syntax: /* @__PURE__ */ new Map([["/", "div"]])
  }
];
var STD_INSTANCES = [
  // Eq instances
  {
    typeclass: "Eq",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "eqNumber"
  },
  {
    typeclass: "Eq",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "eqString"
  },
  {
    typeclass: "Eq",
    forType: "boolean",
    importPath: "@typesugar/std/typeclasses",
    exportName: "eqBoolean"
  },
  {
    typeclass: "Eq",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "eqBigInt"
  },
  {
    typeclass: "Eq",
    forType: "Date",
    importPath: "@typesugar/std/typeclasses",
    exportName: "eqDate"
  },
  // Ord instances
  {
    typeclass: "Ord",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "ordNumber"
  },
  {
    typeclass: "Ord",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "ordString"
  },
  {
    typeclass: "Ord",
    forType: "boolean",
    importPath: "@typesugar/std/typeclasses",
    exportName: "ordBoolean"
  },
  {
    typeclass: "Ord",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "ordBigInt"
  },
  {
    typeclass: "Ord",
    forType: "Date",
    importPath: "@typesugar/std/typeclasses",
    exportName: "ordDate"
  },
  // Semigroup instances
  {
    typeclass: "Semigroup",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "semigroupNumber"
  },
  {
    typeclass: "Semigroup",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "semigroupString"
  },
  {
    typeclass: "Semigroup",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "semigroupBigInt"
  },
  // Monoid instances
  {
    typeclass: "Monoid",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "monoidNumber"
  },
  {
    typeclass: "Monoid",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "monoidString"
  },
  {
    typeclass: "Monoid",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "monoidBigInt"
  },
  // Group instances
  {
    typeclass: "Group",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "groupNumber"
  },
  {
    typeclass: "Group",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "groupBigInt"
  },
  // Bounded instances
  {
    typeclass: "Bounded",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "boundedNumber"
  },
  {
    typeclass: "Bounded",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "boundedBigInt"
  },
  {
    typeclass: "Bounded",
    forType: "boolean",
    importPath: "@typesugar/std/typeclasses",
    exportName: "boundedBoolean"
  },
  {
    typeclass: "Bounded",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "boundedString"
  },
  // Enum instances
  {
    typeclass: "Enum",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "enumNumber"
  },
  {
    typeclass: "Enum",
    forType: "boolean",
    importPath: "@typesugar/std/typeclasses",
    exportName: "enumBoolean"
  },
  {
    typeclass: "Enum",
    forType: "string",
    importPath: "@typesugar/std/typeclasses",
    exportName: "enumString"
  },
  // Numeric instances (Ring with Op<+>, Op<->, Op<*>)
  {
    typeclass: "Numeric",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "numericNumber"
  },
  {
    typeclass: "Numeric",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "numericBigInt"
  },
  // Integral instances (Euclidean Ring with Op</>, Op<%>)
  {
    typeclass: "Integral",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "integralNumber"
  },
  {
    typeclass: "Integral",
    forType: "bigint",
    importPath: "@typesugar/std/typeclasses",
    exportName: "integralBigInt"
  },
  // Fractional instances (Field with Op</>)
  {
    typeclass: "Fractional",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "fractionalNumber"
  },
  // Floating instances (transcendental functions)
  {
    typeclass: "Floating",
    forType: "number",
    importPath: "@typesugar/std/typeclasses",
    exportName: "floatingNumber"
  },
  // FlatMap instances (HKT)
  {
    typeclass: "FlatMap",
    forType: "Array",
    importPath: "@typesugar/std/typeclasses/flatmap",
    exportName: "flatMapArray"
  },
  {
    typeclass: "FlatMap",
    forType: "Promise",
    importPath: "@typesugar/std/typeclasses/flatmap",
    exportName: "flatMapPromise"
  },
  {
    typeclass: "FlatMap",
    forType: "Iterable",
    importPath: "@typesugar/std/typeclasses/flatmap",
    exportName: "flatMapIterable"
  },
  {
    typeclass: "FlatMap",
    forType: "AsyncIterable",
    importPath: "@typesugar/std/typeclasses/flatmap",
    exportName: "flatMapAsyncIterable"
  },
  // Data type instances
  { typeclass: "Eq", forType: "Range", importPath: "@typesugar/std/data", exportName: "eqRange" },
  { typeclass: "Ord", forType: "Range", importPath: "@typesugar/std/data", exportName: "ordRange" }
];
var _registered = false;
function performRegistration() {
  if (_registered)
    return;
  _registered = true;
  for (const tcDef of TYPECLASS_DEFS) {
    registerTypeclassDef(tcDef);
  }
  for (const inst of STD_INSTANCES) {
    const info = {
      typeclassName: inst.typeclass,
      forType: inst.forType,
      instanceName: inst.exportName,
      derived: false
    };
    registerInstanceWithMeta(info);
  }
}
performRegistration();
var registerStdInstancesMacro = defineExpressionMacro2({
  name: "registerStdInstances",
  module: "@typesugar/std/macros",
  description: "Register all @typesugar/std typeclass instances for summon<>() and operator dispatch",
  expand(ctx, _callExpr, _args) {
    const { factory } = ctx;
    return factory.createVoidExpression(factory.createNumericLiteral("0"));
  }
});
function registerStdInstances() {
}
function register() {
  globalRegistry4.register(registerStdInstancesMacro);
}
register();

export {
  letYieldMacro,
  registerLetYield,
  parYieldMacro,
  registerParYield,
  when,
  otherwise,
  isType,
  P,
  match,
  matchLiteral,
  matchGuard,
  matchMacro,
  matchLiteralMacro,
  matchGuardMacro,
  registerStdInstancesMacro,
  registerStdInstances
};
//# sourceMappingURL=chunk-7M4W4PN2.js.map