Skip to main content
NM-RFC-0035

Bounded classical functions

Design document · Original source

RFCs record designs and changes. A proposal appearing here does not mean its feature is ready to use. Explore current language support

Status recorded in the original: Local experimental candidate · product promotion pending

Bound original source · SHA-256
ad912072a547523b38ee5fbdde0ae43bcb91c8725fc009f3697efcd198422ce6

Status: local runtime-experimental candidate; product catalog/promotion pending Date: 2026-09-19 Current 2026-09-20 extensions: The staged sections below record earlier slices. Their original restrictions on helper loops, all-local immutability and computed helper indices are superseded by T08 bounded helper loops. Pure helpers support explicit mutable Int/Float locals, fixed literal 0–256 end-exclusive for ranges and checked Int-expression indices; parameters, normal let, ok payloads and arrays stay immutable. Loop indices and per-iteration locals remain scoped; nested loops/calls share 4096 evaluation steps and a fallback return after the loop is required. Main indexing is unchanged. Analytic gradients/training reject loops, mutation and dynamic indices. Earlier main-block and Result-local restrictions are superseded only within the documented T06 main-control and T07 helper Result-recovery scopes; main Result locals/matches remain unsupported. Güncel 20 Eylül kapsamı: Önceki dilimlerin döngü, tüm yerellerin değiştirilemezliği ve hesaplanan yardımcı indisleriyle ilgili sınırları yukarıdaki T08 rehberiyle güncellenmiştir. Yalnız açık let mut Int/Float yeniden atanabilir; dizi/parametre/normal let/ok payload değiştirilemez. Sabit aralık ve 4096 adım bütçesi geçerlidir, main indisleri değişmez. T06/T07 eklemeleri kendi rehberleriyle sınırlıdır; main Result yereli/match eklenmez. 2026-09-20 extension: Shared bounded Float sin/cos/sqrt intrinsics now work in typed main declarations, helpers and explicitly enabled direct gate angles. Signatures, runtime and analytic differentiation share one catalogue; Int conversion remains explicit, and parameter-dependent sqrt at zero is conservatively unsupported for gradients. See the TR/EN implementation guide and task T05. Prototype contract: 0.1-internal-prototype 2026-09-21 extension / genişletme: The shared unary Float catalogue additionally supports exp, log, log1p, expm1, tanh, and sigmoid, including analytic chain rules and IDE signatures. Domain/overflow failures preserve the existing bounded Float contract; the six new names are reserved in helpers. See the TR/EN math guide. Ortak tek argümanlı Float kataloğu bu altı işlemi, zincir kuralını ve editör imzalarını kapsar; domain/taşma hataları açıkça reddedilir. Yerel geliştirmedir; paket yayını veya capability terfisi değildir. Depends on: NM-RFC-0005 numeric semantics; NM-RFC-0007 typed main results (Bool extension described below)

2026-09-21 piecewise extension: abs, floor, ceil, and round accept/return bounded Float and canonicalize zero results to positive zero. Round ties go toward positive infinity. Analytic derivatives reject parameter-dependent abs at zero, floor/ceil at integer inputs and round at exact half-integers; otherwise abs uses its sign and rounding uses zero. Dependency provenance is retained. Parçalı işlemler aynı Float sözleşmesini ve pozitif sıfır normalizasyonunu kullanır; türev süreksizlikleri reddedilir, sıfır türev bağımlılığı silmez. Bu kapsam min/max/clamp veya vektör işlemleri eklemez.

1. Purpose and implementation boundary

Reusable classical calculations need named functions with parameters, local values and checked return types. The first slice implements a separate source analyzer and evaluator in lib/nm/classical-functions. Both require { enabled: true } explicitly. They accept a function-only source module and an explicitly selected entry function.

The second slice connects parseNMCode and executeNMCode through experimental.classicalFunctions=true, requiring typedClassicalValues=true independently. It statically lowers bounded calls to existing typed classical statements and retains function/call provenance on the parsed program. Core, Worker, CLI, MCP and LSP carry the flag; VS Code exposes a default-off setting. The third slice adds the Playground toggle, example and bilingual guide. This is a local candidate, not a promoted capability or released package; the product capability catalog is unchanged pending the remaining integration work. Existing fn main() -> Result<T, Error> behavior still requires its own functionResults flag.

2. Historical first-slice grammar

This section records the initial numeric-only prototype. The helper-array and Bool/branch extensions below define the current additions.

nm
module classical_demo;

fn square(x: Float) -> Float {
  return x * x;
}

fn energy(theta: Float, weight: Float) -> Float {
  let scaled: Float = weight * square(theta);
  return scaled + 0.5;
}

  • One optional module name; header, then one or more function declarations.
  • Parameter and result types are exactly Int or Float.
  • Each body contains zero or more immutable typed let declarations followed by exactly one final return expression;.
  • Expressions support decimal literals with a leading digit, earlier locals, parameters, parentheses, unary minus, +, -, *, /, %, named calls and explicit int_to_float(...).
  • Declarations may appear after their callers. Calls are statically resolved within this source module; no imports, closures or captured globals exist.
  • Duplicate functions/parameters/locals, use before declaration, function-name shadowing and reserved names are errors. main is reserved to avoid confusing this selected-function API with program execution.
  • Signatures require exact types: an Int argument never satisfies a Float parameter implicitly. Existing NM-RFC-0005 arithmetic is reused: / produces Float, mixed numeric arithmetic produces Float, and % requires Int operands.
  • Decimal exponent notation, arrays, Bit/Bool, quantum values, branches, loops, mutation, visibility/export syntax, Result propagation and higher-order functions are outside this slice.

3. Analysis and execution

All declarations are checked, including unused functions. A call graph rejects direct and indirect recursion and limits the longest call chain before execution. Each call gets a fresh Map environment; prototype-shaped names such as __proto__ cannot mutate object prototypes. Arguments are evaluated once, left to right. Calls and expression evaluations share a per-execution step budget, so an acyclic exponentially expanding call graph is still bounded.

The public-facing internal entry points are analyzeNMClassicalFunctions(source, options) and executeNMClassicalFunction(source, entry, typedArguments, options). Execution always revalidates original source rather than trusting a supplied AST or analysis result. Analysis returns signatures, not an executable serialized artifact. Call arguments are copied and checked for exact type and numeric bounds.

Integer values remain safe integers; Float values must be finite with absolute value at most 10^12. Division/remainder by zero and out-of-bounds intermediate values fail. Failures publish a diagnostic, never a partial result. Success publishes the typed scalar or numeric array value, prototype contract version and deterministic evaluation step count; it is not a quantum simulation or programResult.

4. Limits

Table 1
ResourceMaximum
UTF-8 source bytes32,768
Non-trivia tokens4,096
Functions per source module32
Parameters / arguments8
Local declarations per function32
Expression nesting / AST path nodes32
Simultaneously active function calls16
Call entries plus expression evaluations4,096

Source length is checked before tokenization. Parser nesting and semantic AST depth are checked separately; a flat additive chain cannot bypass the AST depth bound. Exact boundary acceptance is covered by tests where applicable.

5. Diagnostics and localization

Every diagnostic carries a one-based line/column and both English and Turkish messages. Source identifiers and ASTs are not embedded in error messages.

