diff --git a/.github/workflows/macos-application-parity.yml b/.github/workflows/macos-application-parity.yml index 5fae6c5..c3dc65c 100644 --- a/.github/workflows/macos-application-parity.yml +++ b/.github/workflows/macos-application-parity.yml @@ -25,8 +25,15 @@ name: macOS application platform checks - 'tests/tools/native_owned_lifetime.py' - 'tests/tools/native_symbol_surface.py' - 'tests/tools/file_modified_at_contract.py' + - 'tests/rooted_file_snapshot_tests.cpp' + - 'tests/tools/rooted_file_snapshot_contract.py' + - 'tests/language/rooted-file-snapshot*.ny' + - 'tests/webview_*' + - 'tests/tools/webview_intrinsic_contract.py' - 'tests/tools/formatted_text_contract.py' - 'tests/tools/markup_contract.py' + - 'tests/tools/module_alias_contract.py' + - 'tests/tools/checked_conversion_intrinsic_contract.py' - 'tests/language/formatted-text*' - 'tests/language/markup*' - 'tests/routes/ny_route_matrix.py' @@ -165,21 +172,23 @@ jobs: set -o pipefail cmake --build build/application --parallel 2 --target \ nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilbuild niltest aperture nilruntime_shared \ - nil_vscode_host_runner nil_file_time_support_tests nil_compiler_module_darwin_tests \ + nil_vscode_host_runner nil_file_time_support_tests nil_rooted_file_snapshot_tests nil_webview_runtime_tests \ + nil_compiler_module_darwin_tests \ nil_darwin_toolchain_inputs_tests nil_freestanding_hook_default nil_freestanding_hook_override \ nildebugger_core_tests nildebugger_source_metadata_tests nildebugger_dap_owner_tests \ 2>&1 | tee build/application-evidence/build.log - - name: Verify formatted text and markup through interpreter and native routes + - name: Verify formatted text, markup, module aliases and checked conversions if: ${{ !cancelled() && steps.tools.outcome == 'success' }} timeout-minutes: 8 run: | python3 - <<'PYTHON' import json, subprocess, xml.etree.ElementTree as ET from pathlib import Path - expected = {'nil.formatted-text-contract', 'nil.markup-contract'} + expected = {'nil.formatted-text-contract', 'nil.markup-contract', + 'nil.module-alias', 'nil.checked-conversion-intrinsic-contract'} expected.update('ny.'+route+'.'+fixture for route in ['routes', 'tools'] for fixture in ['formatted-text', 'formatted-text-matrix', 'markup', 'markup-matrix']) - pattern = r'^(nil[.](formatted-text-contract|markup-contract)|ny[.](routes|tools)[.](formatted-text|markup)(-matrix)?)$' + pattern = r'^(nil[.](formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract)|ny[.](routes|tools)[.](formatted-text|markup)(-matrix)?)$' base = ['ctest', '--test-dir', 'build/application', '-R', pattern] root = Path('build/application-evidence').resolve() inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) @@ -234,7 +243,7 @@ jobs: run: >- python3 -B scripts/ci/macos-toolchain-census.py --build build/application --output build/application-evidence/toolchain-census - - name: Verify actual native lifetime and timestamp contracts + - name: Verify native lifetime, timestamps, rooted files and WebView contracts if: ${{ !cancelled() && steps.tools.outcome == 'success' && steps.heap.outcome == 'success' }} timeout-minutes: 16 run: | @@ -243,8 +252,10 @@ jobs: from pathlib import Path expected = {'compiler.darwin-module-fingerprint', 'ny.native-managed-lifetime', 'ny.native-owned-lifetime', 'nil.file-time-support', 'nil.file-modified-at-contract', + 'nil.rooted-file-snapshot', 'nil.rooted-file-snapshot-contract', + 'nil.webview-runtime', 'nil.webview-intrinsic-contract', 'nil.freestanding-hook-default', 'nil.freestanding-hook-override', 'nil.native-symbol-surface'} - pattern = r'^(compiler[.]darwin-module-fingerprint|ny[.]native-(managed|owned)-lifetime|nil[.]file-(time-support|modified-at-contract)|nil[.]freestanding-hook-(default|override)|nil[.]native-symbol-surface)$' + pattern = r'^(compiler[.]darwin-module-fingerprint|ny[.]native-(managed|owned)-lifetime|nil[.]file-(time-support|modified-at-contract)|nil[.]rooted-file-snapshot(-contract)?|nil[.]webview-(runtime|intrinsic-contract)|nil[.]freestanding-hook-(default|override)|nil[.]native-symbol-surface)$' base = ['ctest', '--test-dir', 'build/application', '-R', pattern] root = Path('build/application-evidence').resolve() inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) @@ -262,6 +273,7 @@ jobs: for kind in ['failure','error','skipped']) for case in cases) PYTHON - name: Verify project, discovery, assembler, context, archive and packaging contracts + id: sdk_contracts if: ${{ !cancelled() && steps.tools.outcome == 'success' }} timeout-minutes: 30 run: | @@ -288,6 +300,19 @@ jobs: assert all(case.get('status') == 'run' and all(case.find(kind) is None for kind in ['failure','error','skipped']) for case in cases) PYTHON + - name: Preserve early project and packaging failure evidence + if: ${{ failure() && steps.sdk_contracts.outcome == 'failure' }} + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: macos-sdk-contract-failure-${{ matrix.host.arch }}-${{ github.sha }}-${{ github.run_attempt }} + path: | + build/application-evidence/sdk-contract-inventory.json + build/application-evidence/sdk-contracts.log + build/application-evidence/sdk-contract-results.xml + build/application-evidence/revision.txt + build/application-evidence/host.txt + if-no-files-found: error + retention-days: 14 - name: Verify default native toolchain and real incremental reuse if: ${{ !cancelled() && steps.tools.outcome == 'success' }} timeout-minutes: 20 diff --git a/.github/workflows/rooted-file-native-parity.yml b/.github/workflows/rooted-file-native-parity.yml new file mode 100644 index 0000000..8445ddf --- /dev/null +++ b/.github/workflows/rooted-file-native-parity.yml @@ -0,0 +1,329 @@ +name: Historical rooted file native macOS replay + +"on": + workflow_dispatch: + # Replay the original fixed-source campaign only when explicitly dispatched. + # Current-source PR qualification is in macos-application-parity.yml, which + # includes the rooted-file and WebView contracts in its exact test inventory. + +permissions: + contents: read + +# This campaign tests a fixed source revision. The workflow revision is recorded +# separately; neither an installed SDK nor any release artifact is replaced. +jobs: + native: + name: macOS ${{ matrix.host.arch }} rooted file native contract + runs-on: ${{ matrix.host.runner }} + timeout-minutes: 65 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + host: + - {runner: macos-15-intel, arch: x86_64} + - {runner: macos-15, arch: arm64} + defaults: + run: + shell: bash + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + PYTHONDONTWRITEBYTECODE: '1' + PYTHONUTF8: '1' + NIL_TESTED_SOURCE: 93515c3d4c2b6e0e7c3b870eb283fce26392d613 + NIL_EXPECTED_ARCH: ${{ matrix.host.arch }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: 93515c3d4c2b6e0e7c3b870eb283fce26392d613 + path: source + persist-credentials: false + - name: Record identities and prepare bounded commands + timeout-minutes: 2 + run: | + mkdir -p build/rooted-native-evidence + cat > build/rooted_native_campaign.py <<'PY' + import hashlib, json, os, stat, subprocess, sys + from pathlib import Path + + ROOT = Path(os.environ['GITHUB_WORKSPACE']).resolve() + SOURCE = ROOT / 'source' + BUILD = ROOT / 'build/rooted-native' + EVIDENCE = ROOT / 'build/rooted-native-evidence' + sys.path.insert(0, str(SOURCE / 'tests/tools')) + import ordinary_io_parity_contract as support + + def save(name, value): + (EVIDENCE / name).write_text(json.dumps(value, indent=2) + '\n') + + def record(path): + return {**support.file_record(path), 'mode': stat.S_IMODE(path.stat().st_mode)} + + def source_identity(): + revision = subprocess.check_output(['git', '-C', str(SOURCE), 'rev-parse', 'HEAD'], + text=True, timeout=15).strip() + dirty = subprocess.check_output(['git', '-C', str(SOURCE), 'status', '--porcelain', + '--untracked-files=no'], text=True, timeout=15) + assert revision == os.environ['NIL_TESTED_SOURCE'] and not dirty + return revision + + def run(name, command, timeout, environment=None): + # The canonical owner retains/reaps the process group and caps raw + # pipes. Keep full bounded logs, but print only their final 64 KiB. + support.MAX_OUTPUT = 8 * 1024**2 + row = support.run_process(support.load_ownership(SOURCE), command, ROOT, + environment or dict(os.environ), EVIDENCE, name, timeout) + save(name + '.json', row) + for key in ('stdout', 'stderr'): + path = EVIDENCE / row[key] + if path.is_file(): + data = path.read_bytes() + print(key + ': ' + str(len(data)) + ' bytes retained') + print(data[-65536:].decode('utf-8', errors='replace')) + assert row['status'] == 'PASS' and row['exit_code'] == 0 + assert row['cleanup_verified'] is True and not row.get('timed_out') and not row.get('error') + return row + + def seal(): + files = [BUILD / 'bin' / name for name in + ('nilcompiler', 'nilinterpreter', 'nil_rooted_file_snapshot_tests')] + files.append(BUILD / 'lib/libnil.a') + files.extend(path for path in (SOURCE / 'nilstd/src').rglob('*') if path.is_file()) + files.extend(SOURCE / name for name in ( + 'tests/tools/rooted_file_snapshot_contract.py', + 'tests/tools/ordinary_io_parity_contract.py', 'tests/native_output_staging.py', + 'validation/ny-3d/scripts/debugger_process.py', 'tests/rooted_file_snapshot_tests.cpp', + 'tests/language/rooted-file-snapshot.ny', 'tests/language/text-from-bytes.ny', + 'tests/language/text-from-bytes-native-reject.ny', + 'tests/language/rooted-file-snapshot-invalid-schema.ny', + 'tests/language/rooted-file-snapshot-invalid-signature.ny')) + return {str(path.relative_to(ROOT)): record(path) for path in sorted(files)} + PY + python3 - <<'PY' + import os, platform, re, subprocess, sys + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + assert platform.system() == 'Darwin' and platform.machine() == os.environ['NIL_EXPECTED_ARCH'] + workflow_revision = os.environ['GITHUB_WORKFLOW_SHA'] + assert re.fullmatch(r'[0-9a-f]{40}', workflow_revision) + campaign.save('identity.json', dict(tested_source_revision=campaign.source_identity(), + workflow_revision=workflow_revision, dispatch_revision=os.environ['GITHUB_SHA'], + workflow_ref=os.environ['GITHUB_WORKFLOW_REF'], run_id=os.environ['GITHUB_RUN_ID'], + run_attempt=os.environ['GITHUB_RUN_ATTEMPT'], system=platform.system(), + machine=platform.machine(), python=sys.version, + macos=subprocess.check_output(['sw_vers'], text=True, timeout=15), + llvm=True, scope='Pinned source-library host, interpreter, LLVM AOT/JIT contracts; no installed SDK or release activation')) + PY + - name: Configure LLVM Release build + timeout-minutes: 8 + run: | + python3 - <<'PY' + import subprocess, sys + from pathlib import Path + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + prefix = Path(subprocess.check_output(['brew', '--prefix', 'llvm@18'], text=True, timeout=30).strip()) + version = subprocess.check_output([str(prefix/'bin/llvm-config'), '--version'], text=True, timeout=15).strip() + assert version.startswith('18.') + campaign.save('toolchain.json', dict(llvm_prefix=str(prefix), llvm_version=version, + sdk_path=subprocess.check_output(['xcrun', '--show-sdk-path'], text=True, timeout=15).strip(), + xcode=subprocess.check_output(['xcodebuild', '-version'], text=True, timeout=15))) + campaign.run('configure', ['cmake', '-S', str(campaign.SOURCE), '-B', str(campaign.BUILD), + '-DCMAKE_BUILD_TYPE=Release', '-DBUILD_TESTING=ON', '-DNIL_ENABLE_LLVM=ON', + '-DLLVM_DIR=' + str(prefix/'lib/cmake/llvm'), '-DPython3_EXECUTABLE=' + sys.executable, + '-DNILCOMPILER_SQLITE_INCLUDE_DIR=OFF', '-DNILCOMPILER_POSTGRESQL_INCLUDE_DIR=OFF'], 390) + PY + - name: Build compiler interpreter and host fixture + timeout-minutes: 40 + run: | + python3 - <<'PY' + import sys + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + campaign.run('build', ['cmake', '--build', str(campaign.BUILD), '--config', 'Release', + '--parallel', '2', '--target', 'nilcompiler', 'nilinterpreter', 'nil_rooted_file_snapshot_tests'], 2350) + campaign.save('seal-before.json', campaign.seal()) + PY + - name: Run exactly two rooted file contracts + timeout-minutes: 8 + run: | + python3 - <<'PY' + import json, os, subprocess, sys, xml.etree.ElementTree as ET + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + expected = {'nil.rooted-file-snapshot', 'nil.rooted-file-snapshot-contract'} + base = ['ctest', '--test-dir', str(campaign.BUILD), '-C', 'Release', '-R', + r'^nil[.]rooted-file-snapshot(-contract)?$'] + inventory = subprocess.check_output(base + ['--show-only=json-v1'], timeout=30) + (campaign.EVIDENCE/'inventory.json').write_bytes(inventory) + tests = json.loads(inventory)['tests'] + assert len(tests) == 2 and {test['name'] for test in tests} == expected + language = next(test for test in tests if test['name'].endswith('-contract'))['command'] + assert language[language.index('--llvm') + 1] == 'ON' + assert language[language.index('--compiler') + 1] == str(campaign.BUILD/'bin/nilcompiler') + assert language[language.index('--interpreter') + 1] == str(campaign.BUILD/'bin/nilinterpreter') + assert language[language.index('--nilstd') + 1] == str(campaign.SOURCE/'nilstd/src') + temporary = campaign.BUILD/'owned-test-temp' + temporary.mkdir(mode=0o700) + environment = dict(os.environ, TMPDIR=str(temporary) + os.sep) + campaign.run('ctest', base + ['--parallel', '1', '--no-tests=error', '--output-on-failure', + '--test-output-size-passed', '65536', '--test-output-size-failed', '65536', + '--output-junit', str(campaign.EVIDENCE/'results.xml')], 440, environment) + cases = list(ET.parse(campaign.EVIDENCE/'results.xml').getroot().iter('testcase')) + assert len(cases) == 2 and {case.get('name') for case in cases} == expected + assert all(case.get('status') == 'run' and all(case.find(kind) is None + for kind in ('failure', 'error', 'skipped')) for case in cases) + host = next(case for case in cases if case.get('name') == 'nil.rooted-file-snapshot') + assert host.findtext('system-out', '').strip() == '87 rooted snapshot checks passed' + assert not list(temporary.iterdir()), 'Owned host/compiler temporary files remain' + PY + - name: Independently verify route inventories raw output and seals + timeout-minutes: 3 + run: | + python3 - <<'PY' + import hashlib, json, sys + from pathlib import Path + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + roots = list((campaign.BUILD/'test-evidence').glob('rooted-file-snapshot-*')) + assert len(roots) == 1 and roots[0].is_dir() and not roots[0].is_symlink() + root = roots[0] + report = json.loads((root/'report.json').read_text()) + assert report['schema'] == 'nil.rooted-file-snapshot.v1' and report['status'] == 'PASS' + assert report['llvm_enabled'] is True and report['cleanup_verified'] is True + routes = {'text-interpreter', 'binary-interpreter', 'llvm-aot', 'llvm-jit'} + stages = {'initial', 'same-size-time-replacement'} + snapshot = report['snapshot_routes'] + assert len(snapshot) == 8 and {(row['stage'], row['route']) for row in snapshot} == { + (stage, route) for stage in stages for route in routes} + for row in snapshot: + seed = 19 if row['stage'] == 'initial' else 21 + digest = hashlib.sha256(bytes((index * 73 + seed) % 256 for index in range(256))).hexdigest() + assert row['status'] == 'PASS' and row['sha256'] == digest and row['bytes'] == 256 + assert row['exact_payload_bytes_checked'] == 256 and row['modified_ms'] == 1600000000123 + assert all(row[key] is True for key in ('empty_file_checked', + 'descendant_and_final_links_rejected', 'namespace_unchanged')) + unbox = report['unbox_rejections'] + assert len(unbox) == 4 and {row['route'] for row in unbox} == routes + conversions = report['conversion_routes'] + assert len(conversions) == 2 and {row['route'] for row in conversions} == {'text-interpreter', 'binary-interpreter'} + for row in conversions: + assert row['status'] == 'PASS' and all(row[key] is True for key in + ('all_256_byte_values', 'copy_independent_of_source_mutation', 'empty_and_1MiB_payloads')) + rejections = report['native_rejections'] + assert len(rejections) == 6 and {(row['case'], row['route']) for row in rejections} == { + (case, route) for case in ('text.from_bytes', 'invalid-schema', 'invalid-signature') + for route in ('llvm-aot', 'llvm-jit')} + expected_output = {'compile-snapshot-' + encoding: b'' for encoding in ('text', 'binary', 'native')} + for stage in stages: + for route in routes: + expected_output[stage + '-' + route] = b'snapshot-content-ok\nsnapshot-errors-ok\nsnapshot-links-ok\n' + expected_errors = {} + for row in unbox: + reason = ("anything type mismatch: expected 'array', got 'array'" + if row['route'].startswith('llvm-') else + "anything contains 'array', cannot extract 'array'") + assert row['status'] == 'PASS' and row['reason'] == reason + expected_errors['wrong-element-' + row['route']] = reason.encode() + for encoding in ('text', 'binary'): + expected_output['compile-conversion-' + encoding] = b'' + expected_output['conversion-' + encoding] = b'from-bytes-ok\n' + for row in rejections: + if row['case'] == 'text.from_bytes': + name = 'conversion-rejected-' + row['route'] + reason = "unsupported native annotation '@intrinsic(\"text.from_bytes\")'" + else: + name = 'snapshot-rejected-' + row['case'] + '-' + row['route'] + reason = 'file.read_rooted_snapshot requires (text,text,i64) -> Result' + assert row['status'] == 'PASS' and row['reason'] == reason + expected_errors[name] = reason.encode() + commands = report['commands'] + assert len(commands) == 25 and {row['name'] for row in commands} == set(expected_output) | set(expected_errors) + for row in commands: + assert row['cleanup_verified'] is True and not row.get('timed_out') and not row.get('error') + streams = {} + for stream in ('stdout', 'stderr'): + path = root/'logs'/row[stream] + assert path.parent == root/'logs' and path.name == row['name'] + '.' + stream + assert campaign.support.file_record(path, 1024**2) == row[stream + '_record'] + streams[stream] = path.read_bytes() + if row['name'] in expected_errors: + assert row['status'] == 'FAIL' and row['exit_code'] > 0 and not streams['stdout'] + assert expected_errors[row['name']] in streams['stderr'] + if '-rejected-' in row['name']: + target = Path(row['argv'][row['argv'].index('-o') + 1]) + assert not target.exists() and not target.is_symlink() + else: + assert row['status'] == 'PASS' and row['exit_code'] == 0 and not streams['stderr'] + assert streams['stdout'] == expected_output[row['name']] + paths = {name: campaign.SOURCE/'tests/language'/name for name in ( + 'rooted-file-snapshot.ny', 'text-from-bytes.ny', 'text-from-bytes-native-reject.ny', + 'rooted-file-snapshot-invalid-schema.ny', 'rooted-file-snapshot-invalid-signature.ny')} + paths.update(compiler=campaign.BUILD/'bin/nilcompiler', interpreter=campaign.BUILD/'bin/nilinterpreter', + file_library=campaign.SOURCE/'nilstd/src/io/file.ny', text_library=campaign.SOURCE/'nilstd/src/text/string_utils.ny', + contract=campaign.SOURCE/'tests/tools/rooted_file_snapshot_contract.py', + process_owner=campaign.SOURCE/'validation/ny-3d/scripts/debugger_process.py', + process_support=campaign.SOURCE/'tests/tools/ordinary_io_parity_contract.py') + assert set(report['inputs']) == set(paths) and report['nilstd'] == str(campaign.SOURCE/'nilstd/src') + for name, path in paths.items(): + item = report['inputs'][name] + assert item['path'] == str(path) and campaign.support.file_record(path) == { + key: item[key] for key in ('bytes', 'sha256')} + after = campaign.seal() + campaign.save('seal-after.json', after) + assert after == json.loads((campaign.EVIDENCE/'seal-before.json').read_text()) + assert not list((campaign.BUILD/'owned-test-temp').iterdir()) + campaign.save('replay.json', dict(status='PASS', tested_source_revision=campaign.source_identity(), + host_checks=87, snapshot_observations=8, wrong_element_rejections=4, + byte_conversions=2, native_compile_rejections=6, commands=25, raw_streams=50, + source_std_tools_unchanged=True, process_cleanup_verified=True, owned_temp_empty=True, + report=campaign.support.file_record(root/'report.json'))) + print('PASS: 87 host checks; 8 snapshot, 4 unbox, 2 conversion, 6 native rejection observations; 25 owned commands') + PY + - name: Preserve complete or partial evidence without product binaries + if: always() + timeout-minutes: 3 + run: | + python3 - <<'PY' + import hashlib, json, shutil, stat, sys + from pathlib import Path + sys.path.insert(0, 'build') + import rooted_native_campaign as campaign + destination = campaign.EVIDENCE/'contracts' + destination.mkdir(exist_ok=True) + for root in sorted((campaign.BUILD/'test-evidence').glob('rooted-file-snapshot-*')): + assert root.is_dir() and not root.is_symlink() + output = destination/root.name + output.mkdir() + paths = [root/'report.json', *sorted((root/'logs').glob('*'))] + for path in paths: + if not path.exists(): + continue + assert stat.S_ISREG(path.lstat().st_mode) and not path.is_symlink() + assert path.stat().st_size <= 8 * 1024**2 + target = output/path.relative_to(root) + target.parent.mkdir(exist_ok=True) + shutil.copyfile(path, target) + files = {} + total = 0 + for path in sorted(campaign.EVIDENCE.rglob('*')): + if path.is_dir(): + continue + assert stat.S_ISREG(path.lstat().st_mode) and not path.is_symlink() + assert path.stat().st_size <= 8 * 1024**2 + total += path.stat().st_size + assert total <= 64 * 1024**2 + files[str(path.relative_to(campaign.EVIDENCE))] = campaign.support.file_record(path, 8 * 1024**2) + campaign.save('evidence.json', dict(tested_source_revision=campaign.source_identity(), + workflow_revision=__import__('os').environ['GITHUB_WORKFLOW_SHA'], + scope='Evidence and bounded logs only; generated executables, objects, SDKs and fixture data excluded', + total_bytes=total, files=files)) + PY + - name: Upload complete or partial results + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: rooted-file-native-${{ matrix.host.arch }}-source-93515c3-${{ github.sha }}-${{ github.run_attempt }} + path: build/rooted-native-evidence/ + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/web-runtime-parity.yml b/.github/workflows/web-runtime-parity.yml index fd2b4f6..0e1f4ec 100644 --- a/.github/workflows/web-runtime-parity.yml +++ b/.github/workflows/web-runtime-parity.yml @@ -7,12 +7,21 @@ name: Web runtime platform checks - 'CMakeLists.txt' - 'nilcompiler/**' - 'nilstd/**' + - 'common/webview_*' - 'tests/net_*' - 'tests/file_time_support_tests.cpp' + - 'tests/rooted_file_snapshot_tests.cpp' + - 'tests/webview_*' - 'tests/tools/net_socket_contract.py' - 'tests/tools/file_modified_at_contract.py' + - 'tests/tools/rooted_file_snapshot_contract.py' + - 'tests/tools/webview_intrinsic_contract.py' + - 'tests/language/rooted-file-snapshot.ny' + - 'tests/language/text-from-bytes*.ny' - 'tests/tools/formatted_text_contract.py' - 'tests/tools/markup_contract.py' + - 'tests/tools/module_alias_contract.py' + - 'tests/tools/checked_conversion_intrinsic_contract.py' - 'tests/language/formatted-text*' - 'tests/language/markup*' - 'tests/routes/ny_route_matrix.py' @@ -85,8 +94,9 @@ jobs: run: | set -o pipefail cmake --build build/web-parity --config Release --parallel 2 \ - --target nilcompiler nilinterpreter nil_net_support_tests \ + --target nilcompiler nilinterpreter nilassembler nil_net_support_tests \ nil_net_lifecycle_tests nil_file_time_support_tests \ + nil_rooted_file_snapshot_tests nil_webview_runtime_tests \ 2>&1 | tee build/web-parity-evidence/build.log - name: Run real peer and language contracts timeout-minutes: 8 @@ -94,14 +104,17 @@ jobs: "$NIL_CI_PYTHON" - <<'PY' import json, subprocess from pathlib import Path - pattern = r'^(net[.](support-contract|lifecycle-contract|socket-contract)|nil[.](file-time-support|file-modified-at-contract|formatted-text-contract|markup-contract)|matrix[.]execution)$' + pattern = r'^(net[.](support-contract|lifecycle-contract|socket-contract)|nil[.](file-time-support|file-modified-at-contract|rooted-file-snapshot|rooted-file-snapshot-contract|webview-runtime|webview-intrinsic-contract|formatted-text-contract|markup-contract|module-alias|checked-conversion-intrinsic-contract)|matrix[.]execution)$' base = ['ctest', '--test-dir', 'build/web-parity', '-C', 'Release', '-R', pattern] root = Path('build/web-parity-evidence').resolve() inventory = subprocess.check_output(base+['--show-only=json-v1'], timeout=30) (root/'inventory.json').write_bytes(inventory) expected = {'net.support-contract', 'net.lifecycle-contract', 'net.socket-contract', 'nil.file-time-support', 'nil.file-modified-at-contract', 'matrix.execution', - 'nil.formatted-text-contract', 'nil.markup-contract'} + 'nil.rooted-file-snapshot', 'nil.rooted-file-snapshot-contract', + 'nil.webview-runtime', 'nil.webview-intrinsic-contract', + 'nil.formatted-text-contract', 'nil.markup-contract', + 'nil.module-alias', 'nil.checked-conversion-intrinsic-contract'} assert {test['name'] for test in json.loads(inventory)['tests']} == expected with (root/'ctest.log').open('wb') as output: result = subprocess.run(base+['--no-tests=error', '--output-on-failure', diff --git a/CMakeLists.txt b/CMakeLists.txt index 78f23a6..61852bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -180,6 +180,28 @@ if(BUILD_TESTING) LABELS "tools;windows;rc" TIMEOUT 30) endif() + # Synthetic checked provider peers exercise loading and ownership without + # a browser engine or signed-in desktop. Never packaged into the SDK. + add_library(nil_webview_fixture_good SHARED tests/webview_provider_fixture.cpp) + add_library(nil_webview_fixture_bad SHARED tests/webview_provider_fixture.cpp) + target_compile_definitions(nil_webview_fixture_bad PRIVATE NILWV_FIXTURE_BAD_ABI=1) + foreach(fixture IN ITEMS nil_webview_fixture_good nil_webview_fixture_bad) + target_compile_features(${fixture} PRIVATE cxx_std_17) + endforeach() + add_executable(nil_webview_runtime_tests tests/webview_runtime_tests.cpp) + target_link_libraries(nil_webview_runtime_tests PRIVATE nilruntime nil_webview_fixture_good Threads::Threads) + target_include_directories(nil_webview_runtime_tests PRIVATE nilcompiler/src) + add_dependencies(nil_webview_runtime_tests nil_webview_fixture_bad) + add_test(NAME nil.webview-runtime COMMAND $ + $ $) + set_tests_properties(nil.webview-runtime PROPERTIES TIMEOUT 20) + + add_executable(nil_rooted_file_snapshot_tests tests/rooted_file_snapshot_tests.cpp) + target_link_libraries(nil_rooted_file_snapshot_tests PRIVATE nilruntime) + target_include_directories(nil_rooted_file_snapshot_tests PRIVATE nilcompiler/src) + add_test(NAME nil.rooted-file-snapshot COMMAND $) + set_tests_properties(nil.rooted-file-snapshot PROPERTIES LABELS "storage;runtime;rc" TIMEOUT 60) + add_executable(nil_utf8_file_paths_tests tests/utf8_file_paths_tests.cpp) target_link_libraries(nil_utf8_file_paths_tests PRIVATE nilruntime) target_include_directories(nil_utf8_file_paths_tests PRIVATE nilcompiler/src) @@ -832,11 +854,21 @@ if(BUILD_TESTING) --lifecycle-test $ --llvm "${NIL_ENABLE_LLVM}" ${NIL_UI_DISPLAY_APPKIT_ARGS}) set_tests_properties(nil.ui-display PROPERTIES LABELS "ui;routes" SKIP_RETURN_CODE 77 TIMEOUT "${NIL_UI_DISPLAY_TIMEOUT}") + add_test(NAME nil.webview-intrinsic-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/webview_intrinsic_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.webview-intrinsic-contract PROPERTIES LABELS "webview;routes" TIMEOUT 180) add_test(NAME nil.ui-intrinsic-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/ui_intrinsic_contract.py" --compiler $ --interpreter $ --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(nil.ui-intrinsic-contract PROPERTIES LABELS "ui;routes;typecheck" TIMEOUT 180) + add_test(NAME nil.checked-conversion-intrinsic-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/checked_conversion_intrinsic_contract.py" + --compiler $ --interpreter $ + --assembler $ --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.checked-conversion-intrinsic-contract PROPERTIES LABELS "routes;typecheck" TIMEOUT 180) add_test(NAME matrix.consider-block-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/consider_block_contract.py" --compiler $ --interpreter $ @@ -1216,6 +1248,14 @@ if(BUILD_TESTING) --llvm "${NIL_ENABLE_LLVM}" --output-parent "${CMAKE_BINARY_DIR}/test-evidence") set_tests_properties(nil.file-modified-at-contract PROPERTIES LABELS "io;routes;rc" TIMEOUT 180) + add_test(NAME nil.rooted-file-snapshot-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/rooted_file_snapshot_contract.py" + --compiler $ + --interpreter $ + --nilstd "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}" + --output-parent "${CMAKE_BINARY_DIR}/test-evidence") + set_tests_properties(nil.rooted-file-snapshot-contract PROPERTIES LABELS "io;routes;rc" TIMEOUT 360) add_test(NAME nillsp.semantic-protocol COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/lsp_semantic_protocol.py" --lsp $) @@ -1759,6 +1799,11 @@ if(BUILD_TESTING) --compiler $ --interpreter $ --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(nil.module-context PROPERTIES LABELS "analysis;typecheck;routes" TIMEOUT 120) + add_test(NAME nil.module-alias + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/module_alias_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.module-alias PROPERTIES LABELS "analysis;typecheck;routes" TIMEOUT 180) set_tests_properties(parser.source-spans parser.matrix-source-spans nil.semantic-index PROPERTIES LABELS "analysis;semantic" TIMEOUT 60) add_test(NAME matrix.function-values diff --git a/README.md b/README.md index 7ee02c9..9befdbd 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,11 @@ File timestamps also pass textual/binary NIL, LLVM JIT and AOT checks everywhere The [platform support matrix](docs/platform-support.md) records exact SDK/source revisions, retained failures and remaining deployment boundaries. +The [current framework integration](https://github.com/exec-software/exec-nil-framework/pull/41) +combines rooted file snapshots, the Matrix WebView bridge and the completed +formatted-text/markup work. Its [qualification record](notebook/2026-11-13-formatted-markup-handoff.md#current-framework-integration) +tracks current-source checks separately from the installed SDK results above. + These are development results. Windows and macOS release qualification remains pending. The [release profile](docs/release/v1-profile.md) defines supported configurations diff --git a/common/webview_json_v1.hpp b/common/webview_json_v1.hpp new file mode 100644 index 0000000..b57a68c --- /dev/null +++ b/common/webview_json_v1.hpp @@ -0,0 +1,127 @@ +// Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT +#pragma once +#include +#include +#include + +// WebView v1 JSON text grammar. This validates without decoding or normalizing +// JSON.stringify output, including escaped lone UTF-16 surrogates. A configuration +// parser with duplicate-key/scalar restrictions is not interchangeable with it. +// The provider and framework carry identical copies of this versioned grammar. +namespace nilwebview::json_v1 { +namespace detail { +class Parser { +public: + explicit Parser(const std::string &source) : source_(source) {} + bool parse() noexcept { whitespace(); return value(0) && (whitespace(), offset_ == source_.size()); } +private: + void whitespace() noexcept { + while (offset_ < source_.size() && (source_[offset_] == ' ' || source_[offset_] == '\t' || + source_[offset_] == '\r' || source_[offset_] == '\n')) ++offset_; + } + bool take(char expected) noexcept { + if (offset_ == source_.size() || source_[offset_] != expected) return false; + ++offset_; return true; + } + bool literal(const char *text) noexcept { + const auto size = std::strlen(text); + if (source_.compare(offset_, size, text) != 0) return false; + offset_ += size; return true; + } + bool string() noexcept { + if (!take('"')) return false; + while (offset_ < source_.size()) { + const auto c = static_cast(source_[offset_++]); + if (c == '"') return true; + if (c < 0x20) return false; + if (c != '\\') continue; + if (offset_ == source_.size()) return false; + const auto escape = source_[offset_++]; + if (escape == 'u') { + for (int index = 0; index < 4; ++index) { + if (offset_ == source_.size()) return false; + const auto digit = source_[offset_++]; + if (!((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f') || + (digit >= 'A' && digit <= 'F'))) return false; + } + } else if (!std::strchr("\"\\/bfnrt", escape)) return false; + } + return false; + } + bool number() noexcept { + take('-'); + if (!take('0')) { + if (offset_ == source_.size() || source_[offset_] < '1' || source_[offset_] > '9') return false; + do { ++offset_; } while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9'); + } + if (take('.')) { + const auto first = offset_; + while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9') ++offset_; + if (offset_ == first) return false; + } + if (take('e') || take('E')) { + if (!take('+')) take('-'); + const auto first = offset_; + while (offset_ < source_.size() && source_[offset_] >= '0' && source_[offset_] <= '9') ++offset_; + if (offset_ == first) return false; + } + return true; + } + bool value(unsigned depth) noexcept { + if (depth > 64 || offset_ == source_.size()) return false; + switch (source_[offset_]) { + case '"': return string(); + case 't': return literal("true"); + case 'f': return literal("false"); + case 'n': return literal("null"); + case '[': { + ++offset_; whitespace(); + if (take(']')) return true; + do { whitespace(); if (!value(depth + 1)) return false; whitespace(); } while (take(',')); + return take(']'); + } + case '{': { + ++offset_; whitespace(); + if (take('}')) return true; + do { + whitespace(); if (!string()) return false; + whitespace(); if (!take(':')) return false; + whitespace(); if (!value(depth + 1)) return false; + whitespace(); + } while (take(',')); + return take('}'); + } + default: return number(); + } + } + const std::string &source_; + std::size_t offset_ = 0; +}; +} // namespace detail + +inline bool valid_utf8(const std::string &text) noexcept { + for (std::size_t index = 0; index < text.size();) { + const auto first = static_cast(text[index++]); + if (!first) return false; + if (first < 0x80) continue; + unsigned count = 0; + std::uint32_t code = 0, minimum = 0; + if (first >= 0xc2 && first <= 0xdf) { count = 1; code = first & 0x1f; minimum = 0x80; } + else if (first >= 0xe0 && first <= 0xef) { count = 2; code = first & 0x0f; minimum = 0x800; } + else if (first >= 0xf0 && first <= 0xf4) { count = 3; code = first & 7; minimum = 0x10000; } + else return false; + if (text.size() - index < count) return false; + while (count--) { + const auto byte = static_cast(text[index++]); + if ((byte & 0xc0) != 0x80) return false; + code = (code << 6) | (byte & 0x3f); + } + if (code < minimum || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return false; + } + return true; +} + +inline bool valid_json(const std::string &text) noexcept { + return text.size() <= 1048576 && valid_utf8(text) && detail::Parser(text).parse(); +} +} // namespace nilwebview::json_v1 diff --git a/common/webview_provider_v1.h b/common/webview_provider_v1.h new file mode 100644 index 0000000..216964e --- /dev/null +++ b/common/webview_provider_v1.h @@ -0,0 +1,191 @@ +/* Checked WebView provider ABI, version 1. + * Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT + */ +#ifndef NILWEBVIEW_PROVIDER_V1_H +#define NILWEBVIEW_PROVIDER_V1_H +#include + +#if defined(_WIN32) +#define NILWV_CALL __cdecl +#else +#define NILWV_CALL +#endif +#if defined(_WIN32) && defined(NILWEBVIEW_PROVIDER_BUILD) +#define NILWV_EXPORT __declspec(dllexport) +#elif defined(__GNUC__) && defined(NILWEBVIEW_PROVIDER_BUILD) +#define NILWV_EXPORT __attribute__((visibility("default"))) +#else +#define NILWV_EXPORT +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define NILWV_ABI_V1 UINT32_C(1) +#define NILWV_MAX_TEXT_BYTES UINT64_C(1048576) +#define NILWV_MAX_QUEUED_BYTES UINT64_C(8388608) +#define NILWV_MAX_EVENTS UINT32_C(256) +#define NILWV_MAX_WINDOWS UINT32_C(16) +#define NILWV_OPERATION_TIMEOUT_MS UINT32_C(30000) + +/* Capability bits describe native sender metadata, never page assertions. + * A valid GTK6 provider may advertise zero. These bits do not prove that a + * display or browser runtime can initialize, or apply to every URL scheme. */ +#define NILWV_CAP_MESSAGE_URL UINT64_C(1) +#define NILWV_CAP_MESSAGE_ORIGIN UINT64_C(2) +#define NILWV_CAP_MESSAGE_FRAME UINT64_C(4) +#define NILWV_CAP_KNOWN_MASK UINT64_C(7) + +typedef struct nilwv_context_v1 nilwv_context_v1; +typedef struct nilwv_text_v1 { + const char *data; + uint64_t size; +} nilwv_text_v1; + +/* Fields are fixed-width; C enums below name values but never cross the ABI. + * UTF-8 is validated, with no embedded NUL. {NULL,0} is the empty string. + * Inputs are borrowed for the call; asynchronous operations copy them. + * Every returned text view is provider-owned until the next call using this + * context, or context destruction. The framework must copy it immediately. + * Error text uses the same rule; probe/create errors survive the next call + * on their owner thread. No allocator or C++ type crosses this boundary. */ +typedef struct nilwv_result_v1 { + uint32_t size; /* caller initializes to sizeof(result) */ + int32_t code; /* 0 success; negative error code */ + int64_t number; /* numeric result; zero when unused */ + nilwv_text_v1 text; /* text result, or diagnostic if code < 0 */ +} nilwv_result_v1; + +enum nilwv_error_code_v1 { + NILWV_E_UNAVAILABLE = -1, + NILWV_E_ARGUMENT = -2, + NILWV_E_HANDLE = -3, + NILWV_E_THREAD = -4, + NILWV_E_NOT_READY = -5, + NILWV_E_BUSY = -6, + NILWV_E_LIMIT = -7, + NILWV_E_NATIVE = -8, + NILWV_E_TIMEOUT = -9, + NILWV_E_PROTOCOL = -10, + NILWV_E_QUEUE_OVERFLOW = -11 +}; + +enum nilwv_event_kind_v1 { + NILWV_EVENT_READY = 1, + NILWV_EVENT_INITIALIZATION_FAILED = 2, + NILWV_EVENT_NAVIGATION_COMPLETED = 3, + NILWV_EVENT_NAVIGATION_FAILED = 4, + NILWV_EVENT_SCRIPT_COMPLETED = 5, + NILWV_EVENT_SCRIPT_FAILED = 6, + NILWV_EVENT_PAGE_MESSAGE = 7, + NILWV_EVENT_NAVIGATION_REQUESTED = 8, + NILWV_EVENT_CLOSE_REQUESTED = 9, + NILWV_EVENT_PROVIDER_FAILED = 10 +}; +enum nilwv_value_kind_v1 { + NILWV_VALUE_NONE = 0, NILWV_VALUE_JSON = 1, NILWV_VALUE_UNDEFINED = 2 +}; +enum nilwv_source_kind_v1 { + NILWV_SOURCE_UNKNOWN = 0, + NILWV_SOURCE_NATIVE_URL = 1, + NILWV_SOURCE_NATIVE_ORIGIN = 2 +}; +enum nilwv_frame_kind_v1 { + NILWV_FRAME_UNKNOWN = 0, NILWV_FRAME_MAIN = 1, NILWV_FRAME_CHILD = 2 +}; +enum nilwv_failure_kind_v1 { + NILWV_FAILURE_NONE = 0, + NILWV_FAILURE_NATIVE = 1, + NILWV_FAILURE_SCRIPT_EXCEPTION = 2, + NILWV_FAILURE_SERIALIZATION = 3, + NILWV_FAILURE_ASYNC_RESULT = 4, + NILWV_FAILURE_PAYLOAD_LIMIT = 5, + NILWV_FAILURE_TIMEOUT = 6, + NILWV_FAILURE_CANCELLED = 7 +}; + +/* One context per framework execution context, owned by its platform UI + * thread: the process main thread on macOS/Linux, the creating STA thread on + * Windows. All methods, including release and destruction, use that thread. + * Public numeric handles are positive, process-unique, never reused, <=INT64_MAX, + * and validated against context, resource kind and lifetime on every call. + * No callback from a provider enters Matrix or the VM. + * + * probe: no window/display initialization; result.number=1 on success. + * create: returns a context or NULL on error; profile state is provider-owned + * and isolated from personal browser profiles. Neither probe nor create starts + * a global event loop. window: returns a pending hidden window, then poll emits + * exactly one Ready/InitializationFailed unless explicitly closed first. + * + * show/close/release_event: number=1. navigate/load_html/evaluate_function: + * positive operation ID, then one matching completion/failure event. Reject + * overlapping navigation/script operations with BUSY; do not queue another. + * navigate authorizes one initial URL request. HTTP redirects and uninitiated + * navigations (including page actions/new windows) are cancelled and reported + * as NavigationRequested; a cancelled active navigation completes as failed. + * After that completion the application may explicitly follow a requested URL. + * load_html has no base URI; evaluate_function accepts a synchronous function + * body with explicit return, JSON.stringify result semantics, distinct undefined, + * and explicit failure for thenables or unsuccessful serialization. + * + * poll pumps a bounded batch (up to 64 native dispatch iterations, 2ms soft budget) and returns an + * owned immutable event snapshot ID, or 0 for empty. Retained snapshots count + * toward queue limits. The framework copies all fields then releases on every + * path. Overflow latches QUEUE_OVERFLOW; operations fail until context teardown. + * No messages or completion events are silently dropped to recover capacity. + * + * event_number names: window, kind, sequence, operation, value_kind, + * source_kind, frame_kind, failure_kind. operation=0 means no initiating call. + * event_text names: payload_json, source_url, source_origin, detail. + * source_url/origin are empty when unavailable; browser current URL and + * JavaScript-supplied URL/origin values must not be represented as sender proof. + * source_origin is only a native engine-reported origin, not parsed from a URL. + * Unknown event property names are ARGUMENT errors, not empty/zero results. + * + * close invalidates the window, its queued/retained events and pending operations. + * Closing again is HANDLE error. Teardown invalidates all context resources. + * Outstanding engine callbacks retain only independent cancelled state, never + * a raw freed context/window pointer. Late callbacks cannot publish new events. + * Browser processes may finish asynchronously after object closure; the provider + * remains responsible for its own isolated profile/cleanup state. No claim is + * made that cancelling a script stops executing JavaScript. + */ +typedef struct nilwv_api_v1 { + uint32_t abi_version; + uint32_t size; + uint64_t capabilities; + const char *provider_name; /* static NUL-terminated UTF-8 */ + const char *provider_build; /* static NUL-terminated UTF-8 */ + + void (NILWV_CALL *probe)(nilwv_result_v1 *); + void (NILWV_CALL *context_create)(nilwv_context_v1 **, nilwv_result_v1 *); + void (NILWV_CALL *context_destroy)(nilwv_context_v1 *); + void (NILWV_CALL *window)(nilwv_context_v1 *, nilwv_text_v1, int64_t, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *show)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *navigate)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *load_html)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *evaluate_function)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *poll)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *event_number)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *event_text)(nilwv_context_v1 *, int64_t, nilwv_text_v1, nilwv_result_v1 *); + void (NILWV_CALL *release_event)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); + void (NILWV_CALL *close)(nilwv_context_v1 *, int64_t, nilwv_result_v1 *); +} nilwv_api_v1; + +typedef const nilwv_api_v1 *(NILWV_CALL *nilwv_get_api_v1_fn)(uint32_t, uint32_t); + +/* Exactly this exported C name; NULL rejects unsupported ABI/table size. + * The table and function pointers remain stable for process lifetime. + * Runtime loads only a caller-selected absolute provider path, validates every + * mandatory pointer and the exact ABI, calls probe, then creates its context. + * The runtime never unloads or hot-reloads a successfully loaded provider. + * No provider call may allow a C++ exception to cross this boundary. + */ +NILWV_EXPORT const nilwv_api_v1 *NILWV_CALL +nilwebview_provider_v1_get_api(uint32_t requested_version, uint32_t minimum_table_size); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/docs/language-reference/modules.md b/docs/language-reference/modules.md index 0c4381b..72af9db 100644 --- a/docs/language-reference/modules.md +++ b/docs/language-reference/modules.md @@ -54,9 +54,16 @@ let result = add(1, 2) import math.utils namespace mu = math.utils -let result = mu.add(1, 2) +let result = mu::add(1, 2) ``` +The alias is local to its declaring module and retains the original function's +identity, visibility, parameter types and generic arguments. It can name a +direct call or a function value. A Ny `namespace` alias does not load a module +by itself; keep the accompanying `import`. Matrix's `read math.utils as mu` +both loads the module and declares the alias. Source and binary libraries use +the same resolution rules, including legacy `ny.lang.*` standard-library names. + ### Using Module Contents ```ny use math.utils diff --git a/docs/platform-support.md b/docs/platform-support.md index 6e6e107..446f72c 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -14,8 +14,8 @@ boundary. A source update does not update an installed SDK. | macOS 15 Intel x86_64 | Relocated `1efbe66` SDK passes all 1,184 consumer routes, twelve PostgreSQL routes, 146 debugger checks, execution checkpoints, twenty installed AppKit desktop/input cases, four desktop DAP sessions and all 88 editor groups. Current `59ffa97` source fixtures pass all 22 application/tooling/packaging CTests. | The installed editor needed a diagnostic rerun after a project-build timeout; it passed unchanged deadlines, with the original cause unconfirmed. The original full source report retains four failures resolved by later fixtures and one ELF-only execution skip. Shared deployment and release qualification remain open. | | macOS 15 Apple Silicon arm64 | Relocated `1efbe66` SDK passes all 1,184 consumer routes, twelve PostgreSQL routes, 146 debugger checks, execution checkpoints, twenty installed AppKit desktop/input cases, four desktop DAP sessions and all 88 editor groups. Current `59ffa97` source fixtures also pass all 22 application/tooling/packaging CTests. | The original full source report retains four failures and one ELF-only execution skip; subsequent hosted checks resolve the four fixture failures. Shared deployment and release qualification remain open. | -The SDKs contain eleven root commands, eighteen compiled standard-library -modules, their source, native runtimes and HTML documentation. The installed +Those pinned baseline SDKs contain eleven root commands, eighteen compiled +standard-library modules, their source, native runtimes and HTML documentation. The installed consumer campaign covers both `nilstd` and `nillib`: 888 retained execution results are independently replayed from raw reports, while 296 object/link routes are checked by the pinned campaign driver. Each private candidate retains @@ -24,6 +24,11 @@ spaces and Unicode. Mac executables are checked as Mach-O for their expected architecture. These candidates have not replaced accepted SDKs or activated a release. +Current source SDKs additionally package `nil.std.markup`, bringing the logical +module inventory to nineteen. See the [current library status](standard-library/index.md); +the exact tools, source, binary modules and documentation are sealed in each +SDK's manifest. + The Linux editor result uses VS Code 1.144.1 in an isolated X11 session and empty profile. Both current Mac application campaigns use VS Code 1.146.0. Each passes 88 distinct groups, all nine test modules, the full-suite completion sentinel diff --git a/docs/release/v1-profile.md b/docs/release/v1-profile.md index ba8bf45..0a9c0f2 100644 --- a/docs/release/v1-profile.md +++ b/docs/release/v1-profile.md @@ -15,8 +15,8 @@ results do not extend this document's pinned release qualification. The reviewed binary release profile targets **Ubuntu 24.04 Linux x86_64**, using LLVM 18.1.3 and GCC 13.3.0. This describes the earlier RC qualification, -not every development build. The current development checkout has been built -with LLVM 21.1.8 and GCC 15.2.0; that toolchain is not covered by the pinned +not every development build. Development builds have also used +LLVM 21.1.8 and GCC 15.2.0; that toolchain is not covered by the pinned [release dependency policy](../../release/dependency-policy.json). Before shipping new binaries, either rebuild and qualify the exact release commit with the reviewed toolchain or review its replacement, notices, dependencies, @@ -92,11 +92,12 @@ packages does not qualify new release binaries. Aperture is a separately versioned analysis/debugging preview; packaging it does not extend the v1 language or debugger guarantees. The LSP has a deliberately limited capability set. `nilbuild` supports the [local-project profile](../tools/projects.md), -with process execution qualified on Linux. `nypm` and `nilaix` are not part of this release. +with development execution checks on Linux, Windows and both Mac architectures; +the reviewed binary release profile remains Linux. `nypm` and `nilaix` are not part of this release. -Current development SDKs strictly compile and package eighteen logical -standard-library modules, including `prelude`. Public imports use `nil.std.*`, -with `ny.lang.*` retained as aliases. Both frontends share the flat module-family +Current development SDKs strictly compile and package nineteen logical +standard-library modules, including `prelude` and `nil.std.markup`. Public imports +use `nil.std.*`, with `ny.lang.*` retained as aliases. Both frontends share the flat module-family layout. Runtime support is API-specific, as described in the [library status](../standard-library/index.md). `nil.std.reflection` provides declaration/annotation snapshots, and `nil.std.db` @@ -154,8 +155,8 @@ automatically. `latest` means newest publication and may be an RC; publication and a stable `v1.0.0` tag remain separate, deliberate release actions. See the [findings log](../../matrix/docs/next-version-findings.md) for open -correctness issues, including fully qualified enum patterns (F25) and Ny local -reads before definite assignment (F21), alongside native array and diagnostic +correctness issues, including Ny local reads before definite assignment (F21), +alongside the remaining native array and diagnostic limitations. Resolve or explicitly exclude affected behavior from the stable profile and qualify the final source revision before selecting a stable tag. Preparing or publishing the source repository does not satisfy these binary diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index ab94ddd..bdd9717 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -1,7 +1,8 @@ # Standard-library status Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its active -Ny and Matrix sources form 18 logical SDK modules, including `prelude`. +Ny and Matrix sources form 19 logical SDK modules, including `prelude` and +`nil.std.markup`. Support remains evidence-scoped. Focused fixtures exercise `nilstd` and `nillib` through textual/binary NIL, bundles, LLVM JIT and AOT, and standalone assembler/linker pipelines. Local SDK qualification records the exact source @@ -38,7 +39,7 @@ averaging, nonfinite compatibility behavior and numerical accuracy limits. ```text nilstd/ - src/ Ny and Matrix sources organized as 18 logical modules + src/ Ny and Matrix sources organized as 19 logical modules native/ 14 preserved C and C++ interoperability shims tests/ 8 preserved design-era library tests experimental/ 65 quarantined Ny sources excluded from the SDK @@ -49,7 +50,7 @@ The active tree uses neutral family folders: `nil.std.io` lives under remain aliases of the same module identities. The active logical modules are `prelude` and `nil.std.core`, `collections`, -`datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nildata`, `reflection`, `runtime`, +`datetime`, `db`, `diagnostics`, `io`, `markup`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `testing`, `text`, `threading`, and `ui`. Quarantine is broader than parser failure: an experimental source may compile yet still lack complete language semantics, an executable provider, or behavioral evidence. @@ -130,6 +131,9 @@ the runtime and included in Aperture's text allocation measurements. For untrusted file/container input, `nil.std.io.read_regular_bytes` accepts an explicit byte ceiling and rejects the final-component symlink, special file, short/growing read, and observed metadata change before returning bytes. +For paths below a trusted directory, [`read_rooted_snapshot`](rooted-file-snapshots.md) +also rejects links in descendant directories and returns the exact byte array, +descriptor-observed modification time, and SHA-256 together. `write_bytes_atomic` stages and flushes bytes in the destination directory, then atomically publishes them; `replace=false` cannot clobber an existing entry (including a dangling symlink), while `replace=true` only replaces a diff --git a/docs/standard-library/integer-conversion.md b/docs/standard-library/integer-conversion.md index bee3739..c1f88a1 100644 --- a/docs/standard-library/integer-conversion.md +++ b/docs/standard-library/integer-conversion.md @@ -50,3 +50,13 @@ run through text/binary NIL, bundles, LLVM JIT/AOT, standalone assembler/linker execution and installed source/binary libraries. This is a native claim for these checked decimal integer APIs; other `Convert` operations retain their separate support boundaries. + +Conversion intrinsic declarations must return the standard +`nil.std.core.Result`, with the provider's exact success type and a text error. +A user-defined enum named `Result` is a different type even when its variants +have the same shape. Source checking and loaded-NIL validation reject that +substitution before execution, including unchecked source emission. This rule +also applies to the interpreter's checked floating-point and boolean conversion +providers; it does not add native support for those providers. Legacy standard +namespace spellings and the explicitly supported unqualified standard Result +wire representation remain accepted. diff --git a/docs/standard-library/rooted-file-snapshots.md b/docs/standard-library/rooted-file-snapshots.md new file mode 100644 index 0000000..7d0e52b --- /dev/null +++ b/docs/standard-library/rooted-file-snapshots.md @@ -0,0 +1,52 @@ +# Rooted file snapshots + +`nil.std.io.read_rooted_snapshot(root, relative, maximum_bytes)` reads one +bounded regular file below a trusted directory. It returns +`Result`: + +| Field | Type | Meaning | +| --- | --- | --- | +| `content` | `array` | The exact bytes read, including NUL and arbitrary high bytes. | +| `modified_ms` | `i64` | Modification time observed on the final file handle, in Unix milliseconds. | +| `sha256` | `text` | The 64 lowercase hexadecimal digits of SHA-256 over `content`. | + +The caller supplies a limit from zero through 512 MiB. A zero limit accepts +an empty file. Oversized input is rejected before allocating its contents. +SHA-256 is computed over the loaded bytes, so replacing content while keeping +its size and timestamp does not preserve its digest. + +```ny +import nil.std.io.file + +fn inspect_asset(root: text) + match nil::std::io::read_rooted_snapshot(root, "assets/site.css", 1048576) + Result.Ok(snapshot) -> + println(snapshot.content.len()) + println(snapshot.modified_ms) + println(snapshot.sha256) + Result.Error(message) -> println(message) + end match +end fn +``` + +The `relative` path must be nonempty strict UTF-8, with `/` separating its +components. Empty components, `.` and `..`, absolute paths, backslashes, +colons, and NUL bytes are rejected. The root selects the trusted directory; +every descendant component is opened relative to an already-open directory. +Descendant symlinks and Windows reparse points are rejected, including the +final component. Directories and other special files cannot be returned as +content. Errors do not include caller-supplied paths. + +The final handle supplies both bytes and metadata, and the runtime checks for +observed changes around the read. This does not make a file continuously +immutable or prevent privileged mount changes, hard links already placed in +the root, or every concurrent write. The returned digest describes the bytes +actually returned; it is not a separate path lookup or a metadata hash. + +The snapshot record uses the same byte-array representation for interpreter, +LLVM JIT, and native executable routes. Code using the interpreter's raw-byte +text representation can convert `snapshot.content` with +[`nil.std.text.from_bytes`](text-spans.md#byte-values). That conversion remains +interpreter-only: native text has a NUL-terminated representation and must not +silently truncate binary content. Native consumers can inspect, hash-check, or +write the byte array without converting it to text. diff --git a/docs/standard-library/text-spans.md b/docs/standard-library/text-spans.md index 0b0d2ba..9b6b2f1 100644 --- a/docs/standard-library/text-spans.md +++ b/docs/standard-library/text-spans.md @@ -67,14 +67,20 @@ assembler/linker execution, and installed source/binary libraries. ## Byte values -`nil.std.text` measures and slices by byte — `length` of `"café"` is 5 — but -until these two existed there was no way to read a byte *as a number* or write -one as text. +`nil.std.text` measures and slices by byte — `length` of `"café"` is 5. +Use explicit byte operations to inspect or construct raw content. | Function | Result | | --- | --- | | `byte_at(s: text, index: i64) -> i64` | The byte at an index, `0..255`, or minus one when the index is outside the text. | | `from_byte(code: i64) -> text` | One byte as text; empty text for a code outside `0..255`. | +| `from_bytes(data: array) -> text` | An independent text copy of every array byte, including NUL and invalid UTF-8. | + +These raw-byte operations are interpreter-only. Native text currently requires +NUL-free values; native compilation rejects the unsupported intrinsics rather +than silently truncating or replacing bytes. `from_bytes` copies the array in +one operation and does not change when the source array is later mutated. +Use a byte array directly for binary data shared with native routes. The conversion that looks like it would do this is `nil.std.core`'s `convert.char_to_i32`, and it will not: it takes a whole @@ -85,7 +91,7 @@ isolated in order to inspect it whole, because isolating it needed the same test. Percent-encoding anything outside ASCII was unreachable because of this, and so was reading arbitrary bytes off a socket. -These two are about bytes and say so in their names. They know nothing about +These operations are about bytes and say so in their names. They know nothing about UTF-8; assembling characters from bytes is the caller's job. `from_byte(195)` is the single byte `0xC3`, where `convert.i32_to_char(195)` is diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index 5d43dc6..cf96d4a 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -633,6 +633,12 @@ say tour.billing::audit-level !!! qualified reference `public` exports; no modifier is private to the book. Book-level initialisers run in declaration order. +`read a.book as alias` loads that book and binds the alias within the reading +book; it does not require a second `read`. Qualified paragraph calls retain the +original declaration's visibility, argument checks and generic parameters in +both source and binary libraries. Different books may use the same alias for +different dependencies. + **Where a book lives.** A book is a NIL module, and the compiler finds one the same way it finds an Ny module: by looking under each `-I` include root for a path mirroring the book's name. `book oculus.window.geometry` lives at diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 93c2fd2..3cfa234 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1054,7 +1054,7 @@ is no new public API or compiler intrinsic in this fix. ### F33 — Native iteration over an array literal selects an absent iterator -**Status:** Confirmed open lowering bug. +**Status:** Fixed by typed array-expression lowering; the old open status was stale. Iterating directly over a text array literal prints its values in the VM, but native compilation names an undefined `__ritual_iter` callee. Both Ny and @@ -1063,13 +1063,18 @@ using `range`/`repeat while` works and is used by the checked-conversion fixtures. Minimal programs and the VM/native comparison are preserved under `build/convert-audit/foreach-literal` in the v1 library checkout. -**Next step:** Carry the iterable expression's resolved array type into loop -lowering, including literals and returned arrays, and qualify element widths, -text lifetimes and empty arrays across routes. +**Resolution:** The tuple-array implementation retains the iterable's checked +type and evaluates array expressions once before index-based traversal. The +November 20 audit reproduced the original text-array case successfully on the +`7419ac1` development SDK. The expanded tuple-array contract also exercises both +frontends through text/binary NIL, bundles, JIT and AOT: literal and returned +text arrays, one-time evaluation, retained text, wide integers, floating-point +elements and empty returned arrays. All 226 checks pass on that baseline SDK. +This does not add an arbitrary user-defined iterator protocol. ### F34 — Renamed module aliases survive into unresolved function calls -**Status:** Confirmed open name-resolution bug. +**Status:** Fixed in source; current qualification is recorded in the November 20 notebook. Ny `namespace words = ny.lang.text` followed by `words::substring(...)` passes source compilation but emits a call containing the alias name rather @@ -1085,9 +1090,13 @@ Fully qualified canonical and legacy module names work; the checked-text fixtures exercise those spellings. Namespace renaming is distinct from the supported built-in `ny.lang.*` to `nil.std.*` compatibility mapping. -**Next step:** Resolve renamed import/namespace owners consistently during -checking and code generation, with mixed-language source and binary-library -tests. +**Resolution:** Identifier nodes retain the exact checked function declaration +separately from their source spelling. Call checking and lowering use that +identity for direct calls, generic specialization and function values. Module +scope and local shadowing remain intact. Matrix `read module as alias` also +loads its target without requiring a redundant ordinary import. The module-alias +contract covers both frontends, source and binary libraries, declaration +visibility, argument rejection, module isolation and the standard namespace alias. ### F35 — A Matrix generic parameter can consume the next parameter @@ -1111,7 +1120,7 @@ need a separately specified grouping syntax. ### F36 — Conversion intrinsics do not preserve a custom Result owner -**Status:** Confirmed open provider-declaration validation gap. +**Status:** Incompatible nominal providers are rejected; custom Result providers remain unsupported. A user-defined `custom::Result` can be declared as the return type of a function annotated `@intrinsic("convert.try_to_i32")`. The native ABI check @@ -1122,10 +1131,14 @@ both routes. Evidence is under `build/text-core-work/review/provider-owner*`. The existing public `nil.std.core.Convert` API uses the standard Result owner and is unaffected. The new checked-i64 provider follows the same ownership -convention; this pass tests malformed structural signatures but does not add -custom enum support. **Next step:** Reject an incompatible nominal provider -owner during source/NIL validation, or explicitly support that owner throughout -construction and matching, with matching VM/native evidence. +convention. Source checking now requires the standard Result owner and exact +provider signature. Textual/binary NIL loading and native generation also +validate the owner and Result schema, including unchecked source emission. +Canonical and legacy standard namespace spellings remain accepted, alongside +the explicitly tested legacy standard Result wire forms. The conversion +intrinsic contract checks both source languages, successful/error outcomes and +rejection before existing artifacts can be overwritten. This does not add +custom enum support or native floating-point/boolean conversion support. ### F37 — Editor and application builds lacked shared project context diff --git a/nilbuild/process.hpp b/nilbuild/process.hpp index 47582b1..3d7f63a 100644 --- a/nilbuild/process.hpp +++ b/nilbuild/process.hpp @@ -201,6 +201,39 @@ class cancellation_scope { sigaction(SIGTERM, &old_term, nullptr); } }; + +namespace detail { +// Only fixed stack storage, integer operations and async-signal-safe syscalls +// are allowed here: this runs after fork and before exec. Use the original +// capture pipe because stderr redirection itself may be the failing step. +template +[[noreturn]] inline void child_setup_failed(int error_pipe, + const char (&stage)[N], + int saved_errno) noexcept { + static_assert(N <= 32, "child setup stage must remain bounded"); + char message[128]; + std::size_t length = 0; + constexpr char prefix[] = "nilbuild: child setup failed at "; + constexpr char middle[] = " (errno="; + for (std::size_t i = 0; i + 1 < sizeof(prefix); ++i) message[length++] = prefix[i]; + for (std::size_t i = 0; i + 1 < N; ++i) message[length++] = stage[i]; + for (std::size_t i = 0; i + 1 < sizeof(middle); ++i) message[length++] = middle[i]; + char digits[sizeof(unsigned) * 3]; + std::size_t count = 0; + auto number = static_cast(saved_errno); + do { digits[count++] = static_cast('0' + number % 10); number /= 10; } while (number); + while (count) message[length++] = digits[--count]; + message[length++] = ')'; + message[length++] = '\n'; + std::size_t written = 0; + for (unsigned attempt = 0; attempt != 4 && written < length; ++attempt) { + const auto result = write(error_pipe, message + written, length - written); + if (result > 0) written += static_cast(result); + else if (result != -1 || errno != EINTR) break; + } + _exit(126); +} +} // namespace detail #endif // The driver never invokes a shell. Compiler processes have bounded capture @@ -605,12 +638,14 @@ inline std::vector execute_many(const std::vector resolved_global_name; + // Exact ordinary function declaration selected by the checker. Retain the + // source spelling separately for diagnostics and editor source positions. + std::optional resolved_function_name; ast_identifier_expr(std::string n, int l = 0) : ast_expr(ast_node_kind::identifier_expr_node, l), name(std::move(n)) {} @@ -1153,6 +1159,9 @@ struct ast_assignment_expr : public ast_expr { // Member access expression (object.member) struct ast_member_access_expr : public ast_expr { + // A module-qualified function value has no runtime receiver. The checker + // retains its identifier lowering while keeping the written member span. + std::shared_ptr resolved_module_function; ast_expr_ptr object; std::string member_name; diff --git a/nilcompiler/src/checked_conversion_intrinsic.hpp b/nilcompiler/src/checked_conversion_intrinsic.hpp new file mode 100644 index 0000000..1e20e7e --- /dev/null +++ b/nilcompiler/src/checked_conversion_intrinsic.hpp @@ -0,0 +1,130 @@ +#pragma once + +#include "annotation_arguments.hpp" +#include "dynamic_type.hpp" +#include "standard_namespace.hpp" +#include +#include +#include +#include + +namespace ny::checked_conversion { + +inline std::optional payload(const std::string &provider) { + if (provider == "convert.try_to_i32") return "i32"; + if (provider == "convert.try_to_i64") return "i64"; + if (provider == "convert.try_to_f64") return "f64"; + if (provider == "convert.try_to_bool") return "bool"; + return std::nullopt; +} + +inline std::string abi_type(const std::string &type) { + return canonical_std_namespace(canonical_dynamic_type(type)); +} + +inline std::string result_type(const std::string &value) { + return "nil::std::core::Result<" + value + ",text>"; +} + +inline bool result_matches(const std::string &type, const std::string &value, + bool legacy = false) { + const auto canonical = abi_type(type); + return canonical == result_type(value) || + (legacy && canonical == "Result<" + value + ",text>"); +} + +inline std::string requirement(const std::string &provider) { + return provider + " requires the standard Result ABI (text) -> " + + result_type(*payload(provider)); +} + +inline std::optional annotation_provider(const std::string &annotation) { + if (!annotation_name_matches(annotation, "intrinsic")) return std::nullopt; + const auto begin = annotation.find('('), end = annotation.find_last_of(')'); + if (begin == std::string::npos || end == std::string::npos || end <= begin) + return std::nullopt; + const auto arguments = parse_annotation_arguments(annotation.substr(begin + 1, end - begin - 1)); + if (!arguments.error.empty() || arguments.arguments.size() != 1 || + arguments.arguments.front().name) return std::nullopt; + const auto &argument = arguments.arguments.front(); + if ((argument.kind != "text" && argument.kind != "symbol") || !payload(argument.value)) + return std::nullopt; + return argument.value; +} + +template +inline void validate_result(const Module &module, const std::string &provider, + const std::string &type) { + const auto value = *payload(provider); + if (!result_matches(type, value, true)) + throw std::runtime_error(requirement(provider) + "; unrelated nominal enums are not compatible"); + std::size_t schemas = 0; + for (const auto &definition : module.enums) { + if (abi_type(definition.name) != abi_type(type)) continue; + ++schemas; + bool ok = false, error = false; + if (definition.variants.size() == 2) { + for (const auto &variant : definition.variants) { + if (variant.name == "Ok" && abi_type(variant.associated_type) == value) ok = true; + if (variant.name == "Error" && abi_type(variant.associated_type) == "text") error = true; + } + } + if (!ok || !error) + throw std::runtime_error(requirement(provider) + "; exact Ok and Error payloads are required"); + } + if (schemas != 1) + throw std::runtime_error(requirement(provider) + "; exactly one matching Result schema is required"); +} + +// The wire format historically allowed unqualified Result and an i64 return +// operand on a matching annotated wrapper. Preserve that tested profile, but +// never infer a custom enum's identity from its shape or final name segment. +template +inline void validate_instruction(const Module &module, const Instruction &instruction, + const std::optional &declared_provider = std::nullopt, + const std::string &declared_result = "") { + const auto &args = instruction.args; + if (instruction.opname != "INTEROP_CALL" || args.size() < 2 || + args[0] != "intrinsic" || !payload(args[1])) return; + if (args.size() != 4 || args[2] != "1") + throw std::runtime_error(requirement(args[1]) + "; one argument and an explicit result type are required"); + if (abi_type(args[3]) == "i64" && declared_provider == args[1]) + validate_result(module, args[1], declared_result); + else + validate_result(module, args[1], args[3]); +} + +template +inline void validate_module(const Module &module) { + for (const auto &function : module.functions) { + std::optional declared_provider; + for (const auto &annotation : function.annotations) { + if (const auto provider = annotation_provider(annotation)) { + validate_result(module, *provider, function.return_type); + bool exact_parameter = false; + if (function.params.size() == 1) { + const auto colon = function.params[0].find(':'); + exact_parameter = colon != std::string::npos && + abi_type(function.params[0].substr(colon + 1)) == "text"; + } + // Historical wrappers took no formal arguments and prepared their + // text operand inside the body. Only their matching i64-metadata + // instruction identifies that already-tested wire compatibility form. + bool legacy_wrapper = false; + if (function.params.empty()) { + for (const auto &instruction : function.body) + if (instruction.opname == "INTEROP_CALL" && + instruction.args == std::vector{"intrinsic", *provider, "1", "i64"}) + legacy_wrapper = true; + } + if ((!exact_parameter && !legacy_wrapper) || !function.generic_params.empty()) + throw std::runtime_error(requirement(*provider) + "; incompatible wrapper parameters"); + declared_provider = provider; + } + } + for (const auto &instruction : function.body) + validate_instruction(module, instruction, declared_provider, function.return_type); + } +} + +} // namespace ny::checked_conversion diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index bde58c9..7fe2b79 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -6,6 +6,7 @@ #include "codegen.hpp" #include "array_intrinsic.hpp" #include "binding_reference.hpp" +#include "checked_conversion_intrinsic.hpp" #include "inline_asm.hpp" #include "diagnostics.hpp" #include "dynamic_type.hpp" @@ -3074,7 +3075,7 @@ class emitter { static_cast(callee); // A local function value can shadow a same-named declaration. return local_bindings.count(identifier.name) ? std::string{} - : identifier.name; + : resolved_function_name(identifier); } if (callee.kind == ast_node_kind::member_access_expr_node) { const auto &member = static_cast(callee); @@ -3624,7 +3625,7 @@ class emitter { const auto &id = static_cast(e); // Check if it's an enum unit variant size_t last_colon = id.name.rfind("::"); - if (last_colon != std::string::npos) { + if (!id.resolved_function_name && last_colon != std::string::npos) { std::string enum_name = id.name.substr(0, last_colon); if (cg_.lookup_enum_decl(enum_name)) { emit_new_variant(id.name, 0, @@ -3649,8 +3650,8 @@ class emitter { reject_escaped_local(id.name, id.line); // Check if this identifier refers to a named function used as a value // (fn-as-value, e.g. router.get("/ping", ping_handler)) - if (cg_.lookup_function_decl(id.name)) { - std::string fqn = cg_.lookup_function_fqn(id.name, current_module_); + const auto fqn = resolved_function_name(id); + if (cg_.lookup_function_decl(fqn)) { push_instr("PUSH_FN_PTR", {mangle_fully(fqn)}, id.line); break; } @@ -4437,7 +4438,8 @@ class emitter { break; } } else if (ce.callee && - ce.callee->kind == ast_node_kind::identifier_expr_node) { + ce.callee->kind == ast_node_kind::identifier_expr_node && + !static_cast(*ce.callee).resolved_function_name) { const auto &id = static_cast(*ce.callee); size_t last_colon = id.name.rfind("::"); if (last_colon != std::string::npos) { @@ -4535,7 +4537,8 @@ class emitter { const auto &id = static_cast(*ce.callee); std::string callee_name = id.name; // Check if this is a struct constructor - if (const auto *struct_decl = cg_.lookup_struct_decl(callee_name)) { + if (const auto *struct_decl = id.resolved_function_name ? nullptr + : cg_.lookup_struct_decl(callee_name)) { // Struct constructor: emit NEW_STRUCT, then SET_FIELD for each arg const auto concrete_type = struct_construction_type( e.inferred_type.value_or(callee_name), contextual_type); @@ -4620,9 +4623,10 @@ class emitter { // Handle the Result/Option constructor aliases before their arguments // are emitted, so nested constructors inherit the same payload context // as qualified variants. - if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { + if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node && + !static_cast(*ce.callee).resolved_function_name) { const auto &id = static_cast(*ce.callee); - std::string bare = cg_.lookup_function_fqn(id.name, current_module_); + std::string bare = resolved_function_name(id); const auto separator = bare.rfind("::"); if (separator != std::string::npos) bare = bare.substr(separator + 2); @@ -4648,7 +4652,7 @@ class emitter { auto call_substitutions = substitutions; if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { const auto &id = static_cast(*ce.callee); - const auto name = cg_.lookup_function_fqn(id.name, current_module_); + const auto name = resolved_function_name(id); const auto *declaration = cg_.lookup_function_decl(name); if (declaration) { call_declaration = declaration; @@ -4721,7 +4725,7 @@ class emitter { if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { const auto &id_vc = static_cast(*ce.callee); - if (const auto *vdecl = cg_.lookup_function_decl(id_vc.name)) { + if (const auto *vdecl = cg_.lookup_function_decl(resolved_function_name(id_vc))) { if (!vdecl->params.empty() && vdecl->params.back().is_variadic) { size_t fixed = vdecl->params.size() - 1; for (size_t i = 0; i < fixed && i < ce.args.size(); ++i) @@ -4750,11 +4754,7 @@ class emitter { std::string fname = ""; if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { const auto &id = static_cast(*ce.callee); - fname = id.name; - // Resolve to the fully-qualified name (handles unqualified names, - // partially-qualified names like "server_config::default" inside a - // module, and cross-module references via the suffix search). - fname = cg_.lookup_function_fqn(fname, current_module_); + fname = resolved_function_name(id); // Check if this is a call to a generic function // We need to look up the symbol to know if it's generic @@ -5591,6 +5591,11 @@ class emitter { break; } case ast_node_kind::member_access_expr_node: { + const auto &reference = static_cast(e).resolved_module_function; + if (reference) { + emit_expr(*reference, contextual_type); + break; + } const auto &ma = static_cast(e); // Check if this is an enum unit variant access: Enum::Variant (no args) @@ -5898,6 +5903,14 @@ class emitter { std::set unavailable_captures; std::size_t local_identity = 0; + std::string resolved_function_name(const ast_identifier_expr &identifier) const { + // A checked declaration identity is already absolute. Do not requalify it + // in the caller's module or choose another declaration by suffix. + if (identifier.resolved_function_name) + return *identifier.resolved_function_name; + return cg_.lookup_function_fqn(identifier.name, current_module_); + } + std::optional resolve_global_operand(const ast_identifier_expr &id) const { if (!local_bindings.count(id.name) && unavailable_captures.count(id.name)) { reject_escaped_local(id.name, id.line); @@ -5917,6 +5930,7 @@ class emitter { "recheck the source before emitting NIL"); return std::nullopt; } + if (id.resolved_function_name) return std::nullopt; return cg_.lookup_global_name(id.name, current_module_); } @@ -6565,15 +6579,16 @@ codegen::assemble_module(const ast_program &program, std::string qualified = current_module.empty() ? fn_decl.name : current_module + "::" + fn_decl.name; - // We store by simple name? No, if we qualify, lookup should use full - // name? Existing lookup_function_decl uses whatever key we put here. But - // resolution usually uses qualified name if imported. Let's store BOTH - // simple (if in current module) and qualified? Or just assume lookup uses - // qualified names by default? For now, key by fn_decl.name (simple) but - // we might overwrite. Better: key by qualified name! But caller of lookup - // might pass simple name. - function_decls_[fn_decl.name] = &fn_decl; // Legacy/Simple - function_decls_[qualified] = &fn_decl; // Qualified + // Keep the legacy simple-name alias without overwriting an actual root + // declaration: its canonical identity is already the bare name. Picking + // another module's AST here would specialize the wrong function even + // though the checker retained the correct root identity. + const auto existing = function_decls_.find(fn_decl.name); + const auto existing_module = existing == function_decls_.end() + ? declaration_modules_.end() : declaration_modules_.find(existing->second); + if (existing_module == declaration_modules_.end() || !existing_module->second.empty()) + function_decls_[fn_decl.name] = &fn_decl; + function_decls_[qualified] = &fn_decl; } // ... enums, classes ... if (decl && decl->kind == ast_node_kind::enum_decl_node) { @@ -7128,7 +7143,8 @@ codegen::assemble_module(const ast_program &program, std::string ret_type_str = "void"; if (intrinsic_name.rfind("regex.", 0) == 0 || intrinsic_name.rfind("nildata.", 0) == 0 || - intrinsic_name.rfind("ui.v1.", 0) == 0) { + intrinsic_name.rfind("ui.v1.", 0) == 0 || + intrinsic_name.rfind("webview.v1.", 0) == 0) { ret_type_str = canonical_nil_type_name(fn.return_type); } else if (is_declared_enum_type(*this, fn.return_type)) { ret_type_str = canonical_nil_type_name(fn.return_type); @@ -7620,8 +7636,9 @@ codegen::assemble_module(const ast_program &program, validate_nil_class_contract(*mod); validate_nil_parallel_contract(*mod); validate_nil_owned_contract(*mod); + checked_conversion::validate_module(*mod); } catch (const std::exception &error) { - reject_codegen_construct(0, error.what(), "use checked ownership scopes and isolated scalar parallel workers"); + reject_codegen_construct(0, error.what(), "correct the reported runtime contract before emitting NIL"); if (diags) diags->insert(diags->end(), rejected_codegen_constructs_.begin(), rejected_codegen_constructs_.end()); return nullptr; } diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 45f22a6..7cce068 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -6,7 +6,9 @@ #include "owned_contract.hpp" #include "diagnostics.hpp" #include "dynamic_type.hpp" +#include "checked_conversion_intrinsic.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "executable_context.hpp" #include "native_runtime.hpp" #include "ordinary_io_intrinsic.hpp" @@ -1525,6 +1527,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::unordered_set parallel_workers; try { parallel_workers = collect_nil_parallel_workers(mod); + checked_conversion::validate_module(mod); validate_nil_owned_contract(mod); } catch (const std::exception &error) { std::cerr << "[NativeCodegen] " << error.what() << '\n'; @@ -2955,10 +2958,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) { impl_->builder->CreateRet(value); } annotation_handled = true; - } else if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("ui.v1.", 0) == 0) { - const auto contract = ui::intrinsic(dispatch_provider); + } else if (dispatch_name == "@intrinsic" && + (dispatch_provider.rfind("ui.v1.", 0) == 0 || dispatch_provider.rfind("webview.v1.", 0) == 0)) { + const bool is_webview = dispatch_provider.rfind("webview.v1.", 0) == 0; + const auto contract = is_webview ? webview::intrinsic(dispatch_provider) : ui::intrinsic(dispatch_provider); + const std::string family = is_webview ? "WebView" : "UI"; if (!contract) { - std::cerr << "[NativeCodegen] unknown UI intrinsic '" << dispatch_provider << "'\n"; + std::cerr << "[NativeCodegen] unknown " << family << " intrinsic '" << dispatch_provider << "'\n"; return false; } std::vector parameter_types; @@ -2980,7 +2986,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { valid = valid && schemas == 1; } if (!valid) { - std::cerr << "[NativeCodegen] " << dispatch_provider << " requires the exact UI ABI " + std::cerr << "[NativeCodegen] " << dispatch_provider << " requires the exact " << family << " ABI " << ui::signature(*contract) << " and the standard Result schema\n"; return false; } @@ -3000,7 +3006,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::vector types; for (auto *argument : arguments) types.push_back(argument->getType()); auto *runtime_type = llvm::FunctionType::get(capability ? word_type : llvm::Type::getInt32Ty(ctx), types, false); - auto runtime = impl_->module->getOrInsertFunction("nyrt_ui_v1_" + contract->operation, runtime_type); + auto runtime = impl_->module->getOrInsertFunction(std::string(is_webview ? "nyrt_webview_v1_" : "nyrt_ui_v1_") + contract->operation, runtime_type); auto *status = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), arguments); if (capability) { impl_->builder->CreateRet(impl_->builder->CreateIntCast(status, impl_->current_function->getReturnType(), false)); @@ -3399,6 +3405,111 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; impl_->builder->CreateRet(error_variant); annotation_handled = true; + } else if (dispatch_name == "@intrinsic" && + dispatch_provider == "file.read_rooted_snapshot") { + const auto result_arguments = + native_generic_arguments(fn.return_type, "result"); + const auto *definition = result_arguments && result_arguments->size() == 2 + ? find_native_aggregate_definition(mod, (*result_arguments)[0]) + : nullptr; + const auto layout_it = definition ? native_struct_layouts.find(definition) + : native_struct_layouts.end(); + bool valid_schema = definition && definition->fields.size() == 3 && + compact_nil_type(definition->name) == "nil::std::io::FileSnapshot" && + layout_it != native_struct_layouts.end() && + layout_it->second.hidden_fields == 0; + const std::pair required_fields[] = { + {"content", "array"}, {"modified_ms", "i64"}, {"sha256", "text"}}; + if (valid_schema) { + for (const auto &[name, type] : required_fields) { + const auto field = layout_it->second.field_indices.find(name); + if (field == layout_it->second.field_indices.end()) { + valid_schema = false; + break; + } + const auto &actual_type = layout_it->second.field_nil_types[field->second]; + valid_schema = valid_schema && + (std::string(type) == "text" + ? native_handle_kind_for_nil_type(actual_type) == native_handle_kind::text + : normalize_nil_type(actual_type) == type); + } + } + if (!valid_schema || fn.params.size() != 3 || + native_handle_kind_for_nil_type(nil_parameter_type(fn.params[0])) != + native_handle_kind::text || + native_handle_kind_for_nil_type(nil_parameter_type(fn.params[1])) != + native_handle_kind::text || + normalize_nil_type(nil_parameter_type(fn.params[2])) != "i64" || + native_handle_kind_for_nil_type((*result_arguments)[1]) != + native_handle_kind::text || + impl_->current_function->arg_size() != 3 || + !impl_->current_function->getReturnType()->isIntegerTy(64)) { + std::cerr << "[NativeCodegen] file.read_rooted_snapshot requires " + "(text,text,i64) -> Result with the " + "exact content/modified_ms/sha256 field schema\n"; + return false; + } + auto *pointer_type = llvm::PointerType::getUnqual(ctx); + auto *word_type = llvm::Type::getInt64Ty(ctx); + auto *bytes_out = impl_->builder->CreateAlloca(pointer_type); + auto *modified_out = impl_->builder->CreateAlloca(word_type); + auto *digest_out = impl_->builder->CreateAlloca(pointer_type); + auto *error_out = impl_->builder->CreateAlloca(pointer_type); + auto *runtime_type = llvm::FunctionType::get( + llvm::Type::getInt32Ty(ctx), + {pointer_type, pointer_type, word_type, pointer_type, pointer_type, + pointer_type, pointer_type}, false); + auto runtime = impl_->module->getOrInsertFunction( + "nyrt_read_rooted_snapshot", runtime_type); + auto *status = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), + {impl_->current_function->getArg(0), impl_->current_function->getArg(1), + impl_->current_function->getArg(2), bytes_out, modified_out, + digest_out, error_out}); + auto *success = llvm::BasicBlock::Create(ctx, "snapshot.success", + impl_->current_function); + auto *failure = llvm::BasicBlock::Create(ctx, "snapshot.failure", + impl_->current_function); + impl_->builder->CreateCondBr(impl_->builder->CreateICmpNE( + status, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0)), + success, failure); + impl_->builder->SetInsertPoint(success); + const auto allocation_size = impl_->module->getDataLayout() + .getTypeAllocSize(layout_it->second.llvm_type).getFixedValue(); + llvm::Value *record = nullptr; + if (impl_->memory_mode == MemoryMode::SAFE_GC) { + auto *allocate_type = llvm::FunctionType::get(pointer_type, {word_type}, false); + auto allocate = impl_->module->getOrInsertFunction("nyrt_alloc", allocate_type); + record = impl_->builder->CreateCall(allocate_type, allocate.getCallee(), + {llvm::ConstantInt::get(word_type, allocation_size)}); + } else { + auto *allocate_type = llvm::FunctionType::get(pointer_type, {native_size_type}, false); + auto allocate = impl_->module->getOrInsertFunction("malloc", allocate_type); + record = impl_->builder->CreateCall(allocate_type, allocate.getCallee(), + {native_size_constant(allocation_size)}); + } + emit_allocation_null_check(record, "FileSnapshot"); + impl_->setNilType(record, definition->name); + llvm::Value *values[] = { + impl_->builder->CreateLoad(pointer_type, bytes_out), + impl_->builder->CreateLoad(word_type, modified_out), + impl_->builder->CreateLoad(pointer_type, digest_out)}; + for (std::size_t index = 0; index < 3; ++index) { + const auto field_index = layout_it->second.field_indices.at(required_fields[index].first); + auto *field_pointer = impl_->builder->CreateStructGEP( + layout_it->second.llvm_type, record, field_index); + impl_->builder->CreateStore(values[index], field_pointer); + } + auto *ok = emit_single_payload_variant("Result::Ok", record, + fn.return_type, definition->name); + if (!ok) return false; + impl_->builder->CreateRet(ok); + impl_->builder->SetInsertPoint(failure); + auto *error = impl_->builder->CreateLoad(pointer_type, error_out); + auto *failed = emit_single_payload_variant("Result::Error", error, + fn.return_type, "text"); + if (!failed) return false; + impl_->builder->CreateRet(failed); + annotation_handled = true; } else if (ann.find("@intrinsic(\"file.read_regular_bytes\")") != std::string::npos || ann.find("@intrinsic(file.read_regular_bytes)") != @@ -9305,6 +9416,17 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { llvm::orc::ExecutorSymbolDef(llvm::orc::ExecutorAddr::fromPtr(address), llvm::JITSymbolFlags::Exported); }; + expose_runtime_symbol("nyrt_webview_v1_configure", &nyrt_webview_v1_configure); + expose_runtime_symbol("nyrt_webview_v1_window", &nyrt_webview_v1_window); + expose_runtime_symbol("nyrt_webview_v1_show", &nyrt_webview_v1_show); + expose_runtime_symbol("nyrt_webview_v1_poll", &nyrt_webview_v1_poll); + expose_runtime_symbol("nyrt_webview_v1_release_event", &nyrt_webview_v1_release_event); + expose_runtime_symbol("nyrt_webview_v1_close", &nyrt_webview_v1_close); + expose_runtime_symbol("nyrt_webview_v1_navigate", &nyrt_webview_v1_navigate); + expose_runtime_symbol("nyrt_webview_v1_load_html", &nyrt_webview_v1_load_html); + expose_runtime_symbol("nyrt_webview_v1_evaluate_function", &nyrt_webview_v1_evaluate_function); + expose_runtime_symbol("nyrt_webview_v1_event_number", &nyrt_webview_v1_event_number); + expose_runtime_symbol("nyrt_webview_v1_event_text", &nyrt_webview_v1_event_text); expose_runtime_symbol("nyrt_ui_v1_available", &nyrt_ui_v1_available); expose_runtime_symbol("nyrt_ui_v1_window", &nyrt_ui_v1_window); expose_runtime_symbol("nyrt_ui_v1_widget", &nyrt_ui_v1_widget); @@ -9396,6 +9518,7 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_buffer_get", &nyrt_buffer_get); expose_runtime_symbol("nyrt_buffer_set", &nyrt_buffer_set); expose_runtime_symbol("nyrt_read_regular_bytes", &nyrt_read_regular_bytes); + expose_runtime_symbol("nyrt_read_rooted_snapshot", &nyrt_read_rooted_snapshot); expose_runtime_symbol("nyrt_write_bytes_atomic", &nyrt_write_bytes_atomic); expose_runtime_symbol("nyrt_io_v1", &nyrt_io_v1); expose_runtime_symbol("nyrt_try_i32", &nyrt_try_i32); diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 5ca7193..0fa1ff5 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -592,17 +592,24 @@ static std::string find_module_name(const std::shared_ptr &p, } } +static std::optional declaration_import_path(const ny::ast_decl &declaration) { + if (declaration.kind == ny::ast_node_kind::import_decl_node) + return static_cast(declaration).module_path; + if (declaration.kind == ny::ast_node_kind::namespace_alias_decl_node) { + const auto &alias = static_cast(declaration); + if (alias.imports_target) return alias.target_module; + } + return std::nullopt; +} + static std::vector collect_import_paths(const std::shared_ptr &p) { std::vector out; for (const auto &d : p->declarations) { if (!d) continue; - if (d->kind == ny::ast_node_kind::import_decl_node) { - auto id = std::dynamic_pointer_cast(d); - if (id && !id->module_path.empty()) - out.push_back(id->module_path); - } + if (const auto path = declaration_import_path(*d); path && !path->empty()) + out.push_back(*path); } return out; } @@ -1401,9 +1408,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) declared_modules.insert(static_cast(*d).name); bool unresolved = false; for (const auto &u : units) for (const auto &d : u.program->declarations) { - if (!d || d->kind != ny::ast_node_kind::import_decl_node) continue; - const auto &import = static_cast(*d); - auto target = import.module_path; + if (!d) continue; + const auto path = declaration_import_path(*d); + if (!path) continue; + auto target = *path; const auto alias = import_aliases.find(target); if (alias != import_aliases.end()) target = alias->second; if (!resolved_import_paths.count(target) && !declared_modules.count(target)) { diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 3790c11..5008c37 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -888,8 +888,9 @@ std::shared_ptr parser::parse_read() { const token &alias_token = peek(); const std::string alias = nil_symbol(advance().lexeme); skip_terminators(); - return named(std::make_shared(alias, path, false, - line), alias_token); + auto declaration = std::make_shared(alias, path, false, line); + declaration->imports_target = true; + return named(std::move(declaration), alias_token); } skip_terminators(); return std::make_shared(path, std::vector{}, @@ -3091,9 +3092,10 @@ ny::ast_expr_ptr parser::parse_primary() { expected_name("after 'the paragraph'"); return nullptr; } - const token &name_token = peek(); - return named(std::make_shared( - resolve_name(advance().lexeme), line), name_token); + // Reuse ordinary name parsing: it preserves lexical folding for bare + // names and the qualified owner plus final-name span for module aliases. + // Taking one token here silently left `::name` outside the value. + return parse_primary(); } error(peek(), "expected 'length of' or 'paragraph' after 'the'"); return nullptr; diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 8300d97..7788163 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,11 +1,13 @@ #include "native_runtime.hpp" #include "../../common/standard_streams.hpp" #include "../../common/strict_json.hpp" +#include "../../common/content_digest.hpp" #include "../../common/windows_environment.hpp" #include "ordinary_io_intrinsic.hpp" #include "dynamic_type.hpp" #include "database_runtime.hpp" #include "ui_runtime.hpp" +#include "webview_runtime.hpp" #include "integer_conversion.hpp" #include "memory_profile.hpp" #include "pattern_engine.hpp" @@ -96,6 +98,7 @@ struct runtime_context { ny::memory_profile::Session profile; ny::database::Context databases; ny::ui::Context ui; + ny::webview::Context webview; struct file { std::unique_ptr stream; bool readable = false; @@ -646,10 +649,77 @@ const char *ui_text_argument(const char *text) { if (!text) throw std::invalid_argument("ui: expected text argument"); return text; } +template +std::int32_t webview_number_result(std::int64_t *value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = 0; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + *value = result.number; + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "webview: host allocation failed"; return 0; } +} +template +std::int32_t webview_text_result(const char **value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = nullptr; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + // The snapshot may be released immediately after this call. Never return + // provider storage, even when its lifetime presently spans the caller. + *value = own_string(result.text); + if (!*value) { *error = "webview: host allocation failed"; return 0; } + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "webview: host allocation failed"; return 0; } +} +const char *webview_text_argument(const char *text) { + if (!text) throw std::invalid_argument("webview: expected text argument"); + return text; +} } // namespace extern "C" { +std::int32_t nyrt_webview_v1_configure(const char *path, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.configure(webview_text_argument(path)); }); +} +std::int32_t nyrt_webview_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.window(webview_text_argument(title), width, height); }); +} +std::int32_t nyrt_webview_v1_show(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.show(handle); }); +} +std::int32_t nyrt_webview_v1_poll(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.poll(handle); }); +} +std::int32_t nyrt_webview_v1_release_event(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.release_event(handle); }); +} +std::int32_t nyrt_webview_v1_close(std::int64_t handle, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.close(handle); }); +} +std::int32_t nyrt_webview_v1_navigate(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.navigate(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_load_html(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.load_html(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_evaluate_function(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.evaluate_function(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_event_number(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept { + return webview_number_result(value, error, [&] { return context.webview.event_number(handle, webview_text_argument(text)); }); +} +std::int32_t nyrt_webview_v1_event_text(std::int64_t handle, const char *text, const char **value, const char **error) noexcept { + return webview_text_result(value, error, [&] { return context.webview.event_text(handle, webview_text_argument(text)); }); +} + std::int64_t nyrt_ui_v1_available() noexcept { return ny::ui::available() ? 1 : 0; } std::int32_t nyrt_ui_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept { @@ -868,6 +938,7 @@ void nyrt_context_end() noexcept { nyrt_fail("NIL native runtime error: memory capture failed\n"); context.databases.clear(); context.ui.clear(); + context.webview.clear(); context.files.clear(); nyrt_owned_v1_unwind(0); context.pending_fault.reset(); @@ -890,6 +961,7 @@ void nyrt_profile_site(const char *file, const char *function, [[noreturn]] void nyrt_fail(const char *message) noexcept { context.ui.clear(); + context.webview.clear(); (void)context.profile.finish("failed", false); if (message != nullptr) std::fputs(message, stderr); @@ -1969,6 +2041,48 @@ std::int32_t nyrt_io_v1(const char *operation, std::uint64_t first, } } +std::int32_t nyrt_read_rooted_snapshot( + const char *root, const char *relative, std::int64_t maximum_bytes, + void **bytes_out, std::int64_t *modified_ms_out, const char **sha256_out, + const char **error_out) noexcept { + if (bytes_out) *bytes_out = nullptr; + if (modified_ms_out) *modified_ms_out = 0; + if (sha256_out) *sha256_out = nullptr; + if (error_out) *error_out = nullptr; + if (!root || !relative || !bytes_out || !modified_ms_out || !sha256_out || + maximum_bytes < 0 || + static_cast(maximum_bytes) > maximum_file_bytes) { + set_error(error_out, "file.read_rooted_snapshot: invalid arguments"); + return 0; + } + try { + auto loaded = ny::detail::read_rooted_file_snapshot_utf8( + root, relative, static_cast(maximum_bytes)); + if (!loaded.ok) { + set_error(error_out, loaded.error); + return 0; + } + nil::detail::sha256 hash; + hash.update(loaded.bytes.data(), loaded.bytes.size()); + const auto digest = hash.finish(); + auto *array = make_array(NYRT_ARRAY_U8, loaded.bytes.size()); + const auto *digest_text = own_string(digest); + if (!array || !digest_text) { + set_error(error_out, "file.read_rooted_snapshot: allocation failed"); + return 0; + } + if (!loaded.bytes.empty()) + std::memcpy(array->data, loaded.bytes.data(), loaded.bytes.size()); + *bytes_out = array; + *modified_ms_out = loaded.modified_ms; + *sha256_out = digest_text; + return 1; + } catch (...) { + set_error(error_out, "file.read_rooted_snapshot: host operation failed"); + return 0; + } +} + std::int32_t nyrt_read_regular_bytes(const char *path, std::int64_t maximum_bytes, void **bytes_out, diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 65f7670..4895d55 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -53,6 +53,19 @@ std::int32_t nyrt_ui_v1_destroy_widget(std::int64_t handle, std::int32_t nyrt_ui_v1_close(std::int64_t window, std::int64_t *value, const char **error) noexcept; +// Checked WebView provider bridge. All text is copied into managed storage. +std::int32_t nyrt_webview_v1_configure(const char *path, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_window(const char *title, std::int64_t width, std::int64_t height, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_show(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_poll(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_release_event(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_close(std::int64_t handle, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_navigate(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_load_html(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_evaluate_function(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_event_number(std::int64_t handle, const char *text, std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_webview_v1_event_text(std::int64_t handle, const char *text, const char **value, const char **error) noexcept; + // Additive database ABI. Success is 1, failure 0; outputs are context-owned. std::int64_t nyrt_db2_available(const char *driver) noexcept; std::int32_t nyrt_db2_open(const char *driver, const char *address, @@ -211,6 +224,12 @@ std::int32_t nyrt_read_regular_bytes(const char *path, std::int64_t maximum_bytes, void **bytes_out, const char **error_out) noexcept; +// All outputs describe the same bounded, rooted file read. The compiler owns +// the language record layout; this ABI only returns its independent fields. +std::int32_t nyrt_read_rooted_snapshot( + const char *root, const char *relative, std::int64_t maximum_bytes, + void **bytes_out, std::int64_t *modified_ms_out, const char **sha256_out, + const char **error_out) noexcept; std::int32_t nyrt_write_bytes_atomic(const char *path, const void *bytes, std::int32_t replace, const char **error_out) noexcept; diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 1a55ea2..0623633 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -3,6 +3,7 @@ #include "nil_contract.hpp" #include "binding_reference.hpp" #include "dynamic_type.hpp" +#include "checked_conversion_intrinsic.hpp" #include "array_intrinsic.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" @@ -1667,10 +1668,14 @@ static void attach_class_metadata(std::vector &program, nil_module const auto ordinal = static_cast(instruction.op); if (ordinal >= opcode_table_size) throw std::runtime_error("Invalid opcode in class program"); function->body.push_back({std::string(opcode_table[ordinal].name), instruction.args, instruction.line}); + } else if (instruction.op == Opcode::INTEROP_CALL) { + const nil_instruction call{"INTEROP_CALL", instruction.args, instruction.line}; + checked_conversion::validate_instruction(metadata, call); } else if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE) throw std::runtime_error("Class or anything instruction outside a declared function"); } + checked_conversion::validate_module(metadata); validate_nil_class_contract(metadata); // Tuple arrays also use exact record schemas at execution time, including // modules that declare no classes at all. @@ -2525,6 +2530,7 @@ std::unique_ptr parseTextNilModule(std::istream &is) { if (!pending_annotations.empty()) throw std::runtime_error( "Function annotations do not precede a function in textual NIL"); + checked_conversion::validate_module(*module); validate_global_storage_contract(*module); validate_nil_fault_contract(*module); validate_nil_class_contract(*module); @@ -3553,6 +3559,7 @@ std::unique_ptr parseBinaryNilModule(std::istream &is) { module->tests.push_back(section.string("test name")); require_section_consumed(section, "module"); } + checked_conversion::validate_module(*module); validate_global_storage_contract(*module); validate_nil_fault_contract(*module); validate_nil_class_contract(*module); diff --git a/nilcompiler/src/secure_file_io.cpp b/nilcompiler/src/secure_file_io.cpp index 076cda6..dda23a8 100644 --- a/nilcompiler/src/secure_file_io.cpp +++ b/nilcompiler/src/secure_file_io.cpp @@ -4,8 +4,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -39,6 +41,7 @@ #define NOMINMAX #endif #include +#include #endif namespace ny::detail { @@ -119,6 +122,50 @@ path_from_api_string(const std::string &path) { } } +constexpr std::uint64_t rooted_snapshot_maximum = 512ULL * 1024 * 1024; + +std::optional +rooted_directory_from_utf8(const std::string &root) { + auto path = path_from_utf8_string(root); + // A trailing separator or '/.' would make O_NOFOLLOW / OPEN_REPARSE_POINT + // inspect the directory reached through a root symlink instead of the link. + // Remove only these trailing spellings, never resolve '..' or ancestors. + while (path && (path->filename().empty() || path->filename() == ".")) { + auto parent = path->parent_path(); + if (parent.empty() || parent == *path) + break; + *path = std::move(parent); + } + return path; +} + +RootedFileSnapshot rooted_failure(const char *reason) { + return {false, {}, 0, std::string("file.read_rooted_snapshot: ") + reason}; +} + +std::optional> +rooted_components(const std::string &relative) { + if (!path_from_utf8_string(relative) || relative.front() == '/' || + relative.find('\\') != std::string::npos || + relative.find(':') != std::string::npos) + return std::nullopt; + std::vector components; + std::size_t start = 0; + for (;;) { + const auto slash = relative.find('/', start); + const std::string component = relative.substr(start, slash - start); + if (component.empty() || component == "." || component == "..") + return std::nullopt; + const auto native = path_from_utf8_string(component); + if (!native) + return std::nullopt; + components.push_back(*native); + if (slash == std::string::npos) + return components; + start = slash + 1; + } +} + } // namespace #ifndef _WIN32 @@ -240,6 +287,81 @@ BoundedFileRead read_regular_file_bounded(const std::filesystem::path &path, return {true, std::move(bytes), {}}; } +RootedFileSnapshot read_rooted_file_snapshot_utf8(const std::string &root, + const std::string &relative, + std::uint64_t maximum_bytes) { + if (maximum_bytes > rooted_snapshot_maximum) + return rooted_failure("invalid maximum_bytes"); + const auto native_root = rooted_directory_from_utf8(root); + const auto components = rooted_components(relative); + if (!native_root || !components) + return rooted_failure("invalid path"); + + const int directory_flags = O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW; + UniqueFileDescriptor directory(::open(native_root->c_str(), directory_flags)); + if (directory.get() < 0) + return rooted_failure("cannot open root directory"); + for (std::size_t index = 0; index + 1 < components->size(); ++index) { + UniqueFileDescriptor child(::openat(directory.get(), (*components)[index].c_str(), + directory_flags)); + if (child.get() < 0) + return rooted_failure("cannot open descendant directory"); + directory = std::move(child); + } + UniqueFileDescriptor input(::openat( + directory.get(), components->back().c_str(), + O_RDONLY | O_CLOEXEC | O_NONBLOCK | O_NOFOLLOW)); + if (input.get() < 0) + return rooted_failure("cannot open regular file"); + + struct stat before {}; + if (::fstat(input.get(), &before) != 0 || !S_ISREG(before.st_mode)) + return rooted_failure("input is not a regular file"); + if (before.st_size < 0 || static_cast(before.st_size) > maximum_bytes) + return rooted_failure("input exceeds maximum_bytes"); +#if defined(__APPLE__) + const auto seconds = before.st_mtimespec.tv_sec; + const auto nanos = before.st_mtimespec.tv_nsec; +#else + const auto seconds = before.st_mtim.tv_sec; + const auto nanos = before.st_mtim.tv_nsec; +#endif + if (seconds < (std::numeric_limits::min)() / 1000 || + seconds > (std::numeric_limits::max)() / 1000 || + nanos < 0 || nanos >= 1000000000) + return rooted_failure("invalid modification timestamp"); + const auto millis = static_cast(seconds) * 1000; + const auto fraction = static_cast(nanos) / 1000000; + if (millis > (std::numeric_limits::max)() - fraction) + return rooted_failure("invalid modification timestamp"); + + std::vector bytes; + try { + bytes.resize(static_cast(before.st_size)); + } catch (const std::bad_alloc &) { + return rooted_failure("cannot allocate snapshot"); + } + std::size_t offset = 0; + while (offset < bytes.size()) { + const ssize_t count = ::read(input.get(), bytes.data() + offset, bytes.size() - offset); + if (count < 0 && errno == EINTR) + continue; + if (count <= 0) + return rooted_failure("input changed or read failed"); + offset += static_cast(count); + } + char extra = 0; + ssize_t count = -1; + do { + count = ::read(input.get(), &extra, 1); + } while (count < 0 && errno == EINTR); + struct stat after {}; + if (count != 0 || ::fstat(input.get(), &after) != 0 || + !S_ISREG(after.st_mode) || !same_regular_file_snapshot(before, after)) + return rooted_failure("input changed or read failed"); + return {true, std::move(bytes), millis + fraction, {}}; +} + AtomicFileWrite write_file_atomic(const std::filesystem::path &path, const std::vector &bytes, bool replace) { @@ -470,6 +592,138 @@ BoundedFileRead read_regular_file_bounded(const std::filesystem::path &path, return {true, std::move(bytes), {}}; } +namespace { + +using RootedNtCreateFile = NTSTATUS (NTAPI *)( + PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, PLARGE_INTEGER, + ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); + +RootedNtCreateFile rooted_nt_create_file() { + static const auto function = []() -> RootedNtCreateFile { + const HMODULE module = GetModuleHandleW(L"ntdll.dll"); + const FARPROC symbol = module ? GetProcAddress(module, "NtCreateFile") : nullptr; + RootedNtCreateFile function = nullptr; + static_assert(sizeof(function) == sizeof(symbol), "Windows function pointer size"); + std::memcpy(&function, &symbol, sizeof(function)); + return function; + }(); + return function; +} + +UniqueWindowsHandle open_rooted_child(HANDLE directory, + const std::filesystem::path &component, + bool is_directory) { + const auto create = rooted_nt_create_file(); + const auto &name = component.native(); + if (!create || name.empty() || name.size() > 32767) + return UniqueWindowsHandle(); + UNICODE_STRING string {}; + string.Buffer = const_cast(name.data()); + string.Length = static_cast(name.size() * sizeof(wchar_t)); + string.MaximumLength = string.Length; + OBJECT_ATTRIBUTES attributes {}; + attributes.Length = sizeof(attributes); + attributes.RootDirectory = directory; + attributes.ObjectName = &string; + attributes.Attributes = 0x40; // OBJ_CASE_INSENSITIVE; do not inherit handles. + IO_STATUS_BLOCK io {}; + HANDLE child = INVALID_HANDLE_VALUE; + constexpr ULONG open_existing = 1; // FILE_OPEN + constexpr ULONG open_reparse = 0x00200000; // FILE_OPEN_REPARSE_POINT + constexpr ULONG synchronous = 0x20; // FILE_SYNCHRONOUS_IO_NONALERT + constexpr ULONG directory_only = 1; // FILE_DIRECTORY_FILE + constexpr ULONG non_directory_only = 0x40; // FILE_NON_DIRECTORY_FILE + const ULONG sharing = is_directory + ? FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE : FILE_SHARE_READ; + const NTSTATUS status = create( + &child, GENERIC_READ | SYNCHRONIZE, &attributes, &io, nullptr, 0, + sharing, open_existing, + open_reparse | synchronous | (is_directory ? directory_only : non_directory_only), + nullptr, 0); + if (status != 0 || io.Status != 0 || io.Information != 1 || + child == nullptr || child == INVALID_HANDLE_VALUE) { + if (child != nullptr && child != INVALID_HANDLE_VALUE) + CloseHandle(child); + return UniqueWindowsHandle(); + } + UniqueWindowsHandle held(child); + BY_HANDLE_FILE_INFORMATION information {}; + if (GetFileType(held.get()) != FILE_TYPE_DISK || + !GetFileInformationByHandle(held.get(), &information) || + (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 || + ((information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) != is_directory) + return UniqueWindowsHandle(); + return held; +} + +} // namespace + +RootedFileSnapshot read_rooted_file_snapshot_utf8(const std::string &root, + const std::string &relative, + std::uint64_t maximum_bytes) { + if (maximum_bytes > rooted_snapshot_maximum) + return rooted_failure("invalid maximum_bytes"); + const auto native_root = rooted_directory_from_utf8(root); + const auto components = rooted_components(relative); + if (!native_root || !components) + return rooted_failure("invalid path"); + UniqueWindowsHandle directory(CreateFileW( + native_root->c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr)); + BY_HANDLE_FILE_INFORMATION root_information {}; + if (directory.get() == INVALID_HANDLE_VALUE || + GetFileType(directory.get()) != FILE_TYPE_DISK || + !GetFileInformationByHandle(directory.get(), &root_information) || + (root_information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 || + (root_information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + return rooted_failure("cannot open root directory"); + for (std::size_t index = 0; index + 1 < components->size(); ++index) { + auto child = open_rooted_child(directory.get(), (*components)[index], true); + if (child.get() == INVALID_HANDLE_VALUE) + return rooted_failure("cannot open descendant directory"); + directory = std::move(child); + } + auto input = open_rooted_child(directory.get(), components->back(), false); + if (input.get() == INVALID_HANDLE_VALUE) + return rooted_failure("cannot open regular file"); + BY_HANDLE_FILE_INFORMATION before {}; + if (!GetFileInformationByHandle(input.get(), &before)) + return rooted_failure("cannot inspect regular file"); + const std::uint64_t size = (static_cast(before.nFileSizeHigh) << 32U) | + before.nFileSizeLow; + if (size > maximum_bytes) + return rooted_failure("input exceeds maximum_bytes"); + const std::uint64_t ticks = (static_cast(before.ftLastWriteTime.dwHighDateTime) << 32U) | + before.ftLastWriteTime.dwLowDateTime; + // Divide before converting: even the largest FILETIME quotient fits i64. + const std::int64_t modified = static_cast(ticks / 10000) - 11644473600000LL; + std::vector bytes; + try { + bytes.resize(static_cast(size)); + } catch (const std::bad_alloc &) { + return rooted_failure("cannot allocate snapshot"); + } + std::size_t offset = 0; + while (offset < bytes.size()) { + const DWORD requested = static_cast(std::min( + bytes.size() - offset, (std::numeric_limits::max)())); + DWORD count = 0; + if (!ReadFile(input.get(), bytes.data() + offset, requested, &count, nullptr) || + count == 0 || count > requested) + return rooted_failure("input changed or read failed"); + offset += count; + } + char extra = 0; + DWORD count = 0; + BY_HANDLE_FILE_INFORMATION after {}; + if (!ReadFile(input.get(), &extra, 1, &count, nullptr) || count != 0 || + !GetFileInformationByHandle(input.get(), &after) || + !same_regular_file_snapshot(before, after)) + return rooted_failure("input changed or read failed"); + return {true, std::move(bytes), modified, {}}; +} + AtomicFileWrite write_file_atomic(const std::filesystem::path &path, const std::vector &bytes, bool replace) { diff --git a/nilcompiler/src/secure_file_io.hpp b/nilcompiler/src/secure_file_io.hpp index 1db9bd2..52e5f33 100644 --- a/nilcompiler/src/secure_file_io.hpp +++ b/nilcompiler/src/secure_file_io.hpp @@ -14,6 +14,26 @@ struct BoundedFileRead { std::string error; }; +struct RootedFileSnapshot { + bool ok = false; + std::vector bytes; + std::int64_t modified_ms = 0; + std::string error; +}; + +// The trusted root selector is opened once. Its ancestors are outside the +// relative-path trust boundary. Every relative component is opened from the +// preceding directory handle, rejecting links/reparse points. The relative +// name is strict UTF-8, slash-separated, with no empty, dot, parent, colon or +// backslash components. Only regular files up to maximum_bytes are read; +// maximum_bytes itself cannot exceed 512 MiB. Bytes and mtime are inspected +// through the same final handle, rejecting observed changes during the read. +// This is an anchored namespace read, not a filesystem transaction: privileged +// mounts, hard links and changes after the snapshot are outside its contract. +RootedFileSnapshot read_rooted_file_snapshot_utf8(const std::string &root, + const std::string &relative, + std::uint64_t maximum_bytes); + struct AtomicFileWrite { bool ok = false; std::string error; diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 6f293a3..dad3bc2 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -6,7 +6,9 @@ #include "type_checker.hpp" #include "diagnostics.hpp" #include "dynamic_type.hpp" +#include "checked_conversion_intrinsic.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" @@ -2791,6 +2793,10 @@ void type_checker::visit(ast_program &p) { const auto &variable = static_cast(*declaration); global_declarations_.emplace(global_module.empty() ? variable.name : global_module + "::" + variable.name, &variable); + } else if (declaration->kind == ast_node_kind::function_decl_node) { + const auto &function = static_cast(*declaration); + function_declaration_names_[&function] = global_module.empty() ? function.name + : global_module + "::" + function.name; } else if (declaration->kind == ast_node_kind::import_decl_node) { global_imports_[global_module].push_back( &static_cast(*declaration)); @@ -3303,16 +3309,49 @@ void type_checker::visit(ast_function_decl &p) { current_function_return_type_ = type_void; } + for (const auto &annotation : p.annotations) { + if (!annotation.has_name("intrinsic")) continue; + const auto parsed = parse_annotation_arguments(annotation.args.value_or("")); + const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; + if (arguments.size() != 1 || arguments.front().name || + (arguments.front().kind != "text" && arguments.front().kind != "symbol")) continue; + const auto &provider = arguments.front().value; + const auto payload = checked_conversion::payload(provider); + if (!payload) continue; + bool standard_owner = false; + if (p.return_type) { + const auto parts = parse_generic_type_string(*p.return_type); + const auto *owner = resolve_pattern_type_symbol(parts.base_name); + standard_owner = owner && owner->defining_node && + owner->defining_node->kind == ast_node_kind::enum_decl_node && + canonical_std_namespace(owner->name) == "nil::std::core::Result"; + if (standard_owner && + parts.type_args.size() == 2) { + p.return_type = "nil::std::core::Result<" + parts.type_args[0] + "," + parts.type_args[1] + ">"; + current_function_return_type_ = type_info{*p.return_type, true}; + } + } + const bool ordinary = !current_class_name_ && p.generic_params.empty() && + p.params.size() == 1 && !p.params[0].is_ref && !p.params[0].is_variadic && + !p.params[0].default_value && + checked_conversion::abi_type(p.params[0].type_name.value_or("")) == "text"; + if (!standard_owner || !ordinary || !checked_conversion::result_matches(p.return_type.value_or("void"), *payload)) + add_error(p.line, checked_conversion::requirement(provider) + + "; use a module-level, non-generic function with one text parameter and import nil.std.core.result"); + } + for (const auto &annotation : p.annotations) { if (!annotation.has_name("intrinsic")) continue; const auto parsed = parse_annotation_arguments(annotation.args.value_or("")); const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; if (arguments.size() != 1 || arguments.front().name || arguments.front().kind != "text") continue; const auto &provider = arguments.front().value; - if (provider.rfind("ui.v1.", 0) != 0) continue; - const auto contract = ui::intrinsic(provider); + const bool is_webview = provider.rfind("webview.v1.", 0) == 0; + if (!is_webview && provider.rfind("ui.v1.", 0) != 0) continue; + const auto contract = is_webview ? webview::intrinsic(provider) : ui::intrinsic(provider); + const std::string family = is_webview ? "WebView" : "UI"; if (!contract) { - add_error(p.line, "Unknown UI intrinsic '" + provider + "'"); + add_error(p.line, "Unknown " + family + " intrinsic '" + provider + "'"); continue; } // Core Result may remain a short built-in name after ordinary import @@ -3334,7 +3373,7 @@ void type_checker::visit(ast_function_decl &p) { ordinary = ordinary && !parameter.is_ref && !parameter.is_variadic && !parameter.default_value; } if (!ordinary || !ui::signature_matches(*contract, parameters, p.return_type.value_or("void"))) - add_error(p.line, provider + " requires the exact UI ABI " + ui::signature(*contract) + + add_error(p.line, provider + " requires the exact " + family + " ABI " + ui::signature(*contract) + "; use a module-level, non-generic function without reference, variadic, or default parameters and import nil.std.core.result"); } @@ -4151,7 +4190,62 @@ void type_checker::visit(ast_if_stmt &s) { s.else_branch->accept(*this); } +std::shared_ptr +type_checker::module_function_reference(const ast_member_access_expr &member) const { + std::string path, root; + const std::function collect = [&](const ast_expr *expression) { + if (!expression) return false; + if (expression->kind == ast_node_kind::identifier_expr_node) { + root = path = static_cast(*expression).name; + return true; + } + if (expression->kind != ast_node_kind::member_access_expr_node) return false; + const auto &part = static_cast(*expression); + if (!collect(part.object.get())) return false; + path += "::" + part.member_name; + return true; + }; + if (!collect(member.object.get()) || symbols_.lookup_non_global(root)) return nullptr; + const auto module = current_module_.value_or(""); + // A value in the current module is a receiver even if a namespace alias + // has the same spelling. Imported globals keep their normal resolution too. + if (global_declarations_.count(module.empty() ? root : module + "::" + root)) + return nullptr; + if (const auto imported = resolve_imported_symbol(root)) { + const auto *value = symbols_.lookup(*imported); + if (value && value->kind == symbol_kind::variable_symbol) return nullptr; + } + const auto aliases = global_namespace_aliases_.find(module); + const auto prefix = root.substr(0, root.find("::")); + const bool alias = aliases != global_namespace_aliases_.end() && aliases->second.count(prefix); + const symbol *owner = symbols_.lookup(path); + if (!owner && !module.empty()) owner = symbols_.lookup(module + "::" + path); + const bool namespace_owner = owner && owner->defining_node && + owner->defining_node->kind == ast_node_kind::module_decl_node; + if (!alias && !namespace_owner) return nullptr; + path += "::" + member.member_name; + const auto *function = resolve_qualified_name(path); + if (function && (function->kind != symbol_kind::function_symbol || + !function->defining_node || + function->defining_node->kind != ast_node_kind::function_decl_node || + !function_declaration_names_.count( + static_cast(function->defining_node)))) + return nullptr; + auto reference = std::make_shared(path, member.line); + reference->source_file = member.source_file; + reference->name_span = member.name_span; + return reference; +} + void type_checker::visit(ast_member_access_expr &e) { + e.resolved_module_function.reset(); + if (auto reference = module_function_reference(e)) { + reference->accept(*this); + e.inferred_type = reference->inferred_type; + e.checked_callable_parameters = reference->checked_callable_parameters; + e.resolved_module_function = std::move(reference); + return; + } // std::cerr << "[type_checker] visit(member_access) member='" << // e.member_name << "'" << std::endl; Check if object is a type (e.g. Enum // name) @@ -5448,6 +5542,14 @@ static callable_parameter_contract callable_parameters( } void type_checker::visit(ast_call_expr &e) { + // Dotted namespace syntax is the same static call as `module::function`. + // Normalize only a proven namespace receiver, before any argument or method + // checking; lexical object receivers retain their ordinary member path. + if (e.callee && e.callee->kind == ast_node_kind::member_access_expr_node) { + if (auto reference = module_function_reference( + static_cast(*e.callee))) + e.callee = std::move(reference); + } e.checked_any_type_test.reset(); if (e.callee && e.callee->kind == ast_node_kind::identifier_expr_node && static_cast(*e.callee).name == "anything_is") { @@ -5557,7 +5659,8 @@ void type_checker::visit(ast_call_expr &e) { std::map source_substitutions; if (!e.type_args.empty() && e.callee && e.callee->kind == ast_node_kind::identifier_expr_node) { - const auto &name = static_cast(*e.callee).name; + const auto &identifier = static_cast(*e.callee); + const auto &name = identifier.resolved_function_name.value_or(identifier.name); if (const auto *function = symbols_.lookup(name)) for (std::size_t i = 0; i < function->generic_params.size() && i < e.type_args.size(); ++i) source_substitutions[function->generic_params[i].name] = e.type_args[i]; @@ -6208,13 +6311,13 @@ void type_checker::visit(ast_call_expr &e) { if (e.callee && e.callee->kind == ast_node_kind::identifier_expr_node) { auto id = std::static_pointer_cast(e.callee); const symbol *parent_type_sym = nullptr; - const symbol *s = symbols_.lookup(id->name); + const symbol *s = symbols_.lookup(id->resolved_function_name.value_or(id->name)); // The symbol table retains unqualified aliases for compatibility. Do not // let an alias owned by another module outrank the caller's own module or // its explicit imports merely because that declaration was registered // later in the combined program. - if (s && id->name.find("::") == std::string::npos && current_module_ && + if (s && !id->resolved_function_name && id->name.find("::") == std::string::npos && current_module_ && s->module && *s->module != *current_module_) s = nullptr; @@ -6243,7 +6346,7 @@ void type_checker::visit(ast_call_expr &e) { // Static Dispatch Lookup (e.g. vec::new) - Always attempt this for // qualified names, as it allows resolving struct methods even if a global // symbol (e.g. mangled or ghost) exists. - if (id->name.find("::") != std::string::npos) { + if (!id->resolved_function_name && id->name.find("::") != std::string::npos) { auto last_sep = id->name.rfind("::"); std::string type_part = id->name.substr(0, last_sep); std::string method_part = id->name.substr(last_sep + 2); @@ -7469,6 +7572,7 @@ void type_checker::visit(ast_assignment_expr &e) { void type_checker::visit(ast_identifier_expr &e) { capture_completion(e); e.resolved_global_name.reset(); + e.resolved_function_name.reset(); e.checked_callable_parameters.reset(); const auto *fault_binding = symbols_.lookup_non_global(e.name); if (fault_binding && fault_binding->defining_node && @@ -7519,6 +7623,12 @@ void type_checker::visit(ast_identifier_expr &e) { if (value.kind == symbol_kind::function_symbol && (!value.defining_node || value.defining_node->kind == ast_node_kind::function_decl_node)) { + if (value.defining_node && is_symbol_visible(&value, current_module_.value_or(""))) { + const auto found = function_declaration_names_.find( + static_cast(value.defining_node)); + if (found != function_declaration_names_.end()) + e.resolved_function_name = found->second; + } if (direct_call_callee_ != &e && std::any_of(value.params.begin(), value.params.end(), [](const ast_param ¶meter) { return parameter.is_ref; })) add_error(e.line, "Functions with reference parameters must be called directly; reference-parameter function values are unavailable"); diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 3abf93f..686eb95 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -137,6 +137,8 @@ class type_checker : public ast_node::ast_visitor { bool is_symbol_visible(const symbol *sym, const std::string &from_module) const; const symbol *resolve_qualified_name(const std::string &qualified_path) const; + std::shared_ptr + module_function_reference(const ast_member_access_expr &member) const; std::optional resolve_imported_symbol(const std::string &name) const; @@ -218,6 +220,7 @@ class type_checker : public ast_node::ast_visitor { std::map> imports_; // importer -> {local_name -> entry} std::map global_declarations_; + std::map function_declaration_names_; std::map> global_imports_; std::map> global_namespace_aliases_; std::optional resolve_source_global(const std::string &name, diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 5231c1f..22df6b6 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -10,6 +10,7 @@ #include "nil_contract.hpp" #include "dynamic_type.hpp" #include "ui_intrinsic.hpp" +#include "webview_intrinsic.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "integer_conversion.hpp" @@ -19,6 +20,7 @@ #include "time_support.hpp" #include "file_time_support.hpp" #include "../../common/windows_environment.hpp" +#include "../../common/content_digest.hpp" #include #include #include @@ -737,6 +739,7 @@ bool VM::finishMemoryProfile(const char *status, bool completed) noexcept { // This hook runs at every invocation terminal, even without profiling. // Paused debugger steps retain their UI until completion/reset. ui_.clear(); + webview_.clear(); closeOpenSockets(); if (!memory_profile_started_ || memory_profile_finished_) return true; @@ -1678,6 +1681,13 @@ void VM::executeInstruction(const Instruction &instr) { const auto *handle = std::get_if(&value); if (!handle) reject(); const auto found = heap_.find(handle->address); + // File/random byte arrays use compact byte storage instead of scalar + // Value slots. They retain the same exact array language identity. + // Do not admit raw u8 pointer allocations or any other array element. + if (found != heap_.end() && expected == "array" && + found->second.type_name == "bytes" && found->second.data.empty() && + found->second.element_count == found->second.byte_data.size()) + return; if (found == heap_.end() || found->second.type_name != "array" || "array<" + canonical_array_type(found->second.element_type) + ">" != expected) reject(); return; @@ -4411,6 +4421,37 @@ void VM::executeInstruction(const Instruction &instr) { return; } + if (fn_name == "text.from_bytes") { + if (args.size() != 1 || !std::holds_alternative(args[0])) + throw std::runtime_error("text.from_bytes: expected a live byte array"); + const auto found = heap_.find(std::get(args[0]).address); + if (found == heap_.end()) + throw std::runtime_error("text.from_bytes: expected a live byte array"); + const auto &block = found->second; + std::string result; + if (block.type_name == "bytes" && block.data.empty() && + block.element_count == block.byte_data.size()) { + if (block.byte_data.size() > max_intrinsic_file_bytes) + throw std::runtime_error("text.from_bytes: input exceeds size limit"); + result.assign(block.byte_data.begin(), block.byte_data.end()); + } else if (block.type_name == "array" && + canonical_array_scalar(block.element_type) == "u8") { + if (block.data.size() > max_intrinsic_file_bytes) + throw std::runtime_error("text.from_bytes: input exceeds size limit"); + result.reserve(block.data.size()); + for (const auto &item : block.data) { + const auto *byte = std::get_if(&item); + if (!byte || *byte < 0 || *byte > 255) + throw std::runtime_error("text.from_bytes: invalid byte element"); + result.push_back(static_cast(static_cast(*byte))); + } + } else { + throw std::runtime_error("text.from_bytes: expected a live byte array"); + } + pushStack(std::move(result)); + return; + } + if (fn_name == "text.from_byte") { std::int64_t code = -1; if (!args.empty()) { @@ -5079,6 +5120,57 @@ void VM::executeInstruction(const Instruction &instr) { pushStack(result); return; } + // Return bytes, timestamp and content identity from one anchored read. + if (fn_name == "file.read_rooted_snapshot") { + auto push_error = [&](const std::string &message) { + EnumValue result; + result.variant_name = "Result::Error"; + result.payloads.push_back(message); + pushStack(result); + }; + if (args.size() != 3 || !std::holds_alternative(args[0]) || + !std::holds_alternative(args[1]) || + !std::holds_alternative(args[2]) || + std::get(args[2]) < 0 || + static_cast(std::get(args[2])) > + max_intrinsic_file_bytes) { + push_error("file.read_rooted_snapshot: invalid arguments"); + return; + } + try { + auto loaded = detail::read_rooted_file_snapshot_utf8( + std::get(args[0]), std::get(args[1]), + static_cast(std::get(args[2]))); + if (!loaded.ok) { + push_error(loaded.error); + return; + } + nil::detail::sha256 hash; + hash.update(loaded.bytes.data(), loaded.bytes.size()); + StructValue snapshot; + snapshot.type_name = "nil::std::io::FileSnapshot"; + snapshot.fields()["modified_ms"] = loaded.modified_ms; + snapshot.string_fields()["sha256"] = hash.finish(); + HeapBlock block; + block.type_name = "bytes"; + block.element_count = loaded.bytes.size(); + block.byte_data = std::move(loaded.bytes); + const std::int64_t handle = next_ptr_; + const std::size_t storage_bytes = + std::max(block.byte_data.size(), 1U); + next_ptr_ += static_cast( + (storage_bytes + 7U) & ~std::size_t(7U)); + storeHeapBlock(handle, std::move(block)); + snapshot.array_fields()["content"] = ArrayHandle{handle}; + EnumValue result; + result.variant_name = "Result::Ok"; + result.payloads.push_back(std::move(snapshot)); + pushStack(result); + } catch (...) { + push_error("file.read_rooted_snapshot: host operation failed"); + } + return; + } // file.read_regular_bytes(path, maximum_bytes) // -> result, text> if (fn_name == "file.read_regular_bytes") { @@ -5458,6 +5550,57 @@ void VM::executeInstruction(const Instruction &instr) { return; } + if (lib_name == "intrinsic" && fn_name.rfind("webview.v1.", 0) == 0) { + const auto contract = webview::intrinsic(fn_name); + if (!contract) throw std::runtime_error("webview: unknown intrinsic '" + fn_name + "'"); + const auto declared = call_stack_.empty() ? functions_.end() + : functions_.find(call_stack_.back().fn_name); + if (declared == functions_.end() || + !webview::signature_matches(*contract, declared->second.parameter_types, + declared->second.return_type) || + instr.args.size() != 4 || webview::abi_type(instr.args[3]) != contract->return_type() || + args.size() != contract->parameters.size()) + throw std::runtime_error(fn_name + " requires the exact WebView ABI " + webview::signature(*contract)); + if (contract->output != webview::Output::capability) { + std::size_t schemas = 0; + if (class_metadata_) + for (const auto &definition : class_metadata_->enums) + if (webview::result_schema_matches(*contract, definition)) ++schemas; + if (schemas != 1) + throw std::runtime_error(fn_name + " requires the standard Result schema with exact Ok and Error payloads"); + } + for (std::size_t index = 0; index < args.size(); ++index) { + const bool valid = contract->parameters[index] == "text" + ? std::holds_alternative(args[index]) + : std::holds_alternative(args[index]); + if (!valid) throw std::runtime_error(fn_name + " argument " + + std::to_string(index + 1) + " requires " + contract->parameters[index]); + } + auto text_arg = [&](std::size_t index) -> const std::string & { + return std::get(args[index]); + }; + auto word_arg = [&](std::size_t index) { return std::get(args[index]); }; + webview::Result result; + const auto &op = contract->operation; + if (op == "configure") result = webview_.configure(text_arg(0)); + else if (op == "window") result = webview_.window(text_arg(0), word_arg(1), word_arg(2)); + else if (op == "show") result = webview_.show(word_arg(0)); + else if (op == "navigate") result = webview_.navigate(word_arg(0), text_arg(1)); + else if (op == "load_html") result = webview_.load_html(word_arg(0), text_arg(1)); + else if (op == "evaluate_function") result = webview_.evaluate_function(word_arg(0), text_arg(1)); + else if (op == "poll") result = webview_.poll(word_arg(0)); + else if (op == "event_number") result = webview_.event_number(word_arg(0), text_arg(1)); + else if (op == "event_text") result = webview_.event_text(word_arg(0), text_arg(1)); + else if (op == "release_event") result = webview_.release_event(word_arg(0)); + else if (op == "close") result = webview_.close(word_arg(0)); + EnumValue value; + value.variant_name = result ? "Result::Ok" : "Result::Error"; + if (!result) value.payloads.push_back(std::move(result.error)); + else if (contract->output == webview::Output::text) value.payloads.push_back(std::move(result.text)); + else value.payloads.push_back(result.number); + pushStack(std::move(value)); + return; + } if (lib_name == "intrinsic" && fn_name.rfind("ui.v1.", 0) == 0) { const auto contract = ui::intrinsic(fn_name); if (!contract) throw std::runtime_error("ui: unknown intrinsic '" + fn_name + "'"); diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 2f7db71..e041981 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -17,6 +17,7 @@ #include "source_debug.hpp" #include "database_runtime.hpp" #include "ui_runtime.hpp" +#include "webview_runtime.hpp" #include "memory_profile.hpp" namespace ny { @@ -561,6 +562,7 @@ class VM { // Heap management for manual memory (unsafe mode) and GC (safe mode) database::Context databases_; ui::Context ui_; + webview::Context webview_; struct HeapBlock { std::string type_name; // Logical element metadata for type_name == "array". Textual and binary diff --git a/nilcompiler/src/webview_intrinsic.hpp b/nilcompiler/src/webview_intrinsic.hpp new file mode 100644 index 0000000..744663d --- /dev/null +++ b/nilcompiler/src/webview_intrinsic.hpp @@ -0,0 +1,28 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#pragma once +#include "ui_intrinsic.hpp" + +namespace ny::webview { +using Intrinsic = ui::Intrinsic; +using Output = ui::Output; +using ui::abi_type; +using ui::signature; +using ui::signature_matches; +using ui::result_schema_matches; + +inline std::optional intrinsic(const std::string &name) { + if (name.rfind("webview.v1.", 0) != 0) return std::nullopt; + Intrinsic value; + value.operation = name.substr(11); + const auto &op = value.operation; + if (op == "configure") value.parameters = {"text"}; + else if (op == "window") value.parameters = {"text", "i64", "i64"}; + else if (op == "navigate" || op == "load_html" || op == "evaluate_function" || op == "event_number") + value.parameters = {"i64", "text"}; + else if (op == "event_text") { value.parameters = {"i64", "text"}; value.output = Output::text; } + else if (op == "show" || op == "poll" || op == "release_event" || op == "close") + value.parameters = {"i64"}; + else return std::nullopt; + return value; +} +} // namespace ny::webview diff --git a/nilcompiler/src/webview_runtime.cpp b/nilcompiler/src/webview_runtime.cpp new file mode 100644 index 0000000..5820cbe --- /dev/null +++ b/nilcompiler/src/webview_runtime.cpp @@ -0,0 +1,299 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#include "webview_runtime.hpp" +#include "../../common/webview_provider_v1.h" +#include "../../common/webview_json_v1.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif + +namespace ny::webview { +namespace { +Result failure(const std::string &message) { return {0, {}, "webview: " + message}; } +Result success(std::int64_t value = 1) { return {value, {}, {}}; } +bool valid_text(const std::string &value) { + if (value.size() > NILWV_MAX_TEXT_BYTES || value.find('\0') != std::string::npos) return false; + return nilwebview::json_v1::valid_utf8(value); +} +nilwv_text_v1 view(const std::string &value) { return {value.data(), value.size()}; } +std::atomic next_handle{1}; +std::int64_t fresh_handle() { + auto value = next_handle.load(std::memory_order_relaxed); + for (;;) { + if (value <= 0 || value == std::numeric_limits::max()) return 0; + if (next_handle.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value; + } +} +struct Library { + const nilwv_api_v1 *api; + void *module; // Intentionally never unloaded, even after a rejected handshake. +}; +// Process-lifetime registry: asynchronous engine callbacks can outlive a +// window/context. Do not let static destructor ordering unload their code. +struct Registry { std::mutex mutex; std::map libraries; }; +Registry ®istry() { static auto *value = new Registry; return *value; } +const nilwv_api_v1 *load_provider(const std::string &path) { + auto &cache = registry(); + std::lock_guard lock(cache.mutex); + auto found = cache.libraries.find(path); + if (found != cache.libraries.end()) return found->second.api; + if (cache.libraries.size() >= 16) return nullptr; + void *module = nullptr; + nilwv_get_api_v1_fn get_api = nullptr; +#ifdef _WIN32 + auto wide = std::filesystem::u8path(path).wstring(); + auto handle = LoadLibraryExW(wide.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + module = handle; + if (handle) get_api = reinterpret_cast(GetProcAddress(handle, "nilwebview_provider_v1_get_api")); +#else + module = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (module) get_api = reinterpret_cast(dlsym(module, "nilwebview_provider_v1_get_api")); +#endif + if (!module) return nullptr; + // Insert before calling foreign code so allocation/validation failure cannot + // make a loaded library eligible for an accidental later unload. + auto &entry = cache.libraries.emplace(path, Library{nullptr, module}).first->second; + const nilwv_api_v1 *api = nullptr; + try { if (get_api) api = get_api(NILWV_ABI_V1, sizeof(nilwv_api_v1)); } catch (...) { return nullptr; } + if (!api || api->abi_version != NILWV_ABI_V1 || api->size < sizeof(nilwv_api_v1) || + (api->capabilities & ~NILWV_CAP_KNOWN_MASK) || + !api->probe || !api->context_create || !api->context_destroy || + !api->window || !api->show || !api->navigate || !api->load_html || + !api->evaluate_function || !api->poll || !api->event_number || + !api->event_text || !api->release_event || !api->close) return nullptr; + entry.api = api; + return api; +} +constexpr std::array number_fields{ + "window", "kind", "sequence", "operation", "value_kind", "source_kind", "frame_kind", "failure_kind"}; +constexpr std::array text_fields{"payload_json", "source_url", "source_origin", "detail"}; +template std::size_t field_index(const Array &fields, const std::string &key) { + return static_cast(std::find(fields.begin(), fields.end(), key) - fields.begin()); +} +} // namespace + +struct Context::Impl { + const std::thread::id thread = std::this_thread::get_id(); + const nilwv_api_v1 *api = nullptr; + nilwv_context_v1 *context = nullptr; + std::string path, fault; + std::map windows; + struct Event { std::array numbers{}; std::array texts; std::size_t bytes = 0; }; + std::map events; + std::size_t event_bytes = 0; + + Result check(bool configured = true) const { + if (thread != std::this_thread::get_id()) return failure("context belongs to another thread"); + if (!fault.empty()) return failure(fault); + if (configured && (!api || !context)) return failure("configure an explicit provider first"); + return success(); + } + Result protocol() { fault = "provider contract violation; close the execution context"; return failure(fault); } + template Result call(Invoke invoke) { + nilwv_result_v1 result{}; + result.size = sizeof(result); + try { invoke(&result); } catch (...) { return protocol(); } + if (result.size != sizeof(result) || result.code > 0 || + result.text.size > NILWV_MAX_TEXT_BYTES || (!result.text.data && result.text.size)) return protocol(); + std::string text; + if (result.text.size) text.assign(result.text.data, static_cast(result.text.size)); + if (!valid_text(text)) return protocol(); + if (result.code < 0) return failure(text.empty() ? "provider reported an unspecified failure" : text); + return {result.number, std::move(text), {}}; + } + std::int64_t native_window(std::int64_t window) const { + auto item = windows.find(window); return item == windows.end() ? 0 : item->second; + } + template Result window_call(std::int64_t window, Invoke invoke, bool operation = false) { + if (auto state = check(); !state) return state; + const auto native = native_window(window); + if (!native) return failure("invalid or closed window handle"); + auto result = call([&](auto *out) { invoke(native, out); }); + if (result && (operation ? result.number <= 0 : result.number != 1)) return protocol(); + return result; + } +}; + +Context::Context() : impl_(std::make_unique()) {} +Context::~Context() { clear(); } +void Context::clear() noexcept { + if (!impl_) return; + // Context ownership cannot be transferred. A foreign-thread teardown must + // not enter a toolkit on the wrong thread; retained provider state remains + // pinned, rather than risking callbacks into freed objects. + if (impl_->thread != std::this_thread::get_id()) return; + try { if (impl_->context && impl_->api) impl_->api->context_destroy(impl_->context); } catch (...) {} + impl_->context = nullptr; impl_->api = nullptr; + impl_->windows.clear(); impl_->events.clear(); impl_->event_bytes = 0; + impl_->fault.clear(); impl_->path.clear(); +} +Result Context::configure(const std::string &path) { + if (auto state = impl_->check(false); !state) return state; + if (!valid_text(path) || path.empty() || !std::filesystem::u8path(path).is_absolute()) + return failure("provider path must be absolute UTF-8 without NUL"); + if (impl_->context) + return path == impl_->path ? success(static_cast(impl_->api->capabilities)) + : failure("this execution already selected a provider"); + const auto *api = load_provider(path); + if (!api) return failure("provider could not be loaded or has an incompatible ABI"); + auto probe = impl_->call([&](auto *out) { api->probe(out); }); + if (!probe) return probe; + if (probe.number != 1) return impl_->protocol(); + nilwv_context_v1 *context = nullptr; + auto created = impl_->call([&](auto *out) { api->context_create(&context, out); }); + if (!created || !context || created.number != 1) { + try { if (context) api->context_destroy(context); } catch (...) {} + return !created ? created : impl_->protocol(); + } + impl_->api = api; impl_->context = context; impl_->path = path; + return success(static_cast(api->capabilities)); +} +Result Context::window(const std::string &title, std::int64_t width, std::int64_t height) { + if (auto state = impl_->check(); !state) return state; + if (!valid_text(title) || width < 1 || width > 16384 || height < 1 || height > 16384) + return failure("window requires valid text and dimensions from 1 to 16384"); + if (impl_->windows.size() >= NILWV_MAX_WINDOWS) return failure("window limit reached"); + auto result = impl_->call([&](auto *out) { impl_->api->window(impl_->context, view(title), width, height, out); }); + if (!result) return result; + if (result.number <= 0 || std::any_of(impl_->windows.begin(), impl_->windows.end(), + [&](const auto &entry) { return entry.second == result.number; })) return impl_->protocol(); + const auto handle = fresh_handle(); + if (!handle) { impl_->call([&](auto *out) { impl_->api->close(impl_->context, result.number, out); }); return failure("handle space exhausted"); } + try { impl_->windows.emplace(handle, result.number); } + catch (...) { impl_->call([&](auto *out) { impl_->api->close(impl_->context, result.number, out); }); throw; } + return success(handle); +} +Result Context::show(std::int64_t window) { + return impl_->window_call(window, [&](auto native, auto *out) { impl_->api->show(impl_->context, native, out); }); +} +#define NILWV_TEXT_OPERATION(name) \ +Result Context::name(std::int64_t window, const std::string &text) { \ + if (!valid_text(text)) return failure("text must be UTF-8 without NUL, at most 1048576 bytes"); \ + return impl_->window_call(window, [&](auto native, auto *out) { impl_->api->name(impl_->context, native, view(text), out); }, true); \ +} +NILWV_TEXT_OPERATION(navigate) +NILWV_TEXT_OPERATION(load_html) +NILWV_TEXT_OPERATION(evaluate_function) +#undef NILWV_TEXT_OPERATION + +Result Context::poll(std::int64_t window) { + if (auto state = impl_->check(); !state) return state; + const auto native = impl_->native_window(window); + if (!native) return failure("invalid or closed window handle"); + if (impl_->events.size() >= NILWV_MAX_EVENTS) return failure("release retained event snapshots before polling"); + auto polled = impl_->call([&](auto *out) { impl_->api->poll(impl_->context, native, out); }); + if (!polled || polled.number == 0) return polled; + if (polled.number < 0) return impl_->protocol(); + struct Release { + Impl *state; std::int64_t handle; bool active = true; + Result run() { active = false; return state->call([&](auto *out) { state->api->release_event(state->context, handle, out); }); } + ~Release() { if (active) { try { run(); } catch (...) {} } } + } release{impl_.get(), polled.number}; + Impl::Event event; + for (std::size_t i = 0; i < number_fields.size(); ++i) { + const std::string key = number_fields[i]; + auto field = impl_->call([&](auto *out) { impl_->api->event_number(impl_->context, polled.number, view(key), out); }); + if (!field) return field; + event.numbers[i] = field.number; + } + for (std::size_t i = 0; i < text_fields.size(); ++i) { + const std::string key = text_fields[i]; + auto field = impl_->call([&](auto *out) { impl_->api->event_text(impl_->context, polled.number, view(key), out); }); + if (!field) return field; + event.bytes += field.text.size(); event.texts[i] = std::move(field.text); + } + const auto &n = event.numbers; + if (n[0] != native || n[1] < NILWV_EVENT_READY || n[1] > NILWV_EVENT_PROVIDER_FAILED || + n[2] <= 0 || n[3] < 0 || n[4] < 0 || n[4] > NILWV_VALUE_UNDEFINED || + n[5] < 0 || n[5] > NILWV_SOURCE_NATIVE_ORIGIN || n[6] < 0 || n[6] > NILWV_FRAME_CHILD || + n[7] < 0 || n[7] > NILWV_FAILURE_CANCELLED) return impl_->protocol(); + const auto caps = impl_->api->capabilities; + if ((n[5] == NILWV_SOURCE_UNKNOWN && (!event.texts[1].empty() || !event.texts[2].empty())) || + (n[5] == NILWV_SOURCE_NATIVE_URL && (event.texts[1].empty() || !event.texts[2].empty() || !(caps & NILWV_CAP_MESSAGE_URL))) || + (n[5] == NILWV_SOURCE_NATIVE_ORIGIN && (event.texts[2].empty() || !(caps & NILWV_CAP_MESSAGE_ORIGIN))) || + (!event.texts[1].empty() && !(caps & NILWV_CAP_MESSAGE_URL)) || + (!event.texts[2].empty() && !(caps & NILWV_CAP_MESSAGE_ORIGIN)) || + (n[6] != NILWV_FRAME_UNKNOWN && !(caps & NILWV_CAP_MESSAGE_FRAME))) return impl_->protocol(); + if (n[4] == NILWV_VALUE_JSON) { + if (!nilwebview::json_v1::valid_json(event.texts[0])) return impl_->protocol(); + } else if (!event.texts[0].empty()) return impl_->protocol(); + const auto kind = n[1]; + const bool completion = kind >= NILWV_EVENT_NAVIGATION_COMPLETED && kind <= NILWV_EVENT_SCRIPT_FAILED; + const bool failed = kind == NILWV_EVENT_INITIALIZATION_FAILED || kind == NILWV_EVENT_NAVIGATION_FAILED || + kind == NILWV_EVENT_SCRIPT_FAILED || kind == NILWV_EVENT_PROVIDER_FAILED; + if ((completion ? n[3] <= 0 : n[3] != 0) || (failed ? n[7] == 0 : n[7] != 0) || + (kind != NILWV_EVENT_PAGE_MESSAGE && (n[5] != NILWV_SOURCE_UNKNOWN || n[6] != NILWV_FRAME_UNKNOWN))) + return impl_->protocol(); + if (kind == NILWV_EVENT_PAGE_MESSAGE || kind == NILWV_EVENT_NAVIGATION_COMPLETED || kind == NILWV_EVENT_NAVIGATION_REQUESTED) { + if (n[4] != NILWV_VALUE_JSON) return impl_->protocol(); + } else if (kind == NILWV_EVENT_SCRIPT_COMPLETED) { + if (n[4] != NILWV_VALUE_JSON && n[4] != NILWV_VALUE_UNDEFINED) return impl_->protocol(); + } else if (kind == NILWV_EVENT_NAVIGATION_FAILED) { + if (n[4] == NILWV_VALUE_UNDEFINED) return impl_->protocol(); + } else if (n[4] != NILWV_VALUE_NONE) return impl_->protocol(); + if ((kind == NILWV_EVENT_NAVIGATION_COMPLETED || kind == NILWV_EVENT_NAVIGATION_REQUESTED || + kind == NILWV_EVENT_NAVIGATION_FAILED) && n[4] == NILWV_VALUE_JSON) { + const auto first = event.texts[0].find_first_not_of(" \t\n\r"); + if (first == std::string::npos || event.texts[0][first] != '"') return impl_->protocol(); + } + auto released = release.run(); + if (!released || released.number != 1) return impl_->protocol(); + if (event.bytes > NILWV_MAX_QUEUED_BYTES - impl_->event_bytes) { + impl_->fault = "retained event byte limit exceeded; close the execution context"; + return failure(impl_->fault); + } + event.numbers[0] = window; + const auto handle = fresh_handle(); + if (!handle) return failure("handle space exhausted"); + const auto bytes = event.bytes; + impl_->events.emplace(handle, std::move(event)); impl_->event_bytes += bytes; + return success(handle); +} +Result Context::event_number(std::int64_t snapshot, const std::string &field) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + const auto index = field_index(number_fields, field); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + if (index == number_fields.size()) return failure("unknown numeric event field"); + return success(event->second.numbers[index]); +} +Result Context::event_text(std::int64_t snapshot, const std::string &field) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + const auto index = field_index(text_fields, field); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + if (index == text_fields.size()) return failure("unknown text event field"); + return {0, event->second.texts[index], {}}; +} +Result Context::release_event(std::int64_t snapshot) { + if (auto state = impl_->check(); !state) return state; + const auto event = impl_->events.find(snapshot); + if (event == impl_->events.end()) return failure("invalid or released event handle"); + impl_->event_bytes -= event->second.bytes; impl_->events.erase(event); + return success(); +} +Result Context::close(std::int64_t window) { + auto result = impl_->window_call(window, [&](auto native, auto *out) { impl_->api->close(impl_->context, native, out); }); + if (!result) return result; + impl_->windows.erase(window); + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (it->second.numbers[0] == window) { impl_->event_bytes -= it->second.bytes; it = impl_->events.erase(it); } + else ++it; + } + return success(); +} +} // namespace ny::webview diff --git a/nilcompiler/src/webview_runtime.hpp b/nilcompiler/src/webview_runtime.hpp new file mode 100644 index 0000000..67d661a --- /dev/null +++ b/nilcompiler/src/webview_runtime.hpp @@ -0,0 +1,40 @@ +/* Copyright (C) 2026 Execute Software. SPDX-License-Identifier: MIT */ +#pragma once +#include +#include +#include + +namespace ny::webview { +struct Result { + std::int64_t number = 0; + std::string text, error; + explicit operator bool() const noexcept { return error.empty(); } +}; + +// Each execution owns a context on the UI thread. The explicit absolute path +// selects trusted native code; the loader is not a sandbox for untrusted DLLs. +// Loaded libraries stay pinned for process lifetime, including late browser +// callbacks. Context handles and copied events never expose native addresses. +class Context { +public: + Context(); + ~Context(); + Context(const Context &) = delete; + Context &operator=(const Context &) = delete; + void clear() noexcept; + Result configure(const std::string &absolute_provider_path); + Result window(const std::string &title, std::int64_t width, std::int64_t height); + Result show(std::int64_t window); + Result navigate(std::int64_t window, const std::string &url); + Result load_html(std::int64_t window, const std::string &html); + Result evaluate_function(std::int64_t window, const std::string &body); + Result poll(std::int64_t window); + Result event_number(std::int64_t snapshot, const std::string &field); + Result event_text(std::int64_t snapshot, const std::string &field); + Result release_event(std::int64_t snapshot); + Result close(std::int64_t window); +private: + struct Impl; + std::unique_ptr impl_; +}; +} // namespace ny::webview diff --git a/nilstd/README.md b/nilstd/README.md index 581173b..ee65ce1 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -24,10 +24,10 @@ are first-party packages rather than standard-library modules and live in ## Current status -The active tree contains 80 sources (68 Ny and 12 Matrix) organized into 18 +The active tree contains 84 sources (72 Ny and 12 Matrix) organized into 19 logical SDK modules: `prelude` plus `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, -`io`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `testing`, `text`, +`io`, `markup`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `testing`, `text`, `threading`, and `ui`. The SDK packaging gate compiles every logical module with normal type checking, emits a NIL library (v2, or v4 when carrying classes), and fails atomically rather than publishing a partial set. Matrix sources retain their @@ -46,7 +46,7 @@ below. | Area | Files | Status | | --- | ---: | --- | -| `src/` | 68 Ny files, 12 Matrix files | Eighteen logical SDK modules. Matrix contributes checked arrays/text spans, sorting, reflection values, vector helpers, random generators, testing helpers and the desktop UI library, consumed from both frontends. | +| `src/` | 72 Ny files, 12 Matrix files | Nineteen logical SDK modules. Matrix contributes checked arrays/text spans, sorting, reflection values, vector helpers, random generators, testing helpers and the desktop UI library, consumed from both frontends. | | `experimental/` | 65 Ny files | Design sources excluded from `nilstd`/`nillib` because language semantics, executable providers, or behavioral evidence are incomplete. | | `tests/` | 8 Ny files | Preserved design-era tests; these are still separate from the registered route fixtures under the repository-level `tests/` tree. | | `native/` | 14 C/C++ files | Preserved platform/provider shims; source presence alone is neither a build, shipment, nor native-support claim. | @@ -55,11 +55,16 @@ below. `nil.std.testing` supplies checks and checked value extraction with co-located niltest cases. `nil.std.ui` supplies typed windows, layouts, controls, events and -model synchronization through the optional GTK 4 provider on Linux and the -Windows development target. See the +model synchronization through GTK 4 on Linux, Win32 on Windows and AppKit on +macOS. See the [testing guide](../docs/tools/testing.md) and [UI reference](../docs/standard-library/ui.md) for execution evidence and current scope. +`nil.std.markup` provides serialized documents, composition and context-specific +escaping for checked markup blocks in Ny and Matrix. See the +[markup contract](../docs/standard-library/markup.md) for supported HTML contexts +and the explicit trusted `raw` bypass. + `nil.std.nildata` replaces NyData with versioned data blocks, one array kind, exact numeric tokens and checked JSON interchange. The compiler conversions and VM/native library share one engine. Legacy imports are explicit. See the diff --git a/nilstd/src/io/file.ny b/nilstd/src/io/file.ny index c105827..dcc70a8 100644 --- a/nilstd/src/io/file.ny +++ b/nilstd/src/io/file.ny @@ -36,6 +36,28 @@ pub fn read_bytes(path: text) -> Result, text> @intrinsic("file.read_regular_bytes") pub fn read_regular_bytes(path: text, maximum_bytes: i64) -> Result, text> +# The exact bytes read, their descriptor-observed modification time in Unix +# milliseconds, and lowercase SHA-256 of those returned bytes. Binary content +# remains an array on every execution route; no text encoding is assumed. +pub struct FileSnapshot + content: array + modified_ms: i64 + sha256: text +end struct + +# Read a bounded regular file below a trusted root directory. The relative +# path uses strict UTF-8 slash-separated components; empty, dot, dot-dot, +# absolute, backslash, colon and NUL spellings are rejected. Every descendant +# component is opened relative to an already-open directory without following +# symlinks or Windows reparse points. The final handle supplies the bytes and +# metadata, with observed changes checked before returning. maximum_bytes is +# 0..512 MiB; zero admits an empty file. Errors contain no caller path values. +# This is a directory-handle containment boundary, not protection against +# privileged mount changes, hard links placed in the root, or all concurrent +# writes. sha256 always describes content, rather than a size/timestamp key. +@intrinsic("file.read_rooted_snapshot") +pub fn read_rooted_snapshot(root: text, relative: text, maximum_bytes: i64) -> Result + # Write text to a file (creates or overwrites) @intrinsic("file.write_text") pub fn write_text(path: text, content: text) -> Result diff --git a/nilstd/src/text/string_utils.ny b/nilstd/src/text/string_utils.ny index 7c59ee5..8275de7 100644 --- a/nilstd/src/text/string_utils.ny +++ b/nilstd/src/text/string_utils.ny @@ -800,7 +800,7 @@ end fn # outside ASCII was unreachable because of this, and so was reading the bytes # off a socket. # -# These two are about bytes and say so in their names. They know nothing about +# These operations are about bytes and say so in their names. They know nothing about # UTF-8; assembling characters from bytes is the caller's job, and now it is a # job that can be done. @@ -821,3 +821,11 @@ pub fn byte_at(s: text, index: i64) -> i64 # A code outside 0..255 gives empty text. @intrinsic("text.from_byte") pub fn from_byte(code: i64) -> text + +# Copy a byte array into interpreter text in one operation. Every byte is +# preserved, including NUL and invalid UTF-8; no decoding or normalization is +# performed, and later array mutation does not change the returned text. +# Interpreter-only, like byte_at/from_byte: native text currently requires +# NUL-free values, so native compilation rejects this intrinsic explicitly. +@intrinsic("text.from_bytes") +pub fn from_bytes(data: array) -> text diff --git a/notebook/2026-11-12-matrix-webview.md b/notebook/2026-11-12-matrix-webview.md new file mode 100644 index 0000000..f57f079 --- /dev/null +++ b/notebook/2026-11-12-matrix-webview.md @@ -0,0 +1,93 @@ +# Matrix WebView provider boundary — 2026-11-12 + +## Status and question + +The archived Ny WebView project has been left untouched. Its modern replacement +is being built as `exec-nil-framework-webview`, with Matrix-facing library code +and separate WebView2, GTK4/WebKitGTK 6 and AppKit/WKWebView providers. Actual +browser qualification remains separate from the framework bridge tests below. + +The question is how a Matrix application can observe a browser's asynchronous +work consistently through interpreted NIL and LLVM AOT/JIT, without reviving the +old unchecked generic interop layer. + +## Decision + +The versioned `webview.v1.*` intrinsic family uses the standard nominal +`Result` and `Result` schemas. The frontend, loaded-NIL +interpreter and native backend each validate the declarations. A provider is +selected by an explicit absolute path to a trusted native library. The C ABI +contains fixed-width fields and borrowed text views; no toolkit object, callback +into Matrix, allocator or C++ container crosses it. Loaded modules remain pinned +for process lifetime because engine callbacks may outlive a closed window. + +Each execution owns its context on the UI thread. Runtime window and event +handles are process-unique and checked against that context. A poll copies all +event fields before releasing the provider's snapshot, including on malformed +output. Closing a window invalidates its retained runtime snapshots. Independent +contexts remain unaffected. Neither browser state nor these external handles is +part of the interpreter's pure same-process checkpoint profile. + +Creation yields a pending window and an eventual Ready or InitializationFailed +event. Navigation and synchronous function evaluation yield operation identities +with explicit completion or failure. Only one such operation is pending per +window; deadlines make a timed-out window unusable until closed and recreated. +Cancelling a request does not claim that executing JavaScript was forcibly stopped. + +The initial common navigation profile authorizes one URL request. Redirects and +page-initiated navigation are reported for explicit application approval instead +of being followed automatically. This avoids making different promises on macOS +15, whose public navigation-action API does not identify HTTP redirects the way +the other engines do. Popups, downloads and native host commands are outside this +profile. The migration document tracks legacy features separately rather than +advertising unimplemented cross-platform aliases. + +## Message and JSON identity + +A message's sender metadata must come from the native engine or remain Unknown. +WebKitGTK 6's public message callback does not expose authenticated sender frame +metadata. A JavaScript field or the browser's current URL cannot fill that gap. +Capability bits distinguish browser-reported URLs, security origins and frames. +An event cannot claim metadata that its provider did not advertise. + +Script results retain JSON.stringify's serialized text, with distinct Undefined, +script exception, serialization failure and unsupported Promise/thenable cases. +An independent review caught a real boundary mismatch: the framework's strict +configuration JSON parser rejected escaped lone surrogates and nesting levels +accepted by the provider. Both sides now use byte-identical WebView JSON grammar +headers: bounded UTF-8 JSON text, depth 64, no decoding of escaped UTF-16 units. +This preserves a legitimate `JSON.stringify` result without turning it into an +invalid UTF-8 scalar string. Depth 65 is rejected explicitly. + +For future AI tooling, operation identity and copied events provide an observable +boundary for browser actions. They do not grant page messages authority to invoke +host operations, and they do not automatically log page content or credentials. + +## Evidence and next qualification + +- 57 framework host checks cover provider ABI rejection, context/thread and + handle ownership, event release, provenance combinations and JSON boundaries. +- 28 intrinsic contract checks cover malformed declarations, disabled source + checking, typed failures and execution routes; the existing 40-check UI + intrinsic contract also passes after sharing native lowering code. +- The Matrix consumer contract passed text NIL, binary NIL, LLVM AOT and JIT + using a synthetic provider, including records retained after event/window + teardown. This is interface proof, not browser proof. +- The initial shared provider logic passed 196 native controls with sanitizers + and 36 checks of the generated JavaScript transport. Browser qualification + was a separate follow-up to this initial synthetic-provider evidence. + +### Browser qualification follow-up — 2026-11-13 + +The public [WebView qualification PR](https://github.com/exec-software/exec-nil-framework-webview/pull/1) +now passes on Linux, Windows, Intel macOS and Apple Silicon macOS at +`63d3e49d953179c81231402cf07dc7d6dbe17939`, using framework +`e7bc2a00e6854084b7b5084e29fa50456cbe8977`. Each host runs all 17 browser +behavior groups through text NIL, binary NIL, AOT and JIT, alongside four +synthetic-provider routes, 209 shared controls and 36 JavaScript checks. +The [platform notes](https://github.com/exec-software/exec-nil-framework-webview/blob/63d3e49d953179c81231402cf07dc7d6dbe17939/docs/platform-support.md) +describe the engine-version evidence, request counts, cleanup checks, source +seals and limits of the implemented profile. This qualifies the initial API profile; +it does not claim that every archived WebView feature has been ported. + +No accepted SDK, installer or release deployment is changed by this work. diff --git a/notebook/2026-11-12-web-server-boundaries.md b/notebook/2026-11-12-web-server-boundaries.md new file mode 100644 index 0000000..51475ad --- /dev/null +++ b/notebook/2026-11-12-web-server-boundaries.md @@ -0,0 +1,95 @@ +# Web server boundaries — 2026-11-12 + +## Status and question + +Implemented in framework `93515c3d4c2b6e0e7c3b870eb283fce26392d613` +([PR 39](https://github.com/exec-software/exec-nil-framework/pull/39)) and the +[web server PR](https://github.com/exec-software/exec-nil-framework-web/pull/1). +The application exposed gaps that isolated language examples did not: request +boundaries, file identity, filesystem containment and binary-value storage. + +The question was how to keep protocol policy in Matrix while giving it one +reliable filesystem observation on Linux, Windows and both macOS architectures. + +## Decision + +`read_rooted_snapshot(root, relative, maximum_bytes)` returns a typed +`FileSnapshot`: byte-array content, same-handle modification time and SHA-256 of +those exact bytes. It opens each descendant relative to an already-open +directory and rejects symlinks or Windows reparse points. Root spellings ending +in a separator or `/.` cannot disguise a final root link. Ancestors of the +trusted root, hard links and privileged mount changes remain outside this +boundary; the API is not a filesystem sandbox. + +Matrix retains HTTP framing, precondition ordering, range decisions and response +construction. A native content digest and one bulk byte-to-text copy avoid a +per-byte interpreter loop on every request. The pure Matrix SHA-256 code remains +a reference checked against independent vectors. The observed local 1 MiB +loopback response took about 10 ms; this is a measurement, not a service SLA. + +Raw `text.from_bytes` is explicitly interpreter-only until native text can +represent embedded NUL. The snapshot itself remains binary-safe on native +routes because its content is an array. Native compilation rejects unsupported +raw-text conversion instead of truncating data or silently changing its type. + +The work also corrected compact byte-array validation inside boxed records. +Exact `array` values from file operations are valid storage; raw pointer +allocations do not become arrays merely because their bytes look compatible. +Forced-GC and function-return controls verify that a boxed snapshot retains its +content and digest on the supported execution routes. + +## Evidence + +- Linux: 87 host filesystem checks; five focused CTest contracts, including + existing UTF-8, dynamic-value and native-runtime regressions. +- The rooted-file language contract checks textual and binary NIL, LLVM JIT + and AOT before and after an equal-size edit with its timestamp restored: + eight positive observations, four wrong-type extraction refusals, two raw + byte-text interpreter cases and six native declaration/provider refusals. +- [Four-host runtime run 43158309597](https://github.com/exec-software/exec-nil-framework/actions/runs/43158309597) + passed the exact eight-contract inventory on Linux, Windows, Intel macOS + and Apple Silicon macOS. These jobs use LLVM OFF; they are not native-route + or installed-SDK qualification. +- A fresh Windows LLVM build of `93515c3` passed 90 host checks and the + complete AOT/JIT snapshot contract. Existing checkouts and accepted SDKs + remained unchanged. Both macOS application/editor jobs also passed; the new + native snapshot contract is qualified separately on both Mac architectures. +- The web platform campaign requires 1,128 unit checks, 38 real-wire checks + including the actual first-byte deadline, and 15 static HTTP checks. Its + Windows run exposed CRLF checkout conversion of a byte-exact CSS fixture. + `.gitattributes` now requires LF text rather than weakening length or digest + expectations. The original failure remains in the CI record. A second run + found a test-oracle gap: Winsock reports deadline closure as error 10053. + The corrected oracle accepts that exact Windows closure, observes readiness + continuously, and rejects early disconnects outside the 19–25 second window. + Sixteen synthetic controls and 76 actual Windows wire checks passed across + two library locations, with closure observed at 20.004 and 20.027 seconds. +- Owned-process timeout controls passed on Linux and Windows, including a real + listening Matrix child, nested Windows Jobs and failed Job assignment before + command release. Test cleanup is part of the pass condition. + +The test implementations live in `tests/rooted_file_snapshot_tests.cpp` and +`tests/tools/rooted_file_snapshot_contract.py`; web consumer tests live in its +own repository. No accepted SDK or release deployment is replaced by this work. + +## Follow-up + +Native snapshot qualification passed on both Mac architectures in +[run 43162404951](https://github.com/exec-software/exec-nil-framework/actions/runs/43162404951), +with the exact 87 host and 8/4/2/6 language-route inventories against fixed +source `93515c3`. The corrected [web run 43162279298](https://github.com/exec-software/exec-nil-framework-web/actions/runs/43162279298) +passed all four hosts at web head `4bcb43f`: 1,128 unit, 16 oracle, 38 wire +and 15 static checks each. The four `web-*` checks now join `secrets` as +required checks; review and the other existing branch protections are unchanged. + +The next project is a clean Matrix WebView package. The archived implementation +has no macOS provider and advertises some Linux-only functions through a shared +wrapper. Its replacement needs a checked provider ABI, bounded event queues and +observable asynchronous completion; generic legacy FFI and provider hot reload +do not establish those guarantees. Browser-origin provenance must come from +native evidence or be marked unavailable, never inferred from a page message. + +For future AI diagnostics, content identities can correlate a file observation +with an action without duplicating its bytes. This is a proposed use, not an +automatic logging or executable-context feature; fingerprints can themselves +be sensitive and need the same deliberate disclosure policy as other context. diff --git a/notebook/2026-11-13-formatted-markup-handoff.md b/notebook/2026-11-13-formatted-markup-handoff.md index 4c03141..3f39acc 100644 --- a/notebook/2026-11-13-formatted-markup-handoff.md +++ b/notebook/2026-11-13-formatted-markup-handoff.md @@ -108,8 +108,55 @@ No accepted SDK, installer or Lich release is changed. The [Matrix WebView repository](https://github.com/exec-software/exec-nil-framework-webview) is now public, with source secret/path audits, four required platform checks and an independent review requirement matching the web server repository. -Linux and both Mac architectures have passed real browser consumers through -text/binary NIL, AOT and JIT. Windows has passed compilation, shared/framework -contracts and synthetic routes; its real browser initialization correction is -being qualified. The repository's platform notes record exact source evidence. +Its [qualification PR](https://github.com/exec-software/exec-nil-framework-webview/pull/1) +tracks provider startup, navigation and teardown across textual/binary NIL, +AOT and JIT, with exact source evidence in the repository's platform notes. This follows the language handoff without activating an accepted SDK. + +## Current framework integration + +The language handoff was merged in +[PR 38](https://github.com/exec-software/exec-nil-framework/pull/38). +[PR 41](https://github.com/exec-software/exec-nil-framework/pull/41) now combines +the reviewed rooted-file snapshot and WebView runtime/Matrix bridge branches +with current master, preserving its freestanding text-comparison correction. +Ordinary merges retain the existing review history. + +The combined checks select twelve interpreter contracts on all four hosts, +twelve native and ten language contracts on both Macs, plus debugger, project, +packaging, incremental-build and actual editor-host checks. These are +current-source CI checks; they do not replace an accepted SDK or promote a +release. The PR records the final tested revision and campaign results. + +Integration exposed a Mach-O test call that omitted its selected symbol reader; +both direct calls now pass through the existing configured helper. Two Intel +first-project builds later exceeded their unchanged 180-second limit. The next +diagnostic revision passed that stage; the cause of those earlier timeouts is +not established. Timeout reporting now retains bounded child output and uploads +project failure evidence before the remaining application checks. + +An Apple Silicon run separately returned child-setup status 126 during the +incremental fixture. The launcher now identifies the failed setup syscall and +saved errno, preserving the original status and cancellation behavior; fixture +failures retain bounded event counts without source contents. The earlier +failure did not identify a syscall, so it cannot yet be assigned a cause. +The editor tuple-definition fixture also now waits for an absent asynchronous +result, while rejecting provider errors, document changes and incorrect +destinations immediately. Neither change increases a deadline or relaxes a +result assertion. Retained failures remain part of the qualification record. + +## Separate editor dependency follow-up + +GitHub's existing [Dependabot alert 9](https://github.com/exec-software/exec-nil-framework/security/dependabot/9) +reports minimatch 10.2.6 in the editor lockfile. The +[upstream advisory](https://github.com/isaacs/minimatch/security/advisories/GHSA-g3hv-75wg-m249) +describes a moderate glob-pattern denial of service, fixed in 11.0.1. +Both `vscode-languageclient` and `@vscode/vsce` currently require the older +major. Minimatch 11 replaces the matcher and removes APIs; an override is a +compatibility change, not a routine lockfile refresh. + +Keep that update separate from this completed language qualification. Before +changing it, audit both consumers' API use, exercise adversarial and ordinary +glob patterns, and rerun extension compilation, packaging and actual editor +host checks on the supported platforms. No dependency override or alert +dismissal was made in this handoff. diff --git a/notebook/2026-11-20-compiler-correctness.md b/notebook/2026-11-20-compiler-correctness.md new file mode 100644 index 0000000..791b9d2 --- /dev/null +++ b/notebook/2026-11-20-compiler-correctness.md @@ -0,0 +1,157 @@ +# Compiler correctness follow-up — November 20, 2026 + +The `7419ac1` source and four-host runtime campaigns completed successfully, +including both Mac application/editor jobs. Goetic records the immutable +development SDK delivered from that revision. The shared SDK default and +release publication remain unchanged; the integration PR still requires +independent review. + +## Reproduce old findings before changing code + +The audit reproduced F34: a renamed module function passed analysis but emitted +an unresolved alias in NIL. F36 was more subtle: a conversion intrinsic declared +to return a user-defined `Result` produced the standard runtime tag, so matching +the claimed custom enum silently missed. Both the interpreter and native route +returned the reproducer's fallthrough value instead of the parsed integer. + +F21 also still reproduces: Ny accepts a text local read before assignment, then +fails during execution/native generation. A proper source-level +definite-assignment analysis remains separate work. + +F33 no longer reproduces. Typed array-expression lowering already corrected it +during the tuple-array implementation. Expanded checks on the unchanged +`7419ac1` SDK pass all 226 tuple-array contract checks, including literal and +returned text arrays, exactly-once evaluation, retained text, wide integers, +floating-point elements and empty returned arrays in both languages on six +execution routes. The findings entry and stale F25 release-profile warning are +corrected rather than presenting existing behavior as a new implementation. + +## Module aliases and conversion providers + +Function references now retain their checker-selected declaration separately +from source spelling. Lowering uses that identity for calls and generic +specialization; function values use the same declaration. Local values retain +precedence, and unrelated constructors/globals cannot replace the selected +function. Matrix `read module as alias` loads its target, and qualified paragraph +values use the ordinary name parser and preserve their final-name source span. +Review also reproduced a root generic function selecting another module's +same-named declaration when explicit source-file order changed. The registry now +preserves the root function's canonical bare name; both input orders have +interpreted and native regression coverage. + +Checked conversion providers require the nominal standard Result owner and +their exact payload/error types. Source checking, unchecked emission, NIL +loading and native generation validate that boundary. Existing standard +namespace aliases and tested legacy wire forms remain supported. This is +validation of the existing providers, not custom enum construction or additional +native conversion support. + +The module-alias contract covers Ny/Matrix providers and consumers, source and +binary libraries, direct/generic calls, interpreted function values, module +isolation and rejection of inaccessible or incorrectly called functions. The +conversion contract covers legitimate results and malformed provider owners, +schemas and signatures, with existing output artifacts protected on failure. +The four-host interpreter workflow now selects fourteen contracts; the Mac +language campaigns select twelve, retaining their previous assertions and +deadlines. Build-tree checks do not update Goetic's installed SDK automatically. + +The complete local LLVM-enabled Release suite passes all 601 CTests with zero +failures or skips. This includes 142 module-alias checks, 129 conversion-provider +checks and the embedding loader controls. The existing integer-conversion, +tuple-array, module-context and editor-analysis contracts also pass. Hosted +results for the final commit are tracked in +[the integration PR](https://github.com/exec-software/exec-nil-framework/pull/41); +the local result does not by itself establish the other hosts' current-source +acceptance. The changed-file audit found no credentials or new private paths. + +## Hosted build dependency correction + +Both the push and PR source campaigns for `332b6f5` passed: 601 LLVM-enabled +tests with zero skips, and 450 LLVM-disabled tests with 145 expected native +skips. Each extension unit campaign passed 167 tests. The SDK from that exact +revision also passed 601 source tests and all 1,184 installed-library executions. + +The first fourteen-contract runtime campaign passed on Linux, Windows and Intel +macOS. Apple Silicon passed thirteen contracts; CTest did not run the conversion +contract because the focused build omitted its declared `nilassembler` +dependency. The original failed run and artifacts are retained: +[runtime run 44858633125](https://github.com/exec-software/exec-nil-framework/actions/runs/44858633125). +Add the assembler to the focused build targets on every host. The test inventory, +timeouts and assertions stay unchanged; the replacement campaign must pass +before claiming this revision's four-host runtime acceptance. This is a workflow +correction, so the separately qualified SDK retains its `332b6f5` source identity. + +## Development SDK handoff and editor include caches + +The immutable Linux development SDK built from `332b6f5` has manifest SHA256 +`c82b532b1ef48b9c91c4ca0022f94fb25bb57d5253928cf177a7426875fd7a98`. +Its eleven tools, nineteen modules, 84 source files and 72 HTML pages passed +601 source tests, 1,184 installed executions, 32 additional markup executions, +and the installed rooted-file contract. All 275 payload hashes were verified +after relocation and consumer testing. + +An isolated committed Goetic snapshot passed its native checks, 24 Matrix +fixtures, nine Node tests and 94 HTTP tests. The Goetic chat independently +verified the physical generation and committed its next-build pin in `c229656`, +preserving its existing application edits. No live application was restarted; +the shared SDK default and stable/Lich publication remain unchanged. + +The first Mac application run passed all non-editor contracts on Apple Silicon, +then failed the include-file restoration navigation check after 43 successful +editor checks. Its original evidence is retained in +[run 44858633162](https://github.com/exec-software/exec-nil-framework/actions/runs/44858633162). +A deterministic regression reproduced a matching failure mode: semantic +validation treated a retained clean closed-tab include model as authoritative +even after the compiler had checked restored disk contents. + +Validation now defers those clean closed-tab caches to exact disk snapshots. +Dirty include aliases still block navigation, and clean open include tabs must +match. Arbitrary local text/diff tab membership now invalidates pending results, +while compiler overlays and providers remain limited to supported languages. +Ten added regression tests cover direct/alias caches, dirty/open tabs and changes +during asynchronous reads. All 177 extension unit tests and the production build +pass; real editor-host acceptance remains a separate check. No host assertion, +deadline or dependency version was changed. + +## Completion result ownership + +Both source campaigns and all four runtime hosts passed at `83dd093`. The next +Apple Silicon editor run passed the include-restoration check and all semantic +checks, then failed after 56 successful checks because a compiler completion +candidate also appeared in tolerant completion results. The failure is preserved +in [run 44861306592](https://github.com/exec-software/exec-nil-framework/actions/runs/44861306592). + +The compiler provider and language-client middleware each made their own +asynchronous decision about compiler availability. Sharing the raw compiler +promise did not share their final snapshot validation or fallback decision. One +could return compiler candidates while the other returned full tolerant symbols. + +Completion now has one result publisher. It combines the internal compiler query +with tolerant server results, validates the captured request before publication, +and filters fallback bindings when compiler results are authoritative. Unsupported +or unavailable compiler queries still retain tolerant fallback, and unavailable +language-server results do not disable compiler completion. The ordinary language +client completion callback no longer publishes a second result. This changes +completion ownership rather than relaxing the host's duplicate-candidate check. + +A deterministic test of the original production registrations reproduced two +same-name items when their semantic validation outcomes differed. Twenty-seven +new controls cover both response orders, unavailable-query recovery, cancelled +or stale contexts, disabled analysis, missing/stopped servers and source changes +during conversion. Virtual output-document changes remain unrelated to source +validation. All 204 extension tests and the production build pass; the unchanged +full editor-host campaigns provide separate acceptance evidence. + +## Editor dependency follow-up + +The existing [minimatch advisory](https://github.com/isaacs/minimatch/security/advisories/GHSA-g3hv-75wg-m249) +requires optimization level 2 or greater. Inspection of the pinned language +client and packaging tool found default level 1 options; none of those inspected +calls enables the affected optimization. This is a scoped applicability finding, +not an alert dismissal or a blanket dependency safety claim. + +Minimatch 11 removes `makeRe()`, which the language client still calls. An +unconditional major override would break those paths. Keep this dependency +change separate: it needs an explicit consumer adaptation, glob compatibility +checks, packaging comparison and actual editor-host validation. No dependency +override or alert dismissal is part of this compiler change. diff --git a/notebook/README.md b/notebook/README.md index 54acc0d..e48741c 100644 --- a/notebook/README.md +++ b/notebook/README.md @@ -13,6 +13,13 @@ and explicit about evidence, uncertainty, and implementation status. - [`2026-11-13-formatted-markup-handoff.md`](2026-11-13-formatted-markup-handoff.md) — multiline text and structured markup completion review, route checks and SDK handoff. +- [`2026-11-12-matrix-webview.md`](2026-11-12-matrix-webview.md) — checked + browser providers, asynchronous operation identity and honest message provenance. +- [`2026-11-12-web-server-boundaries.md`](2026-11-12-web-server-boundaries.md) — + application-driven file snapshots, protocol boundaries, binary values and + the checked provider boundary needed by the planned WebView rewrite. +- [`2026-11-11-web-runtime-parity.md`](2026-11-11-web-runtime-parity.md) — + current-source and installed-SDK platform evidence for the web runtime. - [`2026-11-04-macos-parity-plan.md`](2026-11-04-macos-parity-plan.md) — initial Darwin/Apple Silicon gap audit, hosted and VM testing options, and the Windows-first sequence for establishing macOS parity. diff --git a/tests/language/rooted-file-snapshot-invalid-schema.ny b/tests/language/rooted-file-snapshot-invalid-schema.ny new file mode 100644 index 0000000..86ecbfc --- /dev/null +++ b/tests/language/rooted-file-snapshot-invalid-schema.ny @@ -0,0 +1,22 @@ +module nil.std.io + +import nil.std.core + +# Exact canonical type name, deliberately incompatible timestamp field. The +# native bridge must validate the schema rather than trust its spelling. +pub struct FileSnapshot + content: array + modified_ms: text + sha256: text +end struct + +@intrinsic("file.read_rooted_snapshot") +fn invalid_snapshot(root: text, relative: text, maximum_bytes: i64) -> Result + +fn main() -> i32 + match invalid_snapshot(".", "never-read.bin", 256) + Result.Ok(snapshot) -> println(snapshot.sha256) + Result.Error(message) -> println(message) + end match + return 0 +end fn diff --git a/tests/language/rooted-file-snapshot-invalid-signature.ny b/tests/language/rooted-file-snapshot-invalid-signature.ny new file mode 100644 index 0000000..bfd265c --- /dev/null +++ b/tests/language/rooted-file-snapshot-invalid-signature.ny @@ -0,0 +1,12 @@ +import nil.std.io.file + +@intrinsic("file.read_rooted_snapshot") +fn invalid_snapshot(root: text, relative: text, maximum_bytes: i32) -> Result + +fn main() -> i32 + match invalid_snapshot(".", "never-read.bin", 256) + Result.Ok(snapshot) -> println(snapshot.sha256) + Result.Error(message) -> println(message) + end match + return 0 +end fn diff --git a/tests/language/rooted-file-snapshot.ny b/tests/language/rooted-file-snapshot.ny new file mode 100644 index 0000000..1e70a04 --- /dev/null +++ b/tests/language/rooted-file-snapshot.ny @@ -0,0 +1,82 @@ +module nil.tests.rooted_file_snapshot + +import nil.std.io.file +import nil.std.system.std_sys +import nil.std.text + +fn inspect(snapshot: nil::std::io::FileSnapshot, stamp: i64, digest: text, seed: i64) -> bool + let boxed: anything = snapshot + if not anything_is(boxed) then return false end if + let recovered = boxed as nil::std::io::FileSnapshot + let boxed_content: anything = recovered.content + if not anything_is>(boxed_content) or anything_is>(boxed_content) then return false end if + let recovered_content = boxed_content as array + if recovered.content.len() != 256 then return false end if + if recovered.modified_ms != stamp then return false end if + if recovered.sha256 != digest then return false end if + let mut index: i64 = 0 + while index < 256 + if recovered_content[index] != (((index * 73 + seed) % 256) as u8) then return false end if + index = index + 1 + end while + return true +end fn + +fn reject(root: text, relative: text, maximum: i64, expected: text) -> bool + match nil::std::io::read_rooted_snapshot(root, relative, maximum) + Result.Ok(_) -> return false + Result.Error(message) -> + if not nil::std::text::starts_with(message, "file.read_rooted_snapshot:") then return false end if + if nil::std::text::index_of(message, root) >= 0 then return false end if + if expected != "" and message != expected then return false end if + end match + return true +end fn + +fn main() -> i32 + if nil::std::system::arg_count() != 4 and nil::std::system::arg_count() != 5 then return 60 end if + let root = nil::std::system::arg(0) + let stamp = nil::std::core::Convert.try_to_i64(nil::std::system::arg(1)).unwrap() + let digest = nil::std::system::arg(2) + let seed = nil::std::core::Convert.try_to_i64(nil::std::system::arg(3)).unwrap() + match nil::std::io::read_rooted_snapshot(root, "nested/café-λ.bin", 256) + Result.Error(message) -> + println(message) + return 61 + Result.Ok(snapshot) -> + if not inspect(snapshot, stamp, digest, seed) then return 62 end if + if nil::std::system::arg_count() == 5 then + if nil::std::system::arg(4) != "wrong-element" then return 74 end if + let boxed_content: anything = snapshot.content + let invalid_content = boxed_content as array + println(invalid_content.len()) + return 75 + end if + end match + match nil::std::io::read_rooted_snapshot(root, "empty.bin", 0) + Result.Error(message) -> + println(message) + return 63 + Result.Ok(snapshot) -> + if snapshot.content.len() != 0 or snapshot.modified_ms != stamp then return 64 end if + if snapshot.sha256 != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" then return 65 end if + end match + println("snapshot-content-ok") + if not reject(root, "nested/café-λ.bin", 255, + "file.read_rooted_snapshot: input exceeds maximum_bytes") then return 66 end if + if not reject(root, "empty.bin", -1, "") then return 67 end if + if not reject(root, "empty.bin", 536870913, "") then return 68 end if + let invalid: array = ["", ".", "..", "../outside/sentinel.bin", "nested/../empty.bin", + "/empty.bin", "nested//café-λ.bin", "nested/", "nested\\café-λ.bin", "C:empty.bin", + "missing.bin", "nested"] + for path in invalid + if not reject(root, path, 256, "") then return 69 end if + end for + if not reject(root + "/missing-root", "empty.bin", 256, "") then return 70 end if + if not reject(root + "/empty.bin", "empty.bin", 256, "") then return 71 end if + println("snapshot-errors-ok") + if not reject(root, "linked.bin", 256, "") then return 72 end if + if not reject(root, "via-link/sentinel.bin", 256, "") then return 73 end if + println("snapshot-links-ok") + return 0 +end fn diff --git a/tests/language/text-from-bytes-native-reject.ny b/tests/language/text-from-bytes-native-reject.ny new file mode 100644 index 0000000..9c49ea8 --- /dev/null +++ b/tests/language/text-from-bytes-native-reject.ny @@ -0,0 +1,7 @@ +import nil.std.text + +fn main() -> i32 + let bytes: array = [65 as u8, 66 as u8] + println(nil::std::text::from_bytes(bytes)) + return 0 +end fn diff --git a/tests/language/text-from-bytes.ny b/tests/language/text-from-bytes.ny new file mode 100644 index 0000000..a9b67c1 --- /dev/null +++ b/tests/language/text-from-bytes.ny @@ -0,0 +1,33 @@ +module nil.tests.text_from_bytes + +import nil.std.text +import nil.std.collections.array + +fn main() -> i32 + let mut bytes: array = [] + let mut index: i64 = 0 + while index < 256 + bytes.push(index as u8) + index = index + 1 + end while + let text = nil::std::text::from_bytes(bytes) + if nil::std::text::length(text) != 256 then return 61 end if + bytes[0] = 17 + index = 0 + while index < 256 + if nil::std::text::byte_at(text, index) != index then return 62 end if + index = index + 1 + end while + let empty: array = [] + if nil::std::text::from_bytes(empty) != "" then return 63 end if + let mut large = nil::std::collections::new_u8(1048576, 255 as u8) + large[524288] = 0 + large[1048575] = 128 + let copied = nil::std::text::from_bytes(large) + if nil::std::text::length(copied) != 1048576 then return 64 end if + if nil::std::text::byte_at(copied, 0) != 255 then return 65 end if + if nil::std::text::byte_at(copied, 524288) != 0 then return 66 end if + if nil::std::text::byte_at(copied, 1048575) != 128 then return 67 end if + println("from-bytes-ok") + return 0 +end fn diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp index 03aca39..9c2ee61 100644 --- a/tests/matrix_source_spans.cpp +++ b/tests/matrix_source_spans.cpp @@ -160,6 +160,28 @@ void test_names_and_uses() { "give `value`", "value"); } +void test_qualified_paragraph_values() { + const std::string source = + "book paragraph-spans\r\n" + "!!! café before the source names\r\n" + "main begin paragraph\r\n" + " value callback is the paragraph words::`café-call`\r\n" + " value nested is the paragraph alpha.beta::remote-call\r\n" + "end paragraph\r\n"; + const auto program = parse(source); + const auto function = cast(program->declarations.at(1)); + const auto body = cast(function->body); + const auto first = cast( + cast(body->statements.at(0))->declaration); + const auto second = cast( + cast(body->statements.at(1))->declaration); + check_span(source, first->initializer->name_span, "words::`café-call`", "café-call"); + check_span(source, second->initializer->name_span, "beta::remote-call", "remote-call"); + require(cast(first->initializer)->name == "words::café_call" && + cast(second->initializer)->name == "alpha::beta::remote_call", + "qualified paragraph values retain full owners and final-name spans"); +} + void test_members_and_types() { const std::string source = "book member-check\n" @@ -301,6 +323,7 @@ int main() { test_lexer_source_ranges(); test_formatted_text_source_spans(); test_names_and_uses(); + test_qualified_paragraph_values(); test_members_and_types(); test_lowered_bindings(); test_switch_source_spans(); diff --git a/tests/nil_loader_tests.cpp b/tests/nil_loader_tests.cpp index 9746447..eaa4558 100644 --- a/tests/nil_loader_tests.cpp +++ b/tests/nil_loader_tests.cpp @@ -797,6 +797,29 @@ void test_vm_entry_and_exit_queries() { "VM should distinguish loadable libraries from programs with main"); } +void test_checked_conversion_module_initializers() { + for (const std::string owner : {"nil::std::core::Result", "ny::lang::core::Result", "Result", "impostor::Result"}) { + const auto type = owner + ""; + std::istringstream source("module conversion_initializer\nconst word = \"7\"\n" + "enum " + type + "\nOk: i32\nError: text\nend enum\n" + "PUSH_CONST_STR word\nINTEROP_CALL intrinsic convert.try_to_i32 1 " + type + "\n" + "IS_VARIANT Result::Ok " + type + " i32\n"); + bool accepted = false, rejected_owner = false; + try { + std::unordered_map constants; + const auto program = ny::parseProgram(source, constants); + ny::VM vm; + vm.loadProgram(program, constants); + vm.execute(); + accepted = vm.getStack().size() == 1 && vm.getProgramExitCode() == 1; + } catch (const std::runtime_error &error) { + rejected_owner = std::string(error.what()).find("requires the standard Result ABI") != std::string::npos; + } + check(owner == "impostor::Result" ? rejected_owner && !accepted : accepted && !rejected_owner, + "module initializer conversion preserves exact Result owner: " + owner); + } +} + void test_function_arity_survives_both_nil_formats() { ny::nil_module module; ny::nil_function helper; @@ -1969,6 +1992,7 @@ int main() { test_shared_opcode_mapping(); test_unknown_opcodes_are_rejected(); test_vm_entry_and_exit_queries(); + test_checked_conversion_module_initializers(); test_function_arity_survives_both_nil_formats(); test_function_return_types_survive_both_nil_formats(); test_vm_typed_return_contract(); diff --git a/tests/rooted_file_snapshot_tests.cpp b/tests/rooted_file_snapshot_tests.cpp new file mode 100644 index 0000000..489bf93 --- /dev/null +++ b/tests/rooted_file_snapshot_tests.cpp @@ -0,0 +1,315 @@ +// All paths and concurrent namespace changes belong to this private fixture. +#include "../nilcompiler/src/secure_file_io.hpp" +#include "../common/private_directory.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif + +namespace { +namespace fs = std::filesystem; +int checks = 0; + +void check(bool good, const char *label) { + ++checks; + if (!good) throw std::runtime_error(label); +} + +class Fixture { +public: + Fixture() : path(nil::detail::create_private_directory(fs::temp_directory_path(), "nil-rooted-snapshot-")) {} + ~Fixture() { std::error_code ignored; fs::remove_all(path, ignored); } + fs::path path; +}; + +void write(const fs::path &path, const std::string &bytes) { + std::ofstream output(path, std::ios::binary | std::ios::trunc); + output.write(bytes.data(), static_cast(bytes.size())); + output.close(); + check(!output.fail(), "write owned fixture"); +} + +ny::detail::RootedFileSnapshot read(const fs::path &root, const std::string &relative, + std::uint64_t maximum = 1048576) { + return ny::detail::read_rooted_file_snapshot_utf8(root.u8string(), relative, maximum); +} + +std::string body(const ny::detail::RootedFileSnapshot &result) { + return std::string(result.bytes.begin(), result.bytes.end()); +} + +void refused(const ny::detail::RootedFileSnapshot &result, const char *label, + const fs::path &private_root) { + check(!result.ok && result.bytes.empty(), label); + check(result.error.find(private_root.u8string()) == std::string::npos && + result.error.rfind("file.read_rooted_snapshot: ", 0) == 0, + "refusal has a fixed diagnostic without private paths"); +} + +void timestamp(const fs::path &path, std::int64_t milliseconds) { +#ifdef _WIN32 + HANDLE file = CreateFileW(path.c_str(), FILE_WRITE_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + check(file != INVALID_HANDLE_VALUE, "open owned timestamp fixture"); + const auto ticks = static_cast(milliseconds + 11644473600000LL) * 10000; + FILETIME held {static_cast(ticks), static_cast(ticks >> 32U)}; + const bool okay = SetFileTime(file, nullptr, nullptr, &held) != 0; + CloseHandle(file); + check(okay, "set owned timestamp fixture"); +#else + timespec times[2] {}; + times[0].tv_sec = times[1].tv_sec = milliseconds / 1000; + times[0].tv_nsec = times[1].tv_nsec = (milliseconds % 1000) * 1000000; + check(::utimensat(AT_FDCWD, path.c_str(), times, 0) == 0, "set owned timestamp fixture"); +#endif +} + +void directory_link(const fs::path &link, const fs::path &target) { +#ifdef _WIN32 + // Junctions exercise reparse refusal without requiring symlink privilege. + check(fs::create_directory(link), "create owned junction directory"); + const std::wstring shown = fs::absolute(target).wstring(); + const std::wstring substitute = L"\\??\\" + shown; + struct Junction { + DWORD tag; + USHORT data_length; + USHORT reserved; + USHORT substitute_offset; + USHORT substitute_length; + USHORT print_offset; + USHORT print_length; + WCHAR names[1]; + }; + const auto name_bytes = (substitute.size() + shown.size() + 2) * sizeof(WCHAR); + std::vector storage(offsetof(Junction, names) + name_bytes, 0); + auto *data = reinterpret_cast(storage.data()); + data->tag = IO_REPARSE_TAG_MOUNT_POINT; + data->data_length = static_cast(storage.size() - 8); + data->substitute_length = static_cast(substitute.size() * sizeof(WCHAR)); + data->print_offset = static_cast((substitute.size() + 1) * sizeof(WCHAR)); + data->print_length = static_cast(shown.size() * sizeof(WCHAR)); + std::memcpy(data->names, substitute.data(), data->substitute_length); + std::memcpy(reinterpret_cast(data->names) + data->print_offset, + shown.data(), data->print_length); + HANDLE held = CreateFileW(link.c_str(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + check(held != INVALID_HANDLE_VALUE, "open owned junction directory"); + DWORD returned = 0; + const bool okay = DeviceIoControl(held, FSCTL_SET_REPARSE_POINT, data, + static_cast(storage.size()), nullptr, 0, &returned, nullptr) != 0; + CloseHandle(held); + check(okay, "set owned junction reparse data"); +#else + fs::create_directory_symlink(target, link); +#endif +} + +void contracts(const fs::path &base) { + const auto root = base / "public"; + const auto outside = base / "outside"; + fs::create_directories(root / "nested"); + fs::create_directory(outside); + const std::string binary("A\0\xff\x80Z", 5); + write(root / "nested" / "asset.bin", binary); + write(outside / "asset.bin", "outside-owned-marker"); + timestamp(root / "nested" / "asset.bin", 1700000000123LL); + const auto exact = read(root, "nested/asset.bin", binary.size()); + check(exact.ok && body(exact) == binary && exact.error.empty(), "read exact bounded binary payload"); + check(exact.modified_ms == 1700000000123LL, "return same-handle milliseconds without clock sampling"); + const auto short_limit = read(root, "nested/asset.bin", binary.size() - 1); + refused(short_limit, "reject oversized before allocation", base); + check(short_limit.error == "file.read_rooted_snapshot: input exceeds maximum_bytes", + "oversized refusal is distinct for HTTP mapping"); + refused(read(root, "nested/asset.bin", 512ULL * 1024 * 1024 + 1), "reject excessive requested limit", base); + write(root / "empty", ""); + const auto empty = read(root, "empty", 0); + check(empty.ok && empty.bytes.empty(), "zero limit accepts empty regular file"); + refused(read(root, "nested/asset.bin", 0), "zero limit rejects nonempty file", base); + refused(read(root, "absent"), "missing file refused", base); + refused(read(root, "nested"), "directory cannot be served as a regular file", base); + refused(read(root / "empty", "asset"), "regular file cannot be a root directory", base); + + const std::vector bad_names = { + "", ".", "..", "/nested/asset.bin", "nested/../empty", "nested/./asset.bin", + "nested//asset.bin", "nested/asset.bin/", "nested\\asset.bin", "C:asset.bin", + "empty:stream", std::string("empty\0ignored", 13), std::string("\xc0\xaf", 2), + std::string("\xed\xa0\x80", 3), std::string("\xf4\x90\x80\x80", 4)}; + for (const auto &name : bad_names) + refused(read(root, name), "invalid relative spelling refused", base); + refused(ny::detail::read_rooted_file_snapshot_utf8("", "empty", 10), "empty root refused", base); + refused(ny::detail::read_rooted_file_snapshot_utf8(std::string("\xc0\xaf", 2), "empty", 10), + "malformed UTF-8 root refused before filesystem access", base); + const auto unicode = fs::u8path(u8"space λ 🧪"); + fs::create_directory(root / unicode); + write(root / unicode / "asset.bin", binary); + check(body(read(root, unicode.u8string() + "/asset.bin")) == binary, "UTF-8 descendant names round-trip"); + directory_link(root / "linked", outside); + // This control intentionally demonstrates the old API's documented final- + // component-only boundary, using only a marker owned by the test fixture. + const auto legacy = ny::detail::read_regular_file_bounded(root / "linked" / "asset.bin", 100); + check(legacy.ok && std::string(legacy.bytes.begin(), legacy.bytes.end()) == "outside-owned-marker", + "negative control: final-component-only API follows intermediate link"); + refused(read(root, "linked/asset.bin"), "intermediate directory link refused", base); + refused(read(root, "linked"), "final directory reparse/link refused", base); + refused(read(root / "linked", "asset.bin"), "root final reparse/link refused", base); + refused(read(root / "linked" / "", "asset.bin"), "trailing slash cannot disguise a root link", base); + refused(read(root / "linked" / ".", "asset.bin"), "trailing dot cannot disguise a root link", base); + check(body(read(root / "", "nested/asset.bin")) == binary, + "trailing slash on an ordinary root remains valid"); + check(body(read(root / ".", "nested/asset.bin")) == binary, + "trailing dot on an ordinary root remains valid"); +#ifndef _WIN32 + fs::create_symlink(outside / "asset.bin", root / "final-link"); + refused(read(root, "final-link"), "final file symlink refused", base); + check(::mkfifo((root / "pipe").c_str(), 0600) == 0, "create owned FIFO"); + const auto began = std::chrono::steady_clock::now(); + refused(read(root, "pipe"), "FIFO is refused without opening a writer", base); + check(std::chrono::steady_clock::now() - began < std::chrono::seconds(2), "FIFO refusal is nonblocking"); +#endif +} + +void namespace_race(const fs::path &base) { + const auto root = base / "race-root"; + const auto outside = base / "race-outside"; + fs::create_directories(root / "live"); + fs::create_directory(outside); + write(root / "live" / "asset", "inside-owned-marker"); + write(outside / "asset", "outside-owned-marker"); + directory_link(root / "link-spare", outside); + std::atomic stop{false}; + std::atomic swaps{0}; + std::atomic mutator_failed{false}; + std::thread mutator([&] { + // Windows can briefly reject a directory rename while a descendant file + // handle denies delete sharing. Complete each owned swap before stopping. + const auto finish_rename = [&](const fs::path &from, const fs::path &to) { + const auto bound = std::chrono::steady_clock::now() + std::chrono::seconds(2); + std::error_code error; + do { + fs::rename(from, to, error); + if (!error) return true; + std::this_thread::yield(); + } while (std::chrono::steady_clock::now() < bound); + return false; + }; + while (!stop.load()) { + std::error_code error; + fs::rename(root / "live", root / "safe-spare", error); + if (error) { std::this_thread::yield(); continue; } + if (!finish_rename(root / "link-spare", root / "live")) { mutator_failed = true; break; } + ++swaps; + std::this_thread::yield(); + if (!finish_rename(root / "live", root / "link-spare") || + !finish_rename(root / "safe-spare", root / "live")) { mutator_failed = true; break; } + } + }); + bool escaped = false; + int reads = 0; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + try { + while (reads < 500 && std::chrono::steady_clock::now() < deadline) { + const auto result = read(root, "live/asset"); + ++reads; + if (result.ok && body(result) != "inside-owned-marker") escaped = true; + } + } catch (...) { + stop = true; + mutator.join(); + throw; + } + stop = true; + mutator.join(); + check(!mutator_failed.load(), "owned namespace mutator completed its swaps"); + check(swaps.load() > 0 && reads > 0, "concurrent namespace changes actually occurred"); + check(!escaped, "anchored opens never follow replacement link outside root"); +} + +void coupled_snapshot_race(const fs::path &base) { + const auto root = base / "snapshot-race"; + fs::create_directory(root); + const std::string first(65536, 'a'), second(65536, 'b'); + write(root / "live", first); + write(root / "spare", second); + timestamp(root / "live", 1700000000123LL); + timestamp(root / "spare", 1700000001567LL); + std::atomic stop{false}; + std::atomic swaps{0}; + std::atomic failed{false}; + std::thread publisher([&] { + const auto finish = [&](const char *from, const char *to) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + std::error_code error; + do { + fs::rename(root / from, root / to, error); + if (!error) return true; + std::this_thread::yield(); + } while (std::chrono::steady_clock::now() < deadline); + return false; + }; + while (!stop.load()) { + std::error_code error; + fs::rename(root / "live", root / "park", error); + if (error) { std::this_thread::yield(); continue; } + if (!finish("spare", "live") || !finish("park", "spare")) { + failed = true; + break; + } + ++swaps; + } + }); + bool mixed = false; + int succeeded = 0; + try { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + for (int index = 0; index < 500 && std::chrono::steady_clock::now() < deadline; ++index) { + const auto result = read(root, "live"); + if (result.ok) { + ++succeeded; + const auto bytes = body(result); + if (!((bytes == first && result.modified_ms == 1700000000123LL) || + (bytes == second && result.modified_ms == 1700000001567LL))) mixed = true; + } + } + } catch (...) { + stop = true; + publisher.join(); + throw; + } + stop = true; + publisher.join(); + check(!failed.load() && swaps.load() > 0, "same-handle fixture published distinct file versions"); + check(succeeded > 0, "same-handle fixture observed successful snapshots"); + check(!mixed, "bytes and timestamp always identify the same opened file version"); +} + +} // namespace + +int main() { + try { + Fixture fixture; + contracts(fixture.path); + namespace_race(fixture.path); + coupled_snapshot_race(fixture.path); + std::cout << checks << " rooted snapshot checks passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "rooted snapshot contract failed: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/tools/checked_conversion_intrinsic_contract.py b/tests/tools/checked_conversion_intrinsic_contract.py new file mode 100644 index 0000000..8e0602f --- /dev/null +++ b/tests/tools/checked_conversion_intrinsic_contract.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Checked conversion providers preserve Result ownership across source and NIL.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SENTINEL = b'previous artifact must survive invalid conversion declarations\n' + + +def wire(binary, owner='nil::std::core::Result', *, instruction_owner=None, + declared_owner=None, variants=None, duplicate=False, missing=False, + legacy_operand=False, parameters=None): + result = owner + '' + declaration = (declared_owner or owner) + '' + operand = 'i64' if legacy_operand else (instruction_owner or owner) + '' + variants = variants or [('Ok', 'i32'), ('Error', 'text')] + enums = [] if missing else [(result, variants)] * (2 if duplicate else 1) + functions = [ + ('provider', ['value:text'] if parameters is None else parameters, declaration, ['@intrinsic("convert.try_to_i32")'], [ + ('STORE_LOCAL', ['value']), ('LOAD_LOCAL', ['value']), + ('INTEROP_CALL', ['intrinsic', 'convert.try_to_i32', '1', operand]), ('RET', [])]), + ('main', [], 'i32', [], [('PUSH_CONST_STR', ['value']), ('CALL', ['provider', '1']), + ('IS_VARIANT', ['Result::Ok', result, 'i32']), ('CALL', ['println', '1']), + ('PUSH_CONST', ['0']), ('RET', [])]), + ] + if not binary: + lines = ['module checked_conversion', 'const value = "7"'] + for name, values in enums: + lines += ['enum ' + name, *(f'{variant}: {kind}' for variant, kind in values), 'end enum'] + for name, parameters, returned, annotations, body in functions: + lines += annotations + [f'function {name}({", ".join(parameters)}) -> {returned}:'] + lines += [' '.join([opcode, *(json.dumps(value) for value in arguments)]) + for opcode, arguments in body] + lines += ['end function'] + return ('\n'.join(lines) + '\n').encode() + + def u32(value): + return struct.pack(' impostor::Result<' + value + ',text>\nend fn\n' + + 'fn main() -> i32\n return 0\nend fn\n', + 'matrix': 'book rejected-conversion\nread impostor\nnote intrinsic "' + provider + '"\n' + + 'provider receives input-text as text returns impostor.Result of ' + matrix_type + ', text\n' + + 'main returns override integer begin paragraph\n give 0\nend paragraph\n', + } + for language, contents in sources.items(): + source = work / ('invalid-' + value + '.' + language) + source.write_text(contents, newline='\n') + analysis = run([*analysis_base, '--analyze', source], 1) + report = json.loads(analysis.stdout) + assert not report['success'] and 'standard Result ABI' in analysis.stdout, report + for flags in ([], ['--no-typecheck']): + output = work / 'protected.nil' + output.write_bytes(SENTINEL) + result = run([*base, *flags, '--no-bundle', '-o', output, source], 1) + assert 'standard Result ABI' in result.stderr, result.stderr + assert output.read_bytes() == SENTINEL + if args.llvm == 'ON': + for route in (['--native'], ['--native', '--jit']): + output = work / ('protected-native.exe' if os.name == 'nt' else 'protected-native') + output.write_bytes(SENTINEL) + result = run([*base, '--no-typecheck', *route, '-o', output, source], 1) + assert 'standard Result ABI' in result.stderr, result.stderr + assert output.read_bytes() == SENTINEL + + # The same leaf name, an alias, and matching variant shape cannot grant + # a user enum the runtime's standard Result tag identity. + source = work / 'alias.ny' + source.write_text('import impostor\ntype Converted = impostor::Result\n' + '@intrinsic(convert.try_to_i32)\nfn provider(value: text) -> Converted\nend fn\n' + 'fn main() -> i32\n return 0\nend fn\n', newline='\n') + assert 'standard Result ABI' in run([*analysis_base, '--analyze', source], 1).stdout + + for language, declaration in ( + ('ny', '@intrinsic("convert.try_to_i32")\n' + 'fn provider(input: text) -> nil::std::core::Result\nend fn\n'), + ('matrix', 'book missing-conversion-import\nnote intrinsic "convert.try_to_i32"\n' + 'provider receives input-text as text returns nil.std.core.Result of override integer, text\n'), + ): + source = work / ('missing-import.' + language) + source.write_text(declaration, newline='\n') + result = run([*analysis_base, '--analyze', source], 1) + assert 'standard Result ABI' in result.stdout, result + + for owner in ('nil.std.core', 'ny.lang.core'): + for language in ('ny', 'matrix'): + if language == 'ny': + contents = 'import ' + owner + '.result\ntype Parsed = Result\n' + for value in ('i32', 'i64'): + returned = 'Parsed' if value == 'i32' else 'Result' + contents += '@intrinsic("convert.try_to_' + value + '")\n' +\ + 'fn parse_' + value + '(value: text) -> ' + returned + '\nend fn\n' + contents += 'fn main() -> i32\n' + for value in ('i32', 'i64'): + contents += ' match parse_' + value + '("7")\n' +\ + ' Result.Ok(value) -> println(value)\n Result.Error(error) -> return 1\n end match\n' +\ + ' match parse_' + value + '("bad")\n' +\ + ' Result.Ok(value) -> return 2\n Result.Error(error) -> println("rejected")\n end match\n' + contents += ' return 0\nend fn\n' + else: + contents = 'book accepted-conversion\nread ' + owner + '.result\nParsed means Result of override integer, text\n' + for value in ('i32', 'i64'): + returned = 'Parsed' if value == 'i32' else 'Result of override long, text' + contents += 'note intrinsic "convert.try_to_' + value + '"\n' +\ + 'parse-' + value + ' receives input-text as text returns ' + returned + '\n' + contents += 'main returns override integer begin paragraph\n' + for value in ('i32', 'i64'): + contents += ' consider parse-' + value + ' with "7"\n' +\ + ' when Result.Ok holding parsed-value then say parsed-value\n when Result.Error holding message then give 1\n end consider\n' +\ + ' consider parse-' + value + ' with "bad"\n' +\ + ' when Result.Ok holding parsed-value then give 2\n when Result.Error holding message then say "rejected"\n end consider\n' + contents += ' give 0\nend paragraph\n' + source = work / ('valid-' + owner.replace('.', '-') + '.' + language) + source.write_text(contents, newline='\n') + assert json.loads(run([*analysis_base, '--analyze', source]).stdout)['success'] + for route in ('text', 'binary', 'native', 'jit') if args.llvm == 'ON' else ('text', 'binary'): + output = work / ('run-' + owner + '-' + language + '-' + route + ('.exe' if os.name == 'nt' else '')) + flags = ['--native', '--jit'] if route == 'jit' else ['--native'] if route == 'native' else ['--no-bundle'] + if route == 'binary': flags += ['--emit-binary-nil'] + result = run([*base, *flags, '-o', output, source]) + if route != 'jit': + result = run([output] if route == 'native' else [interpreter, '--no-ai', output]) + assert result.stdout == '7\nrejected\n7\nrejected\n', result + + invalid_wire = { + 'custom-owner': {'owner': 'impostor::Result'}, + 'custom-call-owner': {'instruction_owner': 'impostor::Result'}, + 'custom-declaration-owner': {'declared_owner': 'impostor::Result'}, + 'missing-schema': {'missing': True}, + 'duplicate-schema': {'duplicate': True}, + 'wrong-payload': {'variants': [('Ok', 'i64'), ('Error', 'text')]}, + 'wrong-error': {'variants': [('Ok', 'i32'), ('Error', 'i64')]}, + 'wrong-variants': {'variants': [('Ok', 'i32'), ('Failure', 'text')]}, + 'wrong-input': {'parameters': ['value:i64']}, + 'wrong-arity': {'parameters': ['value:text', 'other:text']}, + } + for binary in (False, True): + for owner in ('nil::std::core::Result', 'ny::lang::core::Result', 'Result'): + for legacy in (False, True): + path = work / 'wire-valid.nil' + path.write_bytes(wire(binary, owner, legacy_operand=legacy)) + assert run([interpreter, '--no-ai', path]).stdout == '1\n' + for name, changes in invalid_wire.items(): + path = work / (name + '.nil') + path.write_bytes(wire(binary, **changes)) + result = run([interpreter, '--no-ai', path], 1) + assert not result.stdout and 'standard Result ABI' in result.stderr, result + if args.llvm == 'ON': + output = work / 'protected.o' + output.write_bytes(SENTINEL) + result = run([assembler, '-o', output, path], 1) + assert 'standard Result ABI' in result.stderr, result + assert output.read_bytes() == SENTINEL + + # Textual NIL admits initializer instructions outside a function. + # The CLI enters main; embedding execution is covered by nil.loader. + # Both paths need the same owner/schema proof as wrapped calls. + for owner, status in (('nil::std::core::Result', 0), ('impostor::Result', 1)): + kind = owner + '' + path = work / 'module-initializer.nil' + path.write_text('module initializer\nconst value = "7"\n' + f'enum {kind}\nOk: i32\nError: text\nend enum\n' + 'PUSH_CONST_STR value\n' + f'INTEROP_CALL intrinsic convert.try_to_i32 1 {kind}\n' + f'IS_VARIANT Result::Ok {kind} i32\nCALL println 1\n' + 'function main() -> i32:\nPUSH_CONST_STR value\n' + f'INTEROP_CALL intrinsic convert.try_to_i32 1 {kind}\n' + f'IS_VARIANT Result::Ok {kind} i32\nCALL println 1\n' + 'PUSH_CONST 0\nRET\nend function\n', newline='\n') + result = run([interpreter, '--no-ai', path], status) + if status: + assert not result.stdout and 'standard Result ABI' in result.stderr, result + else: + assert result.stdout == '1\n', result + print(f'Checked conversion intrinsic ABI: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/checked_integer_conversion_contract.py b/tests/tools/checked_integer_conversion_contract.py index ad42258..7485ec3 100644 --- a/tests/tools/checked_integer_conversion_contract.py +++ b/tests/tools/checked_integer_conversion_contract.py @@ -23,8 +23,8 @@ def main(): 'NIL_STDLIB_PATH', 'NY_LEX_DUMP', 'NY_PARSE_TRACE'): environment.pop(name, None) # The ordinary canonical Result comes from core. Each malformed provider - # changes one boundary independently, with a well-typed call that reaches - # LLVM validation rather than failing ordinary argument/type checking. + # changes one boundary independently. Provider declarations are now checked + # before LLVM lowering, while native artifact-preservation controls remain. cases = ( ('wrong-input', 'i64', 'value: i32', 'Result', '1'), ('wrong-success', 'i64', 'value: text', 'Result', '"1"'), @@ -45,8 +45,8 @@ def main(): 'fn main() -> i32\n' f'let parsed = malformed({arguments})\n' 'return 0\nend fn\n', newline='\n') - sources.append((path, f'convert.try_to_{width} requires the exact ' - f'(text) -> Result<{width},text> ABI')) + sources.append((path, f'convert.try_to_{width} requires the standard Result ABI ' + f'(text) -> nil::std::core::Result<{width},text>')) # Native text has no byte-length argument at this ABI. Reachable NUL # constants must be rejected before a C string could truncate them. for language, source in ( @@ -73,7 +73,7 @@ def main(): sources.append((path, 'contains an embedded NUL byte')) for path, message in sources: for flags in (('--native',), ('--native', '--jit')): - output = root / 'protected-output' + output = root / ('protected-output.exe' if os.name == 'nt' else 'protected-output') output.write_bytes(b'previous artifact') command = [compiler, '--quiet', '--no-stdlib', '--sdk-path', stdlib, *flags, '--output', output, path] diff --git a/tests/tools/incremental_build_contract.py b/tests/tools/incremental_build_contract.py index dc0bf71..c89e271 100644 --- a/tests/tools/incremental_build_contract.py +++ b/tests/tools/incremental_build_contract.py @@ -30,6 +30,30 @@ def read_event(path): return event +def event_summary(directory): + """Bounded failure evidence without entry paths or source contents.""" + counts = {'start': 0, 'finish': 0, 'fail': 0} + records = [] + invalid = 0 + truncated = False + for index, path in enumerate(directory.glob('event-*/record.json')): + if index == 256: + truncated = True + break + try: + kind, _, timestamp = read_event(path) + if timestamp > (1 << 63) - 1: + raise ValueError('fixture timestamp exceeds the diagnostic bound') + except (OSError, ValueError, AssertionError): + invalid += 1 + continue + counts[kind] += 1 + records.append({'kind': kind, 'monotonic_ns': timestamp}) + records.sort(key=lambda record: (record['monotonic_ns'], record['kind'])) + return {'counts': counts, 'latest': records[-16:], + 'invalid_records': invalid, 'truncated': truncated} + + def check_event_publication(root): path = root / 'publication-check.json' expected = ['start', str(root / 'source é.ny'), time.monotonic_ns()] @@ -215,8 +239,22 @@ def run(*arguments, cwd=root, status=0, tool=fake): # Keep fake/containment checks at 60 s and bound real Darwin builds # separately; this changes no assertion or cache admission rule. timeout = 300 if sys.platform == 'darwin' and tool == compiler else 60 - result = subprocess.run(command, cwd=cwd, text=True, capture_output=True, timeout=timeout) + before = event_summary(events) if arguments[0] == 'build' and tool == fake else None + + def report_fixture_events(): + if before is not None: + print('nilbuild fixture events: ' + json.dumps({ + 'before': before, 'after': event_summary(events)}, sort_keys=True), + file=sys.stderr, flush=True) + + try: + result = subprocess.run(command, cwd=cwd, text=True, capture_output=True, timeout=timeout) + except subprocess.TimeoutExpired: + report_fixture_events() + raise checks += 1 + if result.returncode != status: + report_fixture_events() assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) return result diff --git a/tests/tools/module_alias_contract.py b/tests/tools/module_alias_contract.py new file mode 100644 index 0000000..c521da7 --- /dev/null +++ b/tests/tools/module_alias_contract.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Renamed modules retain the checked callable owner across compilation routes.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler = args.compiler.resolve(strict=True) + interpreter = args.interpreter.resolve(strict=True) + stdlib = args.stdlib.resolve(strict=True) + environment = os.environ.copy() + for name in ('NY_LIBRARY_PATH', 'NIL_LIBRARY_PATH', 'NY_STDLIB_PATH', + 'NIL_STDLIB_PATH', 'NY_LEX_DUMP', 'NIL_LEX_DUMP', + 'NY_PARSE_TRACE', 'NIL_PARSE_TRACE'): + environment.pop(name, None) + harness = Path(__file__).resolve().parents[1] / 'routes/ny_route_matrix.py' + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-module-alias-') as directory: + root = Path(directory).resolve() + + def run(command, status=0): + result = subprocess.run([str(item) for item in command], cwd=root, + env=environment, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=90) + assert result.returncode == status, (command, result.returncode, + result.stdout, result.stderr) + return result + + def routes(source, search, expected, name): + nonlocal checks + common = [compiler, '--no-stdlib', '-I', search] + analysis = run([*common, '--analyze', source]) + assert not analysis.stderr and json.loads(analysis.stdout)['success'], analysis + checks += 1 + expected_file = root / (name + '.stdout') + expected_file.write_text(expected, encoding='utf-8', newline='\n') + report = root / (name + '.json') + selection = ('all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary') + run([sys.executable, harness, '--compiler', compiler, + '--interpreter', interpreter, '--source', source, + '--expected-stdout', expected_file, '--expected-exit', '0', + '--compiler-arg=-I', '--compiler-arg=' + str(search), + '--routes', selection, '--strict', '--timeout', '30', + '--work-dir', root / (name + '-routes'), '--report-json', report]) + checks += 6 if args.llvm == 'ON' else 4 + + def source(language, body, imports=''): + if language == 'ny': + return ('module consumer\n' + imports + + 'fn main() -> i32\n' + body + '\nreturn 0\nend fn\n') + return ('book consumer\n' + imports + + 'main returns override integer begin paragraph\n' + body + + '\ngive 0\nend paragraph\n') + + providers = { + 'ny': 'module helper\n' + 'pub fn calculate(input: i32) -> i32\nreturn input + 20\nend fn\n' + 'pub fn select(chosen: T, ignored: i32) -> T\nreturn chosen\nend fn\n' + 'pub fn ok(input: i32) -> i32\nreturn input + 40\nend fn\n' + 'fn hidden(input: i32) -> i32\nreturn input\nend fn\n', + 'matrix': 'book helper\n' + 'public calculate receives input as override integer returns override integer begin paragraph\n' + 'give input plus 20\nend paragraph\n' + 'public select of type T receives chosen as T, ignored as override integer returns T begin paragraph\n' + 'give chosen\nend paragraph\n' + 'public ok receives input as override integer returns override integer begin paragraph\n' + 'give input plus 40\nend paragraph\n' + 'hidden receives input as override integer returns override integer begin paragraph\n' + 'give input\nend paragraph\n', + } + for provider_language, provider_text in providers.items(): + search = root / ('source-' + provider_language) + search.mkdir() + provider = search / ('helper.' + provider_language) + provider.write_text(provider_text, encoding='utf-8', newline='\n') + binary = root / ('binary-' + provider_language) + binary.mkdir() + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-o', binary / 'helper.nil', provider]) + checks += 1 + for library_form, library in (('source', search), ('binary', binary)): + if library_form == 'binary': + provider.unlink() + assert not provider.exists() + for language in ('ny', 'matrix'): + if language == 'ny': + imports = 'import helper\nnamespace words = helper\n' + body = ('println(words::calculate(7))\nprintln(helper::calculate(8))\n' + 'println(words::select(49, 0))\n' + 'println(words::select(50, 0))\nprintln(words.calculate(6))\nprintln(words::ok(11))') + else: + # A read-as declaration must load its dependency itself. + imports = 'read helper as words\n' + body = ('say words::calculate with 7\nsay helper::calculate with 8\n' + 'say words::select with ignored being 0, chosen being 49\n' + 'say words::select of override integer with 50, 0\nsay words.calculate with 6\nsay words::ok with 11') + name = f'{provider_language}-{library_form}-{language}' + consumer = root / (name + '.' + language) + consumer.write_text(source(language, body, imports), encoding='utf-8', newline='\n') + routes(consumer, library, '27\n28\n49\n50\n26\n51\n', name) + + # Aliased functions used as values need the same identity. + # Function-value execution has its own interpreter contract. + body = ('let callback = words::calculate\nprintln(callback(9))\n' + 'let calculate = words.calculate\nprintln(calculate(10))' + if language == 'ny' else + 'value callback is the paragraph words::calculate\nsay callback with 9\n' + 'value calculate is the paragraph words.calculate\nsay calculate with 10') + consumer.write_text(source(language, body, imports), encoding='utf-8', newline='\n') + for encoding, flags in (('text', []), ('binary', ['--emit-binary-nil'])): + output = root / (name + '-value-' + encoding + '.nil') + run([compiler, '--quiet', '--no-stdlib', '-I', library, + '--no-bundle', *flags, '-o', output, consumer]) + result = run([interpreter, '--no-ai', output]) + assert result.stdout == '29\n30\n' and not result.stderr, result + checks += 1 + + provider.write_text(provider_text, encoding='utf-8', newline='\n') + # Privacy and argument checking must use the selected declaration. + for language in ('ny', 'matrix'): + imports = ('import helper\nnamespace words = helper\n' if language == 'ny' + else 'read helper as words\n') + for case, ny_call, matrix_call, message in ( + ('private', 'words::hidden(1)', 'words::hidden with 1', 'private to module'), + ('arity', 'words::calculate(1, 2)', 'words::calculate with 1, 2', 'argument'), + ('type', 'words::calculate("bad")', 'words::calculate with "bad"', 'type'), + ('unknown', 'words::missing(1)', 'words::missing with 1', 'Undefined identifier'), + ): + path = root / f'reject-{provider_language}-{case}.{language}' + body = 'println(' + ny_call + ')' if language == 'ny' else 'say ' + matrix_call + path.write_text(source(language, body, imports), encoding='utf-8', newline='\n') + common = [compiler, '--no-stdlib', '-I', search] + analysis = run([*common, '--analyze', path], 1) + payload = json.loads(analysis.stdout) + assert not payload['success'] and any( + message.lower() in item['message'].lower() and item['severity'] == 'error' + for item in payload['diagnostics']), payload + output = root / 'protected.nil' + output.write_bytes(b'previous artifact') + rejected = run([*common, '--no-bundle', '-o', output, path], 1) + assert message.lower() in rejected.stderr.lower(), rejected + assert output.read_bytes() == b'previous artifact' + checks += 2 + + # Identical alias spellings in distinct modules must not leak. A same- + # named local function still takes precedence over imported functions. + scope = root / 'scope' + scope.mkdir() + for module, offset in (('left', 10), ('right', 20)): + (scope / (module + '.ny')).write_text( + f'module {module}\npub fn calculate(value: i32) -> i32\n' + f'return value + {offset}\nend fn\n', encoding='utf-8', newline='\n') + for module, target in (('first', 'left'), ('second', 'right')): + (scope / (module + '.ny')).write_text( + f'module {module}\nimport {target}\nnamespace words = {target}\n' + 'pub fn invoke() -> i32\nreturn words::calculate(1)\nend fn\n', + encoding='utf-8', newline='\n') + path = root / 'scope.ny' + path.write_text('module entry\nimport first\nimport second\nimport left\n' + 'namespace words = left\nnamespace chained = words\n' + 'fn calculate(value: i32) -> i32\nreturn value + 30\nend fn\n' + 'fn main() -> i32\nprintln(first::invoke())\nprintln(second::invoke())\n' + 'println(chained::calculate(2))\nprintln(calculate(3))\nreturn 0\nend fn\n', + encoding='utf-8', newline='\n') + routes(path, scope, '11\n21\n12\n33\n', 'module-scope') + + path = root / 'object-shadow.ny' + path.write_text('module shadow\nimport left\nnamespace words = left\n' + 'struct Holder\n value: i32\nend struct\n' + 'impl Holder\n fn calculate(self, input: i32) -> i32\n' + 'return self.value + input\nend fn\nend impl\n' + 'fn main() -> i32\nif true then\n' + 'let words = Holder { value: 100 }\nprintln(words.calculate(4))\nend if\n' + 'println(words.calculate(5))\nreturn 0\nend fn\n', + encoding='utf-8', newline='\n') + routes(path, scope, '104\n15\n', 'object-shadow') + + # Canonical and legacy standard-library aliases resolve to one owner. + for language in ('ny', 'matrix'): + imports = ('import nil.std.text\nnamespace words = ny.lang.text\n' + if language == 'ny' else 'read ny.lang.text as words\n') + body = ('println(words::substring("alpha", 1, 2))' if language == 'ny' + else 'say words::substring with "alpha", 1, 2') + path = root / ('standard.' + language) + path.write_text(source(language, body, imports), encoding='utf-8', newline='\n') + routes(path, stdlib, 'lp\n', 'standard-' + language) + + # The bare name is the canonical identity of a root declaration, not + # an expendable compatibility alias for the last similarly named + # module function. Both input orders must specialize the root body. + entry = root / 'root-function.ny' + entry.write_text('fn choose(input: T) -> T\nreturn input\nend fn\n' + 'fn main() -> i32\nprintln(choose(7))\n' + 'println(choose(8))\nreturn 0\nend fn\n', + encoding='utf-8', newline='\n') + unrelated = root / 'unrelated-function.ny' + unrelated.write_text('module unrelated\npub fn choose(input: i32) -> i32\n' + 'return input + 90\nend fn\n', encoding='utf-8', newline='\n') + for order, inputs in enumerate(((entry, unrelated), (unrelated, entry))): + variants = [('text', []), ('binary', ['--emit-binary-nil'])] + if args.llvm == 'ON': + variants += [('aot', ['--native']), ('jit', ['--native', '--jit'])] + for route, flags in variants: + output = root / (f'root-function-{order}-{route}' + + ('.exe' if route == 'aot' and os.name == 'nt' else '.nil')) + compiled = run([compiler, '--quiet', '--no-stdlib', '--no-bundle', + *flags, '-o', output, *inputs]) + result = (compiled if route == 'jit' else run([output]) if route == 'aot' + else run([interpreter, '--no-ai', output])) + assert result.stdout == '7\n8\n' and not result.stderr, (order, route, result) + checks += 1 + + print(f'module alias contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/native_symbol_surface.py b/tests/tools/native_symbol_surface.py index 750b32f..ec5f184 100644 --- a/tests/tools/native_symbol_surface.py +++ b/tests/tools/native_symbol_surface.py @@ -311,8 +311,7 @@ def main() -> int: ' let b: text = "right";\n' ' if a == b then\n return 1;\n end if\n' ' return 0;\n}\n') - compare, _ = emit(args.compiler, args.assembler, root, 'compare', - comparing) + compare, _ = emit_case('compare', comparing) assert compare_import in compare, ( 'a hosted program that compares text must order bytes through ' f'libc; imports: {sorted(compare)}') @@ -322,8 +321,7 @@ def main() -> int: f'unexpected: {sorted(compare - runtime_abi - {compare_import})}') checks += 1 - free_compare, _ = emit(args.compiler, args.assembler, root, - 'free_compare', comparing, freestanding=True) + free_compare, _ = emit_case('free_compare', comparing, freestanding=True) assert freestanding_compare_import in free_compare, ( 'a freestanding program that compares text must order bytes ' 'through the runtime; imports: ' diff --git a/tests/tools/parallel_process_contract.py b/tests/tools/parallel_process_contract.py index b53c4ea..454478f 100644 --- a/tests/tools/parallel_process_contract.py +++ b/tests/tools/parallel_process_contract.py @@ -3,6 +3,7 @@ import argparse from contextlib import contextmanager +import errno import json import os from pathlib import Path @@ -27,7 +28,7 @@ std::string prefix(const std::string &text) { if (text.empty()) return "-"; std::ostringstream output; - for (unsigned char c : text.substr(0, 32)) + for (unsigned char c : text.substr(0, 128)) output << std::hex << std::setw(2) << std::setfill('0') << unsigned(c); return output.str(); } @@ -217,15 +218,17 @@ def process_diagnostic(returncode, output, error): f'stdout={output!r}\nstderr={error!r}') -def run_driver(call, **kwargs): +def run_driver(call, *, record_directory=None, **kwargs): completed = subprocess.run(call, text=True, capture_output=True, **console_options(), **kwargs) - record_driver(call, completed.returncode, completed.stdout, completed.stderr) + record_driver(call, completed.returncode, completed.stdout, completed.stderr, + directory=record_directory) return completed -def record_driver(call, returncode, output, error): - (Path(call[2]) / 'driver-result.json').write_text(json.dumps({ +def record_driver(call, returncode, output, error, *, directory=None): + output_directory = Path(call[2]) if directory is None else directory + (output_directory / 'driver-result.json').write_text(json.dumps({ 'command': call, 'returncode': returncode, 'exitHex': f'0x{returncode & 0xffffffff:08x}', 'stdout': output, 'stderr': error, @@ -265,6 +268,31 @@ def command(name, jobs, modes): return case, [str(driver), str(jobs), str(case), sys.executable, str(worker), *modes] + if os.name != 'nt': + # These exercise the real fork/exec path, preserving the setup + # failure distinction even when no child program has started. + case, call = command('missing-working-directory', 1, ['queued']) + call[2] = str(case / 'absent') + completed = run_driver(call, record_directory=case, timeout=10) + assert completed.returncode == 0, completed + record = results(completed.stdout)[0] + expected = f'nilbuild: child setup failed at chdir (errno={errno.ENOENT})\n' + assert record == {'status': 126, 'started': True, 'cancelled': False, + 'outsize': 0, 'errsize': len(expected), + 'out': '', 'err': expected}, record + assert not (case / 'started-0').exists() + + case, call = command('missing-executable', 1, ['queued']) + call[3] = str(case / 'absent-tool') + completed = run_driver(call, timeout=10) + assert completed.returncode == 0, completed + record = results(completed.stdout)[0] + expected = 'nilbuild: cannot execute child tool\n' + assert record == {'status': 127, 'started': True, 'cancelled': False, + 'outsize': 0, 'errsize': len(expected), + 'out': '', 'err': expected}, record + assert not (case / 'started-0').exists() + for jobs, count, delayed in ((1, 5, False), (2, 5, False), (2, 2, True)): case, call = command(f'success-{jobs}' + ('-delayed' if delayed else ''), jobs, ['success'] * count) diff --git a/tests/tools/project_build_contract.py b/tests/tools/project_build_contract.py index 4b3fede..4cfae91 100644 --- a/tests/tools/project_build_contract.py +++ b/tests/tools/project_build_contract.py @@ -163,6 +163,22 @@ def invoke(command, *flags, status=0, cwd=root, explicit_tools=True, sdk=True, try: result = subprocess.run(call, cwd=cwd, text=True, capture_output=True, encoding='utf-8', timeout=timeout, env=environment) + except subprocess.TimeoutExpired as error: + for name, output in [('stdout', error.stdout), ('stderr', error.stderr)]: + limit = 32 * 1024 + if not output: + print(f'nilbuild contract: timeout {name}: ', flush=True) + continue + retained = output[:limit] + if isinstance(retained, bytes): + retained = retained.decode('utf-8', errors='replace') + encoded = retained.encode('utf-8', errors='replace') + truncated = len(output) > limit or len(encoded) > limit + retained = encoded[:limit].decode('utf-8', errors='ignore') + detail = f'truncated to {limit} UTF-8 bytes' if truncated else 'retained output' + print(f'nilbuild contract: timeout {name} ({detail}):', flush=True) + print(retained, flush=True) + raise finally: if measured_build: print(f'nilbuild contract: {command} elapsed {time.monotonic() - started:.3f}s', flush=True) diff --git a/tests/tools/rooted_file_snapshot_contract.py b/tests/tools/rooted_file_snapshot_contract.py new file mode 100644 index 0000000..d1cf8c0 --- /dev/null +++ b/tests/tools/rooted_file_snapshot_contract.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +"""Bounded public snapshot/byte-conversion routes with independent host oracles. + +This is a source-library regression, not installed SDK or release qualification. +No server is started. Raw process evidence and the owned fixture are retained. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import sys +import tempfile +import time + +import ordinary_io_parity_contract as support + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'tests')) +from native_output_staging import native_output_path + +SNAPSHOT_OUTPUT = b'snapshot-content-ok\nsnapshot-errors-ok\nsnapshot-links-ok\n' +CONVERSION_OUTPUT = b'from-bytes-ok\n' +NATIVE_REJECTION = b"unsupported native annotation '@intrinsic(\"text.from_bytes\")'" +SNAPSHOT_REJECTION = b'file.read_rooted_snapshot requires (text,text,i64) -> Result' +SOURCES = ('rooted-file-snapshot.ny', 'text-from-bytes.ny', 'text-from-bytes-native-reject.ny', + 'rooted-file-snapshot-invalid-schema.ny', 'rooted-file-snapshot-invalid-signature.ny') + + +def snapshot_signature(root: Path) -> dict: + result = support.inventory(root, maximum_entries=32, maximum_file=1024) + for name, entry in result.items(): + path = root / name + if entry['kind'] == 'file': + entry['modified_ns'] = path.stat().st_mtime_ns + elif entry['kind'] == 'link-or-reparse': + entry['target'] = os.readlink(path) + return result + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for name in ('compiler', 'interpreter', 'nilstd'): + parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + destination = parser.add_mutually_exclusive_group() + destination.add_argument('--output', type=Path, help='Fresh exact evidence directory') + destination.add_argument('--output-parent', type=Path, help='Retain a fresh child here') + args = parser.parse_args() + compiler = args.compiler.resolve(strict=True) + interpreter = args.interpreter.resolve(strict=True) + nilstd = args.nilstd.resolve(strict=True) + if args.output_parent: + parent = args.output_parent.resolve() + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix='rooted-file-snapshot-', dir=parent)) + elif args.output: + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False) + else: + output = Path(tempfile.mkdtemp(prefix='rooted-file-snapshot-')) + work, logs = output / 'work', output / 'logs' + work.mkdir() + logs.mkdir() + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + ownership = support.load_ownership(ROOT) + deadline = time.monotonic() + 300 + inputs = {name: {'path': str(path), **support.file_record(path)} for name, path in + [('compiler', compiler), ('interpreter', interpreter), + *[(name, ROOT / 'tests/language' / name) for name in SOURCES], + ('file_library', nilstd / 'io/file.ny'), + ('text_library', nilstd / 'text/string_utils.ny'), + ('contract', Path(__file__).resolve()), + ('process_owner', ROOT / 'validation/ny-3d/scripts/debugger_process.py'), + ('process_support', ROOT / 'tests/tools/ordinary_io_parity_contract.py')]} + report = {'schema': 'nil.rooted-file-snapshot.v1', 'status': 'FAIL', + 'inputs': inputs, 'nilstd': str(nilstd), 'commands': [], + 'snapshot_routes': [], 'conversion_routes': [], 'native_rejections': [], + 'unbox_rejections': [], + 'llvm_enabled': args.llvm == 'ON', 'whole_seconds': 300, + 'scope': 'Source-library interpreter/native regression. FileSnapshot content is a byte array on every route; text.from_bytes is interpreter-only.', + 'link_cases': 'required; POSIX file/directory symlinks, Windows directory junctions (no symlink privilege required)', + 'work_directory_retained': True} + + def run(name, command, expected=b'', limit=60, rejection=None): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise AssertionError('whole snapshot contract deadline exhausted') + row = support.run_process(ownership, [str(value) for value in command], + work, environment, logs, name, min(limit, remaining)) + report['commands'].append(row) + stdout = (logs / row['stdout']).read_bytes() + stderr = (logs / row['stderr']).read_bytes() + if not row['cleanup_verified'] or row.get('timed_out') or row.get('error'): + raise AssertionError(name + ': bounded process cleanup failed') + if rejection: + if row.get('exit_code', 0) <= 0 or stdout or rejection not in stderr: + raise AssertionError(name + ': native compilation did not fail for the exact expected contract') + elif row['status'] != 'PASS' or stderr or (expected is not None and stdout != expected): + raise AssertionError(name + ': exit/stdout/stderr contract failed') + return row + + try: + fixture = work / 'fixtures' + fixture.mkdir() + rooted = fixture / 'root café λ' + rooted.mkdir() + (rooted / 'nested').mkdir() + outside = fixture / 'outside' + outside.mkdir() + sentinel = outside / 'sentinel.bin' + sentinel.write_bytes(b'outside fixture must never be returned\x00\xff') + if os.name == 'nt': + for name in ('linked.bin', 'via-link'): + link = rooted / name + run('create-junction-' + name, + ['cmd.exe', '/d', '/c', 'mklink', '/J', link, outside], expected=None) + if not getattr(link.lstat(), 'st_file_attributes', 0) & 0x400: + raise AssertionError('Windows fixture is not a reparse point') + report['link_fixture_kind'] = 'directory junctions: final reparse entry and intermediate directory escape' + else: + (rooted / 'linked.bin').symlink_to(sentinel) + (rooted / 'via-link').symlink_to(outside, target_is_directory=True) + report['link_fixture_kind'] = 'final file symlink and intermediate directory symlink' + payload = rooted / 'nested/café-λ.bin' + empty = rooted / 'empty.bin' + empty.write_bytes(b'') + fixed_time = 1_600_000_000_123_000_000 + os.utime(empty, ns=(fixed_time, fixed_time)) + sources = {} + for name in SOURCES: + source = work / name + source.write_bytes((ROOT / 'tests/language' / name).read_bytes()) + sources[name] = source + base = [compiler, '--quiet', '--no-stdlib', '--sdk-path', nilstd] + routes = [] + for encoding in ('text', 'binary'): + flags = [] if encoding == 'text' else ['--emit-binary-nil'] + nil = work / ('snapshot-' + encoding + '.nil') + run('compile-snapshot-' + encoding, [*base, '--no-bundle', *flags, '-o', nil, + sources['rooted-file-snapshot.ny']]) + if nil.read_bytes().startswith(b'NIL\0') != (encoding == 'binary'): + raise AssertionError('compiled snapshot encoding differs') + routes.append((encoding + '-interpreter', [interpreter, '--no-ai', nil, '--'])) + if args.llvm == 'ON': + native = work / 'snapshot-native' + run('compile-snapshot-native', [*base, '--native', '-o', native, + sources['rooted-file-snapshot.ny']]) + routes.append(('llvm-aot', [native_output_path(native)])) + routes.append(('llvm-jit', [*base, '--native', '--jit', '-o', work / 'snapshot-jit', + sources['rooted-file-snapshot.ny'], '--'])) + + initial_digest = None + for stage, seed in (('initial', 19), ('same-size-time-replacement', 21)): + data = bytes((index * 73 + seed) % 256 for index in range(256)) + payload.write_bytes(data) + os.utime(payload, ns=(fixed_time, fixed_time)) + stamp = payload.stat().st_mtime_ns // 1_000_000 + if empty.stat().st_mtime_ns // 1_000_000 != stamp: + raise AssertionError('host did not preserve equal fixture timestamps') + digest = hashlib.sha256(data).hexdigest() + if initial_digest is None: + initial_digest = digest + elif digest == initial_digest: + raise AssertionError('same-size/time replacement failed to change content digest') + before = snapshot_signature(fixture) + arguments = [rooted, str(stamp), digest, str(seed)] + for route, command in routes: + row = run(stage + '-' + route, [*command, *arguments], SNAPSHOT_OUTPUT) + if snapshot_signature(fixture) != before: + raise AssertionError('snapshot read changed the owned fixture') + report['snapshot_routes'].append({'stage': stage, 'route': route, 'status': 'PASS', + 'bytes': len(data), 'sha256': digest, 'modified_ms': stamp, + 'exact_payload_bytes_checked': 256, 'empty_file_checked': True, + 'descendant_and_final_links_rejected': True, 'namespace_unchanged': True, + 'elapsed_seconds': row['elapsed_seconds']}) + report[stage + '_namespace'] = before + + for route, command in routes: + expected = (b"anything type mismatch: expected 'array', got 'array'" + if route.startswith('llvm-') else + b"anything contains 'array', cannot extract 'array'") + run('wrong-element-' + route, [*command, *arguments, 'wrong-element'], rejection=expected) + if snapshot_signature(fixture) != before: + raise AssertionError('rejected extraction changed the owned fixture') + report['unbox_rejections'].append({'route': route, 'status': 'PASS', + 'reason': expected.decode()}) + + for encoding in ('text', 'binary'): + flags = [] if encoding == 'text' else ['--emit-binary-nil'] + nil = work / ('conversion-' + encoding + '.nil') + run('compile-conversion-' + encoding, [*base, '--no-bundle', *flags, '-o', nil, + sources['text-from-bytes.ny']]) + if nil.read_bytes().startswith(b'NIL\0') != (encoding == 'binary'): + raise AssertionError('compiled conversion encoding differs') + row = run('conversion-' + encoding, [interpreter, '--no-ai', nil], CONVERSION_OUTPUT) + report['conversion_routes'].append({'route': encoding + '-interpreter', 'status': 'PASS', + 'all_256_byte_values': True, 'copy_independent_of_source_mutation': True, + 'empty_and_1MiB_payloads': True, 'elapsed_seconds': row['elapsed_seconds']}) + if args.llvm == 'ON': + for route, flags in (('llvm-aot', []), ('llvm-jit', ['--jit'])): + target = work / ('conversion-rejected-' + route) + run('conversion-rejected-' + route, [*base, '--native', *flags, '-o', target, + sources['text-from-bytes-native-reject.ny']], + rejection=NATIVE_REJECTION) + if target.exists() or native_output_path(target).exists(): + raise AssertionError('rejected binary text conversion published an executable') + report['native_rejections'].append({'route': route, 'status': 'PASS', + 'case': 'text.from_bytes', + 'reason': NATIVE_REJECTION.decode()}) + for case in ('invalid-schema', 'invalid-signature'): + for route, flags in (('llvm-aot', []), ('llvm-jit', ['--jit'])): + target = work / ('snapshot-rejected-' + case + '-' + route) + run('snapshot-rejected-' + case + '-' + route, + [*base, '--native', *flags, '-o', target, + sources['rooted-file-snapshot-' + case + '.ny']], + rejection=SNAPSHOT_REJECTION) + if target.exists() or native_output_path(target).exists(): + raise AssertionError('invalid snapshot ABI published an executable') + report['native_rejections'].append({'route': route, 'case': case, + 'status': 'PASS', 'reason': SNAPSHOT_REJECTION.decode()}) + if len(report['snapshot_routes']) != (8 if args.llvm == 'ON' else 4): + raise AssertionError('snapshot route inventory incomplete') + if len(report['unbox_rejections']) != (4 if args.llvm == 'ON' else 2): + raise AssertionError('wrong-element extraction route inventory incomplete') + if len(report['conversion_routes']) != 2 or len(report['native_rejections']) != (6 if args.llvm == 'ON' else 0): + raise AssertionError('conversion route inventory incomplete') + for item in inputs.values(): + if support.file_record(Path(item['path'])) != {key: item[key] for key in ('bytes', 'sha256')}: + raise AssertionError('input changed during contract') + report['status'] = 'PASS' + except Exception as error: + report['error'] = str(error) + report['cleanup_verified'] = all(row.get('cleanup_verified') is True for row in report['commands']) + (output / 'report.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') + print(report['status'] + ': ' + str(output / 'report.json')) + if report['status'] != 'PASS': + print(report.get('error', 'snapshot contract failed'), file=sys.stderr) + return 0 if report['status'] == 'PASS' else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/tools/tuple_array_contract.py b/tests/tools/tuple_array_contract.py index 3c1fc1b..af0b1c2 100644 --- a/tests/tools/tuple_array_contract.py +++ b/tests/tools/tuple_array_contract.py @@ -61,6 +61,43 @@ def run(command, status=0): assert analysis['success'], analysis['diagnostics'] checks += 1 + # F33 originally sent literal/computed arrays to an absent iterator + # intrinsic. Keep the scalar/text cases alongside tuple-array lowering: + # computed arrays are evaluated once and empty arrays do not enter. + for language in ('ny', 'matrix'): + ny = language == 'ny' + declarations = ( + 'fn fresh() -> array\nprintln("once")\nreturn ["returned","owned"]\nend fn\n' + 'fn empty() -> array\nreturn []\nend fn\n' if ny else + 'fresh returns array of text begin paragraph\nsay "once"\ngive ["returned","owned"]\nend paragraph\n' + 'empty returns array of number begin paragraph\ngive []\nend paragraph\n') + body = ( + 'for word in ["alpha","beta"]\nprintln(word)\nend for\n' + 'let mut saved: text = "missing"\n' + 'for word in fresh()\nprintln(word)\nsaved = word\nend for\nprintln(saved)\n' + 'for wide in [1 as i64,4294967296]\nprintln(wide)\nend for\n' + 'for scalar in [1.5,-2.25]\nprintln(scalar)\nend for\n' + 'for unused in empty()\nprintln("unexpected")\nend for\n' + 'println("done")' if ny else + 'repeat for each word in ["alpha","beta"]\nsay word\nend repeat\n' + 'variable saved as text is "missing"\n' + 'repeat for each word in (fresh with nothing)\nsay word\nset saved to word\nend repeat\nsay saved\n' + 'repeat for each wide in [(1 becomes number),4294967296]\nsay wide\nend repeat\n' + 'repeat for each scalar in [1.5,negative 2.25]\nsay scalar\nend repeat\n' + 'repeat for each unused in (empty with nothing)\nsay "unexpected"\nend repeat\n' + 'say "done"') + path = root / ('array-expression-iteration.' + language) + path.write_text(program(language, body, declarations), encoding='utf-8', newline='\n') + stdout = path.with_suffix('.stdout') + stdout.write_text('alpha\nbeta\nonce\nreturned\nowned\nowned\n1\n4294967296\n1.5\n-2.25\ndone\n', newline='\n') + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', path, + '--expected-stdout', stdout, '--expected-exit', '0', + '--routes', 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / ('array-expression-iteration-' + language), '--strict']) + checks += 6 if args.llvm == 'ON' else 4 + # Cross-frontend consumers keep tuple schemas and array element identity, # including a binary provider whose original source file is absent. for provider_language in ('ny', 'matrix'): diff --git a/tests/tools/tuple_array_nil_contract.py b/tests/tools/tuple_array_nil_contract.py index b60ac80..a4d4af6 100644 --- a/tests/tools/tuple_array_nil_contract.py +++ b/tests/tools/tuple_array_nil_contract.py @@ -260,7 +260,7 @@ def native(path, name, output, binary): success(result, "1\n") else: assert result.returncode > 0 and not result.stdout, result - assert "expected a fully initialized value of exact type 'Result'" in result.stderr, result + assert "requires the standard Result ABI" in result.stderr, result checks += 1 if args.llvm == "ON": native(path, "valid", expected, binary) diff --git a/tests/tools/webview_intrinsic_contract.py b/tests/tools/webview_intrinsic_contract.py new file mode 100644 index 0000000..6134193 --- /dev/null +++ b/tests/tools/webview_intrinsic_contract.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Reject forged WebView declarations before loading any native provider.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', required=True, type=Path) + parser.add_argument('--interpreter', required=True, type=Path) + parser.add_argument('--llvm', required=True, choices=('ON', 'OFF')) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + environment = {k: v for k, v in os.environ.items() if not k.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-webview-abi-') as directory: + work = Path(directory) + base = [compiler, '--quiet', '--sdk-path', ROOT/'nilstd/src'] + + def run(command, status=0): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=work, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60) + assert result.returncode == status, (result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + imported = 'import nil.std.core.result\n' + entry = 'fn main() -> i32\n return 0\nend fn\n' + invalid = { + 'unknown': ('@intrinsic("webview.v1.unknown")\nfn provider() -> bool\n', 'Unknown WebView intrinsic'), + 'arity': (imported+'@intrinsic("webview.v1.configure")\nfn provider() -> Result\n', 'exact WebView ABI'), + 'width': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i32) -> Result\n', 'exact WebView ABI'), + 'number-result': (imported+'@intrinsic("webview.v1.poll")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'text-result': (imported+'@intrinsic("webview.v1.event_text")\nfn provider(handle:i64,field:text) -> Result\n', 'exact WebView ABI'), + 'error-payload': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'reference': (imported+'@intrinsic("webview.v1.show")\nfn provider(ref handle:i64) -> Result\n', 'exact WebView ABI'), + 'default': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64=0) -> Result\n', 'exact WebView ABI'), + 'variadic': (imported+'@intrinsic("webview.v1.show")\nfn provider(..handles:i64) -> Result\n', 'exact WebView ABI'), + 'generic': (imported+'@intrinsic("webview.v1.show")\nfn provider(handle:i64) -> Result\n', 'exact WebView ABI'), + 'impostor': ('''module impostor +enum Result + Ok(T) + Error(E) +end enum +@intrinsic("webview.v1.show") +fn provider(handle:i64) -> Result +''', 'exact WebView ABI'), + } + for name, (declaration, diagnostic) in invalid.items(): + source, output = work/(name+'.ny'), work/(name+'.nil') + source.write_text(declaration+entry, newline='\n') + output.write_bytes(b'previous artifact') + result = run([*base, '--no-bundle', '-o', output, source], 1) + assert diagnostic in result.stderr + assert output.read_bytes() == b'previous artifact' + + for name, declaration, expression in ( + ('arity', imported+'@intrinsic("webview.v1.configure")\nfn provider() -> Result\n', 'provider()'), + ('return', '@intrinsic("webview.v1.poll")\nfn provider(handle:i64) -> i64\n', 'provider(0)'), + ): + source, output = work/('unchecked-'+name+'.ny'), work/('unchecked-'+name+'.nil') + source.write_text(declaration+'fn main() -> i32\n let value = '+expression+'\n return 0\nend fn\n', newline='\n') + run([*base, '--no-typecheck', '--no-bundle', '-o', output, source]) + result = run([interpreter, '--no-ai', output], 1) + assert 'WebView ABI' in result.stderr + if args.llvm == 'ON': + for flags in ([], ['--jit']): + output.write_bytes(b'previous artifact') + result = run([*base, '--no-typecheck', '--native', *flags, '-o', output, source], 1) + assert 'WebView ABI' in result.stderr + assert output.read_bytes() == b'previous artifact' + + source = work/'checked.ny' + source.write_text(imported+'''@intrinsic("webview.v1.configure") +fn configure(path:text) -> Result +@intrinsic("webview.v1.event_text") +fn event_text(snapshot:i64,field:text) -> Result +fn main() -> i32 + match configure("relative-provider") + Result.Ok(value) -> return 8 + Result.Error(message) -> println("checked WebView configuration failure") + end match + match event_text(0,"payload_json") + Result.Ok(value) -> return 9 + Result.Error(message) -> println("checked WebView event failure") + end match + return 0 +end fn +''', newline='\n') + for route in ['text', 'binary', 'bundle'] + (['native', 'jit'] if args.llvm == 'ON' else []): + output = work/('checked-'+route) + flags = (['--native', '--jit'] if route == 'jit' else ['--native'] if route == 'native' + else [] if route == 'bundle' else ['--no-bundle']) + if route == 'binary': flags += ['--emit-binary-nil'] + result = run([*base, *flags, '-o', output, source]) + if route != 'jit': + executable = output.with_suffix('.exe') if os.name == 'nt' and route in ('native', 'bundle') else output + command = [interpreter, '--no-ai', output] if route in ('text', 'binary') else [executable] + result = run(command) + assert result.stdout == 'checked WebView configuration failure\nchecked WebView event failure\n' + assert not result.stderr + print(f'WebView intrinsic ABI: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/webview_provider_fixture.cpp b/tests/webview_provider_fixture.cpp new file mode 100644 index 0000000..7aadf46 --- /dev/null +++ b/tests/webview_provider_fixture.cpp @@ -0,0 +1,89 @@ +/* Synthetic ABI peer, never a browser provider. SPDX-License-Identifier: MIT */ +#define NILWEBVIEW_PROVIDER_BUILD +#include "../common/webview_provider_v1.h" +#include +#include +#include + +struct nilwv_context_v1 { + bool open = false, event = false; + std::int64_t kind = NILWV_EVENT_READY, operation = 0; + std::string payload, detail, control; +}; +namespace { +std::atomic contexts{0}, releases{0}; +void ok(nilwv_result_v1 *r, std::int64_t value = 1) { *r = {sizeof(*r), 0, value, {nullptr, 0}}; } +void bad(nilwv_result_v1 *r) { static const char text[] = "synthetic invalid handle"; *r = {sizeof(*r), NILWV_E_HANDLE, 0, {text, sizeof(text)-1}}; } +void probe(nilwv_result_v1 *r) { ok(r); } +void create(nilwv_context_v1 **c, nilwv_result_v1 *r) { *c = new nilwv_context_v1; ++contexts; ok(r); } +void destroy(nilwv_context_v1 *c) { delete c; --contexts; } +void window(nilwv_context_v1 *c, nilwv_text_v1, std::int64_t, std::int64_t, nilwv_result_v1 *r) { + if (c->open) { bad(r); return; } + c->open = c->event = true; c->kind = NILWV_EVENT_READY; ok(r, 17); +} +void show(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { if (c->open && w == 17) ok(r); else bad(r); } +void navigate(nilwv_context_v1 *c, std::int64_t w, nilwv_text_v1, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } + c->event = true; c->kind = NILWV_EVENT_NAVIGATION_COMPLETED; c->operation = 31; c->payload = "\"about:blank\""; ok(r, 31); +} +void script(nilwv_context_v1 *c, std::int64_t w, nilwv_text_v1 body, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } + c->event = true; c->kind = NILWV_EVENT_SCRIPT_COMPLETED; c->operation = 32; + const std::string value(body.data, body.size); + c->control = value; + c->payload = value == "bad-json" ? "{invalid" : "{\"answer\":42}"; + if (value == "surrogate") c->payload = "\"\\ud800\""; + if (value == "deep33" || value == "deep64" || value == "deep65") { + const auto depth = value == "deep33" ? 33 : value == "deep64" ? 64 : 65; + c->payload = std::string(depth, '[') + "0" + std::string(depth, ']'); + } + if (value == "bad-message") { c->kind = NILWV_EVENT_PAGE_MESSAGE; c->operation = 0; c->payload.clear(); } + c->detail = value == "bad-text" ? std::string("\xc0\xaf", 2) : ""; + ok(r, 32); +} +void poll(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } ok(r, c->event ? 19 : 0); +} +void number(nilwv_context_v1 *c, std::int64_t e, nilwv_text_v1 property, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + const std::string field(property.data, property.size); + if (field == "window") ok(r,17); + else if (field == "kind") ok(r,c->kind); + else if (field == "sequence") ok(r,1); + else if (field == "operation") ok(r,c->operation); + else if (field == "value_kind") ok(r,c->payload.empty() ? NILWV_VALUE_NONE : NILWV_VALUE_JSON); + else if (field == "source_kind") ok(r,c->control == "bad-origin" ? NILWV_SOURCE_NATIVE_ORIGIN : c->control == "bad-url" ? NILWV_SOURCE_NATIVE_URL : 0); + else if (field == "frame_kind") ok(r,c->control == "bad-frame" ? NILWV_FRAME_MAIN : 0); + else if (field == "failure_kind") ok(r,0); + else bad(r); +} +void text(nilwv_context_v1 *c, std::int64_t e, nilwv_text_v1 property, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + const std::string field(property.data, property.size); + ok(r,0); + if (field == "payload_json") r->text = {c->payload.data(), c->payload.size()}; + else if (field == "detail") r->text = {c->detail.data(), c->detail.size()}; + else if (field != "source_url" && field != "source_origin") bad(r); +} +void release(nilwv_context_v1 *c, std::int64_t e, nilwv_result_v1 *r) { + if (!c->event || e != 19) { bad(r); return; } + c->event = false; c->payload.assign("released storage"); c->detail.assign("released storage"); ++releases; ok(r); +} +void close(nilwv_context_v1 *c, std::int64_t w, nilwv_result_v1 *r) { + if (!c->open || w != 17) { bad(r); return; } c->open = c->event = false; ok(r); +} +const nilwv_api_v1 api{ +#ifdef NILWV_FIXTURE_BAD_ABI + 2, +#else + NILWV_ABI_V1, +#endif + sizeof(nilwv_api_v1), 0, "synthetic", "test-only", probe, create, destroy, + window, show, navigate, navigate, script, poll, number, text, release, close}; +} +extern "C" NILWV_EXPORT const nilwv_api_v1 *NILWV_CALL +nilwebview_provider_v1_get_api(std::uint32_t version, std::uint32_t size) { + return version == NILWV_ABI_V1 && size <= sizeof(api) ? &api : nullptr; +} +extern "C" NILWV_EXPORT std::int64_t nilwebview_fixture_live_contexts() { return contexts; } +extern "C" NILWV_EXPORT std::int64_t nilwebview_fixture_releases() { return releases; } diff --git a/tests/webview_runtime_tests.cpp b/tests/webview_runtime_tests.cpp new file mode 100644 index 0000000..73aef30 --- /dev/null +++ b/tests/webview_runtime_tests.cpp @@ -0,0 +1,97 @@ +/* Checked provider ownership/ABI controls, no desktop. SPDX-License-Identifier: MIT */ +#include "webview_runtime.hpp" +#include +#include +#include +#include +extern "C" std::int64_t nilwebview_fixture_live_contexts(); +extern "C" std::int64_t nilwebview_fixture_releases(); +namespace { +int checks = 0; +void require(bool condition, const char *label) { + ++checks; + if (!condition) { std::cerr << "FAIL: " << label << '\n'; std::exit(1); } +} +} +int main(int argc, char **argv) { + if (argc != 3) return 2; + using ny::webview::Context; + { + Context a, b; + require(!a.window("unset", 640, 480), "unconfigured context"); + require(!a.configure("relative-provider"), "relative provider refused"); + require(!a.configure(argv[2]), "incompatible ABI refused"); + auto configured = a.configure(argv[1]); + require(configured && configured.number == 0, "zero capabilities is successful configuration"); + require(bool(a.configure(argv[1])), "same provider configuration is idempotent"); + require(!a.configure(argv[2]), "cannot switch an active provider"); + require(bool(b.configure(argv[1])), "independent context"); + require(nilwebview_fixture_live_contexts() == 2, "exact live contexts"); + require(!a.window("bad",0,480), "zero dimension rejected"); + require(!a.window(std::string("x\0y",3),640,480), "NUL title rejected"); + require(!a.window(std::string("\xc0\xaf",2),640,480), "invalid UTF-8 title rejected"); + auto wa = a.window("first",640,480), wb = b.window("second",640,480); + require(wa && wb && wa.number != wb.number, "context handles distinct despite repeated native handles"); + require(!a.show(wb.number) && !b.show(wa.number), "cross-context window handles refused"); + bool wrong_thread = false; + std::thread other([&] { wrong_thread = !a.show(wa.number); }); other.join(); + require(wrong_thread, "foreign thread rejected"); + require(bool(a.show(wa.number)), "same-thread operation"); + auto ready = a.poll(wa.number); + require(ready && ready.number > 0, "ready copied"); + require(a.event_number(ready.number,"window").number == wa.number, "native window translated"); + require(a.event_number(ready.number,"kind").number == 1, "event kind preserved"); + require(!a.event_number(ready.number,"unknown"), "unknown number field refused"); + require(!a.event_text(ready.number,"unknown"), "unknown text field refused"); + require(!b.event_number(ready.number,"kind"), "cross-context event handle refused"); + require(nilwebview_fixture_releases() == 1, "provider event released after copy"); + require(a.poll(wa.number).number == 0, "empty event queue"); + require(bool(a.release_event(ready.number)), "copied event released"); + require(!a.release_event(ready.number), "event cannot be released twice"); + require(!a.navigate(wa.number,std::string("x\0y",3)), "NUL operation input rejected"); + auto script = a.evaluate_function(wa.number,"return 42;"); + require(script && script.number == 32, "accepted operation identity"); + auto completed = a.poll(wa.number); + require(completed && completed.number > 0, "script event copied"); + require(a.event_number(completed.number,"operation").number == script.number, "completion identity preserved"); + require(a.event_text(completed.number,"payload_json").text == "{\"answer\":42}", "snapshot survives provider storage mutation"); + require(bool(a.close(wa.number)), "window closed"); + require(!a.event_text(completed.number,"payload_json"), "close invalidates retained snapshots"); + require(!a.close(wa.number) && !a.show(wa.number), "stale window refused"); + require(bool(b.show(wb.number)), "unrelated context remains live"); + a.clear(); b.clear(); + require(nilwebview_fixture_live_contexts() == 0, "explicit context teardown"); + require(bool(a.configure(argv[1])), "context can be reused after terminal cleanup"); + auto w = a.window("invalid-result",640,480); + auto first = a.poll(w.number); a.release_event(first.number); + require(bool(a.evaluate_function(w.number,"bad-json")), "synthetic malformed result accepted asynchronously"); + const auto before = nilwebview_fixture_releases(); + require(!a.poll(w.number), "invalid provider JSON refused"); + require(nilwebview_fixture_releases() == before+1, "malformed event released on error"); + require(!a.show(w.number), "provider protocol fault remains latched"); + a.clear(); + require(bool(a.configure(argv[1])), "teardown resets protocol fault"); + w = a.window("bad-text",640,480); first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,"bad-text"); + require(!a.poll(w.number), "invalid provider UTF-8 refused"); + for (const auto *invalid : {"bad-origin", "bad-url", "bad-frame", "bad-message", "deep65"}) { + a.clear(); a.configure(argv[1]); w = a.window("invalid-event",640,480); + first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,invalid); + const auto released_before = nilwebview_fixture_releases(); + require(!a.poll(w.number), "inconsistent provenance, event kind or depth refused"); + require(nilwebview_fixture_releases() == released_before+1, "invalid snapshot always released"); + } + for (const auto *valid : {"surrogate", "deep33", "deep64"}) { + a.clear(); a.configure(argv[1]); w = a.window("JSON-stringify-result",640,480); + first = a.poll(w.number); a.release_event(first.number); + a.evaluate_function(w.number,valid); + auto found = a.poll(w.number); + require(found && found.number > 0, "bounded JSON.stringify text preserved"); + if (std::string(valid) == "surrogate") + require(a.event_text(found.number,"payload_json").text == "\"\\ud800\"", "escaped lone surrogate remains serialized text"); + } + } + require(nilwebview_fixture_live_contexts() == 0, "destructor cleanup"); + std::cout << checks << " WebView runtime checks passed\n"; +} diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 6bb82bd..2a28993 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Publish compiler and tolerant completion suggestions through one result path, + preventing duplicate names when their asynchronous checks finish differently. + Preserve keyword/snippet suggestions and fallback for unavailable compiler queries. + +- Restore semantic navigation when an included file changes on disk while VS Code + retains an older clean model after its tab closes. Preserve dirty/open include + alias checks and invalidate pending results when arbitrary include tabs change. + - Highlight, indent and fold explicit Matrix `begin block` / `end block` consider arms. The `consider` snippet now includes an explicit block so its body can contain nested `when` conditions; `block` remains an ordinary name @@ -19,8 +27,7 @@ All notable changes to the NIL Framework VS Code extension are documented here. Refresh analysis after project edits in every supported format and recognize optional `projectReferences` in project configuration. -- Pin the VSIX packaging tool's MSAL dependency to patched 7.1.1; the local - dependency audit reports no known vulnerabilities. +- Pin the VSIX packaging tool's MSAL dependency to patched 7.1.1. - Add `.nildata` syntax highlighting, comments, indentation, and folding for the versioned NILData format, with strict JSON scalar and escape highlighting. Keep diff --git a/vscode/README.md b/vscode/README.md index e7c641c..d673563 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -360,6 +360,9 @@ successful check. The extension validates every exported source snapshot against captured buffers or disk before returning a destination, rechecks versions after asynchronous reads, and watches the reached source files. Dirty textual includes with other extensions cannot be overlaid and prevent use of that index. +Clean include models cached after their tabs close defer to verified disk contents. +Open include tabs and their aliases still require matching text; opening or closing +those tabs invalidates pending results, including for extensions such as `.inc`. Member dispatch, fields, type uses, pattern bindings and some function-value or generated references do not yet provide destinations. Expanded Ny units lack @@ -415,6 +418,9 @@ Blank positions, unsupported member/type contexts, parse or import failures, ear failures, ambiguous repeated generic occurrences and binary dependencies retain the tolerant language-server fallback. When compiler candidates are available, its value bindings take precedence while language keywords and snippets remain. +The extension combines those suggestions once per request, so independently timed +compiler and language-server answers cannot publish duplicate bindings. Source or +configuration changes during a request discard the combined result. An older SDK without the query also retains fallback completion. This is an initial identifier-completion profile; general incomplete-code recovery remains future work. diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index 8736d1b..2a1423a 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -9,7 +9,7 @@ import { analysisInvocation, AnalysisResult, createByteRangeMapper, maxAnalysisO parseAnalysisOutput, serializeAnalysisWorkspace } from "./analysisModel"; import { projectForResource } from "./projectContext"; import { isProjectFile } from "./projectModel"; -import { analysisSourcePath, languageDocumentSelector, savedSourcePath, sourceLanguage } from "./languages"; +import { analysisSourcePath, languageDocumentSelector, savedSourcePath } from "./languages"; import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; import { definitionAt, planRename, referencesAt, renamePreservesBindings, SemanticIndex, SemanticLocation, SemanticSource } from "./semanticModel"; @@ -53,6 +53,12 @@ interface CompletionQuery { result: Promise; } +type CompletionLookup = { status: "unavailable" } | { status: "stale" } | + { status: "available"; query: CompletionQuery; completion: CompilerCompletion }; +type TolerantCompletions = (document: vscode.TextDocument, position: vscode.Position, + token: vscode.CancellationToken, context: vscode.CompletionContext) => + Promise; + interface SignatureQuery { job: AnalysisJob; byteOffset: number; @@ -83,15 +89,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, private generation = 0; private tabSources = new Set(); - constructor() { + constructor(private readonly tolerantCompletions: TolerantCompletions = async () => undefined) { this.tabSources = this.openTabSources(); - const tabMembershipChanged = () => { - const sources = this.openTabSources(); - if (sources.size !== this.tabSources.size || [...sources].some(source => !this.tabSources.has(source))) { - this.tabSources = sources; - this.scheduleAll(); - } - }; + const tabMembershipChanged = () => this.updateTabSources(); const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,nildata,json,yaml,yml}"); const changed = (uri: vscode.Uri) => { if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || isProjectFile(uri.fsPath)) this.scheduleAll(); @@ -103,7 +103,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.languages.registerDefinitionProvider(languageDocumentSelector, this), vscode.languages.registerReferenceProvider(languageDocumentSelector, this), vscode.languages.registerRenameProvider(languageDocumentSelector, this), - vscode.languages.registerCompletionItemProvider(languageDocumentSelector, this), + vscode.languages.registerCompletionItemProvider(languageDocumentSelector, this, ".", ":", "_", "-"), vscode.languages.registerSignatureHelpProvider(languageDocumentSelector, this, { triggerCharacters: ["(", ",", " "], retriggerCharacters: [")"] }), @@ -162,10 +162,20 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, usesCompilerDefinitions(document: vscode.TextDocument): boolean { return this.enabled(document); } + private updateTabSources(): void { + const sources = this.openTabSources(); + if (sources.size !== this.tabSources.size || [...sources].some(source => !this.tabSources.has(source))) { + this.tabSources = sources; + this.scheduleAll(); + } + } + private openTabSources(): Set { const sources = new Set(); const add = (uri: vscode.Uri) => { - if (uri.scheme === "untitled" || (uri.scheme === "file" && sourceLanguage(uri.fsPath))) sources.add(uri.toString()); + // Textual includes can have arbitrary extensions. Their open tabs still + // carry editor authority, while supported() limits compiler overlays. + if (uri.scheme === "untitled" || uri.scheme === "file") sources.add(uri.toString()); }; for (const group of vscode.window.tabGroups.all) for (const tab of group.tabs) { if (tab.input instanceof vscode.TabInputText) add(tab.input.uri); @@ -577,7 +587,11 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, const inputs = job.inputs.filter(input => input.identity === path.normalize(source.path)); const models = observed.filter(item => item.identity === path.normalize(source.path)); if (models.some(item => item.dirty && !inputs.some(input => input.document === item.document) && item.document.getText() !== source.text)) return false; - if (!inputs.length && models.some(item => item.document.isDirty || item.document.getText() !== source.text)) return false; + // A retained clean model without a tab is only a disk cache. As in + // workspaceInput/publish, its obsolete text cannot override current disk + // bytes; dirty or open include aliases must still agree with the snapshot. + if (!inputs.length && models.some(item => item.document.isDirty || + (this.tabSources.has(item.document.uri.toString()) && item.document.getText() !== source.text))) return false; if (inputs.length) { if (inputs.some(input => input.text !== source.text)) return false; } else { @@ -622,15 +636,16 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return originSelectionRange && target ? [{ originSelectionRange, targetUri: target.uri, targetRange: target.range, targetSelectionRange: target.range }] : undefined; } - async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { - if (!this.enabled(document) || token.isCancellationRequested) return undefined; + private async compilerCompletion(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + if (token.isCancellationRequested) return { status: "stale" }; + if (!this.enabled(document)) return { status: "unavailable" }; const offset = document.offsetAt(position); const source = document.getText(); // Empty insertion contexts retain the tolerant provider; typed member // prefixes are now resolved by the compiler along with lexical values. - if (!offset || /[\s.:]/.test(source[offset - 1]!)) return undefined; + if (!offset || /[\s.:]/.test(source[offset - 1]!)) return { status: "unavailable" }; const byteOffset = completionByteOffset(source, offset); - if (byteOffset === undefined || Buffer.byteLength(source, "utf8") > maxAnalysisSourceBytes) return undefined; + if (byteOffset === undefined || Buffer.byteLength(source, "utf8") > maxAnalysisSourceBytes) return { status: "unavailable" }; const key = document.uri.toString(); let query = this.completionQueries.get(key); if (!query || query.byteOffset !== byteOffset || !this.current(query.job)) { @@ -648,10 +663,33 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, // An unavailable tool or failed query can recover without a source edit. // Keep concurrent consumers coalesced, but do not cache absence indefinitely. if (!completion && this.completionQueries.get(key) === query) this.completionQueries.delete(key); - if (!completion || query.controller.signal.aborted || token.isCancellationRequested || !this.current(query.job)) return undefined; + if (query.controller.signal.aborted || token.isCancellationRequested || !this.current(query.job)) return { status: "stale" }; + return completion ? { status: "available", query, completion } : { status: "unavailable" }; + } + + async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, + context: vscode.CompletionContext): Promise { + if (this.disposed || document.isClosed || token.isCancellationRequested) return undefined; + const version = document.version, generation = this.generation; + const localDocuments = () => vscode.workspace.textDocuments.filter(item => + (item.uri.scheme === "file" || item.uri.scheme === "untitled") && path.isAbsolute(item.uri.fsPath)); + const observed = localDocuments().map(item => ({ document: item, version: item.version, dirty: item.isDirty })); + const current = () => !this.disposed && !document.isClosed && !token.isCancellationRequested && + document.version === version && this.generation === generation && + localDocuments().length === observed.length && observed.every(item => + !item.document.isClosed && item.document.version === item.version && item.document.isDirty === item.dirty); + // One provider owns the combined answer. Independent publishers could see + // different cancellation outcomes and return both compiler and guessed names. + const [compiler, fallback] = await Promise.all([ + this.compilerCompletion(document, position, token).catch(() => ({ status: "unavailable" } as const)), + Promise.resolve().then(() => this.tolerantCompletions(document, position, token, context)).catch(() => undefined) + ]); + if (!current() || compiler.status === "stale") return undefined; + if (compiler.status === "unavailable") return fallback; + const { query, completion } = compiler; const primary = query.job.inputs.find(input => input.document === document); - if (!primary || completion.cursor !== byteOffset || path.normalize(completion.path) !== primary.identity || - !await this.validateSemantic(query.job, completion, token)) return undefined; + if (!primary || completion.cursor !== query.byteOffset || path.normalize(completion.path) !== primary.identity || + !await this.validateSemantic(query.job, completion, token) || !current()) return undefined; const offsets = createByteRangeMapper(query.job.text)(completion.start, completion.length); const range = offsets && this.semanticRange(query.job.text, offsets.start, offsets.end); if (!range || !range.contains(position)) return undefined; @@ -667,7 +705,11 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, item.filterText = document.getText(new vscode.Range(range.start, position)); return item; }); - return new vscode.CompletionList(items, true); + const names = new Set(items.map(item => typeof item.label === "string" ? item.label : item.label.label)); + const tolerant = (Array.isArray(fallback) ? fallback : fallback?.items ?? []).filter(item => + (item.kind === vscode.CompletionItemKind.Keyword || item.kind === vscode.CompletionItemKind.Snippet || item.detail === "Matrix language") && + !names.has(typeof item.label === "string" ? item.label : item.label.label)); + return new vscode.CompletionList([...items, ...tolerant], true); } async provideSignatureHelp(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index 8fddac3..d3e6a7f 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -119,9 +119,9 @@ async function runProjectTask(provider: NyTaskProvider, kind: "project-check" | export async function activate(context: vscode.ExtensionContext): Promise { const provider = new NyTaskProvider(); const debugIntegration = new NyDebugIntegration(); - const analyzer = new NyAnalyzer(); - languageClientManager = new NyLanguageClientManager(document => analyzer.usesCompilerDefinitions(document), - (document, position, token) => analyzer.provideCompletionItems(document, position, token)); + const analyzer = new NyAnalyzer((document, position, token, completionContext) => + languageClientManager?.provideCompletionItems(document, position, token, completionContext) ?? Promise.resolve(undefined)); + languageClientManager = new NyLanguageClientManager(document => analyzer.usesCompilerDefinitions(document)); context.subscriptions.push( languageClientManager, diff --git a/vscode/src/languageClient.ts b/vscode/src/languageClient.ts index 262fdb9..0806df3 100644 --- a/vscode/src/languageClient.ts +++ b/vscode/src/languageClient.ts @@ -2,6 +2,7 @@ import * as vscode from "vscode"; import { LanguageClient, LanguageClientOptions, + CompletionRequest, RevealOutputChannelOn, ServerOptions } from "vscode-languageclient/node"; @@ -11,8 +12,7 @@ import { languageDocumentSelector } from "./languages"; export class NyLanguageClientManager implements vscode.Disposable { constructor( - private readonly compilerDefinitionsEnabled: (document: vscode.TextDocument) => boolean = () => false, - private readonly compilerCompletions: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) => Promise = async () => undefined + private readonly compilerDefinitionsEnabled: (document: vscode.TextDocument) => boolean = () => false ) {} private client: LanguageClient | undefined; private readonly outputChannel = vscode.window.createOutputChannel( @@ -59,18 +59,9 @@ export class NyLanguageClientManager implements vscode.Disposable { outputChannel: this.outputChannel, revealOutputChannelOn: RevealOutputChannelOn.Error, middleware: { - provideCompletionItem: async (document, position, context, token, next) => { - const [compiler, fallback] = await Promise.all([ - this.compilerCompletions(document, position, token), next(document, position, context, token) - ]); - if (token.isCancellationRequested) return undefined; - if (!compiler || !fallback) return fallback; - const names = new Set(compiler.items.map(item => typeof item.label === "string" ? item.label : item.label.label)); - const items = (Array.isArray(fallback) ? fallback : fallback.items).filter(item => - (item.kind === vscode.CompletionItemKind.Keyword || item.kind === vscode.CompletionItemKind.Snippet || item.detail === "Matrix language") && - !names.has(typeof item.label === "string" ? item.label : item.label.label)); - return new vscode.CompletionList(items, true); - }, + // NyAnalyzer is the sole completion publisher. It requests tolerant + // candidates directly and arbitrates them with one compiler snapshot. + provideCompletionItem: () => undefined, provideDefinition: (document, position, token, next) => this.compilerDefinitionsEnabled(document) ? undefined : next(document, position, token), provideReferences: (document, position, context, token, next) => this.compilerDefinitionsEnabled(document) @@ -106,6 +97,24 @@ export class NyLanguageClientManager implements vscode.Disposable { } } + public async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, + token: vscode.CancellationToken, context: vscode.CompletionContext): Promise { + const client = this.client; + const options = client?.initializeResult?.capabilities.completionProvider; + if (!client?.isRunning() || !options || token.isCancellationRequested) return undefined; + const current = () => this.client === client && client.isRunning() && !token.isCancellationRequested; + try { + const result = await client.sendRequest(CompletionRequest.type, + client.code2ProtocolConverter.asCompletionParams(document, position, context), token); + if (!current()) return undefined; + const converted = await client.protocol2CodeConverter.asCompletionResult(result, options.allCommitCharacters, token); + return current() ? converted : undefined; + } catch { + // A failed/stopped tolerant server must not discard a compiler answer. + return undefined; + } + } + public async stop(): Promise { const activeClient = this.client; this.client = undefined; diff --git a/vscode/src/test/analyzerPublisher.test.ts b/vscode/src/test/analyzerPublisher.test.ts index 9994633..5777bc0 100644 --- a/vscode/src/test/analyzerPublisher.test.ts +++ b/vscode/src/test/analyzerPublisher.test.ts @@ -10,7 +10,7 @@ import type { AnalysisResult } from "../analysisModel"; // Execute the production class and its real helpers, without activating an // editor, registering watchers, or spawning a compiler. Only the VS Code API -// boundary is fake; publisher filesystem reads and byte mapping remain real. +// boundary is fake; publisher/semantic filesystem reads and byte mapping are real. const bundled = buildSync({ entryPoints: [path.resolve(__dirname, "../../src/analyzer.ts")], bundle: true, write: false, platform: "node", format: "cjs", external: ["vscode"], logLevel: "silent" @@ -34,7 +34,15 @@ function document(filename: string, text: string) { return { uri: uri(filename), languageId: "ny", version: 1, isClosed: false, isDirty: false, text, getText() { return this.text; } }; } +type FileUri = ReturnType; +class TabInputText { + constructor(readonly uri: FileUri) {} +} +class TabInputTextDiff { + constructor(readonly original: FileUri, readonly modified: FileUri) {} +} type Document = ReturnType; +type SourceSnapshot = { path: string; text: string }; interface Job { document: Document; version: number; @@ -46,9 +54,15 @@ interface Job { } interface Publisher { tabSources: Set; + generation: number; + timers: Map>; workspaceInput(job: Job): Promise; publish(job: Job, result: AnalysisResult, signal: AbortSignal): Promise; current(job: Job): boolean; + openTabSources(): Set; + updateTabSources(): void; + validateSemantic(job: Job, index: { sources: SourceSnapshot[] }, token: { isCancellationRequested: boolean }): Promise; + matchesDiskSnapshot(source: SourceSnapshot): Promise; } const broken = 'module dep\r\n# é😀\r\npub fn broken() -> i32\r\n return "bad"\r\nend fn\r\n'; @@ -56,22 +70,26 @@ const repaired = broken.replace('"bad"', "1"); async function fixture(operation: (value: { publisher: Publisher; job: Job; result: AnalysisResult; dependency: Document; documents: Document[]; published: Map; output: string[]; depPath: string; -}) => Promise) { + tabs: { input: TabInputText | TabInputTextDiff }[]; +}) => Promise, dependencyName = "dep.ny") { const directory = await fs.mkdtemp(path.join(os.tmpdir(), "nil publisher café 中文-")); try { - const entryText = 'import dep.*\nfn main() -> i32\n return broken()\nend fn\n'; + const entryText = (dependencyName === "dep.ny" ? 'import dep.*\n' : `@include "${dependencyName}"\n`) + + 'fn main() -> i32\n return broken()\nend fn\n'; await fs.writeFile(path.join(directory, "main.ny"), entryText); - await fs.writeFile(path.join(directory, "dep.ny"), broken); + await fs.writeFile(path.join(directory, dependencyName), broken); // Exact canonical spelling makes the cached-document guard observable on // Windows too, independent of drive-letter case produced by a real editor. const entryPath = await fs.realpath(path.join(directory, "main.ny")); - const depPath = await fs.realpath(path.join(directory, "dep.ny")); + const depPath = await fs.realpath(path.join(directory, dependencyName)); const entry = document(entryPath, entryText), dependency = document(depPath, repaired); const documents = [entry, dependency], published = new Map(), output: string[] = []; + const tabs = [{ input: new TabInputText(entry.uri) }] as { input: TabInputText | TabInputTextDiff }[]; const api = { workspace: { textDocuments: documents, isTrusted: true, getConfiguration: () => ({ get: (_key: string, fallback: unknown) => fallback }) }, Uri: { file: uri, parse: (value: string) => uri(fileURLToPath(value)) }, + window: { tabGroups: { all: [{ tabs }] } }, TabInputText, TabInputTextDiff, Position, Range, Diagnostic, DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3 } }; const module = { exports: {} as { NyAnalyzer: { prototype: Publisher } } }; @@ -82,6 +100,8 @@ async function fixture(operation: (value: { const publisher = Object.assign(Object.create(module.exports.NyAnalyzer.prototype) as Publisher, { generation: 1, disposed: false, tabSources: new Set([entry.uri.toString()]), contributions: new Map(), fixes: new Map(), reports: new Map(), + semantics: new Map(), completionQueries: new Map(), signatureQueries: new Map(), + timers: new Map(), pending: new Map(), renameChecks: new Set(), diagnostics: { clear: () => published.clear(), set: (key: ReturnType, items: Diagnostic[]) => published.set(key.toString(), items) }, output: { clear: () => { output.length = 0; }, appendLine: (value: string) => output.push(value) } }); @@ -92,7 +112,8 @@ async function fixture(operation: (value: { reflection: {}, sources: [{ path: depPath, text: broken }], diagnostics: [{ code: "NIL1002", severity: "error", message: "Expected i32", hint: "", path: depPath, start, length: Buffer.byteLength('"bad"'), fix: null }] }; - await operation({ publisher, job, result, dependency, documents, published, output, depPath }); + try { await operation({ publisher, job, result, dependency, documents, published, output, depPath, tabs }); } + finally { for (const timer of publisher.timers.values()) clearTimeout(timer); } } finally { await fs.rm(directory, { recursive: true, force: true }); } } @@ -150,3 +171,102 @@ for (const mode of ["dirty", "open-tab", "changed-disk", "became-dirty", "became assert.ok(output.join("\n").includes("NIL1002"), "Unsafe locations must remain visible in Analysis Output."); }); }); + +async function includeAlias(dependency: Document, depPath: string): Promise { + const directory = path.join(path.dirname(depPath), "include alias"); + await fs.symlink(path.dirname(depPath), directory, process.platform === "win32" ? "junction" : "dir"); + dependency.uri = uri(path.join(directory, path.basename(depPath))); + assert.notEqual(dependency.uri.toString(), uri(depPath).toString()); +} + +for (const alias of [false, true]) test(`semantic validation follows restored disk include with a stale closed-tab ${alias ? "alias" : "model"}`, async () => { + await fixture(async ({ publisher, job, dependency, depPath }) => { + if (alias) await includeAlias(dependency, depPath); + dependency.text = broken; + await publisher.workspaceInput(job); + assert.equal(job.inputs.length, 1, "An arbitrary-extension include is a disk input, not a compiler overlay."); + const sources = [{ path: job.source, text: job.text }, { path: depPath, text: broken }]; + const token = { isCancellationRequested: false }; + assert.equal(await publisher.validateSemantic(job, { sources }, token), true); + await fs.writeFile(depPath, repaired); + sources[1]!.text = repaired; + assert.equal(dependency.isDirty, false); + assert.equal(dependency.isClosed, false, "Closing its tab need not dispose VS Code's clean model."); + assert.equal(await publisher.validateSemantic(job, { sources }, token), true, + "A retained clean closed-tab include must not veto a fresh compiler disk snapshot."); + assert.equal(dependency.getText(), broken, "Validation must not refresh, edit or save the cached model."); + assert.equal(await fs.readFile(depPath, "utf8"), repaired); + }, "helper.inc"); +}); + +for (const mode of ["dirty", "text-tab", "diff-original", "diff-modified"] as const) + test(`semantic validation retains ${mode} authority for arbitrary include aliases`, async () => { + await fixture(async ({ publisher, job, dependency, depPath, tabs }) => { + await includeAlias(dependency, depPath); + if (mode === "dirty") dependency.isDirty = true; + else { + tabs.push({ input: mode === "text-tab" ? new TabInputText(dependency.uri) : + mode === "diff-original" ? new TabInputTextDiff(dependency.uri, job.document.uri) : + new TabInputTextDiff(job.document.uri, dependency.uri) }); + publisher.tabSources = publisher.openTabSources(); + assert.ok(publisher.tabSources.has(dependency.uri.toString()), "Open .inc inputs need the same authority as source tabs."); + } + await publisher.workspaceInput(job); + assert.equal(job.inputs.length, 1, "Tracking an open include must not invent support for include overlays."); + assert.equal(publisher.current(job), true); + const sources = [{ path: job.source, text: job.text }, { path: depPath, text: broken }]; + assert.equal(await publisher.validateSemantic(job, { sources }, { isCancellationRequested: false }), false); + dependency.text = broken; + assert.equal(await publisher.validateSemantic(job, { sources }, { isCancellationRequested: false }), mode !== "dirty", + "Matching clean open includes are navigable; dirty includes still have no supported overlay."); + }, "helper.inc"); + }); + +for (const mode of ["became-dirty", "changed-version", "opened-tab"] as const) + test(`semantic validation rejects an include alias that ${mode} during disk validation`, async () => { + await fixture(async ({ publisher, job, dependency, depPath, tabs }) => { + await includeAlias(dependency, depPath); + await publisher.workspaceInput(job); + const read = publisher.matchesDiskSnapshot.bind(publisher); + let observed = false; + publisher.matchesDiskSnapshot = async source => { + const matches = await read(source); + if (source.path === depPath) { + observed = true; + if (mode === "became-dirty") dependency.isDirty = true; + else if (mode === "changed-version") dependency.version++; + else { + tabs.push({ input: new TabInputText(dependency.uri) }); + publisher.updateTabSources(); + assert.equal(publisher.generation, job.generation + 1, "Opening an include must invalidate the in-flight generation."); + } + } + return matches; + }; + const sources = [{ path: job.source, text: job.text }, { path: depPath, text: broken }]; + assert.equal(await publisher.validateSemantic(job, { sources }, { isCancellationRequested: false }), false); + assert.equal(observed, true, "The race control must reach the real disk comparison before changing the model."); + }, "helper.inc"); + }); + +test("opening and closing an arbitrary include alias invalidate semantic generations", async () => { + await fixture(async ({ publisher, job, dependency, depPath, tabs }) => { + await includeAlias(dependency, depPath); + await publisher.workspaceInput(job); + assert.equal(publisher.current(job), true); + const generation = publisher.generation; + tabs.push({ input: new TabInputText(dependency.uri) }); + publisher.updateTabSources(); + assert.equal(publisher.generation, generation + 1); + assert.equal(publisher.current(job), false); + publisher.updateTabSources(); + assert.equal(publisher.generation, generation + 1, "Unchanged membership must not invalidate a new generation."); + job.generation = publisher.generation; + assert.equal(publisher.current(job), true); + tabs.pop(); + publisher.updateTabSources(); + assert.equal(publisher.generation, generation + 2); + assert.equal(publisher.current(job), false); + assert.equal(dependency.isClosed, false, "Tab closure must invalidate even if VS Code retains the model."); + }, "helper.inc"); +}); diff --git a/vscode/src/test/completionOwner.test.ts b/vscode/src/test/completionOwner.test.ts new file mode 100644 index 0000000..87beace --- /dev/null +++ b/vscode/src/test/completionOwner.test.ts @@ -0,0 +1,283 @@ +import assert from "node:assert/strict"; +import { buildSync } from "esbuild"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import test from "node:test"; +import { pathToFileURL } from "node:url"; +import { Script } from "node:vm"; + +// Exercise both production providers and their actual registrations. Only the +// editor API and external compiler/LSP responses are controlled by this fixture. +const bundled = buildSync({ + stdin: { contents: 'export { NyAnalyzer } from "./analyzer"; export { NyLanguageClientManager } from "./languageClient";', + resolveDir: path.resolve(__dirname, "../../src"), loader: "ts" }, + bundle: true, write: false, platform: "node", format: "cjs", + external: ["vscode", "vscode-languageclient/node"], logLevel: "silent" +}).outputFiles[0]!.text; +const disposable = () => ({ dispose() {} }); +class Position { constructor(readonly line: number, readonly character: number) {} } +class Range { + constructor(readonly start: Position, readonly end: Position) {} + contains(position: Position) { + const compare = (a: Position, b: Position) => a.line - b.line || a.character - b.character; + return compare(this.start, position) <= 0 && compare(position, this.end) <= 0; + } +} +const kinds = { Function: 2, Method: 1, Variable: 5, Field: 4, Keyword: 13, Snippet: 14 }; +class CompletionItem { + detail?: string; insertText?: string; range?: Range; filterText?: string; + constructor(readonly label: string, readonly kind: number) {} +} +class CompletionList { constructor(readonly items: CompletionItem[], readonly isIncomplete = false) {} } +class TabInputText { constructor(readonly uri: ReturnType) {} } +class TabInputTextDiff {} +function fileUri(filename: string) { return { scheme: "file", fsPath: filename, toString: () => pathToFileURL(filename).href }; } +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} +function document(filename: string, text: string) { + return { uri: fileUri(filename), languageId: "ny", version: 1, isClosed: false, isDirty: false, text, + positionAt(offset: number) { + const lines = this.text.slice(0, offset).split(/\r\n|\r|\n/); + return new Position(lines.length - 1, lines.at(-1)!.length); + }, + offsetAt(position: Position) { + let offset = 0; + const breaks = this.text.matchAll(/\r\n|\r|\n/g); + for (let line = 0; line < position.line; line++) { const found = breaks.next().value!; offset = found.index! + found[0].length; } + return offset + position.character; + }, + getText(range?: Range): string { return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text; } + }; +} +type Document = ReturnType; + +async function fixture(operation: (value: any) => Promise) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "nil completion owner-")); + let analyzer: any, manager: any; + const registrations: { provider: any; triggers: string[] }[] = [], documents: Document[] = [], tabs: any[] = []; + const state: any = { analysis: true, compilerCalls: 0, compilerFailures: 0, lspCalls: 0, conversions: 0, + compilerGate: undefined, lspGate: undefined, conversionGate: undefined, compilerEmpty: false, extraSource: undefined }; + const fallbackItems = [new CompletionItem("cafe_value", kinds.Variable), new CompletionItem("return", kinds.Keyword), + new CompletionItem("template", kinds.Snippet), new CompletionItem("guessed_other", kinds.Variable)]; + const fallback = new CompletionList(fallbackItems); + class Client { + static instances: Client[] = []; + running = false; + initializeResult = { capabilities: { completionProvider: { resolveProvider: false, allCommitCharacters: [";"] } } }; + code2ProtocolConverter = { asCompletionParams: (doc: Document, position: Position, context: unknown) => ({ + textDocument: { uri: doc.uri.toString() }, position, context + }) }; + protocol2CodeConverter = { asCompletionResult: async (value: unknown, characters: string[]) => { + state.conversions++; assert.deepEqual(characters, [";"]); + if (state.conversionGate) await state.conversionGate.promise; + return value; + } }; + constructor(_id: string, _name: string, _server: unknown, readonly options: any) { Client.instances.push(this); } + async start() { this.running = true; } + async stop() { this.running = false; } + isRunning() { return this.running; } + async sendRequest(type: any, params: any) { + assert.equal(type.method, "textDocument/completion"); + assert.equal(params.textDocument.uri, documents[0]!.uri.toString()); + state.lspCalls++; + state.lspStarted?.resolve(undefined); + if (state.lspGate) await state.lspGate.promise; + if (state.lspError) throw new Error("LSP unavailable"); + state.lspProduced?.resolve(undefined); + return state.fallbackArray ? fallback.items : fallback; + } + } + const api: any = { + workspace: { textDocuments: documents, isTrusted: true, workspaceFolders: [], getWorkspaceFolder: () => undefined, + getConfiguration: () => ({ get: (key: string, value: unknown) => key === "server.path" ? process.execPath : key === "analysis.enabled" ? state.analysis : value }), + createFileSystemWatcher: () => ({ dispose() {}, onDidChange: disposable, onDidCreate: disposable, onDidDelete: disposable }) }, + window: { createOutputChannel: () => ({ clear() {}, appendLine() {}, dispose() {}, show() {} }), + showInformationMessage() {}, tabGroups: { all: [{ tabs }], onDidChangeTabs: disposable, onDidChangeTabGroups: disposable } }, + languages: { createDiagnosticCollection: () => ({ clear() {}, set() {}, dispose() {} }), + registerCompletionItemProvider: (_selector: unknown, provider: any, ...triggers: string[]) => { + registrations.push({ provider, triggers }); return disposable(); + } }, commands: { registerCommand: disposable }, Uri: { file: fileUri }, + Position, Range, CompletionItem, CompletionList, CompletionItemKind: kinds, TabInputText, TabInputTextDiff, + RelativePattern: class { constructor(readonly base: string, readonly pattern: string) {} }, + CodeActionKind: { QuickFix: "quickfix" } + }; + for (const name of ["onDidOpenTextDocument", "onDidChangeTextDocument", "onDidSaveTextDocument", "onDidCloseTextDocument", + "onDidChangeWorkspaceFolders", "onDidRenameFiles", "onDidDeleteFiles", "onDidGrantWorkspaceTrust", "onDidChangeConfiguration"]) api.workspace[name] = disposable; + for (const name of ["registerCodeActionsProvider", "registerDefinitionProvider", "registerReferenceProvider", "registerRenameProvider", "registerSignatureHelpProvider"]) api.languages[name] = disposable; + const module = { exports: {} as any }; + new Script(bundled, { filename: "completion-owner-production.cjs" }).runInNewContext({ + module, exports: module.exports, require: (name: string) => name === "vscode" ? api : name === "vscode-languageclient/node" ? + { LanguageClient: Client, RevealOutputChannelOn: { Error: 1 }, CompletionRequest: { type: { method: "textDocument/completion" } } } : require(name), + process, Buffer, TextDecoder, AbortController, setTimeout, clearTimeout + }); + try { + analyzer = new module.exports.NyAnalyzer((...args: unknown[]) => manager.provideCompletionItems(...args)); + manager = new module.exports.NyLanguageClientManager((doc: Document) => analyzer.usesCompilerDefinitions(doc)); + await manager.start(); + const text = '# é😀\r\nfn main() -> i32\r\n let cafe_value = 7\r\n return cafe_unfinished\r\nend fn\r\n'; + const filename = path.join(directory, "main.ny"); await fs.writeFile(filename, text); + const entry = document(await fs.realpath(filename), text); documents.push(entry); tabs.push({ input: new TabInputText(entry.uri) }); + analyzer.tabSources = analyzer.openTabSources(); + analyzer.analyzeSnapshot = async (job: any, _signal: unknown, _input: unknown, query: any) => { + state.compilerCalls++; + await analyzer.workspaceInput(job); + state.compilerStarted?.resolve(undefined); + if (state.compilerGate) await state.compilerGate.promise; + if (state.compilerFailures-- > 0) throw new Error("compiler unavailable"); + if (state.compilerUnsupported) return {}; + const sources = job.inputs.map((input: any) => ({ path: input.identity, text: input.text })); + if (state.extraSource) sources.push(state.extraSource); + state.compilerProduced?.resolve(undefined); + return { completion: { schema: "nil.completion.v1", partial: true, path: job.inputs[0].identity, cursor: query.offset, + start: Buffer.byteLength(job.text.slice(0, job.text.indexOf("cafe_unfinished"))), length: "cafe_unfinished".length, + sources, items: state.compilerEmpty ? [] : [{ name: "cafe_value", kind: "variable", type: "i32", insert_text: "cafe_value" }] } }; + }; + const position = entry.positionAt(text.indexOf("cafe_unfinished") + "cafe_".length); + const token = { isCancellationRequested: false, onCancellationRequested: disposable }; + const context = { triggerKind: 1 }; + const query = () => registrations[0]!.provider.provideCompletionItems(entry, position, token, context); + await operation({ analyzer, manager, entry, documents, tabs, position, token, context, query, state, fallback, registrations, + client: Client.instances[0], clients: Client.instances, directory }); + } finally { + state.compilerGate?.resolve(undefined); state.lspGate?.resolve(undefined); state.conversionGate?.resolve(undefined); + await manager?.stop(); analyzer?.dispose(); + await fs.rm(directory, { recursive: true, force: true }); + } +} + +test("one production completion registration publishes compiler and tolerant candidates without a second LSP publisher", async () => { + await fixture(async ({ registrations, client, query, entry, position, token, context, state }) => { + assert.equal(registrations.length, 1); + assert.deepEqual(registrations[0].triggers, [".", ":", "_", "-"]); + let nextCalled = false; + const legacy = await client.options.middleware.provideCompletionItem(entry, position, context, token, () => { nextCalled = true; return []; }); + assert.equal(legacy, undefined); assert.equal(nextCalled, false); + const result = await query(); + assert.deepEqual(Array.from(result.items, (item: CompletionItem) => item.label), ["cafe_value", "return", "template"]); + assert.equal(result.items[0].detail, "variable: i32"); + assert.equal(result.items[0].insertText, "cafe_value"); + assert.equal(entry.getText(result.items[0].range), "cafe_unfinished"); + assert.equal(state.compilerCalls, 1); assert.equal(state.lspCalls, 1); assert.equal(state.conversions, 1); + }); +}); + +for (const first of ["compiler", "lsp"]) test(`completion arbitration is unique when ${first} finishes first`, async () => { + await fixture(async ({ query, state }) => { + state.compilerGate = deferred(); state.lspGate = deferred(); + state.compilerStarted = deferred(); state.lspStarted = deferred(); + state.compilerProduced = deferred(); state.lspProduced = deferred(); + const pending = query(); await Promise.all([state.compilerStarted.promise, state.lspStarted.promise]); + state[first + "Gate"].resolve(undefined); + await state[first + "Produced"].promise; + state[first === "compiler" ? "lspGate" : "compilerGate"].resolve(undefined); + const result = await pending; + assert.equal(result.items.filter((item: CompletionItem) => item.label === "cafe_value").length, 1); + }); +}); + +test("a supported empty compiler answer suppresses guessed symbols while keeping language items", async () => { + await fixture(async ({ query, state }) => { + state.compilerEmpty = true; + assert.deepEqual(Array.from((await query()).items, (item: CompletionItem) => item.label), ["return", "template"]); + }); +}); + +test("an unavailable compiler preserves full fallback and recovers at the same cursor without source edits", async () => { + await fixture(async ({ query, state, fallback, entry }) => { + state.compilerFailures = 1; + assert.equal(await query(), fallback); + assert.equal((await query()).items[0].detail, "variable: i32"); + assert.equal(state.compilerCalls, 2); assert.equal(entry.version, 1); + }); +}); + +for (const array of [false, true]) test(`an older compiler preserves the complete tolerant ${array ? "array" : "list"} result`, async () => { + await fixture(async ({ query, state, fallback }) => { + state.compilerUnsupported = true; state.fallbackArray = array; + assert.equal(await query(), array ? fallback.items : fallback); + state.compilerUnsupported = false; + assert.equal((await query()).items[0].detail, "variable: i32", "Unsupported results must not be cached indefinitely."); + }); +}); + +for (const mode of ["analysis-disabled", "closed-tab", "unsupported-context"]) + test(`${mode} preserves ordinary tolerant completion`, async () => { + await fixture(async ({ query, state, fallback, analyzer, entry, token, context }) => { + if (mode === "analysis-disabled") state.analysis = false; + if (mode === "closed-tab") analyzer.tabSources.clear(); + const result = mode === "unsupported-context" ? await analyzer.provideCompletionItems(entry, new Position(0, 0), token, context) : await query(); + assert.equal(result, fallback); assert.equal(state.compilerCalls, 0); + }); + }); + +for (const mode of ["disabled", "failed", "throwing-callback"]) + test(`compiler completion remains available with ${mode} LSP`, async () => { + await fixture(async ({ query, state, manager, analyzer }) => { + if (mode === "disabled") await manager.stop(); + else if (mode === "failed") state.lspError = true; + else analyzer.tolerantCompletions = () => { throw new Error("synchronous LSP boundary failure"); }; + const result = await query(); + assert.deepEqual(Array.from(result.items, (item: CompletionItem) => item.label), ["cafe_value"]); + }); + }); + +for (const unavailable of [false, true]) for (const change of ["version", "generation", "cancel", "other-model", "local-include"]) + test(`${unavailable ? "fallback" : "compiler"} completion rejects ${change} changes while LSP is pending`, async () => { + await fixture(async ({ query, state, entry, analyzer, token, documents, directory }) => { + state.compilerFailures = unavailable ? 1 : 0; + state.lspGate = deferred(); state.lspStarted = deferred(); + const include = document(path.join(directory, "helper.inc"), "original"); + documents.push(include); + const pending = query(); await state.lspStarted.promise; + if (change === "version") entry.version++; + else if (change === "generation") analyzer.generation++; + else if (change === "cancel") token.isCancellationRequested = true; + else if (change === "other-model") documents.push(document(path.join(directory, "new.inc"), "changed")); + else { include.version++; include.isDirty = true; include.text = "edited"; } + state.lspGate.resolve(undefined); + assert.equal(await pending, undefined); + }); + }); + +test("unrelated virtual output changes do not discard compiler completion", async () => { + await fixture(async ({ query, state, documents, directory }) => { + const output = document(path.join(directory, "analysis.log"), "before"); output.uri.scheme = "output"; + documents.push(output); + state.lspGate = deferred(); state.lspStarted = deferred(); + const pending = query(); await state.lspStarted.promise; + output.version++; output.text = "more output"; + const virtual = document(path.join(directory, "another.log"), "new output"); virtual.uri.scheme = "output"; + documents.push(virtual); + state.lspGate.resolve(undefined); + assert.equal((await pending).items[0].detail, "variable: i32"); + }); +}); + +test("compiler source bytes are revalidated after a delayed tolerant response", async () => { + await fixture(async ({ query, state, directory }) => { + const header = path.join(directory, "helper.inc"); await fs.writeFile(header, "original"); + state.extraSource = { path: await fs.realpath(header), text: "original" }; + state.lspGate = deferred(); state.lspStarted = deferred(); + state.compilerStarted = deferred(); + const pending = query(); await Promise.all([state.lspStarted.promise, state.compilerStarted.promise]); + await fs.writeFile(header, "modified"); + state.lspGate.resolve(undefined); + assert.equal(await pending, undefined, "A stale compiler answer must not become full tolerant fallback."); + }); +}); + +for (const phase of ["request", "conversion"]) test(`LSP lifecycle changes discard old ${phase} results`, async () => { + await fixture(async ({ manager, entry, position, token, context, state }) => { + const gate = deferred(); state[phase === "request" ? "lspGate" : "conversionGate"] = gate; + state.lspStarted = deferred(); + const pending = manager.provideCompletionItems(entry, position, token, context); + await state.lspStarted.promise; + if (phase === "conversion") while (!state.conversions) await new Promise(resolve => setImmediate(resolve)); + await manager.restart(); gate.resolve(undefined); + assert.equal(await pending, undefined); + }); +}); diff --git a/vscode/test/language-values-checks.cjs b/vscode/test/language-values-checks.cjs index 28e3609..d284b7e 100644 --- a/vscode/test/language-values-checks.cjs +++ b/vscode/test/language-values-checks.cjs @@ -5,12 +5,12 @@ const vscode = require("vscode"); const pause = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)); const label = item => typeof item.label === "string" ? item.label : item.label.label; -async function eventually(operation, description) { +async function eventually(operation, description, retryErrors = true) { const until = Date.now() + 15_000; let latest; do { try { const value = await operation(); if (value) return value; } - catch (error) { latest = error; } + catch (error) { if (!retryErrors) throw error; latest = error; } await pause(100); } while (Date.now() < until); throw new Error(`Timed out: ${description}${latest ? ` (${latest})` : ""}`); @@ -113,11 +113,27 @@ exports.run = async ({ check, workspace }) => { assert.deepEqual(await analyze(document), []); const occurrence = language === "ny" ? "println(height)" : "say height"; const selected = await complete(document, occurrence, "height", "hei", language === "ny" ? "f64" : "floating"); - const definitions = await vscode.commands.executeCommand("vscode.executeDefinitionProvider", document.uri, selected.start); + const version = document.version; + let definitionAttempts = 0; + const definitions = await eventually(async () => { + assert.equal(document.version, version, "Definition lookup must use the original tuple document version."); + definitionAttempts++; + const value = await vscode.commands.executeCommand("vscode.executeDefinitionProvider", document.uri, selected.start); + assert.equal(document.version, version, "Definition lookup must not change the tuple document version."); + assert.ok(value == null || Array.isArray(value), "Definition provider must return an array or no result."); + return value?.length && value; + }, "tuple definition after the editor generation settles", false); + // As with semantic-checks, only absence may be retried. A nonempty stale, + // duplicate, or guessed destination must fail immediately. + assert.equal(document.version, version, "Definition lookup must not change the tuple document version."); assert.equal(definitions.length, 1); const expected = range(document, "(width, height)", "height"); - assert.ok((definitions[0].targetSelectionRange || definitions[0].range).isEqual(expected)); - return { language, tupleArity: 2 }; + const [definition] = definitions; + assert.equal(definition.targetUri?.toString(), document.uri.toString()); + assert.ok(definition.originSelectionRange?.isEqual(selected)); + assert.ok(definition.targetSelectionRange?.isEqual(expected)); + assert.ok(definition.targetRange?.isEqual(expected)); + return { language, tupleArity: 2, documentVersion: version, definitionAttempts }; }); await check(`${language}: malformed interpolation reports an editor error and recovers after correction`, async () => {