Table 2
CodeMeaning
NM-CFN-001Explicit prototype opt-in missing
NM-CFN-002Invalid or unsupported syntax
NM-CFN-003Resource budget exceeded
NM-CFN-004Invalid binding or name resolution
NM-CFN-005Invalid type, argument count or numeric literal
NM-CFN-006Recursive call graph
NM-CFN-007Runtime arithmetic failure
NM-CFN-008Invalid selected entry or external arguments
NM-CFN-009Unsupported production call context
NM-CFN-010Missing prerequisites or unsupported feature combination
NM-CFN-011Transformation lacks a function-preserving carrier

6. Remaining integration sequence

  1. Completed locally: negotiated parser lowering with declaration/call provenance; typed bindings and main results accept calls, including measurement-derived arguments. Generated bindings evaluate arguments once in source order and use a reserved __nm_cfn_ namespace.
  2. Completed locally: Core/Worker/CLI/MCP result parity, LSP diagnostics negotiation and a VS Code setting. Completed locally in the next slice: Playground toggle, runnable catalog example and bilingual guide. The IDE slice now adds local signature help, scope-aware go-to-definition and full-range typed document symbols in LSP/VS Code and Playground. Scoped completion, hover and semantic highlighting are available locally. Scoped references and safe rename are available for complete, valid programs in the active file, including helper branches; nested main blocks remain restricted. Legacy global lookup remains disabled for helper sources outside this supported subset.
  3. Completed locally: validated original-source replay and versioned JSON IR with strict readback. Completed locally: QASM3 quantum projection with mandatory v0.4 source sidecar. Completed locally: unitary framework projection with mandatory source sidecar. Pending: source-editing transformations, QASM2 and broader framework operation support. Optimizers and target transpilation still reject function programs explicitly instead of erasing declarations.
  4. Pending: a dedicated capability catalog entry, product reference routes, complete cross-surface documentation and release evidence. No promotion is implied by the new flag.
  5. Workspace helpers are implemented by the extension below; broad fuzzing and cross-platform maximum-workload evidence remain separate validation work.

Current production-source subset

Named definitions must be at module level alongside exactly one main. Calls are allowed within numeric arithmetic in a top-level typed let name: Int|Float|Bool = ...; or return ok(...); in main. Operators +, -, *, /, %, unary minus and parentheses preserve precedence and left-to-right evaluation. Nested calls may appear in arithmetic arguments, such as helper(1 + helper(2)). Int-returning calls may be wrapped in int_to_float, including in another function argument. Numeric Array<Int|Float, N> declarations and array results in main support 1–256 matching elements with calls. Native mean(...) accepts inline or stored numeric arrays; stored arrays support literal indices. Other native wrappers, nested arrays and calls in indices remain outside this slice. Helper bodies support the numeric, array and Bool/branch grammar described below.

Calls inside main branches, main loops or unsupported statements are rejected; helper branches are supported as described in the Bool extension below. Registry imports and expansion-oriented constructs (circuit, generic algorithms/oracles, comptime, training, property, sample and collect blocks) cannot be combined with this slice. Source-level collisions with function names and the generated-binding namespace are rejected. Unsupported token-semantic shadow parsing returns an explicit unsupported result; legacy parsing and the token line-reader route share the lowering.

Additional lowering limits: 1,024 generated bindings, 4,096 expansion work units and 131,072 UTF-8 output bytes. Arithmetic failure in an unused parameter or local is preserved. Generated intermediate expressions are materialized in evaluation order; no substitution duplicates argument execution. The simulator's existing numeric failure code remains authoritative for lowered runtime arithmetic. Diagnostic locations point to the original call-site statement; declaration lines and source text remain in program.classicalFunctions. Generated binding names may appear in raw debug/evidence output; Playground groups them under a collapsed details control. A source-level debugger presentation is pending. The visual circuit editor explicitly marks function declarations unsupported, including unused helpers, so editing a circuit cannot silently erase them.

NM-CFN-009 rejects unsupported call contexts, NM-CFN-010 rejects missing prerequisite flags or unsupported combinations, and NM-CFN-011 rejects transformations without a function-preserving carrier. All have TR/EN translations.

Run the real CLI after building packages:

sh
npm run build:nm-packages
npm run nm -- run docs/examples/classical-functions-runtime.nm --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results --json

The result is programResult: { status: "ok", type: "Float", value: 1, ... }. nm.experimental.classicalFunctions is the VS Code option; experimentalClassicalFunctions is the MCP argument. The LSP initialization path is initializationOptions.nm.experimental.classicalFunctions. The Playground switch enables typed values and typed results as prerequisites for its example. Turning typed values off also disables classical functions. The installed VSIX host scenario has passed locally on VS Code 1.138.0, including negotiated signatures and parameter definitions.

Playground links preserve the flag as classicalFunctions=1. Saved context version 0.4 includes it; strict readers migrate versions 0.1, 0.2 and 0.3 with this new flag false and reject unknown fields/versions. The bilingual guide at /docs/nm-language/function-results#classical-functions links to /playground?example=classicalFunctions. Neither this guide nor the toggle promotes the feature into the stable capability catalog.

7. Local evidence

The first slice passed 63 prototype tests and 25 existing typed-classical/function-result/documentation regression tests. TypeScript, targeted ESLint, architecture budgets and the README baseline check passed. The isolated demo ran in both Turkish and English, returning Float(1.0) in 12 evaluation steps.

The second slice connects the production parser and tools behind explicit experimental flags. Local coverage now includes 81 prototype/integration tests and 126 selected toolchain, typed-value, function-result, optimizer, transpiler and documentation regression tests. Package builds and the real packaged CLI example succeeded with programResult equal to Float(1). The 35-case CLI conformance fixture changes only the help and unknown-command hashes because usage now includes the new option. That slice did not include browser or VS Code host validation; later slices are recorded below. No remote CI or release status is established.

Run npm run demo:nm:classical-functions -- --locale en for the isolated prototype, or the CLI command above for production-parser integration. Run npm run test:unit -- unit/nm-classical-functions.test.ts unit/nm-classical-functions-integration.test.ts for both test layers. Turkish implementation record.

The Playground slice adds saved-context migration, share round trips, catalog execution and visual source-preservation tests (88 feature/integration tests in total). 298 selected regression/documentation tests and 6 Chromium scenarios passed. Local development-browser scenarios cover the guide-to-example flow in both locales at 360/1280 px, automatic prerequisites, collapsed intermediate values, history restore/undo and legacy context restore. These checks do not establish production deployment or packaged VS Code host behavior.

IDE slice

The editor index uses original CST tokens, bounded to the function source/token limits. It tolerates incomplete call expressions and provides typed signatures, the active argument, and definition targets for local functions, parameters and immutable locals. Comment/string tokens are ignored. CRLF and UTF-16 coordinates are preserved. Ambiguous declarations and out-of-scope local names do not resolve. No module import support is implied. The Playground stores options per Monaco model so changing the session toggle does not leak options to another editor.

13 new language-service tests, 76 selected existing toolchain tests, and 2 TR/EN Chromium editor scenarios passed. The installed VSIX passed all 10 host scenarios on VS Code 1.138.0; report: .vscode-test/reports/host-ZnCpkO/report.json. The new host scenario verifies negotiated opt-in, typed document symbols, active-argument signature help, and a parameter definition in the correct function scope. The complete feature/integration set contains 101 tests. These are local results; no remote CI or release is claimed.

Independent review corrections

Visual source preservation now detects named helpers regardless of feature negotiation. Legacy global rename/reference lookup is disabled for sources containing helpers, including incomplete declarations and sources beyond the stricter IDE index limits. At that review stage scoped rename/reference support was pending; the later refactoring slice below supplies it. Main Bit/register bindings resolve independently of same-name helper parameters. Lowering preserves argument token adjacency, including leading-dot Float literals and comment gaps.

Locale drafts carry the versioned experimental context together with source; explicit false values override destination URL/example defaults. Legacy source-only drafts remain readable, while malformed contexts cannot enable experiments.

Local verification passed 115 feature/integration tests, 70 existing regression tests and 3 new Chromium scenarios (both locale directions at 390 px, plus visual source preservation). TypeScript, architecture budgets and targeted ESLint passed with one pre-existing navigation warning. The README browser inventory is 197; that count is not a claim that every browser scenario ran. Logs are in .qa/classical-review-*. These checks used the local development server and do not establish production or remote CI status.

Five existing locale Chromium scenarios also passed (8 browser checks in total), including legacy/shared handoffs, malformed drafts and blocked storage. The N/M package build pipeline succeeded: Core, CLI and VS Code artifacts rebuilt; unchanged MCP/LSP builds reused their validated cache.

Scoped completion and hover slice

Monaco and LSP now negotiate completion/hover through the same local function index. Function suggestions carry parameter/return types, while parameter/local suggestions carry binding types. Forward declarations are supported. Other functions' locals, uninitialized bindings, ambiguous declarations, comment/string tokens and unindexed sources do not produce helper suggestions. Local x takes priority over the case-insensitive built-in X completion. Main registers and ordinary constants remain available; no workspace function import support is added. Hover uses the occurrence range and reports the binding or function signature. Both features remain default-off behind the classical-functions option.

Local evidence: 127 feature/integration tests, 60 existing language-service/server regression tests, 5 documentation tests, 2 TR/EN Chromium scenarios and 10 real installed-VSIX host tests passed. Latest host report: .vscode-test/reports/host-CVhLlV/report.json; logs: .qa/classical-completion-*. TypeScript, targeted ESLint, architecture and README checks passed. The browser inventory is 199, but only the 2 listed browser scenarios ran in this slice. No commit/push, remote CI or production deployment is claimed. Semantic highlighting and refactoring were pending at this stage; subsequent slices are recorded below.

Scoped semantic highlighting slice

The classical-functions option now enables scoped semantic classification in Monaco and LSP/VS Code. Function declarations/calls, parameters and locals carry the shared token legend; declaration modifiers apply to declarations and readonly only to immutable bindings. Main Bit/register bindings remain distinct from same-name helper parameters. Out-of-scope and uninitialized locals do not become resolved tokens. CST comment/string ranges suppress false code classifications; multiline trivia is emitted as single-line tokens with CRLF/UTF-16 positions preserved. Incomplete or unindexed helper sources fail closed. The option-off token path is unchanged.

Monaco refreshes semantic tokens when the session option changes and defines function/parameter/readonly colors explicitly. VS Code applies the user's theme to the shared classifications. Hover and signature information remain available independently of color. The shared encoder avoids divergence between Monaco and LSP wire token streams.

Local evidence: 137 feature/integration tests, 60 existing language-service/LSP tests, 5 documentation tests, 2 TR/EN Chromium computed-color/toggle tests and 10 installed-VSIX host tests passed. Host report: .vscode-test/reports/host-ue5wyD/report.json; logs: .qa/classical-semantic-*. TypeScript, targeted ESLint, architecture and README checks passed. The browser inventory is 201; this does not assert a full-suite run. No commit/push, remote CI or production deployment is established. At this stage, scoped references and safe rename were the remaining editor work; their implementation is recorded below.

Scoped references and safe rename slice

Monaco and LSP/VS Code share a binding graph for local functions, parameters and indexed locals, including main Bit/register bindings. References optionally include the declaration; F2 edits only occurrences of the selected binding. Same-name bindings in other functions, comments and strings remain untouched. Workspace requests return edits only for the active file. Monaco may navigate directly when only one use exists instead of opening a references peek.

Refactoring validates the complete program before and after identifier edits, then compares every occurrence-to-declaration edge using stable token indexes. Reserved names, collisions, capture, incomplete/invalid/ambiguous input and index overflows fail closed. At this historical refactoring stage, nested control blocks and main param/const declarations were outside the slice. The Bool extension adds helper-block refactoring; nested main blocks and main param/const declarations remain restricted. main and the compiler-reserved __nm_cfn_ namespace cannot be renamed. Disabling the experiment never enables legacy global lookup for helper sources. CRLF, Unicode identifiers and UTF-16 offsets are covered.

Browser validation exposed an existing Monaco integration defect: workspace text edits used edit instead of textEdit. Rename and quick fixes now return typed IWorkspaceTextEdit entries with a document version. Since standalone Monaco logs rename rejection to the console, Playground also renders a localized accessible status message; starting another rename or changing source clears it.

Local evidence: 159 feature/integration tests, 60 existing language-service/LSP regressions, 9 documentation/Monaco wiring tests, 2 TR/EN rename browser scenarios, 1 quick-fix browser scenario and 10 installed-VSIX host tests passed. Browser coverage checks preserved sibling scope, unchanged execution results after rename, visible collision feedback and an applied quick fix. Host report: .vscode-test/reports/host-br1979/report.json; logs: .qa/classical-rename-*. TypeScript, targeted ESLint, i18n parity, architecture budgets and README checks passed. Browser inventory is 204, not a full-suite execution claim. No commit/push, remote CI or production deployment is established. At this stage source-preserving printer/versioned IR/export were next; the carrier slice is recorded below.

Original-source replay and versioned IR slice

Classical-function provenance is now 0.2.0-runtime-experimental, carrying the full original source and experimental parse options alongside declarations, calls and generated binding names. printNMProgram reparses that source and compares the complete resulting program before returning it byte-for-byte. Comments, unused helpers, Unicode, CRLF and final-newline presence survive. The indent option does not reformat this carrier. Changed AST/metadata or stale/missing provenance fails with NM-CFN-011; replay never silently discards program edits.

exportToNMIR emits nm-json-ir v0.2 for function programs, with execution: "lowered-classical-functions", original source/provenance in module.classicalFunctions, and lowered execution instructions in statements. This is not a native call-instruction IR engine. Existing programs keep v0.1 and their serialized field order. Core now exports exportToNMIR and readNMClassicalFunctionIR.

readNMClassicalFunctionIR(json, options) accepts at most 2 MiB, requires caller-supplied explicit feature negotiation, rebuilds the artifact from source and compares every field independently of JSON object key order. It rejects malformed JSON, missing/extra/changed fields, unsupported versions and inconsistent source/instructions/resources/diagnostics. Stored flags are never automatically enabled. The result is verified source, not execution of arbitrary imported IR instructions. This checks consistency, not a cryptographic signature or publisher identity.

sh
nm export main.nm --to ir --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results

The json CLI target retains its raw AST behavior; ir selects the versioned carrier. At this IR slice, optimization, target transpilation, QASM2/3 and Qiskit/Cirq/PennyLane export were explicitly blocked; the later QASM3 sidecar slice is recorded below. Replay does not translate modified lowered ASTs back into helper source. At that stage, framework export rejected v0.2 explicitly; the later bounded framework carrier slice is recorded below.

Local evidence: 187 feature/integration tests (28 new carrier tests), 325 existing parser/CLI/function-result/provenance/noise regressions and package builds passed. The packed CLI → IR → packed Core → source/execution round trip preserved the exact example and returned Float(1). Only the help and unknown-command hashes changed in the 35-case CLI fixture, due to the new IR target; all other cases were unchanged. TypeScript, targeted ESLint, i18n, architecture and README checks passed. Logs: .qa/classical-carriers-*. Browser/VS Code host suites were not rerun in this slice; earlier evidence belongs to its recorded slice. No commit/push, remote CI or production deployment is established.

QASM3 quantum projection with mandatory v0.4 source sidecar

exportToQASM3 now accepts classical-function programs in preview and strict modes. Strict lowering operates on an internal expanded source, while v0.2 original-source IR remains in a v0.4 sidecar. The QASM carries quantum operations only: it does not compute classical helpers or their return result. A carrier comment and immutable classicalFunctionSemantics metadata state this boundary. QASM2, Qiskit/Cirq/PennyLane, general optimization and target transpilation were outside that QASM3 slice; the later framework subset is recorded below.

sh
nm export main.nm --to qasm3 --strict --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results

The CLI requires --json to retain the sidecar. MCP nm_export returns sidecar and requiresSidecar: true. Core's importFromQASM3Sidecar(qasm, sidecarJson) validates the source IR and all envelope metadata, regenerates the QASM and verifies the pair before restoring exact source. Edited/mismatched QASM fails; only CRLF/LF carrier transport normalization is accepted. Returned requiredExperimental is advisory and never changes application execution settings. The ordinary importFromQASM path rejects a marked function carrier without its sidecar. Regeneration requires a compatible experimental toolchain; it is not a publisher signature.

Ordinary writers still emit v0.3 and the permanent v0.1/v0.2/v0.3 readers remain intact. The previous IR slice's object-key insertion order affected nested serialization; that is corrected and the v0.3 golden fixture is byte-stable again. The current migration API targets v0.3 and rejects a lossy v0.4 downgrade.

Local evidence: 71 targeted feature/integration tests (20 new QASM scenarios), 30 QASM/transpiler regressions, 12 MCP tests and 1 existing CLI export test passed. The official openqasm3.parser@1.0.1 parsed 6 strict QASM fixtures, including the new function projection; this establishes syntax only. A separate simulator test deliberately removes metadata to compare the standalone projection's quantum probabilities, while sidecar round-trip tests compare the original classical result and final quantum state. Packed CLI → QASM3/v0.4 → packed Core → original source returned Float(1). Package builds, TypeScript, targeted ESLint, architecture, i18n and README checks passed. Logs: .qa/classical-qasm-*. Browser/VS Code host and remote CI were not rerun in this slice; no commit/push or release occurred.

Unitary framework projection and source bundle

Qiskit, Cirq and PennyLane now accept the bounded unitary subset of function programs. Each export item contains code, requiresSidecar: true and a nm-classical-function-framework v0.1 sidecar carrying original-source IR v0.2. Python projects the unitary circuit at export-time parameter values; it does not evaluate helpers, return results or classical runtime errors. Immutable semantics and a Python comment state this boundary.

The common gate set is H/X/Y/Z/S/T/Sdg/Tdg, CNOT/CZ/CY/CH, SWAP/iSWAP, CCNOT/CSWAP, Rx/Ry/Rz/P/CP/CRy/CRz. Measurement, reset, noise/mitigation, conditions, loops, assertions, training and other operations fail closed rather than becoming comments. GPhase/U/RXX/RYY/RZZ need a later target contract. Ordinary programs keep their existing behavior.

Core's readNMClassicalFunctionFramework(code, sidecarJson, options) requires caller-supplied experimental flags, rebuilds source IR and target Python, compares the complete sidecar and code, and returns original source. Imported Python is never executed and stored options are never enabled automatically. Each input is bounded to 2 MiB; only CRLF/LF differences in Python transport are normalized. This is consistency checking, not authentication, and requires a compatible experimental toolchain.

CLI PennyLane export requires --json for function programs. Qiskit/Cirq remain Core/MCP targets. MCP includes the sidecar; Playground's bilingual copy action retains Python plus source sidecar as JSON. QASM2 and general target transpilation remain pending. Source-preserving gate reduction follows the later Task 7 contract below.

Local evidence: 19 new framework tests, 43 existing feature integration/QASM tests, 46 export/framework regressions and 17 MCP/document checks passed. Package builds and TypeScript/lint/i18n/architecture/README checks passed. Packed CLI to PennyLane JSON bundle to packed Core restored the exact source and Int(3). The QASM3 example-inventory expectation was corrected to verify v0.4 source recovery; QASM2 remains rejected. PennyLane 0.45.1 on Python 3.11.15 executed the generated circuit and matched N/M probabilities; source recovery produced Int(3). Existing Bell/training/dataset smoke cases also passed. Qiskit/Cirq were validated through source/IR/code round trips, not native Python runtime execution in this slice. Only help/unknown-command hashes changed in the 35-case CLI fixture. Logs: .qa/classical-framework-*. No browser/VS Code host/remote CI run, commit, push or release was performed.

Calls inside main arithmetic

Main's top-level typed declarations and return ok(...) now accept mixed arithmetic such as energy(0.5, 2.0) + square(0.5) - 0.25 and nested arguments such as helper(1 + helper(2)). Binary + - * / %, unary minus and parentheses preserve precedence and left associativity. Operands are materialized in source order exactly once; an earlier runtime failure prevents later calls. Earlier typed scalar/array/measurement bindings and explicit typed constants reuse the shared type rules. Generated code preserves original source lines and existing work/output limits, with main expansion depth bounded to 32.

At this arithmetic stage, calls in control flow, gate angles, native helper wrappers, array literals and array indices remained unsupported; the later inttofloat extension is recorded below. Existing helper signatures, opt-in flags, previously supported source lowering and carrier versions remain unchanged. Source IR, QASM3/framework sidecars and scoped rename cover the new expressions. The shared Playground example and bilingual Core/CLI/guide documentation now show mixed calls while retaining Float(1).

Local evidence: 246 function tests including 22 new arithmetic cases, 81 selected parser/CLI/MCP/document regressions, and four Chromium scenarios passed. Browser checks cover TR/EN at 360/1280px with the rebuilt Worker, execution results, persisted options, page errors and horizontal overflow; mobile screenshots were inspected. These are viewport tests on a local development server, not physical-device or production validation. The first browser run used an old Worker because direct Next startup bypassed predev; running the existing browser-worker build resolved that setup mismatch. Package builds and packed CLI Float(1), TypeScript, targeted ESLint, i18n, architecture and README checks passed. Logs: .qa/classical-arithmetic-*. VS Code host/external Python were not rerun; no commit, push, remote CI or release was performed.

Explicit Int-to-Float conversion of call results

Main's top-level typed declarations and return ok(...) now accept int_to_float(helper(2)), including as another call's argument: scale(int_to_float(helper(2)), 0.5). Arithmetic and nested calls inside the conversion evaluate once in source order, followed by the shared typed-runtime conversion. No implicit numeric coercion was added.

Exactly one complete Int argument and matching delimiters are required. Extra arguments, trailing commas, mismatched delimiters, trailing calls and Float arguments fail closed. An Int within its own range can still exceed the Float bound; conversion then fails before later operands or calls run. Source positions, expansion budgets and carrier versions are preserved. At this conversion stage, signatures remained Int/Float and array-call positions were outside the subset; the subsequent numeric-array extension is recorded below.

The shared Playground example uses Int-returning double(1) and explicitly converts it for energy, retaining Float(1). The bilingual guide, source fixture and Core/CLI README describe this behavior.

Local evidence: 265 function tests including 19 new conversion cases, 81 selected parser/CLI/MCP/document regressions and four Chromium scenarios passed. Coverage includes bounds and error order, invalid types/arity/syntax, comments/CRLF/expansion budget, signature help/rename, Core/Worker/CLI/MCP result parity and IR/QASM3/framework source recovery. TR/EN browser checks used the rebuilt Worker at 360/1280px; these are viewport checks rather than physical-device tests. Package/Worker builds, packed CLI Float(1), TypeScript, targeted ESLint, i18n, architecture and README checks passed. Logs: .qa/classical-conversion-*. VS Code host, external Python and remote CI were not rerun. No commit, push or release was performed.

Numeric arrays and mean / Sayısal diziler ve ortalama

With the same experimental flags, main can build Array<Int, N> or Array<Float, N> values from function calls: let samples: Array<Int, 2> = [helper(1), helper(2)];. mean(samples) and mean([helper(1), helper(2)]) return Float. Elements must share a numeric type; conversions are explicit. Length is fixed at 1–256, elements execute once from left to right, and existing expansion budgets still apply. Main may return an array with a matching Result type; stored arrays support literal indices. Helpers also accept and return fixed numeric arrays; see the helper-array extension below. Nested arrays remain unsupported; computed indices remain helper-only; main supports constant indices on helper-returned arrays. Main expressions containing helper calls support constant indexing of returned arrays or inline arrays containing calls; bounds are checked before evaluation.

Aynı deneysel seçeneklerle main, fonksiyon sonuçlarından Array<Int, N> veya Array<Float, N> oluşturabilir. mean(samples) ve mean([helper(1), helper(2)]) Float döndürür. Elemanlar aynı sayısal tipte olmalıdır; dönüşümler açıkça yazılır. Uzunluk 1–256 ile sınırlıdır; elemanlar soldan sağa bir kez hesaplanır ve mevcut genişletme sınırları uygulanır. Main uygun Result tipiyle dizi döndürebilir; değişkende saklanan diziler sabit indisle okunabilir. Yardımcı fonksiyonlar sabit sayısal dizileri de alabilir ve döndürebilir; aşağıdaki dizi uzantısına bakın. İç içe diziler desteklenmez; hesaplanan indisler yalnız saf yardımcı gövdelerinde desteklenir; main yardımcıdan dönen dizilerde sabit indisleri destekler. Yardımcı çağrısı içeren main ifadelerinde dönen diziye veya çağrı içeren dizi literaline sabit indis uygulanabilir; sınırlar değerlendirmeden önce denetlenir.

Helper-array parameters and returns / Dizi parametreleri ve dönüşleri

Functions accept and return Array<Int, N> or Array<Float, N> with exactly 1–256 elements. Parameter, local and return types must match element type and length exactly. Helper bodies support array literals, array-returning calls, checked Int-expression indices and native mean(values). Arrays are immutable; arguments and elements are evaluated once, left to right. Nested arrays remain unsupported; computed indices remain helper-only; main supports constant indices on helper-returned arrays. The same three experimental flags apply. IDE signatures, hover and scoped rename include array types.

Fonksiyonlar tam 1–256 elemanlı Array<Int, N> veya Array<Float, N> alabilir ve döndürebilir. Parametre, yerel ve dönüş tiplerinde eleman tipi ve uzunluk tam eşleşmelidir. Yardımcı fonksiyon gövdelerinde dizi literalleri, dizi döndüren çağrılar, sınırı denetlenen Int ifade indisleri ve yerleşik mean(values) desteklenir. Diziler değiştirilemez; argümanlar ve elemanlar soldan sağa bir kez hesaplanır. İç içe diziler desteklenmez; hesaplanan indisler yalnız saf yardımcı gövdelerinde desteklenir; main yardımcıdan dönen dizilerde sabit indisleri destekler. Aynı üç deneysel seçenek kullanılır. IDE imzaları, hover ve kapsamlı yeniden adlandırma dizi tiplerini kapsar.

nm
fn pair(x: Float) -> Array<Float, 2> {
  return [x, x + 2.0];
}
fn average(values: Array<Float, 2>) -> Float {
  return mean(values);
}

Task 2: Bool and helper branches / Görev 2: Bool ve yardımcı fonksiyon dalları

With the same three experimental flags, helpers accept and return scalar Bool alongside numeric types and fixed numeric arrays. Bool is distinct from Int and measurement Bit; there is no implicit numeric or Bit-to-Bool conversion. Use true, false, !, comparisons and short-circuit && / ||. Bool arrays are not supported.

Helpers support if (condition) { ... } else { ... }, nested branches and early returns. The condition must be Bool. An else is optional if a later return covers the remaining path, and every path must return the declared type. Only the selected branch executes; an unselected branch or short-circuited operand cannot trigger an arithmetic error. Branch locals are private to their block: a child block cannot redeclare an outer binding, but sibling blocks may reuse a local name. The 32-local limit counts all helper blocks together.

Main supports top-level let enabled: Bool = ...; and Result<Bool, Error>. Function calls in main branches and main loops remain unsupported. Helper branches support scoped completion, hover, F12, references, rename and semantic colors; edits require a complete valid program and must preserve every binding. Main nested-block refactoring and main param/const renaming remain restricted.

Aynı üç deneysel seçenekle yardımcı fonksiyonlar sayısal tipler ve sabit sayısal dizilerin yanında skaler Bool alabilir ve döndürebilir. Bool, Int ve ölçüm Bit tipinden ayrıdır; sayılardan veya Bit değerinden örtük dönüşüm yapılmaz. true, false, !, karşılaştırmalar ve kısa devreli && / || kullanılır. Bool dizileri desteklenmez.

Yardımcı fonksiyonlarda if (condition) { ... } else { ... }, iç içe dallar ve erken dönüş kullanılabilir. Koşul Bool olmalıdır. Sonraki bir return kalan yolu kapsıyorsa else yazılmayabilir; her yol bildirilen tipte dönmelidir. Yalnız seçilen dal çalışır; seçilmeyen dal veya kısa devre nedeniyle atlanan operand aritmetik hataya yol açmaz. Dal yerelleri kendi bloklarına özeldir: alt blok dış kapsamdaki bir adı yeniden tanımlayamaz, ancak kardeş bloklar aynı yerel adı kullanabilir. 32 yerel sınırı fonksiyonun tüm bloklarının toplamıdır.

Main üst düzey let enabled: Bool = ...; ve Result<Bool, Error> destekler. Main dalları ve main döngüleri içinde fonksiyon çağrıları desteklenmez. Yardımcı fonksiyon dallarında kapsamlı tamamlama, hover, F12, referans, yeniden adlandırma ve semantik renkler kullanılabilir; düzenlemeler eksiksiz geçerli kod gerektirir ve her kullanımın bağlı olduğu tanımı korur. Main iç içe bloklarının düzenlenmesi ve main param/const yeniden adlandırması kısıtlı kalır.

nm
module boolean_result;
fn positive(value: Int) -> Bool {
  if (value > 0) { return true; }
  return false;
}
fn main() -> Result<Bool, Error> {
  let q = qreg[1];
  let enabled: Bool = positive(1);
  return ok(enabled);
}

This section specifies the Task 2 candidate contract. Independent review and final cross-surface validation are tracked separately; it does not assert task completion or a release.

Bu bölüm Görev 2 adayının sözleşmesini açıklar. Bağımsız inceleme ve son yüzeyler arası doğrulama ayrıca izlenir; görevin tamamlandığı veya yayın yapıldığı iddiası değildir.

Helper calls in gate angles (experimental)

With classicalFunctions and typedClassicalValues enabled, top-level main gates Rx, Ry, Rz, P, GPhase, U, RXX, RYY, RZZ, CRy, CRz and CP accept numeric helper expressions, for example Ry(q[0], average(samples)). Each angle is evaluated once, left to right, at the gate's source position. Earlier typed locals, numeric const/param bindings, PI and explicitly converted measurement values are available. Bool and array results cannot be used as angles; helper calls inside main loops and in qubit targets remain unsupported.

IR retains original source and expressions. QASM3 and framework exports resolve statically available inputs to numeric angles and reject measurement-dependent angles. Adjoint gradients use the analytic chain rule with explicit parseOptions; parameter-dependent discrete decisions and Int constants fail explicitly. Existing measurement/noise and unsupported-gate gradient restrictions remain. This does not enable training blocks or direct parameter-shift for helper angles.

Kapı açılarında yardımcı çağrısı (deneysel)

classicalFunctions ve typedClassicalValues açıkken main üst düzeyindeki Rx, Ry, Rz, P, GPhase, U, RXX, RYY, RZZ, CRy, CRz ve CP sayısal helper ifadelerini kabul eder; örneğin Ry(q[0], average(samples)). Her açı kapının kaynak konumunda, soldan sağa bir kez hesaplanır. Önceki tipli yereller, sayısal const/param, PI ve açıkça dönüştürülmüş ölçüm değerleri kullanılabilir. Bool/dizi sonuçları açı olamaz; main döngülerinin içinde ve qubit hedeflerinde helper çağrısı desteklenmez.

IR özgün kaynağı ve ifadeleri korur. QASM3/framework export statik girdileri sayısal açıya çevirir; ölçüme bağlı açıları reddeder. Adjoint gradyan açık parseOptions ile analitik zincir kuralını kullanır; parametreye bağlı ayrık kararlar ve Int sabitleri açık hata verir. Mevcut ölçüm/noise ve desteklenmeyen kapı sınırları korunur. Bu uzantı eğitim bloklarını veya helper açıları için doğrudan parameter-shift kuralını açmaz.

Workspace function imports (experimental)

Use use workspace.helpers; to call the public functions declared in a module named helpers. The CLI indexes neighboring .nm files (or the selected workspace manifest); Core, Worker and MCP accept an explicit workspaceModules: { helpers: source } snapshot. This performs no network access. Unqualified helper names are public by default for legacy compatibility. Explicit public fn / private fn (also pub fn) requires experimental.moduleVisibility; CLI: --experimental-module-visibility.

Only directly imported public names enter the caller's scope. A public function can call its own private helpers and its module's direct imports. Private names and transitively imported names do not become exports. Ambiguous names, local collisions, missing modules and cycles are rejected. Libraries contain module/import directives and helpers; arbitrary top-level execution and captured globals are unsupported. Dependency sources and original module/name ranges are retained; compiler names are never rename targets in the editor. Source limits still apply to the combined closure (32,768 UTF-8 bytes, 32 functions; at most 64 dependency modules).

Try the two files under docs/examples/classical-functions-workspace/. From that directory run nm run main.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results --experimental-module-visibility. The program rotates by one radian and returns Float(1).

IR, QASM3 and framework source readers return an optional validated workspaceModules map. Pass both the returned entry source and modules to the runtime, using explicitly chosen experimental options. A source snapshot grants no permissions. For example: executeNMCode(read.source, { experimental, workspaceModules: read.workspaceModules }) for a successful IR/framework read (QASM calls the entry field code). Single-file readers keep their existing result shape.

Dosyalar arası fonksiyon importu (deneysel)

use workspace.helpers;, helpers modülündeki public fonksiyonları çağırır. CLI aynı klasördeki .nm dosyalarını veya workspace manifestini tarar; Core, Worker ve MCP açık bir workspaceModules: { helpers: kaynak } haritası alır. Ağdan dosya indirilmez. Öneksiz fonksiyonlar eski davranışla uyum için public kabul edilir. Açık public fn / private fn (ve pub fn) için experimental.moduleVisibility; CLI'da --experimental-module-visibility gerekir.

Çağıran dosya yalnız doğrudan import ettiği public adları görür. Public fonksiyon kendi private yardımcılarını ve kendi modülünün importlarını kullanabilir. Private adlar ve dolaylı importlar dışarı açılmaz. Belirsiz adlar, yerel çakışmalar, eksik modüller ve döngüler reddedilir. Kütüphane modül/import tanımları ve yardımcı fonksiyonlar içerir; üst düzey çalıştırılabilir ifadeler ve dış değişken yakalama desteklenmez. Bağımlılık kaynakları ve özgün modül/ad konumları korunur. Toplam kaynak sınırı 32.768 UTF-8 bayt, fonksiyon sınırı 32 ve bağımlılık modülü sınırı 64'tür.

docs/examples/classical-functions-workspace/ altındaki iki dosyayı deneyin. O klasörde nm run main.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results --experimental-module-visibility komutu bir radyanlık dönüş yapar ve Float(1) döndürür.

IR, QASM3 ve framework okuyucuları doğrulanmış workspaceModules haritasını da döndürür. Çalıştırırken giriş kaynağıyla birlikte bu haritayı ve açıkça seçtiğiniz deneysel seçenekleri geçirin. Kaynak kaydı seçenekleri kendiliğinden etkinleştirmez. Başarılı IR/framework okuması için örnek: executeNMCode(read.source, { experimental, workspaceModules: read.workspaceModules }); QASM sonucunda giriş alanı code adındadır. Tek dosyalı sonuçların eski biçimi korunur.

Typed helper results (Task 5 experimental candidate)

With experimental.classicalFunctions, experimental.typedClassicalValues and experimental.functionResults explicitly enabled, a helper can return Result<T, Error>. The payload T is Int, Float, Bool, Array<Int, N> or Array<Float, N> (1–256 elements). Parameters and locals still use base value types: Result parameters/locals, nested Result and Bool arrays are unsupported.

Use return ok(value);, return error("NEGATIVE_THETA"); or the err("NEGATIVE_THETA") alias. Error codes match [A-Z][A-Z0-9_]{0,63}. Postfix ? on a Result helper call unwraps success or returns the error from the enclosing Result-returning helper/main. A propagated array may be indexed as helper()?[0]. A plain-value-returning helper cannot use propagation. Main accepts a typed local initialized with helper(...)?, return helper(...); and return ok(helper(...)?);. Arguments, short-circuit operands and selected branches retain their evaluation order; unselected branches do not run. Typed errors are program results, while arithmetic/runtime failures remain failures.

The shared docs/examples/classical-functions-runtime.nm example uses checked_observations. It returns Float(1); setting enabled to false returns Float(0). Change the call's first argument from 0.5 to -0.5 to return NEGATIVE_THETA before the gate. Run it with nm run docs/examples/classical-functions-runtime.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results.

Numeric helper(...)? can supply supported gate angles at runtime. Analytic differentiation of Result helpers is explicitly unsupported. QASM3/framework projection requires statically successful propagation; error-producing or unavailable propagation is rejected, and the source sidecar remains mandatory. Calls in main branches/loops and recursion remain outside this slice. Source-preserving gate reduction follows the Task 7 contract below. IDE signatures include Result payload types; constructor names are built-ins, error strings are not symbols, and workspace helper references/rename preserve original source bindings. This documents a candidate contract, not a release or a final validation claim.

Tipli yardımcı sonuçları (Görev 5 deneysel adayı)

experimental.classicalFunctions, experimental.typedClassicalValues ve experimental.functionResults açıkça etkinleştirildiğinde yardımcı fonksiyon Result<T, Error> döndürebilir. İç değer tipi T, Int, Float, Bool, Array<Int, N> veya Array<Float, N> olabilir (1–256 eleman). Parametreler ve yereller temel değer tiplerinde kalır: Result parametresi/yereli, iç içe Result ve Bool dizileri desteklenmez.

return ok(value);, return error("NEGATIVE_THETA"); veya err("NEGATIVE_THETA") eş adı kullanılır. Hata kodları [A-Z][A-Z0-9_]{0,63} biçimindedir. Result yardımcı çağrısının sonundaki ?, başarılı değeri açar veya hatayı kapsayan Result döndüren yardımcı/main üzerinden döndürür. Açılan dizi helper()?[0] ile okunabilir. Temel değer döndüren yardımcı hata yayılımı kullanamaz. Main, helper(...)? ile başlatılan tipli yereli, return helper(...); ve return ok(helper(...)?); biçimlerini kabul eder. Argümanlar, kısa devreli operandlar ve seçilen dallar değerlendirme sırasını korur; seçilmeyen dal çalışmaz. Tipli hata bir program sonucudur; aritmetik/çalışma zamanı arızaları hata olarak kalır.

Ortak docs/examples/classical-functions-runtime.nm örneği checked_observations kullanır. Float(1) döndürür; enabled false yapılınca Float(0) döner. Çağrının ilk argümanını 0.5 yerine -0.5 yapınca kapıdan önce NEGATIVE_THETA döner. Çalıştırma komutu: nm run docs/examples/classical-functions-runtime.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results.

Sayısal helper(...)?, çalışma anında desteklenen kapı açılarına verilebilir. Result yardımcılarının analitik türevi açıkça desteklenmez. QASM3/framework aktarımı statik olarak başarılı hata yayılımı gerektirir; hata üreten veya değeri belirlenemeyen yayılım reddedilir ve kaynak yan kaydı zorunlu kalır. Main dalları/döngülerinde çağrı ve özyineleme bu dilimin dışındadır. Kaynağı koruyan kapı azaltma aşağıdaki Görev 7 sözleşmesini kullanır. IDE imzaları Result iç değer tipini gösterir; kurucu adları yerleşiktir, hata metinleri sembol sayılmaz ve workspace yardımcı referansları/yeniden adlandırma özgün kaynak bağlarını korur. Bu bölüm aday sözleşmeyi açıklar; yayın veya son doğrulama iddiası değildir.

Recorded helper debugger (Task 6 experimental candidate)

The debugger observes actual helper execution once and records an immutable timeline; replay does not re-evaluate calls, repeat measurements or run skipped branches. Arguments are evaluated left to right. Call frames show initialized locals, arguments and typed return/error values, including Bool, fixed numeric arrays and Result. Branch locals disappear when their scope ends; return/error snapshots retain the affected frame before it is popped.

Core advanceNMDebugSession(session, command) and Playground support stepIn, stepOver and stepOut, alongside continue/restart/cancel. Step in enters the next recorded call; step over skips nested calls; step out returns to the caller. Matching breakpoints can interrupt step over/out. The Core command step remains an alias of step in; Playground F10 uses step over. Recorded source ids keep imported helpers separate from main, so a library line is not highlighted as a main-editor line. Playground invalidates the visible session when entry code, dependency contents or experimental options change.

All normal language opt-ins still apply: enable classicalFunctions and typedClassicalValues, plus functionResults for Result returns; explicit module visibility also requires moduleVisibility. Pass workspace dependencies in executeOptions.workspaceModules when recording with Core. Scalar helper instrumentation is an internal debugger execution mode, not a public switch that bypasses these requirements. Normal execution does not produce helper debugger events.

A declared Result error is a typed program outcome, not a numeric execution failure. A recorded arithmetic/runtime failure carries executionFailed: true and its error message while replay starts paused; reaching the final failure frame yields failed status. Restart can return to the recorded beginning. Compilation and trace-budget rejection expose no partial timeline. Successfully recording a paused session does not prove successful program execution: inspect executionFailed and the error evidence.

The CLI records and prints a bounded session, including JSON; it is not an interactive stepping terminal. For the shared example, use nm debug docs/examples/classical-functions-runtime.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results. The VS Code extension supplies language editing features; it does not implement a full Debug Adapter Protocol (DAP) debugger or native Run and Debug stepping controls. Use Core or Playground to navigate the recorded helper timeline. No remote target or package release is implied.

Kayıtlı yardımcı hata ayıklayıcısı (Görev 6 deneysel adayı)

Hata ayıklayıcı gerçek yardımcı çalıştırmasını bir kez gözlemler ve değiştirilmeyen bir zaman çizelgesi kaydeder; yeniden izleme çağrıları hesaplamaz, ölçümleri tekrarlamaz veya atlanan dalları çalıştırmaz. Argümanlar soldan sağa değerlendirilir. Çağrı çerçeveleri başlatılmış yerelleri, argümanları ve Bool, sabit sayısal dizi, Result dahil tipli dönüş/hata değerlerini gösterir. Dal yerelleri kapsam bitince görünmez; dönüş/hata kaydı, ilgili çerçeveyi yığından çıkarılmadan önce korur.

Core advanceNMDebugSession(session, command) ve Playground; continue/restart/cancel yanında stepIn, stepOver ve stepOut destekler. İçine gir sıradaki kayıtlı çağrıya girer; Üzerinden geç iç çağrıları atlar; Dışına çık çağırana döner. Eşleşen durak noktası üzerinden geçme/çıkma işlemini durdurabilir. Core step komutu içine gir işleminin eş adı olarak kalır; Playground F10 üzerinden geç işlemini kullanır. Kaynak kimlikleri import edilen yardımcıları main'den ayırır; kütüphane satırı ana editör satırı gibi vurgulanmaz. Playground, giriş kodu, bağımlılık içeriği veya deneysel seçenekler değişince görünen oturumu geçersizleştirir.

Normal dil izinlerinin tamamı geçerlidir: classicalFunctions ve typedClassicalValues, Result dönüşleri için ayrıca functionResults etkinleştirilmelidir; açık modül görünürlüğü moduleVisibility gerektirir. Core ile kayıt oluştururken bağımlılıkları executeOptions.workspaceModules içinde geçirin. Skaler yardımcı gözlemi, debugger'ın dahili çalıştırma kipidir; bu izinleri atlayan genel bir seçenek değildir. Normal çalıştırma yardımcı debugger olayları üretmez.

Bildirilen Result hatası tipli program sonucudur; sayısal çalıştırma arızası değildir. Kaydedilen aritmetik/çalışma zamanı arızasında executionFailed: true ve hata mesajı bulunur; yeniden izleme duraklatılmış başlar, son hatalı adıma ulaşınca durum failed olur. Başa dön kayıt başlangıcına dönebilir. Derleme ve iz bütçesi reddi kısmi zaman çizelgesi sunmaz. Duraklatılmış oturumun başarıyla kaydedilmesi, programın başarılı çalıştığını kanıtlamaz: executionFailed ve hata kanıtını inceleyin.

CLI sınırlı oturumu kaydeder ve JSON dahil çıktısını verir; terminalde etkileşimli adımlama yapmaz. Ortak örnek için nm debug docs/examples/classical-functions-runtime.nm --json --experimental-classical-functions --experimental-typed-classical-values --experimental-function-results kullanın. VS Code eklentisi dil düzenleme özelliklerini sağlar; tam bir Debug Adapter Protocol (DAP) debugger'ı veya yerleşik Run and Debug adımlama kontrolleri uygulamaz. Kayıtlı yardımcı zaman çizelgesinde Core ya da Playground ile gezinin. Uzak hedef veya paket yayını anlamına gelmez.

Source-preserving helper optimization (Task 7 experimental candidate)

Use Core optimizeNMSource(source, { parseOptions }), Playground Optimize, or MCP nm_optimize with the same explicit language options and workspace dependency snapshot as execution. Only adjacent literal inverse quantum gate pairs on identical, explicitly indexed targets in top-level main are removed. For example, H(q[0]); /* keep */ H(q[0]); can be reduced. Comments, whitespace, line endings, source offsets, helper bodies, calls and imported files are preserved. Classical statements, control-flow blocks and other intervening operations are boundaries. Helper-body rewrites, rotation merging, reordering and the source-free optimizeNMProgram path remain unsupported for helper programs.

Candidate edits require both structural checks and actual execution comparison with identical inputs and dependencies. Verification compares typed results/error codes, visible classical values and source locations, complete complex amplitudes including phase, and supported measurement/branch evidence. It is bounded to 14 qubits and requires full dense-state evidence; random measurements require an explicit seed. Noise, mitigation, training and other excluded runtime/resource-sensitive cases are not changed. A skipped/failed check, missing evidence, no eligible pair or zero pass budget retains the original source; Apply stays disabled. This concrete runtime check does not claim correctness for arbitrary future input changes.

Playground shows the exact original/reduced source rather than placeholder helper angles as a numeric circuit. Changing code, experimental options or workspace dependencies invalidates the preview and requires optimization again. Applying changes preserves the dependency snapshot. Core callers must likewise retain that snapshot and check report.verification.status === "passed" before adopting a changed source. The CLI can run/check/export the resulting source with its normal experimental flags; this slice does not add an nm optimize CLI command. VS Code editing support does not imply a native optimizer action. No package release or hardware optimization is claimed.

Kaynağı koruyan yardımcı optimizasyonu (Görev 7 deneysel adayı)

Core optimizeNMSource(source, { parseOptions }), Playground Optimize veya MCP nm_optimize işlemini çalıştırmayla aynı açık dil seçenekleri ve workspace bağımlılık kopyasıyla kullanın. Yalnız main üst düzeyinde aynı açık sabit indisli hedeflere uygulanan komşu, sabit ters kuantum kapı çiftleri kaldırılır. Örneğin H(q[0]); /* koru */ H(q[0]); azaltılabilir. Yorumlar, boşluklar, satır sonları, kaynak konumları, yardımcı gövdeleri, çağrılar ve import edilen dosyalar korunur. Klasik ifadeler, kontrol akışı blokları ve aradaki diğer işlemler sınırdır. Yardımcı gövdesini yeniden yazma, dönüş kapılarını birleştirme, sıralama değiştirme ve kaynaksız optimizeNMProgram yolu yardımcı programlar için desteklenmez.

Aday düzenleme hem yapısal denetim hem aynı girdi ve bağımlılıklarla gerçek çalıştırma karşılaştırması gerektirir. Tipli sonuç/hata kodları, görünür klasik değerler ve kaynak konumları, faz dahil tam karmaşık genlikler ve desteklenen ölçüm/dal kanıtı karşılaştırılır. Doğrulama 14 qubit ile sınırlıdır ve tam yoğun durum kanıtı gerektirir; rastgele ölçümler için açık seed gerekir. Gürültü, azaltım, eğitim ve kapsam dışı çalışma/kaynak duyarlı durumlar değiştirilmez. Atlanan/başarısız denetim, eksik kanıt, uygun çift bulunmaması veya sıfır geçiş bütçesi özgün kaynağı korur; Uygula kapalı kalır. Bu somut çalışma denetimi, gelecekteki her olası girdi için doğruluk iddiası değildir.

Playground yardımcı açıların geçici değerlerini sayısal devre gibi çizmek yerine tam özgün/azaltılmış kaynağı gösterir. Kod, deneysel seçenek veya workspace bağımlılığı değişirse önizleme geçersizleşir ve yeniden optimizasyon gerekir. Uygulama bağımlılık kopyasını korur. Core tüketicisi de bu kopyayı saklamalı ve değişen kaynağı kullanmadan önce report.verification.status === "passed" kontrolü yapmalıdır. CLI sonuç kaynağını normal deneysel seçenekleriyle çalıştırabilir, denetleyebilir veya dışa aktarabilir; bu dilim yeni nm optimize CLI komutu eklemez. VS Code düzenleme desteği yerleşik optimizasyon eylemi anlamına gelmez. Paket yayını veya donanım optimizasyonu iddia edilmez.

Numeric builtin calls (1C, experimental)

The typed expression AST includes a distinct multi-argument numericCall node; unary Float call nodes retain their existing shape. Native typed expressions and helper bodies share numeric inference/evaluation. Calls evaluate their arguments once, left to right. Helper and gradient execution charge linear work proportional to vector size. Numeric builtin names are not reserved: local or workspace user function bindings win. Source-carrying imports are validated and rebuilt from source as before.

TR: Tipli ifade AST'sine çok argümanlı numericCall düğümü eklendi; tek argümanlı Float çağrısının yapısı korunur. Main ve yardımcılar ortak sayısal tip çıkarımı ve değerlendirmeyi kullanır. Argümanlar soldan sağa bir kez hesaplanır. Yardımcı/türev yürütmesi vektör boyutuyla orantılı bütçe tüketir. Sayısal yerleşik adları ayrılmaz; yerel ve workspace kullanıcı fonksiyonları önceliklidir. Kaynak taşıyan aktarımlar kaynaktan yeniden doğrulanır.

The TR/EN numeric guide specifies accepted types, population statistics, tie handling and non-differentiable boundaries. This addition does not enable symbolic array lengths, custom training losses or matrices; those remain separate planned tasks.