From 31f2fb8a5a5887960db341cee184d51d2608b2ac Mon Sep 17 00:00:00 2001 From: Alex Maldonado Date: Mon, 5 Oct 2026 03:03:38 +0000 Subject: [PATCH] Baseline: tree as shared --- .editorconfig | 100 + .gitattributes | 2 + .gitea/workflows/deploy.yml | 75 + .gitignore | 16 + AGENTS.md | 58 + README.md | 117 + docs/Caddyfile | 28 + docs/app.md | 223 + docs/asm-coverage.md | 49 + docs/deploy.md | 34 + docs/engines.md | 31 + docs/exercises.md | 38 + docs/mojo-corpus.md | 141 + docs/sync-coverage.md | 115 + index.html | 30 + mojo/corpus/SOURCES.md | 31 + .../mojo-integration/deferred_ops_errors.mojo | 51 + .../deferred_type_invalid.mojo | 39 + .../elaboration_error/elaboration_error.mojo | 143 + .../elaboration_error_limit.mojo | 71 + .../elaboration_error_options.mojo | 53 + .../elaboration_error_prelude.mojo | 47 + .../elaboration_error_recursion1.mojo | 40 + .../elaboration_error_recursion2.mojo | 38 + .../elaboration_error_recursion3.mojo | 45 + .../elaboration_error_recursion4.mojo | 36 + .../elaboration_error_scc_type_error.mojo | 56 + .../inputs/diags_package/__init__.mojo | 95 + .../parse_time_only_attrs.mojo | 22 + .../closures/capture_lists_errors.mojo | 36 + .../closure_interior_origin_errors.mojo | 60 + ..._marker_conformance_refinement_errors.mojo | 71 + .../files/mojo-parser/closures/errors.mojo | 74 + .../files/mojo-parser/closures/recursion.mojo | 37 + .../struct_explicit_fn_trait_conformance.mojo | 115 + .../unified_closure_implicit_conversion.mojo | 96 + .../closures/unified_closures_errors.mojo | 362 + .../files/mojo-parser/dead_code_warning.mojo | 61 + .../decls/alias/alias_unpack_error.mojo | 55 + .../alias/associated_aliases_errors.mojo | 152 + .../decls/alias/parametric_alias_errors.mojo | 233 + .../decls/align_decorator_errors.mojo | 129 + .../decls/body_constraint_deferral.mojo | 464 + .../decls/builtin_inline_recursion.mojo | 49 + .../decls/conflicting_imports_errors.mojo | 132 + ...nformance_parametric_constraint_alias.mojo | 118 + .../decls/constraint_overload_errors.mojo | 271 + .../files/mojo-parser/decls/decls_errors.mojo | 1397 + .../decls/decorators/decorators_errors.mojo | 348 + .../deprecated/deprecated_errors.mojo | 280 + .../deprecated/inputs/imported_module.mojo | 21 + .../decls/decorators/doc_inline/errors.mojo | 27 + .../decls/decorators/export/errors.mojo | 68 + .../decorators/inputs/imported_module.mojo | 22 + .../decls/decorators/name/errors.mojo | 48 + .../decls/decorators/stable/errors.mojo | 88 + .../decls/decorators/stable/errors_since.mojo | 65 + .../stable/test_std_mock/__init__.mojo | 276 + .../decorators/stable/warn_magic_fn.mojo | 31 + .../unavailable/inputs/imported_module.mojo | 22 + .../unavailable/unavailable_body.mojo | 72 + .../unavailable/unavailable_errors.mojo | 305 + .../decls/deinit_deprecation_warning.mojo | 45 + .../decls/fn_def_decls_errors.mojo | 246 + .../fn_type_where_conversion_errors.mojo | 63 + .../decls/fn_type_where_errors.mojo | 55 + .../mojo-parser/decls/imm_convention.mojo | 82 + .../mojo-parser/decls/implicit_var_decl.mojo | 393 + .../decls/inputs/comptime_a/__init__.mojo | 20 + .../decls/inputs/comptime_b/__init__.mojo | 20 + .../decls/inputs/fn_a/__init__.mojo | 18 + .../decls/inputs/fn_b/__init__.mojo | 17 + .../decls/inputs/fn_c/__init__.mojo | 17 + .../decls/inputs/fn_d/__init__.mojo | 17 + .../decls/inputs/imported_module.mojo | 22 + .../decls/inputs/mlirtype_a/__init__.mojo | 15 + .../decls/inputs/mlirtype_b/__init__.mojo | 15 + .../decls/inputs/struct_a/__init__.mojo | 17 + .../decls/inputs/struct_b/__init__.mojo | 17 + .../decls/inputs/struct_c/__init__.mojo | 17 + .../decls/inputs/struct_d/__init__.mojo | 17 + .../plain_struct.mojo | 17 + .../mojo-parser/decls/keyword_fn_names.mojo | 268 + .../mojo-parser/decls/lookup_errors.mojo | 114 + .../files/mojo-parser/decls/pack_errors.mojo | 190 + .../mojo-parser/decls/param_infer_diags.mojo | 61 + .../decls/parameter_closures_errors.mojo | 92 + .../recursive_signature_literal_size.mojo | 57 + ...pecialized_generator_discharge_errors.mojo | 135 + .../decls/struct_body_constraints.mojo | 210 + .../decls/struct_call_sugar_errors.mojo | 76 + ...al_trait_conformance_duplicate_errors.mojo | 90 + ..._conditional_trait_conformance_errors.mojo | 590 + .../decls/struct_extensions_errors.mojo | 172 + .../struct_extensions_importing_errors.mojo | 27 + .../struct_extensions_shadowed_target.mojo | 39 + .../files/mojo-parser/decls/structs.mojo | 341 + .../decls/trait_composition_errors.mojo | 72 + .../mojo-parser/decls/traits_errors.mojo | 342 + .../mojo-parser/decls/typo_suggestion.mojo | 69 + .../files/mojo-parser/decls/var.mojo | 163 + .../files/mojo-parser/decls/var_errors.mojo | 88 + .../decls/where_conformance_on_return.mojo | 140 + .../decls/where_message_conformance.mojo | 272 + .../decls/where_message_errors.mojo | 130 + .../decls/where_message_parse_errors.mojo | 81 + .../default_associated_alias_error.mojo | 32 + .../default_trait_method_errors.mojo | 100 + .../mojo-parser/deferred_ops_errors.mojo | 29 + .../mojo-parser/deferred_ops_warnings.mojo | 32 + .../mojo-parser/deferred_type_warnings.mojo | 27 + .../files/mojo-parser/docs/__init__.mojo | 21 + .../mojo-parser/docs/parser_doc_errors.mojo | 468 + .../docs/parser_doc_module_errors.mojo | 26 + .../mojo-parser/explicit_destroy_errors.mojo | 324 + .../explicit_destroy_parse_errors.mojo | 112 + .../mojo-parser/explicit_materialization.mojo | 45 + .../files/mojo-parser/expressions.mojo | 1303 + .../exprs/call_emission_errors.mojo | 648 + .../mojo-parser/exprs/expressions_errors.mojo | 1367 + .../files/mojo-parser/exprs/exprs_misc.mojo | 630 + .../getitem_setitem_emission_errors.mojo | 63 + ...is_run_in_comptime_interpreter_errors.mojo | 27 + .../exprs/string_literal_errors.mojo | 74 + .../mojo-parser/exprs/tuple_type_errors.mojo | 46 + .../exprs/type_conversion_errors.mojo | 199 + .../mojo-parser/function_types_errors.mojo | 426 + .../mojo-parser/import/bare_import_gate.mojo | 86 + .../import/import_bad_symlink.mojo | 22 + .../import/import_deep_submodule.mojo | 149 + .../import/import_dotted_no_clash.mojo | 55 + .../import_dual_mount_first_binding_wins.mojo | 39 + .../import/import_dual_mount_module.mojo | 33 + .../import_dual_mount_source_package.mojo | 36 + .../import/import_error_no_stale_binding.mojo | 44 + .../import/import_error_poisoning.mojo | 30 + .../mojo-parser/import/import_errors.mojo | 368 + .../import/import_escaped_dotted_errors.mojo | 34 + .../import/import_fn_overloads.mojo | 63 + .../import_fn_scope_comptime_blocks.mojo | 99 + .../import/import_fn_scope_conflicts.mojo | 56 + .../import/import_fn_scope_no_leak.mojo | 103 + .../import/import_fn_scope_ordering.mojo | 54 + .../import/import_leaf_binding.mojo | 49 + .../import/import_missing_suggestion.mojo | 107 + .../import/import_moved_stdlib_note.mojo | 46 + .../import/import_namespace_ambiguous.mojo | 24 + .../import_namespace_case_sensitive.mojo | 27 + .../import_namespace_shadowed_submodule.mojo | 28 + .../files/mojo-parser/import/import_self.mojo | 57 + .../inputs/fn_overload_package/module1.mojo | 15 + .../inputs/fn_overload_package/module2.mojo | 15 + .../import/inputs/imported_module.mojo | 29 + .../no_sibling_leak/consumer_module.mojo | 17 + .../no_sibling_leak/consumer_reexport.mojo | 17 + .../no_sibling_leak/consumer_symbol.mojo | 17 + .../import/test_import_through_module.mojo | 41 + .../inline_mlir_op_fstring_errors.mojo | 93 + .../files/mojo-parser/lexer_errors.mojo | 307 + .../files/mojo-parser/lexical_errors.mojo | 67 + .../signature_only_conditional_deletable.mojo | 105 + .../files/mojo-parser/main_errors.mojo | 61 + .../mojo-parser/mlir_features_errors.mojo | 122 + .../files/mojo-parser/moco2698.mojo | 22 + .../files/mojo-parser/moco2699.mojo | 19 + .../files/mojo-parser/moco_2314.mojo | 26 + .../ownership/interior_origin_cldiags.mojo | 291 + .../mojo-parser/ownership/ownership.mojo | 1601 + .../mojo-parser/ownership/ownership_cf.mojo | 687 + .../ownership/ownership_cldiags.mojo | 820 + .../mojo-parser/ownership/ownership_eh.mojo | 461 + .../mojo-parser/ownership/ownership_refs.mojo | 606 + .../files/mojo-parser/parameters_errors.mojo | 739 + .../files/mojo-parser/punctuation_tokens.mojo | 68 + .../raising_getter_binds_parameters.mojo | 29 + .../statements/comptime_assert_errors.mojo | 132 + .../statements/control_flow_errors.mojo | 214 + .../mojo-parser/statements/match_diags.mojo | 262 + .../module_scope_control_flow_errors.mojo | 49 + .../statements/module_scope_try_error.mojo | 25 + .../mojo-parser/statements/raise_and_try.mojo | 215 + .../statements/raise_and_try_errors.mojo | 72 + .../type_body_control_flow_errors.mojo | 133 + .../statements/type_body_try_error.mojo | 58 + .../files/mojo-parser/t-strings/errors.mojo | 232 + .../mojo-parser/trait_downcast_error.mojo | 27 + .../type_diff_corresponding_origins.mojo | 38 + .../mojo-parser/type_refinement_negative.mojo | 200 + .../mojo-parser/variadic_binding_error.mojo | 78 + .../mojo-parser/vertical_whitespace.mojo | 232 + mojo/corpus/diagnostics/manifest.json | 34345 +++ mojo/corpus/editor/editor.json | 266 + .../manual/basics/blocks_and_statements.mojo | 57 + .../manual/code/manual/basics/comments.mojo | 26 + .../manual/code/manual/basics/docstrings.mojo | 27 + .../manual/basics/explicit_variables.mojo | 29 + .../manual/code/manual/basics/functions.mojo | 22 + .../code/manual/basics/hello_world.mojo | 18 + .../code/manual/basics/parameterization.mojo | 31 + .../manual/basics/python_integration.mojo | 24 + .../manual/code/manual/basics/structs.mojo | 41 + .../code/manual/basics/structs_fieldwise.mojo | 28 + .../manual/code/manual/basics/traits.mojo | 51 + .../manual/c-ffi/test_c_number_types.mojo | 63 + .../code/manual/c-ffi/test_call_libc.mojo | 117 + .../manual/code/manual/c-ffi/test_memory.mojo | 120 + .../code/manual/c-ffi/test_pointers.mojo | 111 + .../manual/c-ffi/test_shared_libraries.mojo | 36 + .../manual/c-ffi/test_string_lifetime.mojo | 52 + .../code/manual/c-ffi/test_strings.mojo | 73 + .../control-flow/conditional_expression.mojo | 26 + .../code/manual/control-flow/for_loop.mojo | 95 + .../manual/control-flow/if_statement.mojo | 38 + .../manual/control-flow/short_circuit.mojo | 32 + .../code/manual/control-flow/while_loop.mojo | 65 + .../errors/conditional_context_mgr.mojo | 69 + .../code/manual/errors/context_mgr.mojo | 43 + .../code/manual/errors/enumerated_errors.mojo | 70 + .../code/manual/errors/error_interaction.mojo | 71 + .../code/manual/errors/handle_error.mojo | 43 + .../manual/code/manual/errors/never_type.mojo | 54 + .../code/manual/errors/parametric_raises.mojo | 64 + .../code/manual/errors/resource_guard.mojo | 72 + .../code/manual/errors/stacktrace_error.mojo | 22 + .../errors/stacktrace_error_capture.mojo | 31 + .../errors/test_conditional_context_mgr.mojo | 51 + .../code/manual/errors/test_context_mgr.mojo | 36 + .../manual/errors/test_enumerated_errors.mojo | 47 + .../manual/errors/test_error_interaction.mojo | 54 + .../code/manual/errors/test_handle_error.mojo | 38 + .../code/manual/errors/test_never_type.mojo | 38 + .../manual/errors/test_parametric_raises.mojo | 33 + .../manual/errors/test_typed_errors_doc.mojo | 41 + .../errors/test_typed_errors_edge_cases.mojo | 137 + .../errors/test_typed_errors_testing.mojo | 187 + .../manual/errors/test_variant_errors.mojo | 74 + .../code/manual/errors/typed_errors.mojo | 51 + .../errors/typed_errors_edge_cases.mojo | 226 + .../manual/errors/typed_errors_testing.mojo | 208 + .../code/manual/errors/variant_errors.mojo | 72 + .../functions/closures/test_closures.mojo | 386 + .../code/manual/functions/lambda/tests.mojo | 212 + .../manual/code/manual/functions/tests.mojo | 687 + .../manual/code/manual/generics/tests.mojo | 479 + .../manual/code/manual/get-started/tests.mojo | 530 + .../code/manual/lifecycle/death/tests.mojo | 391 + .../lifecycle/explicit-destroy/tests.mojo | 457 + .../lifecycle/initialization/tests.mojo | 182 + .../code/manual/lifecycle/life/tests.mojo | 334 + .../code/manual/lifecycle/trivial/tests.mojo | 114 + .../comptime-evaluation/comptime_for.mojo | 36 + .../comptime-evaluation/comptime_if.mojo | 28 + .../comptime-evaluation/comptime_scope.mojo | 27 + .../comptime-evaluation/overview.mojo | 29 + .../comptime_subexpression.mojo | 34 + .../materialization/global_constant.mojo | 40 + .../materialization/materializing_values.mojo | 62 + .../metaprogramming/reflection/tests.mojo | 636 + .../manual/code/manual/operators/tests.mojo | 229 + .../code/manual/parameters/index/alias.mojo | 39 + .../index/anatomy_parameter_list.mojo | 56 + .../index/automatic_parameterization.mojo | 85 + ...atic_parameterization_partial_binding.mojo | 38 + .../index/conditional_conformance.mojo | 30 + .../fully_bound_partially_bound_etc.mojo | 94 + .../index/infer_only_parameters.mojo | 48 + .../manual/parameters/index/multiplier.mojo | 24 + .../optional_and_inferred_parameters.mojo | 29 + .../optional_and_keyword_parameters.mojo | 27 + .../optional_and_kw_params_in_structs.mojo | 32 + .../index/parameter_expressions_are_just.mojo | 35 + .../parameters/index/parameter_inference.mojo | 74 + .../index/parameterized_functions.mojo | 21 + .../parameterized_structs_staticmethod.mojo | 76 + .../index/parameters_and_generics.mojo | 23 + .../parameters/index/parametric_alias.mojo | 61 + .../powerful_compile_time_programming.mojo | 41 + .../code/manual/parameters/index/rebind.mojo | 25 + .../parameters/index/rsqrt_example.mojo | 27 + .../index/struct_parameter_reference.mojo | 45 + .../manual/parameters/index/use_simd.mojo | 59 + .../parameters/index/variadic_parameters.mojo | 30 + .../manual/pointers/index/arc_pointer.mojo | 23 + .../manual/pointers/index/owned_pointer.mojo | 28 + .../code/manual/pointers/index/pointer.mojo | 30 + .../manual/pointers/index/shared_dict.mojo | 38 + .../pointers/using-pointers/allocation.mojo | 89 + .../pointers/using-pointers/basics.mojo | 98 + .../pointers/using-pointers/bitcast.mojo | 78 + .../using-pointers/foreign_pointers.mojo | 39 + .../using-pointers/multiple_values.mojo | 50 + .../pointers/using-pointers/nullable.mojo | 49 + .../pointers/using-pointers/origins.mojo | 29 + .../using-pointers/python_pointer.mojo | 27 + .../pointers/using-pointers/simd_vectors.mojo | 59 + .../manual/python-to-mojo/python_to_mojo.mojo | 260 + .../python/mojo-from-python/mojo_module.mojo | 35 + .../code/manual/python/types/mojo_types.mojo | 29 + .../manual/python/types/python_compare.mojo | 36 + .../python/types/python_conversions.mojo | 32 + .../code/manual/python/types/python_dict.mojo | 24 + .../code/manual/python/types/python_list.mojo | 25 + .../manual/python/types/python_tuple.mojo | 23 + .../code/manual/quickstart/quickstart.mojo | 52 + .../index/mutable_self_in_function.mojo | 30 + .../code/manual/structs/index/my_pair.mojo | 39 + .../structs/index/object_initialization.mojo | 28 + .../manual/structs/index/static_method.mojo | 32 + .../code/manual/structs/index/tests.mojo | 78 + .../structs/operator-support/tests.mojo | 216 + .../code/manual/structs/reference/tests.mojo | 103 + .../manual/code/manual/traits/tests.mojo | 260 + .../code/manual/types/float_constants.mojo | 35 + .../numeric_literals_and_conversions.mojo | 54 + .../manual/code/manual/types/strings.mojo | 62 + .../values/lifetimes/immutable_name_list.mojo | 37 + .../values/lifetimes/inferred_origin.mojo | 27 + .../manual/values/lifetimes/name_list.mojo | 37 + .../values/value-semantics/def_int.mojo | 23 + .../values/value-semantics/def_simd.mojo | 23 + .../manual/values/value-semantics/fn_int.mojo | 26 + .../values/value-semantics/variable.mojo | 21 + .../manual/code/manual/variables/tests.mojo | 153 + .../reference/cheat-sheets/test_basics.mojo | 92 + .../cheat-sheets/test_compile_time.mojo | 196 + .../cheat-sheets/test_conversions.mojo | 137 + .../cheat-sheets/test_ownership.mojo | 162 + .../reference/cheat-sheets/test_traits.mojo | 136 + .../cheat-sheets/test_types_and_literals.mojo | 125 + .../reference/closure-declarations/tests.mojo | 428 + .../reference/compound-statements/tests.mojo | 352 + .../decorators/align/aligned_field.mojo | 30 + .../reference/decorators/align/arrays.mojo | 42 + .../reference/decorators/align/basic.mojo | 25 + .../reference/decorators/align/generic.mojo | 29 + .../code/reference/decorators/align/heap.mojo | 34 + .../reference/decorators/align/int_8byte.mojo | 25 + .../reference/decorators/align/register.mojo | 28 + .../reference/decorators/align/special.mojo | 26 + .../deprecated/basic_deprecation.mojo | 38 + .../decorators/deprecated/deprecation.mojo | 57 + .../decorators/doc-hidden/doc_hidden.mojo | 81 + .../reference/decorators/implicit/floor.mojo | 47 + .../decorators/implicit/implicit.mojo | 33 + .../parameter/legacy_capturing_closure.mojo | 33 + .../code/reference/expressions/tests.mojo | 401 + .../function-declarations/tests.mojo | 565 + .../code/reference/inline-mlir/tests.mojo | 486 + .../manual/code/reference/keywords/tests.mojo | 147 + .../reference/lambda-expressions/tests.mojo | 546 + .../manual/code/reference/literals/tests.mojo | 238 + .../code/reference/numeric-types/tests.mojo | 346 + .../reference/simple-statements/tests.mojo | 406 + .../reference/struct-declarations/tests.mojo | 281 + .../reference/trait-declarations/tests.mojo | 318 + .../manual/code/reference/types/tests.mojo | 148 + .../code/tools/notebooks/gpu_hello.mojo | 25 + .../manual/code/tools/notebooks/hello.mojo | 16 + .../code/tools/notebooks/hello_writing.mojo | 36 + .../code/tools/notebooks/parameterized.mojo | 28 + .../code/tools/notebooks/vector_addition.mojo | 88 + mojo/corpus/manual/manifest.json | 3667 + .../snippets/manual-control-flow-24.mojo | 7 + .../snippets/manual-control-flow-25.mojo | 7 + .../snippets/manual-control-flow-26.mojo | 7 + .../manual/snippets/manual-errors-1.mojo | 101 + .../manual/snippets/manual-errors-5.mojo | 91 + .../manual/snippets/manual-errors-6.mojo | 29 + .../manual/snippets/manual-errors-7.mojo | 141 + .../manual/snippets/manual-errors-8.mojo | 169 + .../snippets/manual-parameters-index-1.mojo | 61 + .../snippets/manual-parameters-index-2.mojo | 183 + .../snippets/manual-parameters-index-4.mojo | 33 + .../snippets/manual-parameters-index-7.mojo | 85 + .../manual-pointers-using-pointers-4.mojo | 294 + .../snippets/manual-python-types-1.mojo | 13 + .../snippets/manual-python-types-2.mojo | 8 + .../snippets/manual-python-types-3.mojo | 9 + .../snippets/manual-python-types-4.mojo | 7 + .../snippets/manual-python-types-5.mojo | 8 + .../snippets/manual-python-types-6.mojo | 49 + .../manual/snippets/manual-types-7.mojo | 226 + .../snippets/manual-values-lifetimes-1.mojo | 6 + .../snippets/manual-values-lifetimes-2.mojo | 329 + .../snippets/manual-values-lifetimes-3.mojo | 27 + .../snippets/manual-values-ownership-1.mojo | 105 + .../snippets/manual-values-ownership-2.mojo | 11 + .../snippets/manual-values-ownership-3.mojo | 13 + .../snippets/manual-values-ownership-4.mojo | 87 + .../snippets/manual-values-ownership-5.mojo | 19 + .../manual-values-value-semantics-1.mojo | 7 + .../manual-values-value-semantics-2.mojo | 11 + .../reference-decorators-parameter-1.mojo | 17 + mojo/corpus/messages/messages.json | 6584 + mojo/corpus/quest/manifest.json | 4825 + mojo/corpus/quest/solutions/MQ_101.mojo | 19 + mojo/corpus/quest/solutions/MQ_102.mojo | 15 + mojo/corpus/quest/solutions/MQ_103.mojo | 19 + mojo/corpus/quest/solutions/MQ_104.mojo | 19 + mojo/corpus/quest/solutions/MQ_105.mojo | 22 + mojo/corpus/quest/solutions/MQ_106.mojo | 20 + mojo/corpus/quest/solutions/MQ_107.mojo | 19 + mojo/corpus/quest/solutions/MQ_108.mojo | 19 + mojo/corpus/quest/solutions/MQ_109.mojo | 21 + mojo/corpus/quest/solutions/MQ_110.mojo | 22 + mojo/corpus/quest/solutions/MQ_111.mojo | 21 + mojo/corpus/quest/solutions/MQ_113.mojo | 23 + mojo/corpus/quest/solutions/MQ_115.mojo | 21 + mojo/corpus/quest/solutions/MQ_201.mojo | 17 + mojo/corpus/quest/solutions/MQ_202.mojo | 17 + mojo/corpus/quest/solutions/MQ_203.mojo | 16 + mojo/corpus/quest/solutions/MQ_207.mojo | 18 + mojo/corpus/quest/solutions/MQ_208.mojo | 18 + mojo/corpus/quest/solutions/MQ_210.mojo | 19 + mojo/corpus/quest/solutions/MQ_211.mojo | 19 + mojo/corpus/quest/solutions/MQ_213.mojo | 19 + mojo/corpus/quest/solutions/MQ_214.mojo | 21 + mojo/corpus/quest/solutions/MQ_215.mojo | 19 + mojo/corpus/quest/solutions/MQ_219.mojo | 18 + mojo/corpus/quest/solutions/MQ_220.mojo | 25 + mojo/corpus/quest/solutions/MQ_221.mojo | 18 + mojo/corpus/quest/solutions/MQ_222.mojo | 22 + mojo/corpus/quest/solutions/MQ_223.mojo | 22 + mojo/corpus/quest/solutions/MQ_224.mojo | 33 + mojo/corpus/quest/solutions/MQ_301.mojo | 19 + mojo/corpus/quest/solutions/MQ_302.mojo | 20 + mojo/corpus/quest/solutions/MQ_303.mojo | 19 + mojo/corpus/quest/solutions/MQ_304.mojo | 19 + mojo/corpus/quest/solutions/MQ_305.mojo | 22 + mojo/corpus/quest/solutions/MQ_306.mojo | 19 + mojo/corpus/quest/solutions/MQ_308.mojo | 20 + mojo/corpus/quest/solutions/MQ_309.mojo | 19 + mojo/corpus/quest/solutions/MQ_310.mojo | 17 + mojo/corpus/quest/solutions/MQ_312.mojo | 20 + mojo/corpus/quest/solutions/MQ_320.mojo | 23 + mojo/corpus/quest/solutions/MQ_321.mojo | 20 + mojo/corpus/quest/solutions/MQ_322.mojo | 20 + mojo/corpus/quest/solutions/MQ_323.mojo | 26 + mojo/corpus/quest/solutions/MQ_324.mojo | 18 + mojo/corpus/quest/solutions/MQ_325.mojo | 18 + mojo/corpus/quest/solutions/MQ_326.mojo | 23 + mojo/corpus/quest/solutions/MQ_401.mojo | 21 + mojo/corpus/quest/solutions/MQ_402.mojo | 24 + mojo/corpus/quest/solutions/MQ_403.mojo | 26 + mojo/corpus/quest/solutions/MQ_412.mojo | 20 + mojo/corpus/quest/solutions/MQ_501.mojo | 28 + mojo/corpus/quest/solutions/MQ_502.mojo | 26 + mojo/corpus/quest/solutions/MQ_503.mojo | 31 + mojo/corpus/quest/solutions/MQ_504.mojo | 21 + mojo/corpus/quest/solutions/MQ_505.mojo | 25 + mojo/corpus/quest/solutions/MQ_507.mojo | 27 + mojo/corpus/quest/solutions/MQ_510.mojo | 28 + mojo/corpus/quest/solutions/MQ_511.mojo | 27 + mojo/corpus/quest/solutions/MQ_512.mojo | 27 + mojo/corpus/quest/solutions/MQ_513.mojo | 34 + mojo/corpus/quest/solutions/MQ_520.mojo | 19 + mojo/corpus/quest/solutions/MQ_601.mojo | 22 + mojo/corpus/quest/solutions/MQ_602.mojo | 21 + mojo/corpus/quest/solutions/MQ_604.mojo | 28 + mojo/corpus/quest/solutions/MQ_702.mojo | 25 + mojo/corpus/quest/solutions/MQ_703.mojo | 33 + mojo/corpus/quest/solutions/MQ_704.mojo | 27 + mojo/corpus/quest/solutions/MQ_705.mojo | 33 + mojo/corpus/quest/solutions/MQ_706.mojo | 24 + mojo/corpus/quest/solutions/MQ_710.mojo | 32 + mojo/corpus/quest/solutions/MQ_801.mojo | 16 + mojo/corpus/quest/solutions/MQ_803.mojo | 21 + mojo/corpus/quest/solutions/MQ_810.mojo | 19 + mojo/corpus/quest/solutions/MQ_812.mojo | 25 + mojo/corpus/quest/solutions/MQ_825.mojo | 34 + mojo/corpus/quest/solutions/MQ_827.mojo | 32 + mojo/corpus/quest/solutions/MQ_830.mojo | 28 + mojo/corpus/quest/solutions/MQ_835.mojo | 21 + mojo/corpus/quest/solutions/MQ_845.mojo | 21 + mojo/corpus/quest/solutions/MQ_852.mojo | 23 + mojo/corpus/quest/solutions/MQ_858.mojo | 27 + mojo/corpus/quest/solutions/MQ_901.mojo | 24 + mojo/corpus/quest/solutions/MQ_903.mojo | 19 + mojo/corpus/quest/solutions/MQ_950.mojo | 23 + mojo/corpus/quest/solutions/MQ_951.mojo | 26 + mojo/corpus/quest/starters/MQ_101.mojo | 2 + mojo/corpus/quest/starters/MQ_102.mojo | 2 + mojo/corpus/quest/starters/MQ_103.mojo | 6 + mojo/corpus/quest/starters/MQ_104.mojo | 6 + mojo/corpus/quest/starters/MQ_105.mojo | 8 + mojo/corpus/quest/starters/MQ_106.mojo | 6 + mojo/corpus/quest/starters/MQ_107.mojo | 6 + mojo/corpus/quest/starters/MQ_108.mojo | 6 + mojo/corpus/quest/starters/MQ_109.mojo | 8 + mojo/corpus/quest/starters/MQ_110.mojo | 9 + mojo/corpus/quest/starters/MQ_111.mojo | 7 + mojo/corpus/quest/starters/MQ_113.mojo | 6 + mojo/corpus/quest/starters/MQ_115.mojo | 8 + mojo/corpus/quest/starters/MQ_201.mojo | 4 + mojo/corpus/quest/starters/MQ_202.mojo | 4 + mojo/corpus/quest/starters/MQ_203.mojo | 3 + mojo/corpus/quest/starters/MQ_207.mojo | 5 + mojo/corpus/quest/starters/MQ_208.mojo | 5 + mojo/corpus/quest/starters/MQ_210.mojo | 6 + mojo/corpus/quest/starters/MQ_211.mojo | 6 + mojo/corpus/quest/starters/MQ_213.mojo | 3 + mojo/corpus/quest/starters/MQ_214.mojo | 10 + mojo/corpus/quest/starters/MQ_215.mojo | 6 + mojo/corpus/quest/starters/MQ_219.mojo | 6 + mojo/corpus/quest/starters/MQ_220.mojo | 12 + mojo/corpus/quest/starters/MQ_221.mojo | 5 + mojo/corpus/quest/starters/MQ_222.mojo | 9 + mojo/corpus/quest/starters/MQ_223.mojo | 9 + mojo/corpus/quest/starters/MQ_224.mojo | 17 + mojo/corpus/quest/starters/MQ_301.mojo | 6 + mojo/corpus/quest/starters/MQ_302.mojo | 7 + mojo/corpus/quest/starters/MQ_303.mojo | 6 + mojo/corpus/quest/starters/MQ_304.mojo | 6 + mojo/corpus/quest/starters/MQ_305.mojo | 9 + mojo/corpus/quest/starters/MQ_306.mojo | 6 + mojo/corpus/quest/starters/MQ_308.mojo | 7 + mojo/corpus/quest/starters/MQ_309.mojo | 6 + mojo/corpus/quest/starters/MQ_310.mojo | 4 + mojo/corpus/quest/starters/MQ_312.mojo | 7 + mojo/corpus/quest/starters/MQ_320.mojo | 10 + mojo/corpus/quest/starters/MQ_321.mojo | 7 + mojo/corpus/quest/starters/MQ_322.mojo | 7 + mojo/corpus/quest/starters/MQ_323.mojo | 11 + mojo/corpus/quest/starters/MQ_324.mojo | 5 + mojo/corpus/quest/starters/MQ_325.mojo | 5 + mojo/corpus/quest/starters/MQ_326.mojo | 10 + mojo/corpus/quest/starters/MQ_401.mojo | 8 + mojo/corpus/quest/starters/MQ_402.mojo | 8 + mojo/corpus/quest/starters/MQ_403.mojo | 12 + mojo/corpus/quest/starters/MQ_412.mojo | 8 + mojo/corpus/quest/starters/MQ_501.mojo | 13 + mojo/corpus/quest/starters/MQ_502.mojo | 10 + mojo/corpus/quest/starters/MQ_503.mojo | 18 + mojo/corpus/quest/starters/MQ_504.mojo | 7 + mojo/corpus/quest/starters/MQ_505.mojo | 11 + mojo/corpus/quest/starters/MQ_507.mojo | 14 + mojo/corpus/quest/starters/MQ_510.mojo | 12 + mojo/corpus/quest/starters/MQ_511.mojo | 11 + mojo/corpus/quest/starters/MQ_512.mojo | 11 + mojo/corpus/quest/starters/MQ_513.mojo | 14 + mojo/corpus/quest/starters/MQ_520.mojo | 3 + mojo/corpus/quest/starters/MQ_601.mojo | 9 + mojo/corpus/quest/starters/MQ_602.mojo | 8 + mojo/corpus/quest/starters/MQ_604.mojo | 15 + mojo/corpus/quest/starters/MQ_702.mojo | 11 + mojo/corpus/quest/starters/MQ_703.mojo | 14 + mojo/corpus/quest/starters/MQ_704.mojo | 13 + mojo/corpus/quest/starters/MQ_705.mojo | 21 + mojo/corpus/quest/starters/MQ_706.mojo | 11 + mojo/corpus/quest/starters/MQ_710.mojo | 16 + mojo/corpus/quest/starters/MQ_801.mojo | 3 + mojo/corpus/quest/starters/MQ_803.mojo | 6 + mojo/corpus/quest/starters/MQ_810.mojo | 6 + mojo/corpus/quest/starters/MQ_812.mojo | 12 + mojo/corpus/quest/starters/MQ_825.mojo | 21 + mojo/corpus/quest/starters/MQ_827.mojo | 19 + mojo/corpus/quest/starters/MQ_830.mojo | 12 + mojo/corpus/quest/starters/MQ_835.mojo | 8 + mojo/corpus/quest/starters/MQ_845.mojo | 8 + mojo/corpus/quest/starters/MQ_852.mojo | 8 + mojo/corpus/quest/starters/MQ_858.mojo | 14 + mojo/corpus/quest/starters/MQ_901.mojo | 12 + mojo/corpus/quest/starters/MQ_903.mojo | 6 + mojo/corpus/quest/starters/MQ_950.mojo | 10 + mojo/corpus/quest/starters/MQ_951.mojo | 13 + mojo/corpus/release/release.json | 370 + mojo/corpus/report.json | 156 + mojo/corpus/skill/removed-syntax.json | 328 + mojo/corpus/stdindex/stdindex.json | 693 + mojo/corpus/stdtypes/stdtypes.json | 4308 + mojo/corpus/syntax/cases.json | 383 + mojo/corpus/syntax/mojo.syntax.json | 4182 + mojo/corpus/tokens/tokens.json | 785 + ...a6738d83168a10d46b1ce6df18735355609b7.json | 130731 +++++++++++ ...522a804c325ec7e4033221dd665c8f61387a9.json | 74 + ...9eb163957ff6f80d0013ad51df366f11269ba.json | 73 + ...87c4c0dcec4f86e21e32894ed7c62d92d2c6d.json | 77 + ...e6fcd921431999ee4f3da4b88f30102317b7a.json | 74 + ...45d144770f0ae62e4dece79cbb0e3fd1f0e74.json | 75 + ...09c09c109870af3f1bed801c14eb00166f19c.json | 70 + ...6012fd1142d6d8f3a9d75d06bd22689560c3b.json | 70 + ...6364f34976bf787ef33fcc85f9f4d2ebd1966.json | 92 + ...2a813f5e27b04908730f55241b787f51a8320.json | 74 + ...369d2c2067124d7dd070f67dce555a9b48f62.json | 70 + ...10415289f13648734b03dfef889e1a1b2c653.json | 78 + ...9bda78bf1484c3632cb75241aa6b2d6c3629e.json | 70 + ...a78d0fba34f04e43db089fc156d5de9086ec5.json | 74 + ...a4f10914292893dbdc5c8a8238ad824960bd6.json | 70 + ...159d8be3f256e78e954b46e66d65fe7b98031.json | 101 + ...ee4a0bb746bec57397292bb376d9a77bf7c19.json | 111 + ...1e41b440b358c402dbe514d52649ed61dd40d.json | 80 + ...b4a9399c0ad3f98dbf69de4f35bcb3ddaa327.json | 85 + ...edec51e5dd0b5a0b4f5c06296a74a980eb7da.json | 75 + ...2dea1efdb2e01e2719f1428352da4a3235857.json | 90 + ...abc40db126f227d0d9f1067437373d595d7eb.json | 70 + ...35eaeadeb4b70a66203f0fa95432ed266fc4d.json | 92 + ...f1e06e6562714758c0f1f621c738748fa98e6.json | 98 + ...d558cabc4845dc655df0ee5a86c03602afcac.json | 103 + ...a4444d5cb1fd886d8f0bbb113ef05844e3295.json | 74 + ...aea6fd212d1780248ce7e2e40c1d3946fffa4.json | 74 + ...d3f71d2b202748e786abcf80cf8dab13d56aa.json | 74 + ...3b6a0a16473f6aa3a7a1f802921f7e7ec0403.json | 137 + ...8a5f2d36e369d1dec85d1da5b51ae422ad794.json | 78 + ...c074adb88f306e0e8b304ece7e31c3db9f155.json | 76 + ...1d007bf71cdefedfaa6a8d2fd850ed9291946.json | 70 + ...40d3f85a023cd7c8606c6f5cf4609578e01d2.json | 141 + ...a0c3a979c2ca16fcf634d2ea47f259afb99d7.json | 81 + ...d6bedcb2669efa93af96efc61a983f86b4bb9.json | 7649 + ...8fa8c05ebf49a7e8f20161508c835e28f0200.json | 73 + ...6f2f8ac4019e06ca1cb57ee9a538419254298.json | 120 + ...9fd988ce30a67677608dd2467c7ce3b32bc40.json | 77 + ...0839899d7ae98838698615f647d2e487846ce.json | 74 + ...b1dd7e0e362e16572a2092a105507683fafaa.json | 105 + ...4e8302720a96d2f88d84d316280237a1d901e.json | 90 + ...a0601e1effc548ae80e333c67a322fee43885.json | 87 + ...7656e116cdaafb9053cfa3a3b47c6b6d10c24.json | 90 + ...f2f129336332064f90e8d01ff661fe83483c7.json | 83 + ...f81d43a9e4be7f13496e929d42665eebafc58.json | 74 + ...640176730f9faba8602c3bc289673d538d629.json | 74 + ...1ea25f63eea5680a691b1b931ab1285f9121d.json | 89 + ...75b29e8d136e3b016b6a510a5b445f908da29.json | 74 + ...e60741cb9496a70b6ece91841378359cfee0b.json | 96510 ++++++++ ...eb35803a69f12196b20112f8adb83cbc25a63.json | 75 + ...6126ba5e716a5548d7344334567bdfc5743dd.json | 89 + ...88481993fdf07929771b892de183e5da5f456.json | 74 + ...fe2b3d4fd798065553c037352e8c97179eb44.json | 73 + ...e314af9b04fe9aa80fc86e6dba9940fd59e43.json | 74 + ...521f0af61b760c2a6458e6fb2dade41bed5ad.json | 81 + ...920475b65bbf425d1893a50323a2060dcb15f.json | 73 + ...fa05675536665c5d9a0b1fe4b3fdc7a3d424f.json | 77 + ...a12b88674677f7e87deb11183c97f5516a9d5.json | 77 + ...afe98f171f31c317eb2ce878574738a14f1cb.json | 73 + ...077d2555aa0b71d64c5988730f8c579c2a59b.json | 163 + ...5f744a8f3c040f337d24cb0050f5c32f066e8.json | 75 + ...6f82e8a6eb9a72cddb4c7f9f9f470f0a3654a.json | 89 + ...4b4bf6f0b75884b8704c5e3fa0e4b5d2baa06.json | 120 + ...aa9cf5d22ea55c095fb30ccdf0f4981f53be9.json | 87 + ...51c767e656aac71a816f410b5e294abf8c19f.json | 74 + ...1b1d892f50d0473236c1fb6c351fd0aa61d59.json | 77 + ...5659d873f863e0f50dd65625eef3cc0085a8b.json | 75 + ...b63b633505c1b3bf310a874e54d621cf27dc0.json | 73 + ...2d94e7acdbc33750a1367182f34c5368bc99b.json | 74 + ...397b54177cc9eb1c9267157454e06ccee197f.json | 74 + ...0eddf7f5c62c763ffce89707d0b0e83f07eef.json | 92 + ...e9e3b592a96892dd3e08ae227af844e6c5513.json | 97 + ...c1aad378567101ed0755d93c36f06c731a376.json | 70 + ...2cb147c873f34204aabdb45cbb2d761320619.json | 89 + ...735a88908f20fe3782c7a5a5c1c226abcf508.json | 77 + ...7b6be47bb0dbc70087a1d8be8840928377c74.json | 121 + ...b3c3a1f312f4fde644200525ef144ede2b8b3.json | 169 + ...3add0d036a7f7e8b6a1d4432aeacea429c4f1.json | 83 + ...2548cce4fee03debcafb79b0929bf85525c7e.json | 75 + ...ea616bc3e6590e3b682ad2b4b6b7b52a6653c.json | 74 + ...baa287e20c625c6da8d61d8ca03aa59921620.json | 74 + ...d9042e1fb0882d4c80fd2011c418b7f02a19c.json | 74 + ...1cfc6d0a091e6d1af478134183d3a0706348f.json | 75 + ...32190efcd52b3ddf696f4282740e5707c1f4f.json | 74 + ...962094b416d223aa55d38c6482502dbde0ec3.json | 70 + ...244a9f8e7e1542ea987b52e72a4402470a28f.json | 74 + ...6857d18c8fe09bc3f07a662d4b577ff514f71.json | 77 + ...466ebe697d4d9bfe7fc77b501030e1300678d.json | 70 + ...0983ed69ad7920e7a33790f81d1df3bb136df.json | 159 + ...e0d109a59aca4865a164c645a4240805740d4.json | 125 + ...2d4e204874f7a2ca83262000e70c090cd0536.json | 73 + ...23d74ba7ed1d8be04e54260af830d48497fc7.json | 74 + ...e3306c297c6efc7f8d9bf2d7b499432f332c4.json | 80 + ...7c2f8e81fbb20b5c300c9b5acdb8b4c8f2c00.json | 121 + ...308111851d1ac36ee390062dc78daf4972759.json | 74 + ...83ca7ae24e33275d22ef58d74dc0c1d4cda21.json | 74 + ...ddd5402095133b71f487d6c0f803b8e312533.json | 74 + ...072fcceac284bb2881c3318b95260c74deb27.json | 73 + ...8f722a187ae9dec3206deb83214f8613f8ac7.json | 90 + ...85b11634e0f2ec9b8333e4f3712de47fa67fc.json | 75 + ...20e93e5947af2f46b233b7abbd20a5101f62b.json | 90 + ...15d4a29632a967dde7af2ffb10f424f3358d5.json | 122 + ...0335490e58e0b8eb466d30af1c6fca9bc12bd.json | 74 + ...fc2ee1f10ec4aeef1d651cf4812c11095ffdd.json | 96 + ...a3c520d68d4c9b337e5b6b2da685b66e4138c.json | 74 + ...2dcabf6576cd3e9cdb900113c91ae35017681.json | 99263 ++++++++ ...f61bc694e382f4591028bd4366316331a4796.json | 96 + ...dcaca875c74f2607b31ed5abe53c710898791.json | 96 + ...0f4a6043fdba6d3b79932a096329fa4165012.json | 70 + ...e6ab3beb56ba0b5f522a556c515ce6e29848e.json | 141 + ...defbee6eed9541ae160f08228b8341e0d0fc9.json | 74 + ...6087563c4e4d2a136beb7f8988f990cfa2e36.json | 70 + ...cc7f111aa7343452aab5461c5c4705d4f7849.json | 83 + ...432c07eda5efa99c906279978c926c111e341.json | 70 + ...a1f5f29354f6be26ad1135af5c867de5a2f7d.json | 77 + ...b801231578151770218a944a6ffcb2cfb5cc1.json | 83 + ...fbe6e3e46bac15464400f8906075e54fd1273.json | 134 + ...267f272ba5032955a6a5b007f86ceeefaf8af.json | 74 + ...0e69b2f668a31b14dea496aff983ab6ad292a.json | 89 + ...d17a09c4987d1189f4d1f57f7badd34bcb257.json | 95 + ...c5674aad96bda8400c2cefa4dd3e6dbcc3e5c.json | 74 + ...d0544caeb2f944b4d41a5b414228d98fc2394.json | 70 + ...46ac92198d6f46d57c01590615bfc10cd1f16.json | 77 + ...9ba4c45f363f0d9fb8e907c9f56697b2a3768.json | 74 + ...7b2849217de334352916de70c0120d8c73f33.json | 74 + ...9f11249bb75d8ea4ecb65c7beea927e466461.json | 74 + ...11b992471eac67cf8b33de4e59751d7b71e71.json | 121 + ...4f25e6eb4c056d9625ebac0922e627aed3c70.json | 74 + ...246fba8a8e336eae08e47aee6e8da26dd0398.json | 78 + ...a69dac12f3f134f35b55fc31c395ba6dca556.json | 78 + ...cad035f19c0cf3b816438932022147f53863a.json | 77 + ...d576ec7e90a50a3674e60359bd80dc34b5cef.json | 90 + ...f0d1f920723a73aa64d7b85dfe09f42cdbdc6.json | 74 + ...2879e0f47a5691c99c93d04cc7210e5476b5e.json | 77 + ...dfc42e8b72b1d217086850dc266ae24b4ce7a.json | 80 + ...e127d965763c2e83ea99004b719ed135db923.json | 73 + ...a4ea86fae515a66af5f876a784355520736ba.json | 90 + ...f7b0355329173af4ca932264a4ea977b9e728.json | 80 + ...ad0bcb60cafef9615e4f1d28b2c680562f6e7.json | 111 + ...1835f14ee736bc543729485ed9644e7717561.json | 73 + ...1d26945b2105e087f602ad6bb53fadddaaff9.json | 83 + ...a6bedfc60ee9ab16292c0f52b5fd07294fe99.json | 74 + ...2e4bea1c39ebfdee4d61713127d3b25a2cae5.json | 74 + ...e77afe608daa5187d3b05dc4a5451762f2109.json | 77 + ...29adfbfc50bcb33686138cb40d8e214098e72.json | 70 + ...0d2701907b96db7fdb1a48ab84e8cadba73b8.json | 74 + ...422d66276596366d35e2c20fc8dc77e515e4d.json | 74 + ...cd0dedcd774329a6d063fb20c0e2c4e013981.json | 77 + ...163535ff74a9f8b76d06763b8d0fbcedaeb40.json | 76 + ...d3b39c26382ada38968b172f17761b87f47fd.json | 80 + ...56fdbb3414fbdc64aa49e9a765db7be6f47dd.json | 74 + ...1d7befe4928a960f79960d8b3c396071aec5b.json | 77 + ...a2ada00a2879ea6569770c582663f41f68d55.json | 89 + ...ce55ff0b839a1e8727f50199553cc72b78170.json | 77 + ...c10bd6a83a1f77cc397b930ab2f4c55173406.json | 74 + ...6b69b79f5411624f179e0017b0ddc975df740.json | 137 + ...d7aa04a75373ad9067526cef56bd4ac9dfb6b.json | 77 + ...082e18568c01b11c5cd921547d5acccea9387.json | 111 + ...09d980b12493503c75125fada2579075a9ba5.json | 74 + ...0b4e9a897a1cf35d749b1b3539f1ff0c5a348.json | 74 + ...c173ebdb27dd078f72d07014c6cf81b136c83.json | 73 + ...814f7615f2a00a1124976e6f751f087f27b7a.json | 77 + ...7d06e9629a529dcdb6e26a137bdf4b4c48128.json | 74 + ...0920625f775f796b03f96ed48bcae53331588.json | 76 + ...428ea149baf6c40a93391c034197694648fff.json | 93 + ...2d47ac2f47e76a736a2be010a552fcbcd5a31.json | 74 + ...e6862bf9968085247b717766a9c60c9846a16.json | 74 + ...d0102c5325e2416aea3b64724746a70186d70.json | 83 + ...bf040e550c2bf02d766ad4180f441910f1695.json | 1839 + ...b7e7c88a0516526201815d11fb7f9a33b20fb.json | 74 + ...d57f4d66377855da7972cc925c9d6cfe491b9.json | 120 + ...eafab47d29a558bc1c917919bf15f03577e82.json | 89 + ...2906f2c00bd52c8bc9a1a3c774acbb577e903.json | 70 + ...f15412b20efaa048fa23ecf0489f123ba9a40.json | 75 + ...75b70ac8fea29ada292f8eb72c7326640dbe6.json | 70 + ...7d399ddfa40357e5709e13146ba5848449909.json | 73 + ...61c74174df7cf49ec168592b9d0665dae33e6.json | 74 + ...c6e63ee42a3666f4570fc7395fe8c71b81add.json | 89 + ...c043ee63437360505a3ddebfd5cd794086677.json | 81 + ...faa8ddeb6b64bdae1857d9d860c75e470d1a1.json | 74 + ...e3941327d0bbc412b40ec53aa41f8505a31fe.json | 137 + ...12c187e895b18b9f553802072f7dcd371f37b.json | 116 + ...569d445a32576a42ec676d3228b2c90323383.json | 130731 +++++++++++ ...f3e2613443c0041101592d77deb4885b6153f.json | 83 + ...41869263a50cbd7d9b1379f691c10eef21e4f.json | 74 + ...39e79f42677f1d1d1a53a47b2c025cc552511.json | 90 + ...efc166d5f74a0c038611c27169c3d39771b02.json | 74 + ...f8ca9399b7f60473292c1e185172389e513fc.json | 78 + ...3794937678273af280215d4c781988d75ec43.json | 77 + ...8b023414a67e8b3d1ae7f45277b335f8dcd0b.json | 74 + ...5679f0b65a6adf2e609ccc69d392091c8ac0f.json | 74 + ...be3c8bc2e101d0bea54685c2b3bc34f2aca45.json | 85 + ...c98eaabf34ac47f297b47be5e35c660a9ad0f.json | 70 + ...4d0636b5b95163f7e410592ce21b28cbc4995.json | 105 + ...fd47ccb2578dde582d2c55b96128b463bf726.json | 77 + ...f994b2062e1048ab5b7061a2f3ef86f7dd303.json | 80 + ...65f2c0a4db48ac542e48ad71ad2bddc4ceae6.json | 70 + ...1de8a088c7ecc990ab13fccdf83c2de851847.json | 80 + ...88df20e710b012bfcb8fbd1039ec9b82a2bf4.json | 74 + ...d55bf70478f6d259e60d7c40a4a761f85ab1b.json | 105 + ...b1c23bd00d81226d82419bf3a6494d37e6ac2.json | 70 + ...167b3db9a1fab31d82fa5fe678845b966d7f5.json | 73 + ...a15a9e04ac9329ac1004eef22befcd9b603d6.json | 81 + ...93485d26323314e08dbd2ff26af06714f8158.json | 75 + ...675201602a08d87f9df55a6c409d56979074e.json | 74 + ...49368aec63fe4e5a01f1456a068d8b9d4c879.json | 120 + ...4dcb032f1560cf29db0b4bec6a896221fa833.json | 73 + ...09a93936106c380a5314792877913dde3d7b9.json | 93 + ...ef6dfd208058cc1be58614ad6a791075d6e60.json | 92 + ...c7686d6e9948ed057110c012ec524adcf5051.json | 121 + ...11ad8d93415c448ccd4654dc40b9a678eeb2e.json | 89 + ...02ff8d43c5617fc24bec07624cf27daa2e2e8.json | 70 + ...98d6e0107ed2b8889e7ff1ac31f742a0cb186.json | 74 + ...27d6f9b7ddf13abcd1234c8653e4c48700734.json | 70 + ...da572782c61adcff79e03224f195e444947ed.json | 74 + ...d23a517c5428c6873933961b5f1099b5c48fc.json | 74 + ...bac534ebc39116fee387eb9cc1d30885187f6.json | 74 + ...979e381a11960a0679f209cc6f5dcfc322c0a.json | 107 + ...cf33ff48a2493254f2166c950e1fd4aedbeeb.json | 76 + ...434ab5a8d2f946cc6e9eddf9fc3d1d074f2f6.json | 153 + ...2c8c813952f9f327314c365c3f8f9ac2940d5.json | 76 + ...aa47bcca7e059b5504a23cf99e3c85895079e.json | 75 + ...dc2733aeb4046b6781665c25ed0c9506e6307.json | 74 + ...b8b68d9e7856b6da89515c9305f907a6c0028.json | 74 + ...cd37f26cd9489513d8603bc75465eac993ea0.json | 90 + ...1a0ee0c966e76ee4067460f67e6fe2174ba30.json | 74 + ...423a9c067b0fb55c6e7c44524394854864414.json | 84 + ...eb75f10dbe96df6f7347ef96d762a79c82b8d.json | 80 + ...328689600421db1eec8d00669659338740f47.json | 74 + ...f60cac6fa79e003b254aed58d8c1acc0208d8.json | 73 + ...b20d34ed28678f6cf48a5f577f42a1c9ef2a9.json | 74 + ...ed943459542b94a868ad61f891fda2d11b5ef.json | 147 + ...3ee71695c939fd38714d995aa9cebfbc379a3.json | 73 + ...167ed1039c4ee7c6f8ece37032cf9653830c8.json | 80 + ...53ae6e51af8b5de1416a76d90e2d0ebb4b2a7.json | 73 + ...5b22bb0a4b8300132a9031b42e592f82a9d3e.json | 74 + ...01d95eb5832a440c2c99318da9d46d423c65c.json | 77 + ...91402eebe92423db3831000c08caf3eb4de5c.json | 80 + ...ef8bb425ff7517232d3b8d7a2aa29ea5b69b8.json | 95 + ...bde5b52d07c25651dfa4b20e6d7ec0fe6915b.json | 74 + ...9b0d8c9b6f348af61e80d368a3e54d664da98.json | 74 + ...10d2fc5439e86825d3bacf7f0ed3347d6e0d0.json | 121 + ...0b8021ec2b4bad05314d217b53232f5eeb368.json | 74 + ...e2ce68d04056fd7b06e3c454a6c17576cc9f0.json | 74 + ...229da2e212c21de2b23f486fd9e0ba1e05a3a.json | 89 + ...10be672ab121a6a9f8306fc38b9a95108aae5.json | 89 + ...318b93b19a817ae561edc8391c399437c4a14.json | 84 + ...1a3e2d38089f6df9547c9717362871497af86.json | 86 + ...4c89c7492856e611134a886e7854872593baf.json | 77 + ...2376c3f23dd1c447d688835b917410fdfe147.json | 77 + ...1839c207e0f21f57e0b988e16ff21b90223a1.json | 77 + ...fc7e7678fc6bd58851b038b14b0efbf58f8e6.json | 80 + ...734a137bd6d8fca4de3d71da897c30e08a7ee.json | 78 + ...0bd0a91ebe081801c7ef6ae563c927fdb4357.json | 141 + ...c6663328c20cb3ef805d2e27a8d5f6d2c07fd.json | 74 + ...79b85f3daccc3874efe917323b43a5b8507a3.json | 74 + ...8057c3678b0fd592fa81d31fc3ecd7b03d553.json | 70 + ...999e3ebb33700dc2feeb1e20d0d1fbe9814df.json | 70 + ...640069e464c2d824ef813f815ddd9b53510a9.json | 89 + ...1664e46d01ca6e2c9674cb22b6e457988dd32.json | 73 + ...09ec6576d89802354e760beb9b7df29214f5a.json | 70 + ...d7626c839ae0cb61139eb02f7b70a8a78ffda.json | 75 + ...e49c5b56c79ee6c360645d62b14df8e9a65ee.json | 74 + ...dcb7e307b13872b603829e7b7c702a43950a6.json | 99 + ...f80ff9e82de2415845b1d5214e6a788e85f1c.json | 89 + ...a60ffe7f326f923e6a762b6d5f8e730489a13.json | 297 + ...37918c6049f46cb57d630493ac900ee271f2b.json | 70 + ...4178665ddb372df178e5473dc832ef41940a5.json | 95 + ...268b02ebb682974f73fcdbb856ff65ecf95cc.json | 109 + ...17caa7598ead6d4a2aa3e60a83c8d825ca096.json | 74 + ...bc3394335f05520439b151eff5eb83326f506.json | 74 + ...9c879fc9c5d40c4703f7ff8e29be9328208e3.json | 74 + ...8f612da0d905e12c2134d9a55003d0e0236c4.json | 77 + ...f49c7c0eeb464d1f3fcc14c38d00d0f5bfdcc.json | 74 + ...373a689c60744401125f5422fd8e3953fbf22.json | 80 + ...95f78067c63d6d424fad1887baff93868978b.json | 70 + ...87c93b58992e8dce5d2e8b246eee1fe658dfd.json | 105 + ...38ce7a2522f818888b67e3e5ead8b2074ece1.json | 77 + ...1f71df082a60fb3c4ca4ebb5b4b8f5f095159.json | 136 + ...4db6f585f9ec3b4971c02b9ce0518d997f985.json | 74 + ...57148f9241523de12394906e7fea9611fc524.json | 84 + ...99b4cb18a475812bfb263e4d4fb1950e5b151.json | 70 + ...a1b48b6b1d25107966429248086e0921df56e.json | 89 + ...c741ebe372104341f8e07580d9a55bf9b85f7.json | 105 + ...069fe4c2c35fd26a070aa8dacc2271ee49204.json | 10119 + ...4717343c21ea31748271eb35b1ca4b8771f3e.json | 77 + ...4fed342c046741116489e35999f178bf57988.json | 80 + ...379c6b6e5888a86b0dc41df180023802e8f1c.json | 74 + ...08369a3795014abc2e67ca4f66edba2d99b3e.json | 120 + ...91ba00fc834e89c061d9cebe6f284f2724376.json | 80 + ...4fdf9c40ca43d67975ce0d8354faed7ba94e1.json | 89 + ...4d58bed4e931fa3a6771841b3f10ee0a6bfeb.json | 74 + ...7c06c2414a9e4b0137eb0ad150da2a935c04b.json | 75 + ...7a429fd99b811dfa60af184b7b9e3638d28df.json | 89 + ...5275a276ae8fdf8c71cd5748c1df193ad57bb.json | 2211 + ...205b1fd99173f45393c799c75fe1591cfacf2.json | 84 + ...37f35fcfbf84bc8e661613b7e1193d20688ae.json | 80 + ...5f81c65ab0b8860a57e7e3d5f4a9699603d67.json | 80 + ...1d9d21161d9578a879435608375c09aa9093b.json | 217 + ...aa07af747bbf67722ddde2a10946719cf1cb0.json | 121 + ...c50cbe171f7120e822e507a382539af36c7ef.json | 74 + ...9d47b1148a21ea9e361ed1f36961f44458dc0.json | 74 + ...72c024eaf116fb985761669d35dc33caf09f1.json | 70 + ...7b4c54c0ec25160634ec973cf5b28bf85f04f.json | 80 + ...6ab7176ae2a841954a204d7be46d11e165c11.json | 80 + ...f5c258e6a13f3e34c079c5478d47136c79de0.json | 85 + ...57041239310cc833c23494665e940572435aa.json | 74 + ...fd174929fc7eba67b2c6f1c44961c1c9e03db.json | 108 + ...416ab85a72fdaa8ff401716adb76c54fb520e.json | 86 + ...86cba90ac231cb4f03c44a6400e8f9e7e6387.json | 106 + ...6aad884e3dadff28ff76619ba822ed951c04c.json | 89 + ...72a92f4d112e62a946efb104114f7ef9bcae4.json | 87 + ...0155d20e76fc2b9519498549f6679ba3b6920.json | 75 + ...ac16c92d76396b6926885ee462908b874ad52.json | 105 + ...ffd0128010bf5b0191ac099707bf06a2cde91.json | 81 + ...818861a68ab28c0f3f1606c641c30f975de16.json | 83 + ...b0b8cf9b3032222eda8450582db303e66f3d1.json | 70 + ...271ad60ddc002851c16a436e6357f49f89de8.json | 70 + ...19afefd80f53372d1ae036e29f94cfb1ee1b8.json | 80 + ...28fbe98321e13399cdd62c72da3e7d745ad02.json | 74 + ...f66b6009c333f5753d1fa11445e09cd43768d.json | 105 + ...ff00b07cb9389331063805d05af953177d53a.json | 96 + ...65c7c27a657ca85f57d3e916dd60738a57be2.json | 73 + ...fba544247e1da76343dd3bf9454159b1b7eff.json | 107194 +++++++++ ...7f2e391af2f56b8183bbf6acec26ff131edee.json | 80 + ...080a17c84d0be3407a07b4b432f4a1807d05d.json | 74 + ...71aa15c4b6ea22ae61a31c2d936db115a1c0c.json | 74 + ...f35bdb0047c73f3ac0f441f5bc6123f284572.json | 70 + ...cd4bd9063a98979588e58fbcec6516e815e41.json | 179266 +++++++++++++++ ...b0e1d61a685fbd803f5fa3fab6e713d9ee7e9.json | 75 + ...b1c05619abbb289812949a3c0aae93a85cfb0.json | 74 + mojo/golden/STATUS.md | 159 + ...3cefb5375a0b5cfa799d763d673aea29caa5f.json | 81 + ...4b4f49587a35f9b1241f81a03f17b4baec535.json | 77 + ...c9ff46f944046502e5d7ffaf67e38d1ce01df.json | 74 + ...992c6c80293f7b16c6977f432015eb2a01cb5.json | 105 + ...722b3429400a3def5cb6f2b15ac92e74c6869.json | 73 + ...0ae8f999ecc4c655cfa8793b3287f8b2bfd3b.json | 74 + ...94c1c41d14eede8e81b68b5e52473c26dafac.json | 73 + ...a43923109811f5bd23e36b42c7eae8352b46a.json | 84 + ...720ba98fc3fe2d28a80c5ee3b20ed37202719.json | 74 + ...a90ae9a053e61acc95ac357f4053ab00a84f7.json | 77 + ...4415b5877fb360ac9cd213183ba03b71fc11c.json | 70 + ...4c9afd5f43ce7b0889fd8bc217528dd296142.json | 73 + ...171d41518071364d44312c9a0f32bcfb8df51.json | 114 + ...a6015c0ddccb9551a2dc0630238b5da3af114.json | 137 + ...0fa377c059a8020ba5cc392b1e736868cfb6b.json | 57 + ...67c233d659162061078e6d85effefab69227a.json | 99 + ...f05ff0cd5cc80244455b32762dfd0c578196e.json | 77 + ...010d427fed2395e380234120130a915d61a36.json | 74 + ...0da0d6546dc2618eea06d92b69849da34c1d7.json | 74 + ...f2c97d84306af5c7c6c80b52aba1ce347d517.json | 183 + ...21d3e96fa936bac209c212f787fb351fd16d1.json | 70 + ...c1b2f24f8a82461126798499ce0911915cf73.json | 122 + ...9ad15776a517e9ae043ec13a08cec4daffef5.json | 75 + ...6eb6f81ac0c0e50cd4405a2aa1ed87c5ed6e9.json | 80 + ...cf0239f01a2835eaea0231824572ae355d8be.json | 120 + ...06fe6e182f742b8cfb9bc029b202509ee8144.json | 74 + ...61fa3907c5961e08f2b72dfcdbc617bee8161.json | 117 + ...196a0805cddddd67f654427fec82bd64449d7.json | 83 + ...786503215c821227cab9d54c89cbfec3ef47f.json | 74 + ...08a89f8ea51b11867ea26e0a81035603d729a.json | 80 + ...dc746e2ab6d304290cda273355a3160257037.json | 114 + ...b7d2bd6b8aa08210aa9a7fb6e9ceec680de39.json | 74 + ...d2c115ac477639a2ae5135c2d4405e8d59b1c.json | 120 + ...0e3a6cb70546469458f4143e647e06c14528f.json | 81 + ...d690feed1eb4f1757af3f93a5c2dec3ad28e5.json | 73 + ...f2615d16830f8d8fdd12165c43e460f451b11.json | 102 + ...121a2243ca6cd175948822041730668b83c5f.json | 90 + ...f49fa78b9fa2eba1dd47d29a0edcc589218e4.json | 73 + ...b1dbac1feff35ad9894fb56aceb44b9046819.json | 70 + ...9714abe5c7f0b3aa2474d45838a47f574f5c9.json | 75 + ...4752226f4461426c8179cf85f8e31b40e24eb.json | 83 + ...f71aff91b8e73770b714eed1f450a38141e73.json | 74 + ...dae74b1f65d32bd1af318452706456eaa7399.json | 153 + ...aa30b7b74a8d87a997cb93d0477e14bbbf1ff.json | 77 + ...df20832c80c18fa3dbc97a35cb1fd24d666d2.json | 70 + ...b8c632000a790545bd8a792c881e2f7c969da.json | 70 + ...4a42cc806e0d1bbb40f0d44ae91a874b36af4.json | 93 + ...34a0dc1eec279c131738fb07cde4cf2ec77b6.json | 93 + ...5cc1b46df94ca94c33b6eba4bc83890ee659c.json | 80 + ...4ad94ba85a2d5b12dd4442b5cf1bb68e22fd1.json | 70 + ...5bd562800853954a3f6ea0a01a67baf31db80.json | 109 + ...d608de8fcd7e1c906b28e8e23334614afdb33.json | 70 + ...4f720d34ba5fca0b240cf0cdc5f012ab93601.json | 80 + ...a1795a6c077cd593411083469f3b9cae4c855.json | 70 + ...009e5bdc328a515e3d6a8f70f61163c8631ce.json | 77 + ...e39b77b92761f3b3f12f6c8999c1fc637ef91.json | 74 + ...cbb192ca3b3b2803cbc035a91f47d43750c7c.json | 77 + ...0b0bb922fb70dacc446893ef163d235fd7282.json | 70 + ...33498503999d42469f17bd9c104e4fdd1e986.json | 105 + ...af0cb12caf2633bf712c800e85b97345bfaed.json | 74 + ...b85ccb26671e59e4f663ac391ccdeb9cf5ae1.json | 75 + ...c16b7d35e657e8364ddc548b9e59445e15034.json | 105 + ...dbaef4c34c017656ebacdb2c5b9fc5aeb6291.json | 77 + ...fd2f2c5e05035ae952a3ed3f700e9a5b605a0.json | 77 + ...0225967cbe2b66f57e80f771ac9bc7afeb4ec.json | 74 + ...63b7d48c914628be1725c05e28c393c33875f.json | 105 + ...fe4d9f9656fa70959cc07643010f2db2a6a32.json | 77 + ...2c7bccfe81da66c10b619318c3cc16916c6f9.json | 75 + ...6a15b541d6694bdfb482e04746d6853783712.json | 1797 + ...70f14defd78a3d47c9b2d6f4b87b28f457103.json | 105 + ...82b8b2d65f336fd2768dd63913a323a02a11e.json | 73 + ...28d684a9ef580ee02bd4e6b0e8f42249e6514.json | 80 + ...17fe73ac50a839598d89dc5378784df904f94.json | 74 + ...f289b308830ad41f2f3e919a39ba58d8ad481.json | 77 + ...f17e4f1bbc625f3e1f427d2e101a27ab4b14c.json | 121 + ...48f7d8de7a1cb2e3fb4c3695ca87104b6a045.json | 86 + ...50b8643262e5ea5d481a34570ff8c0f526048.json | 10175 + ...a4e73b1417cf978b4448b25b8883ba15bc39b.json | 74 + ...fc883636af61916847677783a3a1a6321b3bf.json | 73 + ...ead19122195186536d644fb10676eb2f0a55e.json | 74 + ...4327acc7801f28ec3f18fc7acf2c97472d7b1.json | 77 + ...81a66c6edccf849bc936950f0f4fd17c4da81.json | 74 + ...115c5b25ca23584ab9103a664e4087dd85f10.json | 120 + ...da8d0f5ed5775a58d0da042eda74028bb8d90.json | 90 + ...f134d1803fd3d8f9b6d77498c0a0d00d6a97f.json | 105 + ...d1fa5d6b6673852e60e9b8767521881e47a87.json | 77 + ...ac9b1cff07e217acc99a5b875182347b1b920.json | 77 + ...24a556944b7864b933ed16e19a98e6658c8c7.json | 89 + ...d926107f2f9acb41cd8ad97a92b3f2f746b8b.json | 74 + ...e7a525c40128a591d0fb4f5164ce330e46693.json | 74 + ...40f97f482fdef5d0ccda2c0caf2fcedd70374.json | 77 + ...b68777cb79561ed1ef65dacdabdb61bb3083c.json | 74 + ...e44905dec53f8e5118082013660c350a686ed.json | 120 + ...b1c4d039a095b19cdb2781598845238aef6ff.json | 74 + ...2aca780cd8669445e1a06e2ce37eda99699e5.json | 107 + ...fe875000cd04f4ba1f5db80603417776ea77b.json | 74 + ...db30f03a5c9d0d11debd70f7f6f4227ebce2b.json | 70 + ...33f86c7342e33b059cf942782fbf9b2957cdc.json | 70 + ...be9de11f684c95f5a885b4d522c500e53d949.json | 91 + ...8751f8bb338989f2d0506de2875f9862f7607.json | 74 + ...ed1f629169bb6fd44c63f019221ee976c3fd2.json | 74 + ...4844c6267b4b9ef4ca4b437c3c1999eeb659b.json | 74 + ...21dd79d91deeedf2e79373352775323dcb30c.json | 74 + ...562d4ff4493921802f17c988a405815734df8.json | 74 + ...ba08eacb9aa93f2b71f0c282b279a78021f3c.json | 70 + ...4e61c89130ee4730ffb9c7f26bdc2b8660475.json | 105 + ...5902ece00f32af1a46514e579f8a0acc10ed8.json | 89 + ...c1b1b00ccd9c1c24f05a1ff283855134bed47.json | 70 + ...c8d131d67772d6220a1aad17323fa31f91d80.json | 84 + ...d9c33ba9837ed1fccd25408d8d7ecce6a9d2f.json | 70 + ...916d0fe2544c4eef6136201d95e984c71a927.json | 74 + ...d1cf741735f814a29646778d1b758dd01afff.json | 73 + ...e06f9b498901b3497af08b518894713d2cb89.json | 74 + ...0f73d15e8d12b5742b0f0ae6c78d7adc1d76e.json | 70 + ...51317da93264dea5782adae1a7c9440e9deec.json | 74 + ...2445bd914a4556171a8caed42d704cb652c0c.json | 120 + ...314ab1ea4bd6482cb62aea9873ac86e01bd82.json | 95 + ...142da8177bf210f8d8e5052452155c5e734a1.json | 70 + ...63cf8ce8d3e5fbe2380093cb8dd2cc18b6ccf.json | 74 + ...e5fe65809e296bcb63f9feb5e0b09e9daafe2.json | 74 + ...a303e61c76870f3af57488363af1e60735e1c.json | 74 + ...31c3d7968e90acc58dc98756fb04941af9d06.json | 70 + ...27316756aecb652844131c949237cf63d9808.json | 73 + ...10bd6953628447daea61c839123dadbb06452.json | 133 + ...98efd68da4bd65608969f7e455bf03fa3909c.json | 74 + ...a91bc8d620a3b7ae4982e422584b21b973361.json | 70 + ...5d5d90f74a65a11725cbe5c319a7c5d017c81.json | 74 + ...46eafd8e38aef656ec08ffb464c2132d49c71.json | 109 + ...867b73054e17c6f199a399d2a60ea24fb3d2c.json | 111 + ...cd184bfe5e7105654b66acc2abf3f54c9ed72.json | 74 + ...cc7b36ffd0871e73d06a45bc7301eb8d446d9.json | 80 + ...50a6d625146d63e45e3e780add54715cc58c7.json | 120 + ...0447a96c7a27fad0ae94b9b2a6e2eb7b8f09d.json | 77 + ...fad6fcaad458650c35323ae2419faf59e448e.json | 75 + ...0bcee72471c1ae4b9a73a2c314e2e9c214cdd.json | 83 + ...795a46a733e5c3d545aa1596220df3b5c3107.json | 70 + ...d5ced0805e5deb091a0867dd77cdc112f5a69.json | 105 + ...c2618a202e75dc1d90af845347490b681d340.json | 70 + ...5117597eda8fea1ced22601a5cd10c9b26c2a.json | 117 + ...adc7d6ba3aedd8a9030ed95b386fc29777427.json | 120 + ...4a6af41b8b1ae1503954f18f282080f5e2a32.json | 83 + ...51c4a5e42de03605634625fbab4e2d356faa3.json | 84 + ...1b816e4a93d51adfc841d6a7a43b9fd4cc4f1.json | 74 + ...c806c43aa9ff9a2254fdccff33caddcb0aed4.json | 142 + ...2f7f1f7231b31d1f0cdfa23c8142824d368e1.json | 89 + ...401f2d2fab0a3641c0a6192de1a6cfc1c27e9.json | 78 + ...bbd27da4df1b22d29b106f09f7069ce26f3d6.json | 117 + ...0d5895295bf8ad34fd9c576823520cbb068b4.json | 74 + ...3396beeae57964ec7f57988e65a83d0468052.json | 74 + ...d8d2bcf75e6e6be91126a44a47b1e1f4ebd3c.json | 121 + ...c1e355597f3bf6df0582b92d4a44a452b7d80.json | 90 + ...4b21cf2bb8ce515c46e928b611026668152c2.json | 89 + ...d320bf760324718c0183b2411cb483e7ae8f9.json | 155 + ...dd9f60fe423013744a70b488e67674fe64390.json | 92 + ...1bf5f9ac23af9a1c6ebb5c1a74dd8d9b0c020.json | 81 + ...d897cd67461c54e8292ccc789ee76aa62bcd2.json | 99 + ...408f9425279c32892d91a8ed28f22c46b3492.json | 74 + ...45a1c51c466d92c764d41ef4bfcaee2063b74.json | 70 + ...694c531b34bfefc5c98a47afde7011581266a.json | 87 + ...d707977e8335a0f3efabe6159e439e74c6745.json | 70 + ...17f23110d09e2c3520ff4f827b042f66c6957.json | 74 + ...b541080d4bd6a742645bc0f7cfc9ba0057bd8.json | 86 + ...da58f23e110628deaca1dde1df030ed8e201e.json | 109 + ...acced2de657b3fe7dc055bde63a12c8d02669.json | 74 + ...8fa82755ffbb1afc608265a4724ed6408d7b8.json | 80 + ...6634c472d53caec5b846a8eac16a138b629be.json | 74 + ...7d1a4cd72cdf540e20b6c9c34455b0951d37f.json | 74 + ...aed16cc59f47244d553e06462c0e5b94ab34f.json | 120 + ...8e9880419b14437f9e459774383d1c3b361bd.json | 70 + ...fce288277a82444f7d5aefe364f0bffc26e86.json | 89 + ...2f8076a48b34aa3081a7dabf0dacd98744de2.json | 137 + ...26660735bc0b6a8be4953c67c17970404ec4d.json | 90 + ...d5f681d1aa09a433fe2b7f572b0ef72129d3a.json | 70 + ...8a91eefda0baad3cabd4f34486df065e7bda8.json | 74 + ...3c66a2ada5b4f89155968102eaf6e7269ee11.json | 70 + ...225f75a94b7b743d558af605646eb4977ed8e.json | 74 + ...76c56ea6e7c33997766a5f4840fa1402cc078.json | 105 + ...de5eaef89364a7bca9d305606b9533e3d81f7.json | 90 + ...3fd18fa410ee8ba8025e3352fa6626df58179.json | 73 + ...97af87c8a1fafabc0d5095b20f82f3ec33d70.json | 70 + ...7714efe3fc44a3aab3d296eda27992523b37e.json | 73 + ...553753c96aa46a437504ed36e4594ed782126.json | 70 + ...007806681dbb9ca70bc6082c22770a95efbd3.json | 70 + ...7177676b01abfafe71f5dbbd26bec41f29204.json | 81 + ...ddc8aac7c6b12e9a4165f5a007a8a616e1493.json | 74 + ...55716639958d759ca26b50b5f8d76f33061fc.json | 74 + ...517f9e98a8e302fb4e8dc5d665be9ea835881.json | 83 + ...d87c2e3a0f8f8e99548b0bc5b727512c620d3.json | 74 + ...9ca400a149f4e3806dce8bc514d5bcc4ff54b.json | 70 + ...3d51291faed30ce670c7fdeb2816f5be2477b.json | 74 + ...1bf72f7921d5b93a1447e1874770ac75d4e82.json | 70 + ...ffa817f3b7c085c50ce3cdeda508ddda6317b.json | 177 + ...b32b14df30f8f26a16e14a0d2988c6be2d5be.json | 73 + ...34450d53ebd017c4daae783eaf76c8d117130.json | 83 + ...65ef9bdcbc57f0bd25821d7ec6a26ef9df0fb.json | 74 + ...303dd378176beacc488aaa06147b7a5a114d7.json | 90 + ...0e21309aa3def8ddc19f8cde1f200bfcb41ea.json | 70 + ...b4c07de8286f0356b2d644562390c4826a932.json | 73 + mojo/golden/status.json | 5518 + mojo/local/best-position.mojo | 20 + mojo/local/binary-search.mojo | 24 + mojo/local/count-base-proved.mojo | 16 + mojo/local/count-base.mojo | 14 + mojo/local/demo.mojo | 239 + mojo/local/edit-distance.mojo | 30 + mojo/local/first-unknown.mojo | 17 + mojo/local/five-bugs.mojo | 16 + mojo/local/gc-fraction.mojo | 16 + mojo/local/hamming.mojo | 17 + mojo/local/kmers.mojo | 21 + mojo/local/match-off-by-one.mojo | 21 + mojo/local/match-proved.mojo | 25 + mojo/local/match-reset.mojo | 21 + mojo/local/match.mojo | 21 + mojo/local/revcomp.mojo | 26 + mojo/local/tally.mojo | 17 + mojo/local/translate-codons.mojo | 26 + mojo/mojo.lock.json | 62 + mojo/pin.json | 72 + mojo/probes/check-aliasing.mojo | 11 + mojo/probes/check-implicit-copy.mojo | 25 + mojo/probes/check-implicit-declaration.mojo | 5 + mojo/probes/check-missing-raises.mojo | 5 + mojo/probes/check-uninitialized.mojo | 5 + .../check-use-after-move-on-one-path.mojo | 30 + mojo/probes/check-use-after-move.mojo | 25 + mojo/probes/comptime-if-for.mojo | 9 + mojo/probes/dialect-del.mojo | 14 + mojo/probes/dialect-fn.mojo | 4 + mojo/probes/dialect-read.mojo | 8 + mojo/probes/dialect-register-passable.mojo | 11 + mojo/probes/dialect-value.mojo | 8 + mojo/probes/dict-missing-key.mojo | 7 + mojo/probes/dict-order.mojo | 12 + mojo/probes/error-assert-statement.mojo | 5 + mojo/probes/error-debug-assert.mojo | 5 + mojo/probes/error-exit-code.mojo | 7 + mojo/probes/error-try-finally.mojo | 10 + mojo/probes/error-unhandled.mojo | 4 + mojo/probes/float-mixed.mojo | 5 + mojo/probes/float-print.mojo | 12 + mojo/probes/float-round.mojo | 6 + mojo/probes/float-special.mojo | 4 + mojo/probes/float-to-int.mojo | 5 + mojo/probes/float32-print.mojo | 5 + mojo/probes/godbolt-asm-and-run.mojo | 8 + mojo/probes/godbolt-asm.mojo | 8 + mojo/probes/godbolt-compile-button.mojo | 10 + mojo/probes/godbolt-line-tables-O0.mojo | 9 + mojo/probes/godbolt-line-tables.mojo | 9 + mojo/probes/godbolt-opt-O0.mojo | 9 + mojo/probes/godbolt-stdin.mojo | 8 + mojo/probes/input-eof.mojo | 5 + mojo/probes/input-lines.mojo | 7 + mojo/probes/input-parse-error.mojo | 6 + mojo/probes/int-div-zero.mojo | 6 + mojo/probes/int-floordiv.mojo | 5 + mojo/probes/int-literal-too-big.mojo | 4 + mojo/probes/int-mod.mojo | 5 + mojo/probes/int-overflow-int.mojo | 7 + mojo/probes/int-overflow-int8.mojo | 8 + mojo/probes/int-pow-shift.mojo | 8 + mojo/probes/int-truediv.mojo | 6 + mojo/probes/int-uint-wrap.mojo | 5 + mojo/probes/lib-parallelize.mojo | 6 + mojo/probes/lib-vectorize.mojo | 6 + mojo/probes/life-asap-expression.mojo | 24 + mojo/probes/life-borrow-lifetime.mojo | 31 + mojo/probes/life-branch-both-sides.mojo | 31 + mojo/probes/life-branch-declared-inside.mojo | 26 + mojo/probes/life-branch-one-side.mojo | 31 + mojo/probes/life-copy-move.mojo | 25 + mojo/probes/life-early-return.mojo | 29 + mojo/probes/life-field-order.mojo | 32 + mojo/probes/life-last-use.mojo | 26 + mojo/probes/life-list-elements.mojo | 25 + mojo/probes/life-loop-local.mojo | 22 + mojo/probes/life-loop-outer-read-inside.mojo | 22 + mojo/probes/life-loop-outer-unused-after.mojo | 22 + mojo/probes/life-move-into-var-arg.mojo | 37 + mojo/probes/life-moved-on-one-path.mojo | 34 + mojo/probes/life-mut-arg.mojo | 9 + mojo/probes/life-reassign-in-loop.mojo | 22 + mojo/probes/life-reassign.mojo | 24 + mojo/probes/life-var-arg.mojo | 29 + mojo/probes/list-index-oob.mojo | 7 + mojo/probes/list-negative-index.mojo | 5 + mojo/probes/list-ops.mojo | 9 + mojo/probes/print-bool-optional.mojo | 7 + mojo/probes/print-dict.mojo | 4 + mojo/probes/print-list.mojo | 8 + mojo/probes/print-sep-end.mojo | 6 + mojo/probes/print-tuple.mojo | 4 + mojo/probes/range-forms.mojo | 9 + mojo/probes/set-order.mojo | 8 + mojo/probes/simd-basics.mojo | 6 + mojo/probes/string-build.mojo | 6 + mojo/probes/string-compare.mojo | 4 + mojo/probes/string-index.mojo | 6 + mojo/probes/string-iterate.mojo | 5 + mojo/probes/string-length.mojo | 6 + mojo/probes/string-slice.mojo | 4 + mojo/probes/struct-writable.mojo | 11 + mojo/stress/bank-account.mojo | 33 + mojo/stress/binary-search.mojo | 26 + mojo/stress/block-scope.mojo | 20 + mojo/stress/bubble-sort.mojo | 21 + mojo/stress/caesar-cipher.mojo | 23 + mojo/stress/closure-counter.mojo | 26 + mojo/stress/collatz.mojo | 26 + mojo/stress/comptime-constants.mojo | 17 + mojo/stress/context-manager.mojo | 32 + mojo/stress/dict-inventory.mojo | 19 + mojo/stress/error-chain.mojo | 29 + mojo/stress/exact-literals.mojo | 13 + mojo/stress/fibonacci-memo.mojo | 25 + mojo/stress/fraction.mojo | 44 + mojo/stress/function-param-thin.mojo | 19 + mojo/stress/function-values.mojo | 22 + mojo/stress/gcd-lcm.mojo | 22 + mojo/stress/grade-book.mojo | 24 + mojo/stress/integer-edges.mojo | 22 + mojo/stress/lambda-capture-param.mojo | 14 + mojo/stress/lambda-map.mojo | 19 + mojo/stress/lifecycle-loop.mojo | 36 + mojo/stress/lifecycle-moves.mojo | 38 + mojo/stress/matrix-multiply.mojo | 26 + mojo/stress/optional-lookup.mojo | 22 + mojo/stress/overloads.mojo | 21 + mojo/stress/ownership-mut.mojo | 27 + mojo/stress/palindromes.mojo | 20 + mojo/stress/prime-sieve.mojo | 21 + mojo/stress/queue-struct.mojo | 26 + mojo/stress/run-length.mojo | 23 + mojo/stress/set-operations.mojo | 22 + mojo/stress/simd-ops.mojo | 16 + mojo/stress/stack-struct.mojo | 33 + mojo/stress/string-builder-fixed.mojo | 22 + mojo/stress/string-builder.mojo | 22 + mojo/stress/temperatures.mojo | 25 + mojo/stress/trait-default.mojo | 35 + mojo/stress/vector2d.mojo | 39 + mojo/stress/word-count.mojo | 20 + package-lock.json | 32 + package.json | 20 + pixi.lock | 1395 + pixi.toml | 64 + quarto/.gitignore | 1 + quarto/README.md | 241 + quarto/_extensions/pplus/_extension.yml | 7 + quarto/_extensions/pplus/course/asm86.css | 2773 + quarto/_extensions/pplus/course/kit.css | 302 + quarto/_extensions/pplus/course/tokens.css | 99 + quarto/_extensions/pplus/pplus-hw.css | 119 + quarto/_extensions/pplus/pplus-views.css | 798 + quarto/_extensions/pplus/pplus.css | 232 + quarto/_extensions/pplus/pplus.js | 302 + quarto/_extensions/pplus/pplus.lua | 781 + quarto/_extensions/pplus/render.mjs | 83 + quarto/_extensions/pplus/syntax/lingo.xml | 155 + quarto/_extensions/pplus/syntax/mojo.xml | 310 + quarto/_extensions/pplus/syntax/pseudo.xml | 238 + quarto/_quarto.yml | 35 + quarto/example/index.qmd | 143 + quarto/example/live.qmd | 68 + quarto/example/machine.qmd | 77 + quarto/example/programs/binary-search.pseudo | 24 + quarto/example/programs/cell.asm | 9 + quarto/example/programs/cell.setup | 5 + quarto/example/programs/count-base.lingo | 7 + quarto/example/programs/count-base.mojo | 14 + quarto/example/programs/count-base.pseudo | 26 + quarto/example/programs/count-base.speco | 4 + quarto/example/programs/five-bugs.pseudo | 15 + quarto/example/programs/lifecycle.mojo | 38 + .../example/programs/match-off-by-one.pseudo | 33 + quarto/example/programs/mean.tex | 3 + quarto/example/programs/two-pointers.asm | 27 + quarto/example/programs/two-pointers.setup | 6 + scratch/.gitignore | 2 + scripts/asm-census.mjs | 68 + scripts/assemble.sh | 14 + scripts/check-pages.mjs | 174 + scripts/deploy.sh | 55 + scripts/engines-diff.mjs | 71 + scripts/mojo/corpus.py | 132 + scripts/mojo/listings.mjs | 135 + scripts/mojo/mojocorpus/__init__.py | 1 + scripts/mojo/mojocorpus/common.py | 233 + scripts/mojo/mojocorpus/emit_ts.py | 169 + scripts/mojo/mojocorpus/fetch.py | 250 + scripts/mojo/mojocorpus/godbolt.py | 125 + scripts/mojo/mojocorpus/harvest.py | 128 + scripts/mojo/mojocorpus/kde.py | 122 + .../mojo/mojocorpus/processors/__init__.py | 58 + .../mojo/mojocorpus/processors/diagnostics.py | 115 + scripts/mojo/mojocorpus/processors/editor.py | 64 + scripts/mojo/mojocorpus/processors/manual.py | 86 + .../mojo/mojocorpus/processors/messages.py | 148 + scripts/mojo/mojocorpus/processors/quest.py | 96 + scripts/mojo/mojocorpus/processors/release.py | 97 + scripts/mojo/mojocorpus/processors/skill.py | 58 + .../mojo/mojocorpus/processors/stdindex.py | 149 + .../mojo/mojocorpus/processors/stdtypes.py | 186 + scripts/mojo/mojocorpus/processors/syntax.py | 90 + scripts/mojo/mojocorpus/processors/tokens.py | 116 + scripts/mojo/mojocorpus/verify.py | 334 + scripts/mojo/new-program.mjs | 59 + scripts/mojo/tests/test_pipeline.py | 387 + scripts/new-exercise.mjs | 75 + scripts/play.mjs | 184 + scripts/quarto-css.mjs | 158 + scripts/quarto-engine.mjs | 39 + scripts/quarto-export.mjs | 46 + scripts/vendor/build.mjs | 15 + scripts/vendor/codemirror.sh | 45 + scripts/vendor/entry.ts | 6 + scripts/vendor/relink.mjs | 24 + scripts/vendor/tsconfig.cm.json | 64 + src/core/areas.ts | 129 + src/core/catalog.ts | 55 + src/core/compiles.ts | 118 + src/core/fuzz.ts | 430 + src/core/hardware.ts | 301 + src/core/prefs.ts | 37 + src/core/provenance.ts | 14 + src/core/reference.ts | 449 + src/core/runview.ts | 242 + src/core/session.ts | 567 + src/core/state.ts | 330 + src/core/types.ts | 146 + src/core/versions.ts | 220 + src/curriculum/advanced.ts | 307 + src/curriculum/concepts.ts | 58 + src/curriculum/core.ts | 388 + src/curriculum/foundations.ts | 311 + src/curriculum/index.ts | 75 + src/curriculum/science.ts | 87 + src/curriculum/types.ts | 103 + src/engines/asm86/cache.js | 250 + src/engines/asm86/dom.js | 35 + src/engines/asm86/encode.js | 590 + src/engines/asm86/hwviews.js | 1347 + src/engines/asm86/interp.js | 2575 + src/engines/asm86/machine.js | 331 + src/engines/asm86/ooo.js | 370 + src/engines/asm86/paging.js | 130 + src/engines/asm86/pipeline.js | 169 + src/engines/asm86/sandbox.js | 420 + src/engines/asm86/specs-hw.js | 670 + src/engines/asm86/specs.js | 844 + src/engines/asm86/uops.js | 401 + src/engines/asm86/views.js | 1312 + src/engines/pseudo/analyze.js | 660 + src/engines/pseudo/check.js | 1199 + src/engines/pseudo/coach.js | 420 + src/engines/pseudo/dom.js | 35 + src/engines/pseudo/editor.js | 147 + src/engines/pseudo/english.js | 3191 + src/engines/pseudo/exercise.js | 393 + src/engines/pseudo/highlight.js | 49 + src/engines/pseudo/interp.js | 1377 + src/engines/pseudo/lab.js | 226 + src/engines/pseudo/lang.js | 400 + src/engines/pseudo/logic.js | 477 + src/engines/pseudo/parse.js | 1331 + src/engines/pseudo/plan.js | 501 + src/engines/pseudo/planner.js | 143 + src/engines/pseudo/sharpen.js | 793 + src/engines/pseudo/solver.js | 597 + src/engines/pseudo/specs.js | 854 + src/engines/pseudo/study.js | 83 + src/engines/pseudo/testing.js | 385 + src/engines/pseudo/translate.js | 541 + src/engines/pseudo/vague.js | 366 + src/engines/pseudo/vcgen.js | 914 + src/engines/pseudo/views-analysis.js | 803 + src/engines/pseudo/views.js | 653 + src/engines/shared/dom.js | 66 + src/engines/shared/share.js | 19 + src/engines/shared/text.js | 27 + src/engines/shared/viz.js | 714 + src/exercises/_helpers.ts | 21 + src/exercises/_template.ts | 46 + src/exercises/asm-branchless.ts | 16 + src/exercises/asm-cmov.ts | 16 + src/exercises/asm-first-instructions.ts | 16 + src/exercises/asm-pack-bits.ts | 15 + src/exercises/asm-register-widths.ts | 15 + src/exercises/asm-two-pointers.ts | 15 + src/exercises/asm-vector.ts | 16 + src/exercises/best-position.ts | 17 + src/exercises/binary-search.ts | 21 + src/exercises/count-base-proved.ts | 22 + src/exercises/count-base.ts | 28 + src/exercises/demo.ts | 19 + src/exercises/edit-distance.ts | 17 + src/exercises/first-unknown.ts | 23 + src/exercises/five-bugs.ts | 16 + src/exercises/gc-fraction.ts | 18 + src/exercises/hamming.ts | 17 + src/exercises/index.ts | 61 + src/exercises/kmers.ts | 16 + src/exercises/match-off-by-one.ts | 16 + src/exercises/match-proved.ts | 22 + src/exercises/match-reset.ts | 17 + src/exercises/match.ts | 23 + src/exercises/revcomp.ts | 23 + src/exercises/tally.ts | 16 + src/exercises/translate-codons.ts | 17 + src/exercises/types.ts | 52 + src/main.ts | 114 + src/mojo/att.ts | 377 + src/mojo/check.ts | 59 + src/mojo/editing.ts | 23 + src/mojo/flow.ts | 458 + src/mojo/flowir.ts | 121 + src/mojo/generated/editor.ts | 26 + src/mojo/generated/listings.ts | 24 + src/mojo/generated/pin.ts | 13 + src/mojo/generated/programs.ts | 116 + src/mojo/generated/stdlib.ts | 648 + src/mojo/generated/tokens.ts | 343 + src/mojo/generated/types.ts | 1759 + src/mojo/interp.ts | 1786 + src/mojo/lex.ts | 126 + src/mojo/lifetimes.ts | 238 + src/mojo/parse.ts | 697 + src/mojo/practices.ts | 661 + src/mojo/properties.ts | 144 + src/mojo/reference.ts | 34 + src/mojo/resolve.ts | 231 + src/mojo/tokenize.ts | 160 + src/mojo/typecheck.ts | 511 + src/mojo/values.ts | 219 + src/mojo/warnings.ts | 71 + src/quarto/dom.ts | 351 + src/quarto/machine.ts | 194 + src/quarto/program.ts | 71 + src/quarto/render.ts | 508 + src/quarto/shortcodes.ts | 139 + src/services/asm.ts | 152 + src/services/godbolt.ts | 243 + src/services/index.ts | 18 + src/services/lingo.ts | 102 + src/services/matho.ts | 1199 + src/services/mojo.ts | 32 + src/services/pseudo-study.ts | 175 + src/services/pseudo.ts | 192 + src/services/speco.ts | 413 + src/sync/compare.ts | 48 + src/sync/header.ts | 6 + src/sync/hub.ts | 338 + src/sync/pseudo-to-lingo.ts | 543 + src/sync/pseudo-to-matho.ts | 617 + src/sync/pseudo-to-mojo.ts | 908 + src/sync/types.ts | 36 + src/ui/dom.ts | 60 + src/ui/editor.ts | 417 + src/ui/embed.ts | 225 + src/ui/home.ts | 319 + src/ui/hw/board.ts | 329 + src/ui/hw/lines.ts | 49 + src/ui/minirun.ts | 115 + src/ui/nav.ts | 20 + src/ui/provenance.ts | 43 + src/ui/quarto.ts | 387 + src/ui/reference.ts | 48 + src/ui/shell.ts | 998 + src/ui/splitter.ts | 32 + src/ui/stepkinds.ts | 36 + src/ui/theme.ts | 69 + src/ui/tooltip.ts | 26 + src/ui/views/compiler.ts | 240 + src/ui/views/lifetimes.ts | 75 + src/ui/views/panels.ts | 177 + src/ui/views/practices.ts | 43 + src/ui/views/run.ts | 205 + src/ui/views/tests.ts | 149 + src/ui/views/trace.ts | 536 + src/ui/views/viz.ts | 858 + src/vendor/CODEMIRROR-LICENSE | 21 + .../cm-types/commands/src/commands.d.ts | 98 + src/vendor/cm-types/commands/src/comment.d.ts | 16 + src/vendor/cm-types/commands/src/history.d.ts | 19 + src/vendor/cm-types/commands/src/index.d.ts | 3 + src/vendor/cm-types/common/src/index.d.ts | 3 + src/vendor/cm-types/common/src/mix.d.ts | 14 + src/vendor/cm-types/common/src/parse.d.ts | 48 + src/vendor/cm-types/common/src/tree.d.ts | 282 + src/vendor/cm-types/crelt/index.d.ts | 4 + .../find-cluster-break/src/index.d.ts | 15 + .../cm-types/highlight/src/highlight.d.ts | 116 + src/vendor/cm-types/language/src/fold.d.ts | 57 + .../cm-types/language/src/highlight.d.ts | 27 + src/vendor/cm-types/language/src/indent.d.ts | 48 + src/vendor/cm-types/language/src/index.d.ts | 8 + src/vendor/cm-types/language/src/isolate.d.ts | 4 + .../cm-types/language/src/language.d.ts | 116 + .../cm-types/language/src/matchbrackets.d.ts | 23 + .../cm-types/language/src/stream-parser.d.ts | 25 + .../cm-types/language/src/stringstream.d.ts | 25 + src/vendor/cm-types/lr/src/constants.d.ts | 45 + src/vendor/cm-types/lr/src/decode.d.ts | 5 + src/vendor/cm-types/lr/src/index.d.ts | 3 + src/vendor/cm-types/lr/src/parse.d.ts | 110 + src/vendor/cm-types/lr/src/stack.d.ts | 38 + src/vendor/cm-types/lr/src/token.d.ts | 46 + src/vendor/cm-types/search/src/cursor.d.ts | 28 + src/vendor/cm-types/search/src/goto-line.d.ts | 2 + src/vendor/cm-types/search/src/index.d.ts | 5 + src/vendor/cm-types/search/src/regexp.d.ts | 35 + src/vendor/cm-types/search/src/search.d.ts | 54 + .../cm-types/search/src/selection-match.d.ts | 10 + src/vendor/cm-types/state/src/change.d.ts | 42 + src/vendor/cm-types/state/src/char.d.ts | 4 + .../cm-types/state/src/charcategory.d.ts | 6 + src/vendor/cm-types/state/src/column.d.ts | 2 + src/vendor/cm-types/state/src/config.d.ts | 4 + src/vendor/cm-types/state/src/extension.d.ts | 18 + src/vendor/cm-types/state/src/facet.d.ts | 115 + src/vendor/cm-types/state/src/index.d.ts | 12 + src/vendor/cm-types/state/src/rangeset.d.ts | 73 + src/vendor/cm-types/state/src/selection.d.ts | 36 + src/vendor/cm-types/state/src/state.d.ts | 67 + src/vendor/cm-types/state/src/text.d.ts | 33 + .../cm-types/state/src/transaction.d.ts | 65 + .../cm-types/style-mod/src/style-mod.d.ts | 16 + src/vendor/cm-types/view/src/active-line.d.ts | 2 + src/vendor/cm-types/view/src/attributes.d.ts | 9 + src/vendor/cm-types/view/src/bidi.d.ts | 23 + src/vendor/cm-types/view/src/browser.d.ts | 19 + src/vendor/cm-types/view/src/buildtile.d.ts | 95 + src/vendor/cm-types/view/src/cursor.d.ts | 26 + src/vendor/cm-types/view/src/decoration.d.ts | 104 + src/vendor/cm-types/view/src/dialog.d.ts | 20 + src/vendor/cm-types/view/src/docview.d.ts | 67 + src/vendor/cm-types/view/src/dom.d.ts | 68 + src/vendor/cm-types/view/src/domchange.d.ts | 27 + src/vendor/cm-types/view/src/domobserver.d.ts | 109 + src/vendor/cm-types/view/src/domreader.d.ts | 22 + .../cm-types/view/src/draw-selection.d.ts | 9 + src/vendor/cm-types/view/src/dropcursor.d.ts | 2 + src/vendor/cm-types/view/src/editorview.d.ts | 185 + src/vendor/cm-types/view/src/extension.d.ts | 137 + src/vendor/cm-types/view/src/gutter.d.ts | 41 + src/vendor/cm-types/view/src/heightmap.d.ts | 71 + .../cm-types/view/src/highlight-space.d.ts | 3 + src/vendor/cm-types/view/src/index.d.ts | 22 + src/vendor/cm-types/view/src/input.d.ts | 94 + src/vendor/cm-types/view/src/keymap.d.ts | 17 + src/vendor/cm-types/view/src/layer.d.ts | 32 + .../cm-types/view/src/matchdecorator.d.ts | 19 + src/vendor/cm-types/view/src/panel.d.ts | 19 + src/vendor/cm-types/view/src/placeholder.d.ts | 3 + .../view/src/rectangular-selection.d.ts | 7 + .../cm-types/view/src/scrollpastend.d.ts | 2 + .../cm-types/view/src/special-chars.d.ts | 8 + src/vendor/cm-types/view/src/theme.d.ts | 15 + src/vendor/cm-types/view/src/tile.d.ts | 161 + src/vendor/cm-types/view/src/tooltip.d.ts | 45 + src/vendor/cm-types/view/src/viewstate.d.ts | 95 + src/vendor/cm-types/w3c-keyname/index.d.ts | 5 + src/vendor/codemirror.d.ts | 5 + src/vendor/codemirror.js | 68 + styles.css | 4239 + styles/course/README.md | 26 + styles/course/asm86.css | 2773 + styles/course/bridge.css | 142 + styles/course/kit.css | 302 + styles/course/tokens.css | 99 + tests/areas.test.mjs | 151 + tests/asm-coverage.test.mjs | 67 + tests/asm-float.test.mjs | 254 + tests/badges.test.mjs | 129 + tests/bridge.test.mjs | 132 + tests/corpus.test.mjs | 38 + tests/corpus/01-arithmetic.pseudo | 26 + tests/corpus/02-temperature.pseudo | 11 + tests/corpus/03-compound-interest.pseudo | 11 + tests/corpus/04-gcd-recursion.pseudo | 13 + tests/corpus/05-primes-sieve.pseudo | 19 + tests/corpus/06-fibonacci-memo.pseudo | 25 + tests/corpus/07-word-count.pseudo | 34 + tests/corpus/08-caesar.pseudo | 17 + tests/corpus/09-palindrome.pseudo | 17 + tests/corpus/10-insertion-sort.pseudo | 19 + tests/corpus/11-matrix-multiply.pseudo | 27 + tests/corpus/12-records.pseudo | 37 + tests/corpus/13-stack-brackets.pseudo | 25 + tests/corpus/14-queue-bfs.pseudo | 30 + tests/corpus/15-game-of-life.pseudo | 49 + tests/corpus/16-running-stats.pseudo | 29 + tests/corpus/17-case-grades.pseudo | 17 + tests/corpus/18-repeat-input.pseudo | 10 + tests/corpus/19-max-subarray.pseudo | 16 + tests/corpus/20-two-sum.pseudo | 18 + tests/corpus/21-sets.pseudo | 17 + tests/corpus/22-binary-to-decimal.pseudo | 25 + tests/corpus/23-dice.pseudo | 17 + tests/corpus/24-string-builtins.pseudo | 17 + tests/corpus/25-nested-collections.pseudo | 20 + tests/corpus/26-swap-byref.pseudo | 22 + tests/corpus/27-quantifiers.pseudo | 11 + tests/corpus/28-float-trap.pseudo | 7 + tests/corpus/29-early-exit-flag.pseudo | 38 + tests/corpus/30-state-machine.pseudo | 37 + tests/corpus/31-edges.pseudo | 20 + tests/corpus/32-stops.pseudo | 7 + tests/corpus/33-stops-div.pseudo | 11 + tests/corpus/34-stops-depth.pseudo | 6 + tests/corpus/35-stops-unset.pseudo | 4 + tests/corpus/36-stops-counter.pseudo | 6 + tests/corpus/37-static-errors.pseudo | 14 + tests/corpus/38-continue.pseudo | 11 + tests/corpus/39-constants-codons.pseudo | 29 + tests/corpus/40-text-builtins.pseudo | 24 + tests/corpus/41-reserved-name.pseudo | 7 + tests/corpus/42-numerics.pseudo | 17 + tests/corpus/43-parallel-map.pseudo | 30 + tests/corpus/44-parallel-race.pseudo | 10 + .../corpus/45-parallel-neighbour-race.pseudo | 8 + tests/corpus/46-projectile.pseudo | 25 + tests/corpus/47-binomial-and-ph.pseudo | 22 + tests/corpus/48-declare-with-value.pseudo | 32 + tests/course-css.test.mjs | 27 + tests/curriculum.test.mjs | 117 + tests/editor.test.mjs | 31 + tests/exercises.test.mjs | 38 + tests/fuzz.test.mjs | 90 + tests/hardware.test.mjs | 261 + tests/helpers/sync-programs.mjs | 194 + tests/listings.test.mjs | 75 + tests/matho.test.mjs | 184 + tests/mojo-check.test.mjs | 226 + tests/mojo-run.test.mjs | 182 + tests/mojo.test.mjs | 327 + tests/practices-switch.test.mjs | 83 + tests/practices.test.mjs | 145 + tests/pseudo-declare-init.test.mjs | 52 + tests/quarto-gallery.test.mjs | 46 + tests/quarto-render.test.mjs | 212 + tests/quarto.test.mjs | 263 + tests/quarto/harness.lua | 36 + tests/reference.test.mjs | 129 + tests/runview.test.mjs | 100 + tests/services.test.mjs | 113 + tests/snapshots/practices.json | 68 + tests/snapshots/sync-mojo/best-position.mojo | 19 + tests/snapshots/sync-mojo/binary-search.mojo | 25 + .../sync-mojo/count-base-proved.mojo | 18 + tests/snapshots/sync-mojo/count-base.mojo | 21 + tests/snapshots/sync-mojo/edit-distance.mojo | 31 + tests/snapshots/sync-mojo/first-unknown.mojo | 16 + tests/snapshots/sync-mojo/gc-fraction.mojo | 16 + tests/snapshots/sync-mojo/hamming.mojo | 17 + tests/snapshots/sync-mojo/kmers.mojo | 21 + .../snapshots/sync-mojo/match-off-by-one.mojo | 27 + tests/snapshots/sync-mojo/match-proved.mojo | 28 + tests/snapshots/sync-mojo/match-reset.mojo | 23 + tests/snapshots/sync-mojo/match.mojo | 27 + tests/snapshots/sync-mojo/revcomp.mojo | 25 + tests/snapshots/sync-mojo/tally.mojo | 17 + .../snapshots/sync-mojo/translate-codons.mojo | 34 + tests/state.test.mjs | 93 + tests/sync-coverage.test.mjs | 104 + tests/sync-hub.test.mjs | 298 + tests/sync-lingo.test.mjs | 112 + tests/sync-matho.test.mjs | 234 + tests/sync-mojo.test.mjs | 268 + tests/sync-speco.test.mjs | 150 + tests/tasks.test.mjs | 68 + tests/versions.test.mjs | 229 + tsconfig.json | 42 + 1679 files changed, 1024562 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitea/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 README.md create mode 100644 docs/Caddyfile create mode 100644 docs/app.md create mode 100644 docs/asm-coverage.md create mode 100644 docs/deploy.md create mode 100644 docs/engines.md create mode 100644 docs/exercises.md create mode 100644 docs/mojo-corpus.md create mode 100644 docs/sync-coverage.md create mode 100644 index.html create mode 100644 mojo/corpus/SOURCES.md create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/deferred_ops_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/deferred_type_invalid.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_limit.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_options.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_prelude.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_recursion1.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_recursion2.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_recursion3.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_recursion4.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/elaboration_error/elaboration_error_scc_type_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/inputs/diags_package/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-integration/parse_time_only_attrs.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/capture_lists_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/closure_interior_origin_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/closure_marker_conformance_refinement_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/recursion.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/struct_explicit_fn_trait_conformance.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/unified_closure_implicit_conversion.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/closures/unified_closures_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/dead_code_warning.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/alias/alias_unpack_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/alias/associated_aliases_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/alias/parametric_alias_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/align_decorator_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/body_constraint_deferral.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/builtin_inline_recursion.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/conflicting_imports_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/conformance_parametric_constraint_alias.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/constraint_overload_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decls_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/decorators_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/deprecated/deprecated_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/deprecated/inputs/imported_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/doc_inline/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/export/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/inputs/imported_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/name/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/stable/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/stable/errors_since.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/stable/test_std_mock/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/stable/warn_magic_fn.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/unavailable/inputs/imported_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/unavailable/unavailable_body.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/decorators/unavailable/unavailable_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/deinit_deprecation_warning.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/fn_def_decls_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/fn_type_where_conversion_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/fn_type_where_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/imm_convention.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/implicit_var_decl.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/comptime_a/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/comptime_b/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/fn_a/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/fn_b/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/fn_c/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/fn_d/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/imported_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/mlirtype_a/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/mlirtype_b/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/struct_a/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/struct_b/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/struct_c/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/struct_d/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/inputs/struct_package_for_conflict/plain_struct.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/keyword_fn_names.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/lookup_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/pack_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/param_infer_diags.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/parameter_closures_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/recursive_signature_literal_size.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/specialized_generator_discharge_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_body_constraints.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_call_sugar_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_conditional_trait_conformance_duplicate_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_conditional_trait_conformance_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_extensions_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_extensions_importing_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/struct_extensions_shadowed_target.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/structs.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/trait_composition_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/traits_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/typo_suggestion.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/var.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/var_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/where_conformance_on_return.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/where_message_conformance.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/where_message_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/decls/where_message_parse_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/default_associated_alias_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/default_trait_method_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/deferred_ops_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/deferred_ops_warnings.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/deferred_type_warnings.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/docs/__init__.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/docs/parser_doc_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/docs/parser_doc_module_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/explicit_destroy_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/explicit_destroy_parse_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/explicit_materialization.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/expressions.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/call_emission_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/expressions_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/exprs_misc.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/getitem_setitem_emission_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/is_run_in_comptime_interpreter_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/string_literal_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/tuple_type_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/exprs/type_conversion_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/function_types_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/bare_import_gate.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_bad_symlink.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_deep_submodule.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_dotted_no_clash.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_dual_mount_first_binding_wins.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_dual_mount_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_dual_mount_source_package.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_error_no_stale_binding.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_error_poisoning.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_escaped_dotted_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_fn_overloads.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_fn_scope_comptime_blocks.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_fn_scope_conflicts.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_fn_scope_no_leak.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_fn_scope_ordering.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_leaf_binding.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_missing_suggestion.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_moved_stdlib_note.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_namespace_ambiguous.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_namespace_case_sensitive.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_namespace_shadowed_submodule.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/import_self.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/fn_overload_package/module1.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/fn_overload_package/module2.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/imported_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/no_sibling_leak/consumer_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/no_sibling_leak/consumer_reexport.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/inputs/no_sibling_leak/consumer_symbol.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/import/test_import_through_module.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/inline_mlir_op_fstring_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/lexer_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/lexical_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/lsp/signature_only_conditional_deletable.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/main_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/mlir_features_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/moco2698.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/moco2699.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/moco_2314.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/interior_origin_cldiags.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/ownership.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/ownership_cf.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/ownership_cldiags.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/ownership_eh.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/ownership/ownership_refs.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/parameters_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/punctuation_tokens.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/raising_getter_binds_parameters.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/comptime_assert_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/control_flow_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/match_diags.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/module_scope_control_flow_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/module_scope_try_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/raise_and_try.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/raise_and_try_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/type_body_control_flow_errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/statements/type_body_try_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/t-strings/errors.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/trait_downcast_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/type_diff_corresponding_origins.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/type_refinement_negative.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/variadic_binding_error.mojo create mode 100644 mojo/corpus/diagnostics/files/mojo-parser/vertical_whitespace.mojo create mode 100644 mojo/corpus/diagnostics/manifest.json create mode 100644 mojo/corpus/editor/editor.json create mode 100644 mojo/corpus/manual/code/manual/basics/blocks_and_statements.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/comments.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/docstrings.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/explicit_variables.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/functions.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/hello_world.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/parameterization.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/python_integration.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/structs.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/structs_fieldwise.mojo create mode 100644 mojo/corpus/manual/code/manual/basics/traits.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_c_number_types.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_call_libc.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_memory.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_pointers.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_shared_libraries.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_string_lifetime.mojo create mode 100644 mojo/corpus/manual/code/manual/c-ffi/test_strings.mojo create mode 100644 mojo/corpus/manual/code/manual/control-flow/conditional_expression.mojo create mode 100644 mojo/corpus/manual/code/manual/control-flow/for_loop.mojo create mode 100644 mojo/corpus/manual/code/manual/control-flow/if_statement.mojo create mode 100644 mojo/corpus/manual/code/manual/control-flow/short_circuit.mojo create mode 100644 mojo/corpus/manual/code/manual/control-flow/while_loop.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/conditional_context_mgr.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/context_mgr.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/enumerated_errors.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/error_interaction.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/handle_error.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/never_type.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/parametric_raises.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/resource_guard.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/stacktrace_error.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/stacktrace_error_capture.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_conditional_context_mgr.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_context_mgr.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_enumerated_errors.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_error_interaction.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_handle_error.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_never_type.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_parametric_raises.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_typed_errors_doc.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_typed_errors_edge_cases.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_typed_errors_testing.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/test_variant_errors.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/typed_errors.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/typed_errors_edge_cases.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/typed_errors_testing.mojo create mode 100644 mojo/corpus/manual/code/manual/errors/variant_errors.mojo create mode 100644 mojo/corpus/manual/code/manual/functions/closures/test_closures.mojo create mode 100644 mojo/corpus/manual/code/manual/functions/lambda/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/functions/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/generics/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/get-started/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/lifecycle/death/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/lifecycle/explicit-destroy/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/lifecycle/initialization/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/lifecycle/life/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/lifecycle/trivial/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/comptime-evaluation/comptime_for.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/comptime-evaluation/comptime_if.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/comptime-evaluation/comptime_scope.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/comptime-evaluation/overview.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/materialization/comptime_subexpression.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/materialization/global_constant.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/materialization/materializing_values.mojo create mode 100644 mojo/corpus/manual/code/manual/metaprogramming/reflection/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/operators/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/alias.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/anatomy_parameter_list.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/automatic_parameterization.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/automatic_parameterization_partial_binding.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/conditional_conformance.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/fully_bound_partially_bound_etc.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/infer_only_parameters.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/multiplier.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/optional_and_inferred_parameters.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/optional_and_keyword_parameters.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/optional_and_kw_params_in_structs.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parameter_expressions_are_just.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parameter_inference.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parameterized_functions.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parameterized_structs_staticmethod.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parameters_and_generics.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/parametric_alias.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/powerful_compile_time_programming.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/rebind.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/rsqrt_example.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/struct_parameter_reference.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/use_simd.mojo create mode 100644 mojo/corpus/manual/code/manual/parameters/index/variadic_parameters.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/index/arc_pointer.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/index/owned_pointer.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/index/pointer.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/index/shared_dict.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/allocation.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/basics.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/bitcast.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/foreign_pointers.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/multiple_values.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/nullable.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/origins.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/python_pointer.mojo create mode 100644 mojo/corpus/manual/code/manual/pointers/using-pointers/simd_vectors.mojo create mode 100644 mojo/corpus/manual/code/manual/python-to-mojo/python_to_mojo.mojo create mode 100644 mojo/corpus/manual/code/manual/python/mojo-from-python/mojo_module.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/mojo_types.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/python_compare.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/python_conversions.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/python_dict.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/python_list.mojo create mode 100644 mojo/corpus/manual/code/manual/python/types/python_tuple.mojo create mode 100644 mojo/corpus/manual/code/manual/quickstart/quickstart.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/index/mutable_self_in_function.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/index/my_pair.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/index/object_initialization.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/index/static_method.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/index/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/operator-support/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/structs/reference/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/traits/tests.mojo create mode 100644 mojo/corpus/manual/code/manual/types/float_constants.mojo create mode 100644 mojo/corpus/manual/code/manual/types/numeric_literals_and_conversions.mojo create mode 100644 mojo/corpus/manual/code/manual/types/strings.mojo create mode 100644 mojo/corpus/manual/code/manual/values/lifetimes/immutable_name_list.mojo create mode 100644 mojo/corpus/manual/code/manual/values/lifetimes/inferred_origin.mojo create mode 100644 mojo/corpus/manual/code/manual/values/lifetimes/name_list.mojo create mode 100644 mojo/corpus/manual/code/manual/values/value-semantics/def_int.mojo create mode 100644 mojo/corpus/manual/code/manual/values/value-semantics/def_simd.mojo create mode 100644 mojo/corpus/manual/code/manual/values/value-semantics/fn_int.mojo create mode 100644 mojo/corpus/manual/code/manual/values/value-semantics/variable.mojo create mode 100644 mojo/corpus/manual/code/manual/variables/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_basics.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_compile_time.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_conversions.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_ownership.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_traits.mojo create mode 100644 mojo/corpus/manual/code/reference/cheat-sheets/test_types_and_literals.mojo create mode 100644 mojo/corpus/manual/code/reference/closure-declarations/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/compound-statements/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/aligned_field.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/arrays.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/basic.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/generic.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/heap.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/int_8byte.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/register.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/align/special.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/deprecated/basic_deprecation.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/deprecated/deprecation.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/doc-hidden/doc_hidden.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/implicit/floor.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/implicit/implicit.mojo create mode 100644 mojo/corpus/manual/code/reference/decorators/parameter/legacy_capturing_closure.mojo create mode 100644 mojo/corpus/manual/code/reference/expressions/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/function-declarations/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/inline-mlir/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/keywords/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/lambda-expressions/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/literals/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/numeric-types/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/simple-statements/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/struct-declarations/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/trait-declarations/tests.mojo create mode 100644 mojo/corpus/manual/code/reference/types/tests.mojo create mode 100644 mojo/corpus/manual/code/tools/notebooks/gpu_hello.mojo create mode 100644 mojo/corpus/manual/code/tools/notebooks/hello.mojo create mode 100644 mojo/corpus/manual/code/tools/notebooks/hello_writing.mojo create mode 100644 mojo/corpus/manual/code/tools/notebooks/parameterized.mojo create mode 100644 mojo/corpus/manual/code/tools/notebooks/vector_addition.mojo create mode 100644 mojo/corpus/manual/manifest.json create mode 100644 mojo/corpus/manual/snippets/manual-control-flow-24.mojo create mode 100644 mojo/corpus/manual/snippets/manual-control-flow-25.mojo create mode 100644 mojo/corpus/manual/snippets/manual-control-flow-26.mojo create mode 100644 mojo/corpus/manual/snippets/manual-errors-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-errors-5.mojo create mode 100644 mojo/corpus/manual/snippets/manual-errors-6.mojo create mode 100644 mojo/corpus/manual/snippets/manual-errors-7.mojo create mode 100644 mojo/corpus/manual/snippets/manual-errors-8.mojo create mode 100644 mojo/corpus/manual/snippets/manual-parameters-index-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-parameters-index-2.mojo create mode 100644 mojo/corpus/manual/snippets/manual-parameters-index-4.mojo create mode 100644 mojo/corpus/manual/snippets/manual-parameters-index-7.mojo create mode 100644 mojo/corpus/manual/snippets/manual-pointers-using-pointers-4.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-2.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-3.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-4.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-5.mojo create mode 100644 mojo/corpus/manual/snippets/manual-python-types-6.mojo create mode 100644 mojo/corpus/manual/snippets/manual-types-7.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-lifetimes-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-lifetimes-2.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-lifetimes-3.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-ownership-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-ownership-2.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-ownership-3.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-ownership-4.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-ownership-5.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-value-semantics-1.mojo create mode 100644 mojo/corpus/manual/snippets/manual-values-value-semantics-2.mojo create mode 100644 mojo/corpus/manual/snippets/reference-decorators-parameter-1.mojo create mode 100644 mojo/corpus/messages/messages.json create mode 100644 mojo/corpus/quest/manifest.json create mode 100644 mojo/corpus/quest/solutions/MQ_101.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_102.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_103.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_104.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_105.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_106.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_107.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_108.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_109.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_110.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_111.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_113.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_115.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_201.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_202.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_203.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_207.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_208.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_210.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_211.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_213.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_214.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_215.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_219.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_220.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_221.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_222.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_223.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_224.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_301.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_302.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_303.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_304.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_305.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_306.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_308.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_309.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_310.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_312.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_320.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_321.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_322.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_323.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_324.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_325.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_326.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_401.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_402.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_403.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_412.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_501.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_502.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_503.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_504.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_505.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_507.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_510.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_511.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_512.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_513.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_520.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_601.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_602.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_604.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_702.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_703.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_704.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_705.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_706.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_710.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_801.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_803.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_810.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_812.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_825.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_827.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_830.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_835.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_845.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_852.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_858.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_901.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_903.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_950.mojo create mode 100644 mojo/corpus/quest/solutions/MQ_951.mojo create mode 100644 mojo/corpus/quest/starters/MQ_101.mojo create mode 100644 mojo/corpus/quest/starters/MQ_102.mojo create mode 100644 mojo/corpus/quest/starters/MQ_103.mojo create mode 100644 mojo/corpus/quest/starters/MQ_104.mojo create mode 100644 mojo/corpus/quest/starters/MQ_105.mojo create mode 100644 mojo/corpus/quest/starters/MQ_106.mojo create mode 100644 mojo/corpus/quest/starters/MQ_107.mojo create mode 100644 mojo/corpus/quest/starters/MQ_108.mojo create mode 100644 mojo/corpus/quest/starters/MQ_109.mojo create mode 100644 mojo/corpus/quest/starters/MQ_110.mojo create mode 100644 mojo/corpus/quest/starters/MQ_111.mojo create mode 100644 mojo/corpus/quest/starters/MQ_113.mojo create mode 100644 mojo/corpus/quest/starters/MQ_115.mojo create mode 100644 mojo/corpus/quest/starters/MQ_201.mojo create mode 100644 mojo/corpus/quest/starters/MQ_202.mojo create mode 100644 mojo/corpus/quest/starters/MQ_203.mojo create mode 100644 mojo/corpus/quest/starters/MQ_207.mojo create mode 100644 mojo/corpus/quest/starters/MQ_208.mojo create mode 100644 mojo/corpus/quest/starters/MQ_210.mojo create mode 100644 mojo/corpus/quest/starters/MQ_211.mojo create mode 100644 mojo/corpus/quest/starters/MQ_213.mojo create mode 100644 mojo/corpus/quest/starters/MQ_214.mojo create mode 100644 mojo/corpus/quest/starters/MQ_215.mojo create mode 100644 mojo/corpus/quest/starters/MQ_219.mojo create mode 100644 mojo/corpus/quest/starters/MQ_220.mojo create mode 100644 mojo/corpus/quest/starters/MQ_221.mojo create mode 100644 mojo/corpus/quest/starters/MQ_222.mojo create mode 100644 mojo/corpus/quest/starters/MQ_223.mojo create mode 100644 mojo/corpus/quest/starters/MQ_224.mojo create mode 100644 mojo/corpus/quest/starters/MQ_301.mojo create mode 100644 mojo/corpus/quest/starters/MQ_302.mojo create mode 100644 mojo/corpus/quest/starters/MQ_303.mojo create mode 100644 mojo/corpus/quest/starters/MQ_304.mojo create mode 100644 mojo/corpus/quest/starters/MQ_305.mojo create mode 100644 mojo/corpus/quest/starters/MQ_306.mojo create mode 100644 mojo/corpus/quest/starters/MQ_308.mojo create mode 100644 mojo/corpus/quest/starters/MQ_309.mojo create mode 100644 mojo/corpus/quest/starters/MQ_310.mojo create mode 100644 mojo/corpus/quest/starters/MQ_312.mojo create mode 100644 mojo/corpus/quest/starters/MQ_320.mojo create mode 100644 mojo/corpus/quest/starters/MQ_321.mojo create mode 100644 mojo/corpus/quest/starters/MQ_322.mojo create mode 100644 mojo/corpus/quest/starters/MQ_323.mojo create mode 100644 mojo/corpus/quest/starters/MQ_324.mojo create mode 100644 mojo/corpus/quest/starters/MQ_325.mojo create mode 100644 mojo/corpus/quest/starters/MQ_326.mojo create mode 100644 mojo/corpus/quest/starters/MQ_401.mojo create mode 100644 mojo/corpus/quest/starters/MQ_402.mojo create mode 100644 mojo/corpus/quest/starters/MQ_403.mojo create mode 100644 mojo/corpus/quest/starters/MQ_412.mojo create mode 100644 mojo/corpus/quest/starters/MQ_501.mojo create mode 100644 mojo/corpus/quest/starters/MQ_502.mojo create mode 100644 mojo/corpus/quest/starters/MQ_503.mojo create mode 100644 mojo/corpus/quest/starters/MQ_504.mojo create mode 100644 mojo/corpus/quest/starters/MQ_505.mojo create mode 100644 mojo/corpus/quest/starters/MQ_507.mojo create mode 100644 mojo/corpus/quest/starters/MQ_510.mojo create mode 100644 mojo/corpus/quest/starters/MQ_511.mojo create mode 100644 mojo/corpus/quest/starters/MQ_512.mojo create mode 100644 mojo/corpus/quest/starters/MQ_513.mojo create mode 100644 mojo/corpus/quest/starters/MQ_520.mojo create mode 100644 mojo/corpus/quest/starters/MQ_601.mojo create mode 100644 mojo/corpus/quest/starters/MQ_602.mojo create mode 100644 mojo/corpus/quest/starters/MQ_604.mojo create mode 100644 mojo/corpus/quest/starters/MQ_702.mojo create mode 100644 mojo/corpus/quest/starters/MQ_703.mojo create mode 100644 mojo/corpus/quest/starters/MQ_704.mojo create mode 100644 mojo/corpus/quest/starters/MQ_705.mojo create mode 100644 mojo/corpus/quest/starters/MQ_706.mojo create mode 100644 mojo/corpus/quest/starters/MQ_710.mojo create mode 100644 mojo/corpus/quest/starters/MQ_801.mojo create mode 100644 mojo/corpus/quest/starters/MQ_803.mojo create mode 100644 mojo/corpus/quest/starters/MQ_810.mojo create mode 100644 mojo/corpus/quest/starters/MQ_812.mojo create mode 100644 mojo/corpus/quest/starters/MQ_825.mojo create mode 100644 mojo/corpus/quest/starters/MQ_827.mojo create mode 100644 mojo/corpus/quest/starters/MQ_830.mojo create mode 100644 mojo/corpus/quest/starters/MQ_835.mojo create mode 100644 mojo/corpus/quest/starters/MQ_845.mojo create mode 100644 mojo/corpus/quest/starters/MQ_852.mojo create mode 100644 mojo/corpus/quest/starters/MQ_858.mojo create mode 100644 mojo/corpus/quest/starters/MQ_901.mojo create mode 100644 mojo/corpus/quest/starters/MQ_903.mojo create mode 100644 mojo/corpus/quest/starters/MQ_950.mojo create mode 100644 mojo/corpus/quest/starters/MQ_951.mojo create mode 100644 mojo/corpus/release/release.json create mode 100644 mojo/corpus/report.json create mode 100644 mojo/corpus/skill/removed-syntax.json create mode 100644 mojo/corpus/stdindex/stdindex.json create mode 100644 mojo/corpus/stdtypes/stdtypes.json create mode 100644 mojo/corpus/syntax/cases.json create mode 100644 mojo/corpus/syntax/mojo.syntax.json create mode 100644 mojo/corpus/tokens/tokens.json create mode 100644 mojo/golden/00633f3ab0d58df9d0eb19d4aa8a6738d83168a10d46b1ce6df18735355609b7.json create mode 100644 mojo/golden/00d314582eae02331ad0b13903f522a804c325ec7e4033221dd665c8f61387a9.json create mode 100644 mojo/golden/00f1f0a157c3933dbe1c303907e9eb163957ff6f80d0013ad51df366f11269ba.json create mode 100644 mojo/golden/025561dfa1186ae92f0b3e0cbd787c4c0dcec4f86e21e32894ed7c62d92d2c6d.json create mode 100644 mojo/golden/02ee2c2a7cd5e642bc24b3c42ede6fcd921431999ee4f3da4b88f30102317b7a.json create mode 100644 mojo/golden/0359233eff3e12402296409b56645d144770f0ae62e4dece79cbb0e3fd1f0e74.json create mode 100644 mojo/golden/03ea7b3d5d2b2d9dba0edcc953909c09c109870af3f1bed801c14eb00166f19c.json create mode 100644 mojo/golden/04618bfa9309d9c2592a1bf04906012fd1142d6d8f3a9d75d06bd22689560c3b.json create mode 100644 mojo/golden/0512ed605b3102ec1f6a3a782696364f34976bf787ef33fcc85f9f4d2ebd1966.json create mode 100644 mojo/golden/0535ed686c666125b197336c71f2a813f5e27b04908730f55241b787f51a8320.json create mode 100644 mojo/golden/0551c855cee622eed3ce6b24e36369d2c2067124d7dd070f67dce555a9b48f62.json create mode 100644 mojo/golden/0596b842e004b667eb7ee1a0e6610415289f13648734b03dfef889e1a1b2c653.json create mode 100644 mojo/golden/061e64b5488aa5642489f0cf1209bda78bf1484c3632cb75241aa6b2d6c3629e.json create mode 100644 mojo/golden/066eb7c877e5b571ededcc3a7e6a78d0fba34f04e43db089fc156d5de9086ec5.json create mode 100644 mojo/golden/06f192f7c0453f4bba5473ee0dea4f10914292893dbdc5c8a8238ad824960bd6.json create mode 100644 mojo/golden/08596bb99d5d74f4a519912d735159d8be3f256e78e954b46e66d65fe7b98031.json create mode 100644 mojo/golden/09349057b6d48fcf7417d881a75ee4a0bb746bec57397292bb376d9a77bf7c19.json create mode 100644 mojo/golden/0a732eea40ad64d45826f1c2a8d1e41b440b358c402dbe514d52649ed61dd40d.json create mode 100644 mojo/golden/0b318b0cba50736417d5b17b99db4a9399c0ad3f98dbf69de4f35bcb3ddaa327.json create mode 100644 mojo/golden/0bce9f9238853f5e15590c673a2edec51e5dd0b5a0b4f5c06296a74a980eb7da.json create mode 100644 mojo/golden/0d0f82a93003b99d0bc0494f4092dea1efdb2e01e2719f1428352da4a3235857.json create mode 100644 mojo/golden/0d32a6a3924fc2c16ef6da188d2abc40db126f227d0d9f1067437373d595d7eb.json create mode 100644 mojo/golden/0d4372ff2697c38e9968f1c653135eaeadeb4b70a66203f0fa95432ed266fc4d.json create mode 100644 mojo/golden/0d944813beac045b055422ff016f1e06e6562714758c0f1f621c738748fa98e6.json create mode 100644 mojo/golden/0d9a9787b9a0b79f9d2a17c0fd2d558cabc4845dc655df0ee5a86c03602afcac.json create mode 100644 mojo/golden/0ec396ca7045c00c1d0729691aba4444d5cb1fd886d8f0bbb113ef05844e3295.json create mode 100644 mojo/golden/0ece01ee912ac887eaa33ed5092aea6fd212d1780248ce7e2e40c1d3946fffa4.json create mode 100644 mojo/golden/0ee340117cbbe2549ba4eadd20ad3f71d2b202748e786abcf80cf8dab13d56aa.json create mode 100644 mojo/golden/0fea3ee15b9a131d65668ebc6e73b6a0a16473f6aa3a7a1f802921f7e7ec0403.json create mode 100644 mojo/golden/0ffff81a45fd906b4cbd37866238a5f2d36e369d1dec85d1da5b51ae422ad794.json create mode 100644 mojo/golden/105ee8b586b56572f6bcf3cfbd1c074adb88f306e0e8b304ece7e31c3db9f155.json create mode 100644 mojo/golden/11d194ec98d92ccf72709c4ab221d007bf71cdefedfaa6a8d2fd850ed9291946.json create mode 100644 mojo/golden/121ad55aac3086079a7ef20a40540d3f85a023cd7c8606c6f5cf4609578e01d2.json create mode 100644 mojo/golden/12432b36e5a24064f98f577310ea0c3a979c2ca16fcf634d2ea47f259afb99d7.json create mode 100644 mojo/golden/1270f808bda440a617818039758d6bedcb2669efa93af96efc61a983f86b4bb9.json create mode 100644 mojo/golden/12ee992bf235dab88700e33b36e8fa8c05ebf49a7e8f20161508c835e28f0200.json create mode 100644 mojo/golden/1305fba05533064c3e51605754d6f2f8ac4019e06ca1cb57ee9a538419254298.json create mode 100644 mojo/golden/130ade9ef172753911ca63acfcc9fd988ce30a67677608dd2467c7ce3b32bc40.json create mode 100644 mojo/golden/138277e191110dd916b26320df60839899d7ae98838698615f647d2e487846ce.json create mode 100644 mojo/golden/14591c1a3f95f76a8e6a1d7c0a1b1dd7e0e362e16572a2092a105507683fafaa.json create mode 100644 mojo/golden/1484f1203e252d92666798240b94e8302720a96d2f88d84d316280237a1d901e.json create mode 100644 mojo/golden/14ae7179f4fc3f7d05e1ae4da04a0601e1effc548ae80e333c67a322fee43885.json create mode 100644 mojo/golden/153f2e6dbd63746179ec625a2527656e116cdaafb9053cfa3a3b47c6b6d10c24.json create mode 100644 mojo/golden/16f3f7e05eebd9e4ce559819656f2f129336332064f90e8d01ff661fe83483c7.json create mode 100644 mojo/golden/174f47ac97f5af6385dfaf99982f81d43a9e4be7f13496e929d42665eebafc58.json create mode 100644 mojo/golden/1839560333c48957566d69f53c4640176730f9faba8602c3bc289673d538d629.json create mode 100644 mojo/golden/188a646beef4d2815911e46c12f1ea25f63eea5680a691b1b931ab1285f9121d.json create mode 100644 mojo/golden/18fd33900770a4edc792b3812dd75b29e8d136e3b016b6a510a5b445f908da29.json create mode 100644 mojo/golden/19d963efc3314cd571cd99ca190e60741cb9496a70b6ece91841378359cfee0b.json create mode 100644 mojo/golden/1a72c45677a05122b52e83d74afeb35803a69f12196b20112f8adb83cbc25a63.json create mode 100644 mojo/golden/1b3d5baeff96bf4fa08ca11aee56126ba5e716a5548d7344334567bdfc5743dd.json create mode 100644 mojo/golden/1b4a2aa2f3577260f2225903e4288481993fdf07929771b892de183e5da5f456.json create mode 100644 mojo/golden/1b5795811a40f49b40fa4fba1abfe2b3d4fd798065553c037352e8c97179eb44.json create mode 100644 mojo/golden/1b82dfc5af5168d9c9d7fbb9723e314af9b04fe9aa80fc86e6dba9940fd59e43.json create mode 100644 mojo/golden/1bbd9d46002801b136411ff1632521f0af61b760c2a6458e6fb2dade41bed5ad.json create mode 100644 mojo/golden/1d98ed646c3ea3b20651addf91a920475b65bbf425d1893a50323a2060dcb15f.json create mode 100644 mojo/golden/1dad7920b309ce9278185634d83fa05675536665c5d9a0b1fe4b3fdc7a3d424f.json create mode 100644 mojo/golden/1ddc0df00196859e2a580099d1aa12b88674677f7e87deb11183c97f5516a9d5.json create mode 100644 mojo/golden/1e3537391cab1a0cabd814461e9afe98f171f31c317eb2ce878574738a14f1cb.json create mode 100644 mojo/golden/1e91c2fa0dccbc2967c792b3d26077d2555aa0b71d64c5988730f8c579c2a59b.json create mode 100644 mojo/golden/1eb0dfbe098ee2f0fa077b268b45f744a8f3c040f337d24cb0050f5c32f066e8.json create mode 100644 mojo/golden/1eecf67159909cf5cadbc72f4f26f82e8a6eb9a72cddb4c7f9f9f470f0a3654a.json create mode 100644 mojo/golden/1f62641257a20f052753ffc096b4b4bf6f0b75884b8704c5e3fa0e4b5d2baa06.json create mode 100644 mojo/golden/1fb31db6975a839a49c2f0a1310aa9cf5d22ea55c095fb30ccdf0f4981f53be9.json create mode 100644 mojo/golden/20095836a0d8688071cec2f38e251c767e656aac71a816f410b5e294abf8c19f.json create mode 100644 mojo/golden/20f3c39986f1971b938153404231b1d892f50d0473236c1fb6c351fd0aa61d59.json create mode 100644 mojo/golden/214779587fd945f32f7ee7f00135659d873f863e0f50dd65625eef3cc0085a8b.json create mode 100644 mojo/golden/216ddc7f1d4cad8cec4b459299bb63b633505c1b3bf310a874e54d621cf27dc0.json create mode 100644 mojo/golden/21bed3e1ef7bf3eff7aa4669b412d94e7acdbc33750a1367182f34c5368bc99b.json create mode 100644 mojo/golden/226cb79ce80d2aa9c515f337a50397b54177cc9eb1c9267157454e06ccee197f.json create mode 100644 mojo/golden/2432d132695d84659d8854c9bd20eddf7f5c62c763ffce89707d0b0e83f07eef.json create mode 100644 mojo/golden/2458b40afeafddb0c641d8aca75e9e3b592a96892dd3e08ae227af844e6c5513.json create mode 100644 mojo/golden/250b56e93a92866600339d3933fc1aad378567101ed0755d93c36f06c731a376.json create mode 100644 mojo/golden/253e7bbfc16fcf548fc3cef4ade2cb147c873f34204aabdb45cbb2d761320619.json create mode 100644 mojo/golden/25cc1f8a8610541749956993d07735a88908f20fe3782c7a5a5c1c226abcf508.json create mode 100644 mojo/golden/25d1767ccdf7b2150ca811e59bd7b6be47bb0dbc70087a1d8be8840928377c74.json create mode 100644 mojo/golden/25e92660ae0cb42ec3d695adca3b3c3a1f312f4fde644200525ef144ede2b8b3.json create mode 100644 mojo/golden/269dc652b9173820cece6cbf0613add0d036a7f7e8b6a1d4432aeacea429c4f1.json create mode 100644 mojo/golden/26f06819f20d7812554af8e03362548cce4fee03debcafb79b0929bf85525c7e.json create mode 100644 mojo/golden/2743aced3ecd6321265ca68fa06ea616bc3e6590e3b682ad2b4b6b7b52a6653c.json create mode 100644 mojo/golden/27768ec16fc6ffc9b83fdbf1e1bbaa287e20c625c6da8d61d8ca03aa59921620.json create mode 100644 mojo/golden/27f32db9d5de0c7b0528612e6a0d9042e1fb0882d4c80fd2011c418b7f02a19c.json create mode 100644 mojo/golden/2874e464fdce099a4a69391531c1cfc6d0a091e6d1af478134183d3a0706348f.json create mode 100644 mojo/golden/288904722c3a13a09ee9ad086a432190efcd52b3ddf696f4282740e5707c1f4f.json create mode 100644 mojo/golden/288bc2973111d1e3cdfc0094677962094b416d223aa55d38c6482502dbde0ec3.json create mode 100644 mojo/golden/28dd89ad0cc0e7bd00923dc2515244a9f8e7e1542ea987b52e72a4402470a28f.json create mode 100644 mojo/golden/29829a8561915308c70fdc9ecfb6857d18c8fe09bc3f07a662d4b577ff514f71.json create mode 100644 mojo/golden/2aefee2ba60c3c8cd0b16a72265466ebe697d4d9bfe7fc77b501030e1300678d.json create mode 100644 mojo/golden/2bc5f61e04820d7f95e41b55f6b0983ed69ad7920e7a33790f81d1df3bb136df.json create mode 100644 mojo/golden/2be50cfabc13f3b670211eb0863e0d109a59aca4865a164c645a4240805740d4.json create mode 100644 mojo/golden/2ca288205a5fc9410cae0cd408b2d4e204874f7a2ca83262000e70c090cd0536.json create mode 100644 mojo/golden/2d0e0b3e4402852d89acef6621523d74ba7ed1d8be04e54260af830d48497fc7.json create mode 100644 mojo/golden/2d2cecea19a07ea6e62ef55cf0ee3306c297c6efc7f8d9bf2d7b499432f332c4.json create mode 100644 mojo/golden/2da89671cfe40fa40d16ef8d7427c2f8e81fbb20b5c300c9b5acdb8b4c8f2c00.json create mode 100644 mojo/golden/2dda7e8fb822b2ef52aa1a871f4308111851d1ac36ee390062dc78daf4972759.json create mode 100644 mojo/golden/2ea036de3717b75d713d59ef0df83ca7ae24e33275d22ef58d74dc0c1d4cda21.json create mode 100644 mojo/golden/2f07b29fda3aab9169b48dbf360ddd5402095133b71f487d6c0f803b8e312533.json create mode 100644 mojo/golden/2f1c3cd2a2539ff0d017c9dc529072fcceac284bb2881c3318b95260c74deb27.json create mode 100644 mojo/golden/2f7e2588816151c83072d45555c8f722a187ae9dec3206deb83214f8613f8ac7.json create mode 100644 mojo/golden/2fc2c3e7b4e3b2d36bccab66e0685b11634e0f2ec9b8333e4f3712de47fa67fc.json create mode 100644 mojo/golden/31add604960de4a6530dfb8177520e93e5947af2f46b233b7abbd20a5101f62b.json create mode 100644 mojo/golden/31c72d1cc9bbe94268d2686006e15d4a29632a967dde7af2ffb10f424f3358d5.json create mode 100644 mojo/golden/31cbba60db6acd8c967bf345e280335490e58e0b8eb466d30af1c6fca9bc12bd.json create mode 100644 mojo/golden/321863193d7815e88acfb56d921fc2ee1f10ec4aeef1d651cf4812c11095ffdd.json create mode 100644 mojo/golden/333c5ba5f990fe27f79022776eca3c520d68d4c9b337e5b6b2da685b66e4138c.json create mode 100644 mojo/golden/338c21467efbd7e026c1737a5e72dcabf6576cd3e9cdb900113c91ae35017681.json create mode 100644 mojo/golden/33a37ca6ded1ba287d3aa552b40f61bc694e382f4591028bd4366316331a4796.json create mode 100644 mojo/golden/33b8985bddb10885a50756cef38dcaca875c74f2607b31ed5abe53c710898791.json create mode 100644 mojo/golden/33e015818150e00474169bea89c0f4a6043fdba6d3b79932a096329fa4165012.json create mode 100644 mojo/golden/34315cebd02a611681c00716150e6ab3beb56ba0b5f522a556c515ce6e29848e.json create mode 100644 mojo/golden/3503e915777659197ac12c36d33defbee6eed9541ae160f08228b8341e0d0fc9.json create mode 100644 mojo/golden/3514f47652f3f1e95eb543994a46087563c4e4d2a136beb7f8988f990cfa2e36.json create mode 100644 mojo/golden/3561572f3be4cc4732d6521c576cc7f111aa7343452aab5461c5c4705d4f7849.json create mode 100644 mojo/golden/3583f370e2c964c4b4b253ffc21432c07eda5efa99c906279978c926c111e341.json create mode 100644 mojo/golden/3636e96dcc72b81e91c6abd6784a1f5f29354f6be26ad1135af5c867de5a2f7d.json create mode 100644 mojo/golden/366d93f42bbd69c174d07ad1dcbb801231578151770218a944a6ffcb2cfb5cc1.json create mode 100644 mojo/golden/36d31a2527e60555ec77c313ee1fbe6e3e46bac15464400f8906075e54fd1273.json create mode 100644 mojo/golden/3815235e2736fd881dd5aa8c166267f272ba5032955a6a5b007f86ceeefaf8af.json create mode 100644 mojo/golden/38763a41e972af9eb365323b5a00e69b2f668a31b14dea496aff983ab6ad292a.json create mode 100644 mojo/golden/38f1db1026a6663361238d15926d17a09c4987d1189f4d1f57f7badd34bcb257.json create mode 100644 mojo/golden/3921a47fc26b06c8573858e3ce0c5674aad96bda8400c2cefa4dd3e6dbcc3e5c.json create mode 100644 mojo/golden/39224fa989d6c45189309cc314ad0544caeb2f944b4d41a5b414228d98fc2394.json create mode 100644 mojo/golden/3a2013834f83992e0ebd69ff22c46ac92198d6f46d57c01590615bfc10cd1f16.json create mode 100644 mojo/golden/3a2bdad0ea3232014a1d9c186fb9ba4c45f363f0d9fb8e907c9f56697b2a3768.json create mode 100644 mojo/golden/3aa6f027eb216c39a87609492ac7b2849217de334352916de70c0120d8c73f33.json create mode 100644 mojo/golden/3aee550f9b2bf35ec6f704b2ffe9f11249bb75d8ea4ecb65c7beea927e466461.json create mode 100644 mojo/golden/3b186cd81069cf9fa85cc91edc911b992471eac67cf8b33de4e59751d7b71e71.json create mode 100644 mojo/golden/3b970280d787b98f6480483b6834f25e6eb4c056d9625ebac0922e627aed3c70.json create mode 100644 mojo/golden/3bbbcaf4de61533eed2e3387b78246fba8a8e336eae08e47aee6e8da26dd0398.json create mode 100644 mojo/golden/3d10487906885adee022c957a7ba69dac12f3f134f35b55fc31c395ba6dca556.json create mode 100644 mojo/golden/3d9efc7681ec1c474879a866b28cad035f19c0cf3b816438932022147f53863a.json create mode 100644 mojo/golden/3df22843d33e0f59ee7fa288d5dd576ec7e90a50a3674e60359bd80dc34b5cef.json create mode 100644 mojo/golden/3e61b4e0e6e4d6768b35d854f73f0d1f920723a73aa64d7b85dfe09f42cdbdc6.json create mode 100644 mojo/golden/3f06d84b15fe337c231541254932879e0f47a5691c99c93d04cc7210e5476b5e.json create mode 100644 mojo/golden/3f5dc1a46fd4ea389676ba7e85fdfc42e8b72b1d217086850dc266ae24b4ce7a.json create mode 100644 mojo/golden/3faaec58348926136d21c1cf839e127d965763c2e83ea99004b719ed135db923.json create mode 100644 mojo/golden/3fddbe7fa855af4e4b69464b7d8a4ea86fae515a66af5f876a784355520736ba.json create mode 100644 mojo/golden/40059568a4c3ea161be71884be6f7b0355329173af4ca932264a4ea977b9e728.json create mode 100644 mojo/golden/40726f6846ce00919d1f27c7e6dad0bcb60cafef9615e4f1d28b2c680562f6e7.json create mode 100644 mojo/golden/410a1052ecdfb66c9a7becb90c11835f14ee736bc543729485ed9644e7717561.json create mode 100644 mojo/golden/429af755903512be717509b0a931d26945b2105e087f602ad6bb53fadddaaff9.json create mode 100644 mojo/golden/42aa2c664273ec2332483bcea7aa6bedfc60ee9ab16292c0f52b5fd07294fe99.json create mode 100644 mojo/golden/436454d56f5c631c566f7414ade2e4bea1c39ebfdee4d61713127d3b25a2cae5.json create mode 100644 mojo/golden/44691852be0937ba44821c0d13ae77afe608daa5187d3b05dc4a5451762f2109.json create mode 100644 mojo/golden/44e221d14c7707916415848e5c929adfbfc50bcb33686138cb40d8e214098e72.json create mode 100644 mojo/golden/4503a3a2098d7751781b797512e0d2701907b96db7fdb1a48ab84e8cadba73b8.json create mode 100644 mojo/golden/458c7d579b3697a115cd2e5b1dc422d66276596366d35e2c20fc8dc77e515e4d.json create mode 100644 mojo/golden/46edfe45565eb0188cafc8775bacd0dedcd774329a6d063fb20c0e2c4e013981.json create mode 100644 mojo/golden/4710b5967c5169f33eb740837ce163535ff74a9f8b76d06763b8d0fbcedaeb40.json create mode 100644 mojo/golden/475c0830b115f299bf24c891dc3d3b39c26382ada38968b172f17761b87f47fd.json create mode 100644 mojo/golden/4928511a652bbbd57b2da01372a56fdbb3414fbdc64aa49e9a765db7be6f47dd.json create mode 100644 mojo/golden/498718f740c2cf3b31b616c4db31d7befe4928a960f79960d8b3c396071aec5b.json create mode 100644 mojo/golden/49d8de0729493c63ccc90d1647aa2ada00a2879ea6569770c582663f41f68d55.json create mode 100644 mojo/golden/4af68e1e730770b752443b6433fce55ff0b839a1e8727f50199553cc72b78170.json create mode 100644 mojo/golden/4b39c393e415a86f96c5f09b138c10bd6a83a1f77cc397b930ab2f4c55173406.json create mode 100644 mojo/golden/4c148bbde513a21efb74348e90c6b69b79f5411624f179e0017b0ddc975df740.json create mode 100644 mojo/golden/4c2d708ebb1b852398b444b4725d7aa04a75373ad9067526cef56bd4ac9dfb6b.json create mode 100644 mojo/golden/4c316f6adcc32751d892bb2f640082e18568c01b11c5cd921547d5acccea9387.json create mode 100644 mojo/golden/4c32c9a796035cbc077618c9da909d980b12493503c75125fada2579075a9ba5.json create mode 100644 mojo/golden/4cd61b2d70a0c7a877c948cd4f80b4e9a897a1cf35d749b1b3539f1ff0c5a348.json create mode 100644 mojo/golden/4d1f1ab2a52f9e192d788e3ff10c173ebdb27dd078f72d07014c6cf81b136c83.json create mode 100644 mojo/golden/4d569789bfe8dbcb4ce206e9514814f7615f2a00a1124976e6f751f087f27b7a.json create mode 100644 mojo/golden/4dd08a04c6197d3317cbcb2cbba7d06e9629a529dcdb6e26a137bdf4b4c48128.json create mode 100644 mojo/golden/4e19e32bef9de206532fb7a715d0920625f775f796b03f96ed48bcae53331588.json create mode 100644 mojo/golden/4e29313a522e658ee42ee326c89428ea149baf6c40a93391c034197694648fff.json create mode 100644 mojo/golden/4e7c69d5e4a6359d80cbfe94fae2d47ac2f47e76a736a2be010a552fcbcd5a31.json create mode 100644 mojo/golden/4e9ee7c2b30432f3baa7eb0b49de6862bf9968085247b717766a9c60c9846a16.json create mode 100644 mojo/golden/4ed7aad6813c73b461b973834c3d0102c5325e2416aea3b64724746a70186d70.json create mode 100644 mojo/golden/4f39ba4ca17767cb4594d1ad162bf040e550c2bf02d766ad4180f441910f1695.json create mode 100644 mojo/golden/4fedfb721c18f7f831e7c94c41cb7e7c88a0516526201815d11fb7f9a33b20fb.json create mode 100644 mojo/golden/5039090e7acceeb0add875578b3d57f4d66377855da7972cc925c9d6cfe491b9.json create mode 100644 mojo/golden/511d6d3561888146ac76d17adabeafab47d29a558bc1c917919bf15f03577e82.json create mode 100644 mojo/golden/51376c8cace388ac5999334af0a2906f2c00bd52c8bc9a1a3c774acbb577e903.json create mode 100644 mojo/golden/51bb9033b0658b9eefd4f98c681f15412b20efaa048fa23ecf0489f123ba9a40.json create mode 100644 mojo/golden/52853fadac0e03e1d7d895bb28675b70ac8fea29ada292f8eb72c7326640dbe6.json create mode 100644 mojo/golden/531f115610de3dbb74b65a8e5097d399ddfa40357e5709e13146ba5848449909.json create mode 100644 mojo/golden/53e52b77f5e56e5077856e7817361c74174df7cf49ec168592b9d0665dae33e6.json create mode 100644 mojo/golden/54c4e35a32bc5f4374ba48b70aec6e63ee42a3666f4570fc7395fe8c71b81add.json create mode 100644 mojo/golden/54fafb6b513f1c0bb589ecc8e75c043ee63437360505a3ddebfd5cd794086677.json create mode 100644 mojo/golden/555320a247e6b2668ccb38311f2faa8ddeb6b64bdae1857d9d860c75e470d1a1.json create mode 100644 mojo/golden/55b20aaacc62450bc88d70dc5d9e3941327d0bbc412b40ec53aa41f8505a31fe.json create mode 100644 mojo/golden/560c19bd156ad9fb351791868a512c187e895b18b9f553802072f7dcd371f37b.json create mode 100644 mojo/golden/56478fa65f8d7fe8b14c15c39ac569d445a32576a42ec676d3228b2c90323383.json create mode 100644 mojo/golden/57060de67193d8334fbe7fe66faf3e2613443c0041101592d77deb4885b6153f.json create mode 100644 mojo/golden/573f9c8e07f80c85dd9cdca528a41869263a50cbd7d9b1379f691c10eef21e4f.json create mode 100644 mojo/golden/575f067f33c439fb95d1cec5de339e79f42677f1d1d1a53a47b2c025cc552511.json create mode 100644 mojo/golden/58841d14b7da3f5360bb51fc057efc166d5f74a0c038611c27169c3d39771b02.json create mode 100644 mojo/golden/59c53fa5b49ca4cc906c20ae497f8ca9399b7f60473292c1e185172389e513fc.json create mode 100644 mojo/golden/59d039d9c2f2d02271226b4bbca3794937678273af280215d4c781988d75ec43.json create mode 100644 mojo/golden/5a0e07a4566774b35601b5007928b023414a67e8b3d1ae7f45277b335f8dcd0b.json create mode 100644 mojo/golden/5a6a2d4dee91ce37dc677a695af5679f0b65a6adf2e609ccc69d392091c8ac0f.json create mode 100644 mojo/golden/5aa3d2bc8814f184ac623a22a7ebe3c8bc2e101d0bea54685c2b3bc34f2aca45.json create mode 100644 mojo/golden/5abb9e757023d9be070cb82b404c98eaabf34ac47f297b47be5e35c660a9ad0f.json create mode 100644 mojo/golden/5b49de43629228c91468df8ace24d0636b5b95163f7e410592ce21b28cbc4995.json create mode 100644 mojo/golden/5c04f8c16abbeaa43d05e81dd2ffd47ccb2578dde582d2c55b96128b463bf726.json create mode 100644 mojo/golden/5c5657619e009b838af20d5e50bf994b2062e1048ab5b7061a2f3ef86f7dd303.json create mode 100644 mojo/golden/5d9075f7153996e950cda24306b65f2c0a4db48ac542e48ad71ad2bddc4ceae6.json create mode 100644 mojo/golden/5dfc3f197eba63fe2472f4299bc1de8a088c7ecc990ab13fccdf83c2de851847.json create mode 100644 mojo/golden/5e3600fa1396437fc2fc869a1b188df20e710b012bfcb8fbd1039ec9b82a2bf4.json create mode 100644 mojo/golden/5ee6eeb844b22afd44938980653d55bf70478f6d259e60d7c40a4a761f85ab1b.json create mode 100644 mojo/golden/5f7a53ed6b25ba4303f774c9d1fb1c23bd00d81226d82419bf3a6494d37e6ac2.json create mode 100644 mojo/golden/5fe310f511133fe704b7a06e10b167b3db9a1fab31d82fa5fe678845b966d7f5.json create mode 100644 mojo/golden/5ff4b92ac66543ec76274f67106a15a9e04ac9329ac1004eef22befcd9b603d6.json create mode 100644 mojo/golden/5ffa33b6774b7b13ea31dc74ee793485d26323314e08dbd2ff26af06714f8158.json create mode 100644 mojo/golden/60287279683f550ab8aa72a99cf675201602a08d87f9df55a6c409d56979074e.json create mode 100644 mojo/golden/616d56806414d82455e032f3c1049368aec63fe4e5a01f1456a068d8b9d4c879.json create mode 100644 mojo/golden/61ab537d065ffa5bafa5bf330da4dcb032f1560cf29db0b4bec6a896221fa833.json create mode 100644 mojo/golden/6204e1670f0dee06fd2f2f045b609a93936106c380a5314792877913dde3d7b9.json create mode 100644 mojo/golden/6248433dfda1c930f640a8cce0eef6dfd208058cc1be58614ad6a791075d6e60.json create mode 100644 mojo/golden/63b74741b0559a592ef6091516dc7686d6e9948ed057110c012ec524adcf5051.json create mode 100644 mojo/golden/6410cb19f941f0b5ef13b87923c11ad8d93415c448ccd4654dc40b9a678eeb2e.json create mode 100644 mojo/golden/64ce32bedb77298d7df1f9022f502ff8d43c5617fc24bec07624cf27daa2e2e8.json create mode 100644 mojo/golden/64d62b5142a79250b805b0a159998d6e0107ed2b8889e7ff1ac31f742a0cb186.json create mode 100644 mojo/golden/655e9a75a1479d4aa6e1f230dfa27d6f9b7ddf13abcd1234c8653e4c48700734.json create mode 100644 mojo/golden/65cf0f855640d914a3da91ca0c3da572782c61adcff79e03224f195e444947ed.json create mode 100644 mojo/golden/66cb8d0de595075a9fb5003f1d7d23a517c5428c6873933961b5f1099b5c48fc.json create mode 100644 mojo/golden/6764720b5db5786d4fdb20d9a46bac534ebc39116fee387eb9cc1d30885187f6.json create mode 100644 mojo/golden/676ca3faaa7138c89f6ccc84bb9979e381a11960a0679f209cc6f5dcfc322c0a.json create mode 100644 mojo/golden/67f4b47331c3b7f5764ab2a26e9cf33ff48a2493254f2166c950e1fd4aedbeeb.json create mode 100644 mojo/golden/687d3ba9f6f28516c28dcc4a24d434ab5a8d2f946cc6e9eddf9fc3d1d074f2f6.json create mode 100644 mojo/golden/6892f14cf5325b53d408e1c2fb12c8c813952f9f327314c365c3f8f9ac2940d5.json create mode 100644 mojo/golden/68b695967213970788b0f8d798daa47bcca7e059b5504a23cf99e3c85895079e.json create mode 100644 mojo/golden/69f4d7af0d3a158f9a712fba0b6dc2733aeb4046b6781665c25ed0c9506e6307.json create mode 100644 mojo/golden/6aa80063166ab859dffc8714505b8b68d9e7856b6da89515c9305f907a6c0028.json create mode 100644 mojo/golden/6b5a6e1c800d0447c44a6c64984cd37f26cd9489513d8603bc75465eac993ea0.json create mode 100644 mojo/golden/6b8bcaf46f0276e4d6ef7297d341a0ee0c966e76ee4067460f67e6fe2174ba30.json create mode 100644 mojo/golden/6ca6ee67046bde61a3775fba7be423a9c067b0fb55c6e7c44524394854864414.json create mode 100644 mojo/golden/6ca7bd462ccf425f80f62046437eb75f10dbe96df6f7347ef96d762a79c82b8d.json create mode 100644 mojo/golden/6ca7f2860bbd0123e5c3b41f8b1328689600421db1eec8d00669659338740f47.json create mode 100644 mojo/golden/6cb3cbf811bba62de8ba98e35def60cac6fa79e003b254aed58d8c1acc0208d8.json create mode 100644 mojo/golden/6e152cce3a4f515dff1b5049f3cb20d34ed28678f6cf48a5f577f42a1c9ef2a9.json create mode 100644 mojo/golden/6e1c0993aa385a71e06a9bd4926ed943459542b94a868ad61f891fda2d11b5ef.json create mode 100644 mojo/golden/6e6791b52bfa0cddccaca3b4d0c3ee71695c939fd38714d995aa9cebfbc379a3.json create mode 100644 mojo/golden/6eecc9efe2edb20f9d02ac35106167ed1039c4ee7c6f8ece37032cf9653830c8.json create mode 100644 mojo/golden/6f2b7392be15b29cf55cabb0f4453ae6e51af8b5de1416a76d90e2d0ebb4b2a7.json create mode 100644 mojo/golden/6f6897cc04a0d56cafeac43237f5b22bb0a4b8300132a9031b42e592f82a9d3e.json create mode 100644 mojo/golden/6f74a259825e8231b43ec9084a901d95eb5832a440c2c99318da9d46d423c65c.json create mode 100644 mojo/golden/6f75e953c224b787f53bbb93d1b91402eebe92423db3831000c08caf3eb4de5c.json create mode 100644 mojo/golden/6f7de58ba5519c258455c3bfc3bef8bb425ff7517232d3b8d7a2aa29ea5b69b8.json create mode 100644 mojo/golden/6fc1cef2e4ba1c16408784ebc9fbde5b52d07c25651dfa4b20e6d7ec0fe6915b.json create mode 100644 mojo/golden/704a144e8480f7bf418a20b48a59b0d8c9b6f348af61e80d368a3e54d664da98.json create mode 100644 mojo/golden/70f30d9f2e85942cf5969958d7810d2fc5439e86825d3bacf7f0ed3347d6e0d0.json create mode 100644 mojo/golden/72229617ba0a5cf501094ecbbb70b8021ec2b4bad05314d217b53232f5eeb368.json create mode 100644 mojo/golden/72ef797f134258459d178abb298e2ce68d04056fd7b06e3c454a6c17576cc9f0.json create mode 100644 mojo/golden/74b0083636a07c769fe67fd21e1229da2e212c21de2b23f486fd9e0ba1e05a3a.json create mode 100644 mojo/golden/74c703b82fbb98412a3ab31fca010be672ab121a6a9f8306fc38b9a95108aae5.json create mode 100644 mojo/golden/7544c225e078d1664a1653f6750318b93b19a817ae561edc8391c399437c4a14.json create mode 100644 mojo/golden/7549709790cb52702d8a52daae61a3e2d38089f6df9547c9717362871497af86.json create mode 100644 mojo/golden/75a6d81a7602e04ea68b0bcf3864c89c7492856e611134a886e7854872593baf.json create mode 100644 mojo/golden/75bf5b4d9758c5f6e4240552de22376c3f23dd1c447d688835b917410fdfe147.json create mode 100644 mojo/golden/75d5ec51ac04e3b2bafcd72c3f81839c207e0f21f57e0b988e16ff21b90223a1.json create mode 100644 mojo/golden/75f5eb733be7c66ae9e41a3fbb0fc7e7678fc6bd58851b038b14b0efbf58f8e6.json create mode 100644 mojo/golden/760e18275b67a938bbde8dd8ac6734a137bd6d8fca4de3d71da897c30e08a7ee.json create mode 100644 mojo/golden/76bb15d537b1fbcbede9c78acec0bd0a91ebe081801c7ef6ae563c927fdb4357.json create mode 100644 mojo/golden/773c020e54b8ffe20a4120604c1c6663328c20cb3ef805d2e27a8d5f6d2c07fd.json create mode 100644 mojo/golden/77c0c70e498faa707b288cc9ba079b85f3daccc3874efe917323b43a5b8507a3.json create mode 100644 mojo/golden/786fa28663ff0a1820cac1b59a58057c3678b0fd592fa81d31fc3ecd7b03d553.json create mode 100644 mojo/golden/790f486d97f5e33b6b1f82ec205999e3ebb33700dc2feeb1e20d0d1fbe9814df.json create mode 100644 mojo/golden/7930f5217f1aba3c9c9832ad5e9640069e464c2d824ef813f815ddd9b53510a9.json create mode 100644 mojo/golden/79facebbda5dcb17d95d71a16c01664e46d01ca6e2c9674cb22b6e457988dd32.json create mode 100644 mojo/golden/7a2c363ec9eac165847d6fac1e409ec6576d89802354e760beb9b7df29214f5a.json create mode 100644 mojo/golden/7b4cfa5b4bb0c06ba49bcf93ef9d7626c839ae0cb61139eb02f7b70a8a78ffda.json create mode 100644 mojo/golden/7b9bba02338696094c14f7b9c3be49c5b56c79ee6c360645d62b14df8e9a65ee.json create mode 100644 mojo/golden/7c3759d871389eb9c2841d624fadcb7e307b13872b603829e7b7c702a43950a6.json create mode 100644 mojo/golden/7cce04085cae16873b22a526b3df80ff9e82de2415845b1d5214e6a788e85f1c.json create mode 100644 mojo/golden/7ce26d59eb63885653eb9b8846ba60ffe7f326f923e6a762b6d5f8e730489a13.json create mode 100644 mojo/golden/7d3e3e9c9631f080224ef75c1e237918c6049f46cb57d630493ac900ee271f2b.json create mode 100644 mojo/golden/7d72363d1f42be2d6fe8a79b53b4178665ddb372df178e5473dc832ef41940a5.json create mode 100644 mojo/golden/7ea28d619f069e993c47070a925268b02ebb682974f73fcdbb856ff65ecf95cc.json create mode 100644 mojo/golden/7f3195c9583723f6232604fb8dc17caa7598ead6d4a2aa3e60a83c8d825ca096.json create mode 100644 mojo/golden/802c49ba265cb8c34e8183bcc9ebc3394335f05520439b151eff5eb83326f506.json create mode 100644 mojo/golden/80cdc6f940706d4bc175df15ebc9c879fc9c5d40c4703f7ff8e29be9328208e3.json create mode 100644 mojo/golden/811e9773b1c36fa9e1e4d8f38e58f612da0d905e12c2134d9a55003d0e0236c4.json create mode 100644 mojo/golden/81886444bf7515a1c38b6f3505bf49c7c0eeb464d1f3fcc14c38d00d0f5bfdcc.json create mode 100644 mojo/golden/81990c53bab4c9e9cec4901449a373a689c60744401125f5422fd8e3953fbf22.json create mode 100644 mojo/golden/82af11e92337e1a2a8451da2acc95f78067c63d6d424fad1887baff93868978b.json create mode 100644 mojo/golden/836ff7c1131d5d04bf043bdf90387c93b58992e8dce5d2e8b246eee1fe658dfd.json create mode 100644 mojo/golden/84add5b56853fdb310b76cb033838ce7a2522f818888b67e3e5ead8b2074ece1.json create mode 100644 mojo/golden/850fafc645f4d84929ec84c80711f71df082a60fb3c4ca4ebb5b4b8f5f095159.json create mode 100644 mojo/golden/85104b1e4d76af9c7c22cb246e24db6f585f9ec3b4971c02b9ce0518d997f985.json create mode 100644 mojo/golden/8552818dc5efcbe6e3f92f3739157148f9241523de12394906e7fea9611fc524.json create mode 100644 mojo/golden/858cfdd82ef34543091c363382e99b4cb18a475812bfb263e4d4fb1950e5b151.json create mode 100644 mojo/golden/85f36588c235bf02a30ce1f8c18a1b48b6b1d25107966429248086e0921df56e.json create mode 100644 mojo/golden/875cbd15f2147430c133f2f7284c741ebe372104341f8e07580d9a55bf9b85f7.json create mode 100644 mojo/golden/880820ccaf247f10d075f33540a069fe4c2c35fd26a070aa8dacc2271ee49204.json create mode 100644 mojo/golden/8916f7504ab42b0998f60201cd54717343c21ea31748271eb35b1ca4b8771f3e.json create mode 100644 mojo/golden/897a1cb9c21bf9f6cd35e44a10d4fed342c046741116489e35999f178bf57988.json create mode 100644 mojo/golden/89d73995333d0c38134374aa7a2379c6b6e5888a86b0dc41df180023802e8f1c.json create mode 100644 mojo/golden/8a723dadf96770958424498434c08369a3795014abc2e67ca4f66edba2d99b3e.json create mode 100644 mojo/golden/8a80f22abec478aebc552d514d991ba00fc834e89c061d9cebe6f284f2724376.json create mode 100644 mojo/golden/8b3a88b513ed4f70acf18ed29064fdf9c40ca43d67975ce0d8354faed7ba94e1.json create mode 100644 mojo/golden/8b6838f89e03a0f9fd8003283eb4d58bed4e931fa3a6771841b3f10ee0a6bfeb.json create mode 100644 mojo/golden/8c7e23a1bacbc6a8ccaa24d3d4d7c06c2414a9e4b0137eb0ad150da2a935c04b.json create mode 100644 mojo/golden/8cb30c6ba2969cbed87c76d52957a429fd99b811dfa60af184b7b9e3638d28df.json create mode 100644 mojo/golden/8d18761aa7163a631b9441680ea5275a276ae8fdf8c71cd5748c1df193ad57bb.json create mode 100644 mojo/golden/8dfc26b635c51a199ec7d6e5867205b1fd99173f45393c799c75fe1591cfacf2.json create mode 100644 mojo/golden/8e50a88aaa8816307828e86a28a37f35fcfbf84bc8e661613b7e1193d20688ae.json create mode 100644 mojo/golden/8ea9f13ce7e43b31a2aed4652df5f81c65ab0b8860a57e7e3d5f4a9699603d67.json create mode 100644 mojo/golden/8ef817a9673d70999ef655fb3fd1d9d21161d9578a879435608375c09aa9093b.json create mode 100644 mojo/golden/8f0f198a8ce601cc230cf0519b3aa07af747bbf67722ddde2a10946719cf1cb0.json create mode 100644 mojo/golden/8fdc87fc24f6c71f5bf77bf395fc50cbe171f7120e822e507a382539af36c7ef.json create mode 100644 mojo/golden/90ecf6f327f0d6fd724f514b84b9d47b1148a21ea9e361ed1f36961f44458dc0.json create mode 100644 mojo/golden/91ba65ac5fe9a33349a5b3bcac772c024eaf116fb985761669d35dc33caf09f1.json create mode 100644 mojo/golden/91d2bc7469166d808726294580e7b4c54c0ec25160634ec973cf5b28bf85f04f.json create mode 100644 mojo/golden/925978d4bb6f6c3d95ac22706eb6ab7176ae2a841954a204d7be46d11e165c11.json create mode 100644 mojo/golden/931e0a78cd1da30ff982251a967f5c258e6a13f3e34c079c5478d47136c79de0.json create mode 100644 mojo/golden/93cf3b57780f8691fbce82e00e357041239310cc833c23494665e940572435aa.json create mode 100644 mojo/golden/953f2140c1c1a6fbd53e431f6a0fd174929fc7eba67b2c6f1c44961c1c9e03db.json create mode 100644 mojo/golden/95447459ad6538ec27e69d5a226416ab85a72fdaa8ff401716adb76c54fb520e.json create mode 100644 mojo/golden/95612ae78e77347cb67df804d3f86cba90ac231cb4f03c44a6400e8f9e7e6387.json create mode 100644 mojo/golden/95fba74b6de6917598ff9d8a5fb6aad884e3dadff28ff76619ba822ed951c04c.json create mode 100644 mojo/golden/9623c9752f8afbf1845ef82622472a92f4d112e62a946efb104114f7ef9bcae4.json create mode 100644 mojo/golden/9683282831cb77d9f8d730069ce0155d20e76fc2b9519498549f6679ba3b6920.json create mode 100644 mojo/golden/96d9d37974f741a1f5b761c3958ac16c92d76396b6926885ee462908b874ad52.json create mode 100644 mojo/golden/97619fe53b5cf22c6921635fc29ffd0128010bf5b0191ac099707bf06a2cde91.json create mode 100644 mojo/golden/977b46f65720546e6dece17975f818861a68ab28c0f3f1606c641c30f975de16.json create mode 100644 mojo/golden/97da10ff928b03b2c34edfd24c0b0b8cf9b3032222eda8450582db303e66f3d1.json create mode 100644 mojo/golden/985ecfc3e185f386884f1ac8a0d271ad60ddc002851c16a436e6357f49f89de8.json create mode 100644 mojo/golden/9860879044734150215d3f0247a19afefd80f53372d1ae036e29f94cfb1ee1b8.json create mode 100644 mojo/golden/991a47d66a79545308d7116a86b28fbe98321e13399cdd62c72da3e7d745ad02.json create mode 100644 mojo/golden/9961cab419f780ef749a252d40df66b6009c333f5753d1fa11445e09cd43768d.json create mode 100644 mojo/golden/997f207ae25f41ca72e781aef4fff00b07cb9389331063805d05af953177d53a.json create mode 100644 mojo/golden/9b34b1a7543de36e378f0652b1865c7c27a657ca85f57d3e916dd60738a57be2.json create mode 100644 mojo/golden/9bf55e988ddabf1640310c4ef88fba544247e1da76343dd3bf9454159b1b7eff.json create mode 100644 mojo/golden/9c636b81e76061f46bc705ed36a7f2e391af2f56b8183bbf6acec26ff131edee.json create mode 100644 mojo/golden/9c75e52d1886518da0c480f4d8e080a17c84d0be3407a07b4b432f4a1807d05d.json create mode 100644 mojo/golden/9c912cbfa4d27bac37310d3dfef71aa15c4b6ea22ae61a31c2d936db115a1c0c.json create mode 100644 mojo/golden/9dfcef79467591900ac50810978f35bdb0047c73f3ac0f441f5bc6123f284572.json create mode 100644 mojo/golden/9ea999ea8d664a7f7d0b0744e4dcd4bd9063a98979588e58fbcec6516e815e41.json create mode 100644 mojo/golden/9efe5dbca82885e34c28414495bb0e1d61a685fbd803f5fa3fab6e713d9ee7e9.json create mode 100644 mojo/golden/9faeb8e37f243580c2fe5d62538b1c05619abbb289812949a3c0aae93a85cfb0.json create mode 100644 mojo/golden/STATUS.md create mode 100644 mojo/golden/a08ea67f2ded38409e6ef3682dd3cefb5375a0b5cfa799d763d673aea29caa5f.json create mode 100644 mojo/golden/a093040e68efecc51a26711f9364b4f49587a35f9b1241f81a03f17b4baec535.json create mode 100644 mojo/golden/a0a2671183a65c27cc38be3d061c9ff46f944046502e5d7ffaf67e38d1ce01df.json create mode 100644 mojo/golden/a0bf5ca8b5b2d6368a75c63a9bc992c6c80293f7b16c6977f432015eb2a01cb5.json create mode 100644 mojo/golden/a0eace2d4e3e1e19252bc3ac7de722b3429400a3def5cb6f2b15ac92e74c6869.json create mode 100644 mojo/golden/a0fbcd8661c987cf9b57dc3e8a00ae8f999ecc4c655cfa8793b3287f8b2bfd3b.json create mode 100644 mojo/golden/a14a5dfe45a575d8ad793c6ddc794c1c41d14eede8e81b68b5e52473c26dafac.json create mode 100644 mojo/golden/a19f0decf330711e054eb167d0aa43923109811f5bd23e36b42c7eae8352b46a.json create mode 100644 mojo/golden/a1ac5c5456a57560a1a00d88dd6720ba98fc3fe2d28a80c5ee3b20ed37202719.json create mode 100644 mojo/golden/a1b95392250b0afbdeb0b318caaa90ae9a053e61acc95ac357f4053ab00a84f7.json create mode 100644 mojo/golden/a2c30095537a33f70fa2383ea954415b5877fb360ac9cd213183ba03b71fc11c.json create mode 100644 mojo/golden/a2c8fbaf92dfd90c708bb5599eb4c9afd5f43ce7b0889fd8bc217528dd296142.json create mode 100644 mojo/golden/a411393636a060f817d565d2b95171d41518071364d44312c9a0f32bcfb8df51.json create mode 100644 mojo/golden/a502623b200de2aed639bad0e0da6015c0ddccb9551a2dc0630238b5da3af114.json create mode 100644 mojo/golden/a5cdbcf8f13930ec977ea000a540fa377c059a8020ba5cc392b1e736868cfb6b.json create mode 100644 mojo/golden/a5d9b891bb583f90311544e4b4167c233d659162061078e6d85effefab69227a.json create mode 100644 mojo/golden/a66a070913ba730e33595e389eaf05ff0cd5cc80244455b32762dfd0c578196e.json create mode 100644 mojo/golden/a6bddbf01dd755d5602b05ae379010d427fed2395e380234120130a915d61a36.json create mode 100644 mojo/golden/a7cc139aa7a412e910828e02d350da0d6546dc2618eea06d92b69849da34c1d7.json create mode 100644 mojo/golden/a7f18abf83dc878542a3eaf8a75f2c97d84306af5c7c6c80b52aba1ce347d517.json create mode 100644 mojo/golden/a7fded94c85030caa47b4bcfbcb21d3e96fa936bac209c212f787fb351fd16d1.json create mode 100644 mojo/golden/a80d6c070de791a2b4e993b29f3c1b2f24f8a82461126798499ce0911915cf73.json create mode 100644 mojo/golden/a81bbd179e65062f525963b46dc9ad15776a517e9ae043ec13a08cec4daffef5.json create mode 100644 mojo/golden/a8fcafe2c0752008b571a371fb56eb6f81ac0c0e50cd4405a2aa1ed87c5ed6e9.json create mode 100644 mojo/golden/a995e575fbcabbafd5f3f6bdd62cf0239f01a2835eaea0231824572ae355d8be.json create mode 100644 mojo/golden/a9ad8b9d854be27ff81a4eb33eb06fe6e182f742b8cfb9bc029b202509ee8144.json create mode 100644 mojo/golden/a9d7e37fa5a57a5e11e60986de061fa3907c5961e08f2b72dfcdbc617bee8161.json create mode 100644 mojo/golden/a9ec46219c62eb44c78dc4a6838196a0805cddddd67f654427fec82bd64449d7.json create mode 100644 mojo/golden/aa705fcb8057464d7a2e0ebd538786503215c821227cab9d54c89cbfec3ef47f.json create mode 100644 mojo/golden/aa781a1e8c166a4ef95c1f5039308a89f8ea51b11867ea26e0a81035603d729a.json create mode 100644 mojo/golden/aac3dc76ee3cc608f49db014a31dc746e2ab6d304290cda273355a3160257037.json create mode 100644 mojo/golden/ab0ecf6397edfdf1f7d6fbbdfefb7d2bd6b8aa08210aa9a7fb6e9ceec680de39.json create mode 100644 mojo/golden/ab38d29a882090d278e4e4304e8d2c115ac477639a2ae5135c2d4405e8d59b1c.json create mode 100644 mojo/golden/ab578c02eb212711cf797e2183b0e3a6cb70546469458f4143e647e06c14528f.json create mode 100644 mojo/golden/ab839a2674e8a3fc472a1eeee12d690feed1eb4f1757af3f93a5c2dec3ad28e5.json create mode 100644 mojo/golden/abb5df9da6e88ab56d5017997c8f2615d16830f8d8fdd12165c43e460f451b11.json create mode 100644 mojo/golden/abbb5b7950ae2f7937a56f74702121a2243ca6cd175948822041730668b83c5f.json create mode 100644 mojo/golden/ac361ec846595dea9de5690bdf0f49fa78b9fa2eba1dd47d29a0edcc589218e4.json create mode 100644 mojo/golden/ac84be2d8238b13ecb6c1c827a6b1dbac1feff35ad9894fb56aceb44b9046819.json create mode 100644 mojo/golden/acb1304f624c19c496610540aaf9714abe5c7f0b3aa2474d45838a47f574f5c9.json create mode 100644 mojo/golden/ad1a532894ed98ff842005356d34752226f4461426c8179cf85f8e31b40e24eb.json create mode 100644 mojo/golden/adcb02a04b0442024a59126647bf71aff91b8e73770b714eed1f450a38141e73.json create mode 100644 mojo/golden/af7190d57c7badfb015712ba068dae74b1f65d32bd1af318452706456eaa7399.json create mode 100644 mojo/golden/afa5306a7a69d4282866b4a1229aa30b7b74a8d87a997cb93d0477e14bbbf1ff.json create mode 100644 mojo/golden/afe3f3b3b4e25d7f92bf34774a7df20832c80c18fa3dbc97a35cb1fd24d666d2.json create mode 100644 mojo/golden/b02a762b65471732458986b9a36b8c632000a790545bd8a792c881e2f7c969da.json create mode 100644 mojo/golden/b0f3eb74b28124b0fa7cb6378ce4a42cc806e0d1bbb40f0d44ae91a874b36af4.json create mode 100644 mojo/golden/b14cd579659e4749f1b680ce56434a0dc1eec279c131738fb07cde4cf2ec77b6.json create mode 100644 mojo/golden/b169575a2415bf5d165aca2de2e5cc1b46df94ca94c33b6eba4bc83890ee659c.json create mode 100644 mojo/golden/b19abfffb39918164d6a1ef87884ad94ba85a2d5b12dd4442b5cf1bb68e22fd1.json create mode 100644 mojo/golden/b1ce238ec4fa2acc28fb13fa3745bd562800853954a3f6ea0a01a67baf31db80.json create mode 100644 mojo/golden/b248473c2be1cec0e97225c9755d608de8fcd7e1c906b28e8e23334614afdb33.json create mode 100644 mojo/golden/b2e355eca148cde4eb91adb6f3e4f720d34ba5fca0b240cf0cdc5f012ab93601.json create mode 100644 mojo/golden/b3bf3168af5bc987adc949fd9c6a1795a6c077cd593411083469f3b9cae4c855.json create mode 100644 mojo/golden/b42a3a79e987241aec7bad530f0009e5bdc328a515e3d6a8f70f61163c8631ce.json create mode 100644 mojo/golden/b49cb1a052e6fd2121ac5c4f9e2e39b77b92761f3b3f12f6c8999c1fc637ef91.json create mode 100644 mojo/golden/b4ac8a35cf76d392b1821ce4e05cbb192ca3b3b2803cbc035a91f47d43750c7c.json create mode 100644 mojo/golden/b4be87c36f7a03a54a56874e55b0b0bb922fb70dacc446893ef163d235fd7282.json create mode 100644 mojo/golden/b4c598603f4ed256919ee75eb3733498503999d42469f17bd9c104e4fdd1e986.json create mode 100644 mojo/golden/b4feab7b7237ddcef04f50eb131af0cb12caf2633bf712c800e85b97345bfaed.json create mode 100644 mojo/golden/b5f258b9b78539a451858281d20b85ccb26671e59e4f663ac391ccdeb9cf5ae1.json create mode 100644 mojo/golden/b61a27f47b625b4f1d67c2f26ffc16b7d35e657e8364ddc548b9e59445e15034.json create mode 100644 mojo/golden/b6a4042104e1795373fed58f203dbaef4c34c017656ebacdb2c5b9fc5aeb6291.json create mode 100644 mojo/golden/b6eb8c340006fef855489431cf6fd2f2c5e05035ae952a3ed3f700e9a5b605a0.json create mode 100644 mojo/golden/b81c444e4280bf30d963b3501210225967cbe2b66f57e80f771ac9bc7afeb4ec.json create mode 100644 mojo/golden/b8c1e34fa23301965f41cd8f7ea63b7d48c914628be1725c05e28c393c33875f.json create mode 100644 mojo/golden/b8f14ee1dcfab1b46a51cb7c47cfe4d9f9656fa70959cc07643010f2db2a6a32.json create mode 100644 mojo/golden/b959cf08a3ad4c8e1539b3fd77d2c7bccfe81da66c10b619318c3cc16916c6f9.json create mode 100644 mojo/golden/ba15bf9e4a376a2da5d0db197e96a15b541d6694bdfb482e04746d6853783712.json create mode 100644 mojo/golden/ba9574c1c5d634373ef85db14a870f14defd78a3d47c9b2d6f4b87b28f457103.json create mode 100644 mojo/golden/baaa536e9fa151eda828aa07a4e82b8b2d65f336fd2768dd63913a323a02a11e.json create mode 100644 mojo/golden/bb3231fd8aa7f28397707357b4b28d684a9ef580ee02bd4e6b0e8f42249e6514.json create mode 100644 mojo/golden/bbd68ea77a89019e8807c69009517fe73ac50a839598d89dc5378784df904f94.json create mode 100644 mojo/golden/bbeadf9d8208dde39efb0a454e0f289b308830ad41f2f3e919a39ba58d8ad481.json create mode 100644 mojo/golden/bc283ba471f444730b571a387e6f17e4f1bbc625f3e1f427d2e101a27ab4b14c.json create mode 100644 mojo/golden/bc4de8381f43c82c23910c6deba48f7d8de7a1cb2e3fb4c3695ca87104b6a045.json create mode 100644 mojo/golden/bcbdcc261900d7b1386bdfe68a450b8643262e5ea5d481a34570ff8c0f526048.json create mode 100644 mojo/golden/be0252c2670c80563fe07c5f23ba4e73b1417cf978b4448b25b8883ba15bc39b.json create mode 100644 mojo/golden/be85360da85f9d9e42333ee2b73fc883636af61916847677783a3a1a6321b3bf.json create mode 100644 mojo/golden/bfe942db24cfac9aacb13f24017ead19122195186536d644fb10676eb2f0a55e.json create mode 100644 mojo/golden/c0f6d4c7e5a09ddc1af58d5655d4327acc7801f28ec3f18fc7acf2c97472d7b1.json create mode 100644 mojo/golden/c10749fa0cffd8f3d3c62a6200c81a66c6edccf849bc936950f0f4fd17c4da81.json create mode 100644 mojo/golden/c2515909f3ba77d6e4f20d5a81f115c5b25ca23584ab9103a664e4087dd85f10.json create mode 100644 mojo/golden/c25459519a40561cd86ced55feeda8d0f5ed5775a58d0da042eda74028bb8d90.json create mode 100644 mojo/golden/c2929c0f5af009d2198b45169c7f134d1803fd3d8f9b6d77498c0a0d00d6a97f.json create mode 100644 mojo/golden/c33106274cb5d52f01b43f50c66d1fa5d6b6673852e60e9b8767521881e47a87.json create mode 100644 mojo/golden/c343cc55298cb75897366882018ac9b1cff07e217acc99a5b875182347b1b920.json create mode 100644 mojo/golden/c3c5273897d5c3db22c86b94b7024a556944b7864b933ed16e19a98e6658c8c7.json create mode 100644 mojo/golden/c3d2f50b0608726d2d455e6245cd926107f2f9acb41cd8ad97a92b3f2f746b8b.json create mode 100644 mojo/golden/c3f9482acab18d08b9d3878520be7a525c40128a591d0fb4f5164ce330e46693.json create mode 100644 mojo/golden/c4d98263aa80872ee86dd0ceec840f97f482fdef5d0ccda2c0caf2fcedd70374.json create mode 100644 mojo/golden/c4e04add704ff8e3257c9e23034b68777cb79561ed1ef65dacdabdb61bb3083c.json create mode 100644 mojo/golden/c56effd95b2f5c379bfef797751e44905dec53f8e5118082013660c350a686ed.json create mode 100644 mojo/golden/c5937768d9ebd7a2c0eece614deb1c4d039a095b19cdb2781598845238aef6ff.json create mode 100644 mojo/golden/c5b421a876cfee1e24625ae2e5e2aca780cd8669445e1a06e2ce37eda99699e5.json create mode 100644 mojo/golden/c64e12bbd81cd92946949852142fe875000cd04f4ba1f5db80603417776ea77b.json create mode 100644 mojo/golden/c733cba6d11d939000b022413bcdb30f03a5c9d0d11debd70f7f6f4227ebce2b.json create mode 100644 mojo/golden/c787effda13e91f54915f3b2afb33f86c7342e33b059cf942782fbf9b2957cdc.json create mode 100644 mojo/golden/c7c67c41299bb2399830de15ae0be9de11f684c95f5a885b4d522c500e53d949.json create mode 100644 mojo/golden/c81d8d531e98071dfa89ebea2238751f8bb338989f2d0506de2875f9862f7607.json create mode 100644 mojo/golden/c957f4c0a7497a8e9a00ff06fcaed1f629169bb6fd44c63f019221ee976c3fd2.json create mode 100644 mojo/golden/c9cd3c55f34e203e52c6d92e6dc4844c6267b4b9ef4ca4b437c3c1999eeb659b.json create mode 100644 mojo/golden/c9ffe8b5f256a5bff54653a31b621dd79d91deeedf2e79373352775323dcb30c.json create mode 100644 mojo/golden/ca694ecc76fe808084efc425844562d4ff4493921802f17c988a405815734df8.json create mode 100644 mojo/golden/caadcdee022dd7c600c97531e88ba08eacb9aa93f2b71f0c282b279a78021f3c.json create mode 100644 mojo/golden/cb86f81eadfef7930a3251876034e61c89130ee4730ffb9c7f26bdc2b8660475.json create mode 100644 mojo/golden/cbe155ce01fb6c0f1c3e57eb9a75902ece00f32af1a46514e579f8a0acc10ed8.json create mode 100644 mojo/golden/cc4221ee6f566c8bbd9ebce0fbdc1b1b00ccd9c1c24f05a1ff283855134bed47.json create mode 100644 mojo/golden/cc9369e0f395415ccca5e5c9cc3c8d131d67772d6220a1aad17323fa31f91d80.json create mode 100644 mojo/golden/ccbb52874a9b79702f88879ecb7d9c33ba9837ed1fccd25408d8d7ecce6a9d2f.json create mode 100644 mojo/golden/cd3525e34954b4237a3f0683982916d0fe2544c4eef6136201d95e984c71a927.json create mode 100644 mojo/golden/ceea0b3487dcb321336d93b1254d1cf741735f814a29646778d1b758dd01afff.json create mode 100644 mojo/golden/cfd83e2a12c927add32fbbe8bbee06f9b498901b3497af08b518894713d2cb89.json create mode 100644 mojo/golden/d195c3eaa7015f9050cb960af130f73d15e8d12b5742b0f0ae6c78d7adc1d76e.json create mode 100644 mojo/golden/d1970d3030ed37d1571d945322051317da93264dea5782adae1a7c9440e9deec.json create mode 100644 mojo/golden/d1b60bef3305e7b53bc4e6716cd2445bd914a4556171a8caed42d704cb652c0c.json create mode 100644 mojo/golden/d1e0e7bd34fd7faf43080e7b52e314ab1ea4bd6482cb62aea9873ac86e01bd82.json create mode 100644 mojo/golden/d386f6fd70fb903125fdae6102a142da8177bf210f8d8e5052452155c5e734a1.json create mode 100644 mojo/golden/d3c94b66a32cef707c849ffac7363cf8ce8d3e5fbe2380093cb8dd2cc18b6ccf.json create mode 100644 mojo/golden/d42603a57e0e10b229116aab654e5fe65809e296bcb63f9feb5e0b09e9daafe2.json create mode 100644 mojo/golden/d48dd3b4823fddebe97fd9766cfa303e61c76870f3af57488363af1e60735e1c.json create mode 100644 mojo/golden/d58e3d8640552167d06e35d1f4631c3d7968e90acc58dc98756fb04941af9d06.json create mode 100644 mojo/golden/d5e77b685fd3df61dd96cb315b627316756aecb652844131c949237cf63d9808.json create mode 100644 mojo/golden/d77bbec6aa354f24b3159f7c06b10bd6953628447daea61c839123dadbb06452.json create mode 100644 mojo/golden/d7fdebff9d785013c2192de039098efd68da4bd65608969f7e455bf03fa3909c.json create mode 100644 mojo/golden/d8b0f6b238ac250088060297da7a91bc8d620a3b7ae4982e422584b21b973361.json create mode 100644 mojo/golden/d8e5596691dc17a4445ed1cd5825d5d90f74a65a11725cbe5c319a7c5d017c81.json create mode 100644 mojo/golden/d9429b0693ed02014747208344d46eafd8e38aef656ec08ffb464c2132d49c71.json create mode 100644 mojo/golden/da7d5f9dac47abf05d5fa0408ac867b73054e17c6f199a399d2a60ea24fb3d2c.json create mode 100644 mojo/golden/da96521ab502816515f7cceb0e7cd184bfe5e7105654b66acc2abf3f54c9ed72.json create mode 100644 mojo/golden/db48c7e6968d24f02cd023a5051cc7b36ffd0871e73d06a45bc7301eb8d446d9.json create mode 100644 mojo/golden/dca13039ccaaeb802c80c005c5750a6d625146d63e45e3e780add54715cc58c7.json create mode 100644 mojo/golden/dd58a0b3bd94c0cf75dd05eb8950447a96c7a27fad0ae94b9b2a6e2eb7b8f09d.json create mode 100644 mojo/golden/dd6ea26fe197ff309fbd5903110fad6fcaad458650c35323ae2419faf59e448e.json create mode 100644 mojo/golden/ddea9d5c99d1059b27bead201d30bcee72471c1ae4b9a73a2c314e2e9c214cdd.json create mode 100644 mojo/golden/de651199af3557bce043b202d24795a46a733e5c3d545aa1596220df3b5c3107.json create mode 100644 mojo/golden/de7a3f2dd7273ea6ec33fa1ee6cd5ced0805e5deb091a0867dd77cdc112f5a69.json create mode 100644 mojo/golden/dedf99ae2f88b252ad3c134a149c2618a202e75dc1d90af845347490b681d340.json create mode 100644 mojo/golden/df30c8fcdb3805100a8f99c47985117597eda8fea1ced22601a5cd10c9b26c2a.json create mode 100644 mojo/golden/dfdb8be37a914544e5878c4d36dadc7d6ba3aedd8a9030ed95b386fc29777427.json create mode 100644 mojo/golden/dffe0e6764d5f200d7cfbd44bb64a6af41b8b1ae1503954f18f282080f5e2a32.json create mode 100644 mojo/golden/e06aeaee67a1157777e3f63b67551c4a5e42de03605634625fbab4e2d356faa3.json create mode 100644 mojo/golden/e0da59ada23e132eeac007fc8dc1b816e4a93d51adfc841d6a7a43b9fd4cc4f1.json create mode 100644 mojo/golden/e19657c1a5977428b5d482df0acc806c43aa9ff9a2254fdccff33caddcb0aed4.json create mode 100644 mojo/golden/e1c0c4d96bb4aa9e963b880a7192f7f1f7231b31d1f0cdfa23c8142824d368e1.json create mode 100644 mojo/golden/e23ae971ac4cea951a55c0c6d14401f2d2fab0a3641c0a6192de1a6cfc1c27e9.json create mode 100644 mojo/golden/e2bce355dca443ba27c9d99d3cdbbd27da4df1b22d29b106f09f7069ce26f3d6.json create mode 100644 mojo/golden/e47054aeab1e9a3d43fbd9e48270d5895295bf8ad34fd9c576823520cbb068b4.json create mode 100644 mojo/golden/e5bfc27c759278e4cca92289ba53396beeae57964ec7f57988e65a83d0468052.json create mode 100644 mojo/golden/e65ec32b552dba41a2a0dbec9e3d8d2bcf75e6e6be91126a44a47b1e1f4ebd3c.json create mode 100644 mojo/golden/e68aadd6a2123648f3c659f4aa8c1e355597f3bf6df0582b92d4a44a452b7d80.json create mode 100644 mojo/golden/e6b5a4c9daffe4d11617c57f0d04b21cf2bb8ce515c46e928b611026668152c2.json create mode 100644 mojo/golden/e72c9196e314067a5283bd432b9d320bf760324718c0183b2411cb483e7ae8f9.json create mode 100644 mojo/golden/e84d6a3210e7797233c9261260add9f60fe423013744a70b488e67674fe64390.json create mode 100644 mojo/golden/e91fd86e85dbef026701587e0bb1bf5f9ac23af9a1c6ebb5c1a74dd8d9b0c020.json create mode 100644 mojo/golden/e9254da04fba10912221298a816d897cd67461c54e8292ccc789ee76aa62bcd2.json create mode 100644 mojo/golden/e94e9902da5625499ac71b4b6f2408f9425279c32892d91a8ed28f22c46b3492.json create mode 100644 mojo/golden/ea1f65bbcb5da88250902687c5145a1c51c466d92c764d41ef4bfcaee2063b74.json create mode 100644 mojo/golden/ea5c7cf789f38ef4a082c7f8901694c531b34bfefc5c98a47afde7011581266a.json create mode 100644 mojo/golden/ead2773747e9aec8f36334e399bd707977e8335a0f3efabe6159e439e74c6745.json create mode 100644 mojo/golden/eb6fc02a5fe2ac1f0623fadf53617f23110d09e2c3520ff4f827b042f66c6957.json create mode 100644 mojo/golden/ec0a12b928581c6e500a318bc82b541080d4bd6a742645bc0f7cfc9ba0057bd8.json create mode 100644 mojo/golden/ec1ef315c49e228ff84d2e6092fda58f23e110628deaca1dde1df030ed8e201e.json create mode 100644 mojo/golden/ec93dde69affce3b40c704d4abcacced2de657b3fe7dc055bde63a12c8d02669.json create mode 100644 mojo/golden/eca505776fea3f59aae192969348fa82755ffbb1afc608265a4724ed6408d7b8.json create mode 100644 mojo/golden/ed74e58e7670bb25f953ce113cc6634c472d53caec5b846a8eac16a138b629be.json create mode 100644 mojo/golden/eeadf1bfa7164fc9a21278ada9b7d1a4cd72cdf540e20b6c9c34455b0951d37f.json create mode 100644 mojo/golden/f01d021c8b06f6cdf99682aadc7aed16cc59f47244d553e06462c0e5b94ab34f.json create mode 100644 mojo/golden/f06026a33e57edd0cfd7488c5cb8e9880419b14437f9e459774383d1c3b361bd.json create mode 100644 mojo/golden/f08497700c1c1c2d878f3f222a2fce288277a82444f7d5aefe364f0bffc26e86.json create mode 100644 mojo/golden/f0db8a5f6b1de6a8e8872e72f892f8076a48b34aa3081a7dabf0dacd98744de2.json create mode 100644 mojo/golden/f199efca793b722fb6c5fe0258b26660735bc0b6a8be4953c67c17970404ec4d.json create mode 100644 mojo/golden/f37f563a387892ad5540ccd76d5d5f681d1aa09a433fe2b7f572b0ef72129d3a.json create mode 100644 mojo/golden/f38f623c812a82ff7cb4f41d8498a91eefda0baad3cabd4f34486df065e7bda8.json create mode 100644 mojo/golden/f3abf6bd73db4b523033e4580673c66a2ada5b4f89155968102eaf6e7269ee11.json create mode 100644 mojo/golden/f3e39a1e6924c4f8285ae4ff232225f75a94b7b743d558af605646eb4977ed8e.json create mode 100644 mojo/golden/f44eb23829a935901ce4edc9b9276c56ea6e7c33997766a5f4840fa1402cc078.json create mode 100644 mojo/golden/f496802e850aeca8d3d3bea4c93de5eaef89364a7bca9d305606b9533e3d81f7.json create mode 100644 mojo/golden/f49f6bdfc75b662e951fa771ed23fd18fa410ee8ba8025e3352fa6626df58179.json create mode 100644 mojo/golden/f55d506ec0f1470de85119ab69b97af87c8a1fafabc0d5095b20f82f3ec33d70.json create mode 100644 mojo/golden/f5909e300e655926e123bccc39e7714efe3fc44a3aab3d296eda27992523b37e.json create mode 100644 mojo/golden/f62302e882968f72bccaa8319b6553753c96aa46a437504ed36e4594ed782126.json create mode 100644 mojo/golden/f63279a6768616c6495e5f485c1007806681dbb9ca70bc6082c22770a95efbd3.json create mode 100644 mojo/golden/f72ae1a3417ce3450d4df950d407177676b01abfafe71f5dbbd26bec41f29204.json create mode 100644 mojo/golden/f945b547c57245be0f5ae47000bddc8aac7c6b12e9a4165f5a007a8a616e1493.json create mode 100644 mojo/golden/f9e11c8f81213f6108a665a091055716639958d759ca26b50b5f8d76f33061fc.json create mode 100644 mojo/golden/fa3275adc8b834be8a583f17729517f9e98a8e302fb4e8dc5d665be9ea835881.json create mode 100644 mojo/golden/faf9052d6517b9f00ff73d4cba4d87c2e3a0f8f8e99548b0bc5b727512c620d3.json create mode 100644 mojo/golden/fb7fbba240ee3243f704fb6a4cd9ca400a149f4e3806dce8bc514d5bcc4ff54b.json create mode 100644 mojo/golden/fb81fb9af62fd1febb2396a24aa3d51291faed30ce670c7fdeb2816f5be2477b.json create mode 100644 mojo/golden/fbb69bccd2459bba4f9e7872e701bf72f7921d5b93a1447e1874770ac75d4e82.json create mode 100644 mojo/golden/fbcc5968d771c2f8c102828e69affa817f3b7c085c50ce3cdeda508ddda6317b.json create mode 100644 mojo/golden/fc5b16a1619f14571291654306db32b14df30f8f26a16e14a0d2988c6be2d5be.json create mode 100644 mojo/golden/fcea73b49e8fa2116f244be961534450d53ebd017c4daae783eaf76c8d117130.json create mode 100644 mojo/golden/fe0160a7ca4d6ffaec87125b95265ef9bdcbc57f0bd25821d7ec6a26ef9df0fb.json create mode 100644 mojo/golden/fea6e45bb470a8cfead2489c570303dd378176beacc488aaa06147b7a5a114d7.json create mode 100644 mojo/golden/feeeba9d6f3a3884962758038ea0e21309aa3def8ddc19f8cde1f200bfcb41ea.json create mode 100644 mojo/golden/ff18d04ffda83759a6c12e39ffcb4c07de8286f0356b2d644562390c4826a932.json create mode 100644 mojo/golden/status.json create mode 100644 mojo/local/best-position.mojo create mode 100644 mojo/local/binary-search.mojo create mode 100644 mojo/local/count-base-proved.mojo create mode 100644 mojo/local/count-base.mojo create mode 100644 mojo/local/demo.mojo create mode 100644 mojo/local/edit-distance.mojo create mode 100644 mojo/local/first-unknown.mojo create mode 100644 mojo/local/five-bugs.mojo create mode 100644 mojo/local/gc-fraction.mojo create mode 100644 mojo/local/hamming.mojo create mode 100644 mojo/local/kmers.mojo create mode 100644 mojo/local/match-off-by-one.mojo create mode 100644 mojo/local/match-proved.mojo create mode 100644 mojo/local/match-reset.mojo create mode 100644 mojo/local/match.mojo create mode 100644 mojo/local/revcomp.mojo create mode 100644 mojo/local/tally.mojo create mode 100644 mojo/local/translate-codons.mojo create mode 100644 mojo/mojo.lock.json create mode 100644 mojo/pin.json create mode 100644 mojo/probes/check-aliasing.mojo create mode 100644 mojo/probes/check-implicit-copy.mojo create mode 100644 mojo/probes/check-implicit-declaration.mojo create mode 100644 mojo/probes/check-missing-raises.mojo create mode 100644 mojo/probes/check-uninitialized.mojo create mode 100644 mojo/probes/check-use-after-move-on-one-path.mojo create mode 100644 mojo/probes/check-use-after-move.mojo create mode 100644 mojo/probes/comptime-if-for.mojo create mode 100644 mojo/probes/dialect-del.mojo create mode 100644 mojo/probes/dialect-fn.mojo create mode 100644 mojo/probes/dialect-read.mojo create mode 100644 mojo/probes/dialect-register-passable.mojo create mode 100644 mojo/probes/dialect-value.mojo create mode 100644 mojo/probes/dict-missing-key.mojo create mode 100644 mojo/probes/dict-order.mojo create mode 100644 mojo/probes/error-assert-statement.mojo create mode 100644 mojo/probes/error-debug-assert.mojo create mode 100644 mojo/probes/error-exit-code.mojo create mode 100644 mojo/probes/error-try-finally.mojo create mode 100644 mojo/probes/error-unhandled.mojo create mode 100644 mojo/probes/float-mixed.mojo create mode 100644 mojo/probes/float-print.mojo create mode 100644 mojo/probes/float-round.mojo create mode 100644 mojo/probes/float-special.mojo create mode 100644 mojo/probes/float-to-int.mojo create mode 100644 mojo/probes/float32-print.mojo create mode 100644 mojo/probes/godbolt-asm-and-run.mojo create mode 100644 mojo/probes/godbolt-asm.mojo create mode 100644 mojo/probes/godbolt-compile-button.mojo create mode 100644 mojo/probes/godbolt-line-tables-O0.mojo create mode 100644 mojo/probes/godbolt-line-tables.mojo create mode 100644 mojo/probes/godbolt-opt-O0.mojo create mode 100644 mojo/probes/godbolt-stdin.mojo create mode 100644 mojo/probes/input-eof.mojo create mode 100644 mojo/probes/input-lines.mojo create mode 100644 mojo/probes/input-parse-error.mojo create mode 100644 mojo/probes/int-div-zero.mojo create mode 100644 mojo/probes/int-floordiv.mojo create mode 100644 mojo/probes/int-literal-too-big.mojo create mode 100644 mojo/probes/int-mod.mojo create mode 100644 mojo/probes/int-overflow-int.mojo create mode 100644 mojo/probes/int-overflow-int8.mojo create mode 100644 mojo/probes/int-pow-shift.mojo create mode 100644 mojo/probes/int-truediv.mojo create mode 100644 mojo/probes/int-uint-wrap.mojo create mode 100644 mojo/probes/lib-parallelize.mojo create mode 100644 mojo/probes/lib-vectorize.mojo create mode 100644 mojo/probes/life-asap-expression.mojo create mode 100644 mojo/probes/life-borrow-lifetime.mojo create mode 100644 mojo/probes/life-branch-both-sides.mojo create mode 100644 mojo/probes/life-branch-declared-inside.mojo create mode 100644 mojo/probes/life-branch-one-side.mojo create mode 100644 mojo/probes/life-copy-move.mojo create mode 100644 mojo/probes/life-early-return.mojo create mode 100644 mojo/probes/life-field-order.mojo create mode 100644 mojo/probes/life-last-use.mojo create mode 100644 mojo/probes/life-list-elements.mojo create mode 100644 mojo/probes/life-loop-local.mojo create mode 100644 mojo/probes/life-loop-outer-read-inside.mojo create mode 100644 mojo/probes/life-loop-outer-unused-after.mojo create mode 100644 mojo/probes/life-move-into-var-arg.mojo create mode 100644 mojo/probes/life-moved-on-one-path.mojo create mode 100644 mojo/probes/life-mut-arg.mojo create mode 100644 mojo/probes/life-reassign-in-loop.mojo create mode 100644 mojo/probes/life-reassign.mojo create mode 100644 mojo/probes/life-var-arg.mojo create mode 100644 mojo/probes/list-index-oob.mojo create mode 100644 mojo/probes/list-negative-index.mojo create mode 100644 mojo/probes/list-ops.mojo create mode 100644 mojo/probes/print-bool-optional.mojo create mode 100644 mojo/probes/print-dict.mojo create mode 100644 mojo/probes/print-list.mojo create mode 100644 mojo/probes/print-sep-end.mojo create mode 100644 mojo/probes/print-tuple.mojo create mode 100644 mojo/probes/range-forms.mojo create mode 100644 mojo/probes/set-order.mojo create mode 100644 mojo/probes/simd-basics.mojo create mode 100644 mojo/probes/string-build.mojo create mode 100644 mojo/probes/string-compare.mojo create mode 100644 mojo/probes/string-index.mojo create mode 100644 mojo/probes/string-iterate.mojo create mode 100644 mojo/probes/string-length.mojo create mode 100644 mojo/probes/string-slice.mojo create mode 100644 mojo/probes/struct-writable.mojo create mode 100644 mojo/stress/bank-account.mojo create mode 100644 mojo/stress/binary-search.mojo create mode 100644 mojo/stress/block-scope.mojo create mode 100644 mojo/stress/bubble-sort.mojo create mode 100644 mojo/stress/caesar-cipher.mojo create mode 100644 mojo/stress/closure-counter.mojo create mode 100644 mojo/stress/collatz.mojo create mode 100644 mojo/stress/comptime-constants.mojo create mode 100644 mojo/stress/context-manager.mojo create mode 100644 mojo/stress/dict-inventory.mojo create mode 100644 mojo/stress/error-chain.mojo create mode 100644 mojo/stress/exact-literals.mojo create mode 100644 mojo/stress/fibonacci-memo.mojo create mode 100644 mojo/stress/fraction.mojo create mode 100644 mojo/stress/function-param-thin.mojo create mode 100644 mojo/stress/function-values.mojo create mode 100644 mojo/stress/gcd-lcm.mojo create mode 100644 mojo/stress/grade-book.mojo create mode 100644 mojo/stress/integer-edges.mojo create mode 100644 mojo/stress/lambda-capture-param.mojo create mode 100644 mojo/stress/lambda-map.mojo create mode 100644 mojo/stress/lifecycle-loop.mojo create mode 100644 mojo/stress/lifecycle-moves.mojo create mode 100644 mojo/stress/matrix-multiply.mojo create mode 100644 mojo/stress/optional-lookup.mojo create mode 100644 mojo/stress/overloads.mojo create mode 100644 mojo/stress/ownership-mut.mojo create mode 100644 mojo/stress/palindromes.mojo create mode 100644 mojo/stress/prime-sieve.mojo create mode 100644 mojo/stress/queue-struct.mojo create mode 100644 mojo/stress/run-length.mojo create mode 100644 mojo/stress/set-operations.mojo create mode 100644 mojo/stress/simd-ops.mojo create mode 100644 mojo/stress/stack-struct.mojo create mode 100644 mojo/stress/string-builder-fixed.mojo create mode 100644 mojo/stress/string-builder.mojo create mode 100644 mojo/stress/temperatures.mojo create mode 100644 mojo/stress/trait-default.mojo create mode 100644 mojo/stress/vector2d.mojo create mode 100644 mojo/stress/word-count.mojo create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 pixi.lock create mode 100644 pixi.toml create mode 100644 quarto/.gitignore create mode 100644 quarto/README.md create mode 100644 quarto/_extensions/pplus/_extension.yml create mode 100644 quarto/_extensions/pplus/course/asm86.css create mode 100644 quarto/_extensions/pplus/course/kit.css create mode 100644 quarto/_extensions/pplus/course/tokens.css create mode 100644 quarto/_extensions/pplus/pplus-hw.css create mode 100644 quarto/_extensions/pplus/pplus-views.css create mode 100644 quarto/_extensions/pplus/pplus.css create mode 100644 quarto/_extensions/pplus/pplus.js create mode 100644 quarto/_extensions/pplus/pplus.lua create mode 100644 quarto/_extensions/pplus/render.mjs create mode 100644 quarto/_extensions/pplus/syntax/lingo.xml create mode 100644 quarto/_extensions/pplus/syntax/mojo.xml create mode 100644 quarto/_extensions/pplus/syntax/pseudo.xml create mode 100644 quarto/_quarto.yml create mode 100644 quarto/example/index.qmd create mode 100644 quarto/example/live.qmd create mode 100644 quarto/example/machine.qmd create mode 100644 quarto/example/programs/binary-search.pseudo create mode 100644 quarto/example/programs/cell.asm create mode 100644 quarto/example/programs/cell.setup create mode 100644 quarto/example/programs/count-base.lingo create mode 100644 quarto/example/programs/count-base.mojo create mode 100644 quarto/example/programs/count-base.pseudo create mode 100644 quarto/example/programs/count-base.speco create mode 100644 quarto/example/programs/five-bugs.pseudo create mode 100644 quarto/example/programs/lifecycle.mojo create mode 100644 quarto/example/programs/match-off-by-one.pseudo create mode 100644 quarto/example/programs/mean.tex create mode 100644 quarto/example/programs/two-pointers.asm create mode 100644 quarto/example/programs/two-pointers.setup create mode 100644 scratch/.gitignore create mode 100644 scripts/asm-census.mjs create mode 100755 scripts/assemble.sh create mode 100644 scripts/check-pages.mjs create mode 100755 scripts/deploy.sh create mode 100644 scripts/engines-diff.mjs create mode 100644 scripts/mojo/corpus.py create mode 100644 scripts/mojo/listings.mjs create mode 100644 scripts/mojo/mojocorpus/__init__.py create mode 100644 scripts/mojo/mojocorpus/common.py create mode 100644 scripts/mojo/mojocorpus/emit_ts.py create mode 100644 scripts/mojo/mojocorpus/fetch.py create mode 100644 scripts/mojo/mojocorpus/godbolt.py create mode 100644 scripts/mojo/mojocorpus/harvest.py create mode 100644 scripts/mojo/mojocorpus/kde.py create mode 100644 scripts/mojo/mojocorpus/processors/__init__.py create mode 100644 scripts/mojo/mojocorpus/processors/diagnostics.py create mode 100644 scripts/mojo/mojocorpus/processors/editor.py create mode 100644 scripts/mojo/mojocorpus/processors/manual.py create mode 100644 scripts/mojo/mojocorpus/processors/messages.py create mode 100644 scripts/mojo/mojocorpus/processors/quest.py create mode 100644 scripts/mojo/mojocorpus/processors/release.py create mode 100644 scripts/mojo/mojocorpus/processors/skill.py create mode 100644 scripts/mojo/mojocorpus/processors/stdindex.py create mode 100644 scripts/mojo/mojocorpus/processors/stdtypes.py create mode 100644 scripts/mojo/mojocorpus/processors/syntax.py create mode 100644 scripts/mojo/mojocorpus/processors/tokens.py create mode 100644 scripts/mojo/mojocorpus/verify.py create mode 100644 scripts/mojo/new-program.mjs create mode 100644 scripts/mojo/tests/test_pipeline.py create mode 100644 scripts/new-exercise.mjs create mode 100644 scripts/play.mjs create mode 100644 scripts/quarto-css.mjs create mode 100644 scripts/quarto-engine.mjs create mode 100644 scripts/quarto-export.mjs create mode 100644 scripts/vendor/build.mjs create mode 100755 scripts/vendor/codemirror.sh create mode 100644 scripts/vendor/entry.ts create mode 100644 scripts/vendor/relink.mjs create mode 100644 scripts/vendor/tsconfig.cm.json create mode 100644 src/core/areas.ts create mode 100644 src/core/catalog.ts create mode 100644 src/core/compiles.ts create mode 100644 src/core/fuzz.ts create mode 100644 src/core/hardware.ts create mode 100644 src/core/prefs.ts create mode 100644 src/core/provenance.ts create mode 100644 src/core/reference.ts create mode 100644 src/core/runview.ts create mode 100644 src/core/session.ts create mode 100644 src/core/state.ts create mode 100644 src/core/types.ts create mode 100644 src/core/versions.ts create mode 100644 src/curriculum/advanced.ts create mode 100644 src/curriculum/concepts.ts create mode 100644 src/curriculum/core.ts create mode 100644 src/curriculum/foundations.ts create mode 100644 src/curriculum/index.ts create mode 100644 src/curriculum/science.ts create mode 100644 src/curriculum/types.ts create mode 100644 src/engines/asm86/cache.js create mode 100644 src/engines/asm86/dom.js create mode 100644 src/engines/asm86/encode.js create mode 100644 src/engines/asm86/hwviews.js create mode 100644 src/engines/asm86/interp.js create mode 100644 src/engines/asm86/machine.js create mode 100644 src/engines/asm86/ooo.js create mode 100644 src/engines/asm86/paging.js create mode 100644 src/engines/asm86/pipeline.js create mode 100644 src/engines/asm86/sandbox.js create mode 100644 src/engines/asm86/specs-hw.js create mode 100644 src/engines/asm86/specs.js create mode 100644 src/engines/asm86/uops.js create mode 100644 src/engines/asm86/views.js create mode 100644 src/engines/pseudo/analyze.js create mode 100644 src/engines/pseudo/check.js create mode 100644 src/engines/pseudo/coach.js create mode 100644 src/engines/pseudo/dom.js create mode 100644 src/engines/pseudo/editor.js create mode 100644 src/engines/pseudo/english.js create mode 100644 src/engines/pseudo/exercise.js create mode 100644 src/engines/pseudo/highlight.js create mode 100644 src/engines/pseudo/interp.js create mode 100644 src/engines/pseudo/lab.js create mode 100644 src/engines/pseudo/lang.js create mode 100644 src/engines/pseudo/logic.js create mode 100644 src/engines/pseudo/parse.js create mode 100644 src/engines/pseudo/plan.js create mode 100644 src/engines/pseudo/planner.js create mode 100644 src/engines/pseudo/sharpen.js create mode 100644 src/engines/pseudo/solver.js create mode 100644 src/engines/pseudo/specs.js create mode 100644 src/engines/pseudo/study.js create mode 100644 src/engines/pseudo/testing.js create mode 100644 src/engines/pseudo/translate.js create mode 100644 src/engines/pseudo/vague.js create mode 100644 src/engines/pseudo/vcgen.js create mode 100644 src/engines/pseudo/views-analysis.js create mode 100644 src/engines/pseudo/views.js create mode 100644 src/engines/shared/dom.js create mode 100644 src/engines/shared/share.js create mode 100644 src/engines/shared/text.js create mode 100644 src/engines/shared/viz.js create mode 100644 src/exercises/_helpers.ts create mode 100644 src/exercises/_template.ts create mode 100644 src/exercises/asm-branchless.ts create mode 100644 src/exercises/asm-cmov.ts create mode 100644 src/exercises/asm-first-instructions.ts create mode 100644 src/exercises/asm-pack-bits.ts create mode 100644 src/exercises/asm-register-widths.ts create mode 100644 src/exercises/asm-two-pointers.ts create mode 100644 src/exercises/asm-vector.ts create mode 100644 src/exercises/best-position.ts create mode 100644 src/exercises/binary-search.ts create mode 100644 src/exercises/count-base-proved.ts create mode 100644 src/exercises/count-base.ts create mode 100644 src/exercises/demo.ts create mode 100644 src/exercises/edit-distance.ts create mode 100644 src/exercises/first-unknown.ts create mode 100644 src/exercises/five-bugs.ts create mode 100644 src/exercises/gc-fraction.ts create mode 100644 src/exercises/hamming.ts create mode 100644 src/exercises/index.ts create mode 100644 src/exercises/kmers.ts create mode 100644 src/exercises/match-off-by-one.ts create mode 100644 src/exercises/match-proved.ts create mode 100644 src/exercises/match-reset.ts create mode 100644 src/exercises/match.ts create mode 100644 src/exercises/revcomp.ts create mode 100644 src/exercises/tally.ts create mode 100644 src/exercises/translate-codons.ts create mode 100644 src/exercises/types.ts create mode 100644 src/main.ts create mode 100644 src/mojo/att.ts create mode 100644 src/mojo/check.ts create mode 100644 src/mojo/editing.ts create mode 100644 src/mojo/flow.ts create mode 100644 src/mojo/flowir.ts create mode 100644 src/mojo/generated/editor.ts create mode 100644 src/mojo/generated/listings.ts create mode 100644 src/mojo/generated/pin.ts create mode 100644 src/mojo/generated/programs.ts create mode 100644 src/mojo/generated/stdlib.ts create mode 100644 src/mojo/generated/tokens.ts create mode 100644 src/mojo/generated/types.ts create mode 100644 src/mojo/interp.ts create mode 100644 src/mojo/lex.ts create mode 100644 src/mojo/lifetimes.ts create mode 100644 src/mojo/parse.ts create mode 100644 src/mojo/practices.ts create mode 100644 src/mojo/properties.ts create mode 100644 src/mojo/reference.ts create mode 100644 src/mojo/resolve.ts create mode 100644 src/mojo/tokenize.ts create mode 100644 src/mojo/typecheck.ts create mode 100644 src/mojo/values.ts create mode 100644 src/mojo/warnings.ts create mode 100644 src/quarto/dom.ts create mode 100644 src/quarto/machine.ts create mode 100644 src/quarto/program.ts create mode 100644 src/quarto/render.ts create mode 100644 src/quarto/shortcodes.ts create mode 100644 src/services/asm.ts create mode 100644 src/services/godbolt.ts create mode 100644 src/services/index.ts create mode 100644 src/services/lingo.ts create mode 100644 src/services/matho.ts create mode 100644 src/services/mojo.ts create mode 100644 src/services/pseudo-study.ts create mode 100644 src/services/pseudo.ts create mode 100644 src/services/speco.ts create mode 100644 src/sync/compare.ts create mode 100644 src/sync/header.ts create mode 100644 src/sync/hub.ts create mode 100644 src/sync/pseudo-to-lingo.ts create mode 100644 src/sync/pseudo-to-matho.ts create mode 100644 src/sync/pseudo-to-mojo.ts create mode 100644 src/sync/types.ts create mode 100644 src/ui/dom.ts create mode 100644 src/ui/editor.ts create mode 100644 src/ui/embed.ts create mode 100644 src/ui/home.ts create mode 100644 src/ui/hw/board.ts create mode 100644 src/ui/hw/lines.ts create mode 100644 src/ui/minirun.ts create mode 100644 src/ui/nav.ts create mode 100644 src/ui/provenance.ts create mode 100644 src/ui/quarto.ts create mode 100644 src/ui/reference.ts create mode 100644 src/ui/shell.ts create mode 100644 src/ui/splitter.ts create mode 100644 src/ui/stepkinds.ts create mode 100644 src/ui/theme.ts create mode 100644 src/ui/tooltip.ts create mode 100644 src/ui/views/compiler.ts create mode 100644 src/ui/views/lifetimes.ts create mode 100644 src/ui/views/panels.ts create mode 100644 src/ui/views/practices.ts create mode 100644 src/ui/views/run.ts create mode 100644 src/ui/views/tests.ts create mode 100644 src/ui/views/trace.ts create mode 100644 src/ui/views/viz.ts create mode 100644 src/vendor/CODEMIRROR-LICENSE create mode 100644 src/vendor/cm-types/commands/src/commands.d.ts create mode 100644 src/vendor/cm-types/commands/src/comment.d.ts create mode 100644 src/vendor/cm-types/commands/src/history.d.ts create mode 100644 src/vendor/cm-types/commands/src/index.d.ts create mode 100644 src/vendor/cm-types/common/src/index.d.ts create mode 100644 src/vendor/cm-types/common/src/mix.d.ts create mode 100644 src/vendor/cm-types/common/src/parse.d.ts create mode 100644 src/vendor/cm-types/common/src/tree.d.ts create mode 100644 src/vendor/cm-types/crelt/index.d.ts create mode 100644 src/vendor/cm-types/find-cluster-break/src/index.d.ts create mode 100644 src/vendor/cm-types/highlight/src/highlight.d.ts create mode 100644 src/vendor/cm-types/language/src/fold.d.ts create mode 100644 src/vendor/cm-types/language/src/highlight.d.ts create mode 100644 src/vendor/cm-types/language/src/indent.d.ts create mode 100644 src/vendor/cm-types/language/src/index.d.ts create mode 100644 src/vendor/cm-types/language/src/isolate.d.ts create mode 100644 src/vendor/cm-types/language/src/language.d.ts create mode 100644 src/vendor/cm-types/language/src/matchbrackets.d.ts create mode 100644 src/vendor/cm-types/language/src/stream-parser.d.ts create mode 100644 src/vendor/cm-types/language/src/stringstream.d.ts create mode 100644 src/vendor/cm-types/lr/src/constants.d.ts create mode 100644 src/vendor/cm-types/lr/src/decode.d.ts create mode 100644 src/vendor/cm-types/lr/src/index.d.ts create mode 100644 src/vendor/cm-types/lr/src/parse.d.ts create mode 100644 src/vendor/cm-types/lr/src/stack.d.ts create mode 100644 src/vendor/cm-types/lr/src/token.d.ts create mode 100644 src/vendor/cm-types/search/src/cursor.d.ts create mode 100644 src/vendor/cm-types/search/src/goto-line.d.ts create mode 100644 src/vendor/cm-types/search/src/index.d.ts create mode 100644 src/vendor/cm-types/search/src/regexp.d.ts create mode 100644 src/vendor/cm-types/search/src/search.d.ts create mode 100644 src/vendor/cm-types/search/src/selection-match.d.ts create mode 100644 src/vendor/cm-types/state/src/change.d.ts create mode 100644 src/vendor/cm-types/state/src/char.d.ts create mode 100644 src/vendor/cm-types/state/src/charcategory.d.ts create mode 100644 src/vendor/cm-types/state/src/column.d.ts create mode 100644 src/vendor/cm-types/state/src/config.d.ts create mode 100644 src/vendor/cm-types/state/src/extension.d.ts create mode 100644 src/vendor/cm-types/state/src/facet.d.ts create mode 100644 src/vendor/cm-types/state/src/index.d.ts create mode 100644 src/vendor/cm-types/state/src/rangeset.d.ts create mode 100644 src/vendor/cm-types/state/src/selection.d.ts create mode 100644 src/vendor/cm-types/state/src/state.d.ts create mode 100644 src/vendor/cm-types/state/src/text.d.ts create mode 100644 src/vendor/cm-types/state/src/transaction.d.ts create mode 100644 src/vendor/cm-types/style-mod/src/style-mod.d.ts create mode 100644 src/vendor/cm-types/view/src/active-line.d.ts create mode 100644 src/vendor/cm-types/view/src/attributes.d.ts create mode 100644 src/vendor/cm-types/view/src/bidi.d.ts create mode 100644 src/vendor/cm-types/view/src/browser.d.ts create mode 100644 src/vendor/cm-types/view/src/buildtile.d.ts create mode 100644 src/vendor/cm-types/view/src/cursor.d.ts create mode 100644 src/vendor/cm-types/view/src/decoration.d.ts create mode 100644 src/vendor/cm-types/view/src/dialog.d.ts create mode 100644 src/vendor/cm-types/view/src/docview.d.ts create mode 100644 src/vendor/cm-types/view/src/dom.d.ts create mode 100644 src/vendor/cm-types/view/src/domchange.d.ts create mode 100644 src/vendor/cm-types/view/src/domobserver.d.ts create mode 100644 src/vendor/cm-types/view/src/domreader.d.ts create mode 100644 src/vendor/cm-types/view/src/draw-selection.d.ts create mode 100644 src/vendor/cm-types/view/src/dropcursor.d.ts create mode 100644 src/vendor/cm-types/view/src/editorview.d.ts create mode 100644 src/vendor/cm-types/view/src/extension.d.ts create mode 100644 src/vendor/cm-types/view/src/gutter.d.ts create mode 100644 src/vendor/cm-types/view/src/heightmap.d.ts create mode 100644 src/vendor/cm-types/view/src/highlight-space.d.ts create mode 100644 src/vendor/cm-types/view/src/index.d.ts create mode 100644 src/vendor/cm-types/view/src/input.d.ts create mode 100644 src/vendor/cm-types/view/src/keymap.d.ts create mode 100644 src/vendor/cm-types/view/src/layer.d.ts create mode 100644 src/vendor/cm-types/view/src/matchdecorator.d.ts create mode 100644 src/vendor/cm-types/view/src/panel.d.ts create mode 100644 src/vendor/cm-types/view/src/placeholder.d.ts create mode 100644 src/vendor/cm-types/view/src/rectangular-selection.d.ts create mode 100644 src/vendor/cm-types/view/src/scrollpastend.d.ts create mode 100644 src/vendor/cm-types/view/src/special-chars.d.ts create mode 100644 src/vendor/cm-types/view/src/theme.d.ts create mode 100644 src/vendor/cm-types/view/src/tile.d.ts create mode 100644 src/vendor/cm-types/view/src/tooltip.d.ts create mode 100644 src/vendor/cm-types/view/src/viewstate.d.ts create mode 100644 src/vendor/cm-types/w3c-keyname/index.d.ts create mode 100644 src/vendor/codemirror.d.ts create mode 100644 src/vendor/codemirror.js create mode 100644 styles.css create mode 100644 styles/course/README.md create mode 100644 styles/course/asm86.css create mode 100644 styles/course/bridge.css create mode 100644 styles/course/kit.css create mode 100644 styles/course/tokens.css create mode 100644 tests/areas.test.mjs create mode 100644 tests/asm-coverage.test.mjs create mode 100644 tests/asm-float.test.mjs create mode 100644 tests/badges.test.mjs create mode 100644 tests/bridge.test.mjs create mode 100644 tests/corpus.test.mjs create mode 100644 tests/corpus/01-arithmetic.pseudo create mode 100644 tests/corpus/02-temperature.pseudo create mode 100644 tests/corpus/03-compound-interest.pseudo create mode 100644 tests/corpus/04-gcd-recursion.pseudo create mode 100644 tests/corpus/05-primes-sieve.pseudo create mode 100644 tests/corpus/06-fibonacci-memo.pseudo create mode 100644 tests/corpus/07-word-count.pseudo create mode 100644 tests/corpus/08-caesar.pseudo create mode 100644 tests/corpus/09-palindrome.pseudo create mode 100644 tests/corpus/10-insertion-sort.pseudo create mode 100644 tests/corpus/11-matrix-multiply.pseudo create mode 100644 tests/corpus/12-records.pseudo create mode 100644 tests/corpus/13-stack-brackets.pseudo create mode 100644 tests/corpus/14-queue-bfs.pseudo create mode 100644 tests/corpus/15-game-of-life.pseudo create mode 100644 tests/corpus/16-running-stats.pseudo create mode 100644 tests/corpus/17-case-grades.pseudo create mode 100644 tests/corpus/18-repeat-input.pseudo create mode 100644 tests/corpus/19-max-subarray.pseudo create mode 100644 tests/corpus/20-two-sum.pseudo create mode 100644 tests/corpus/21-sets.pseudo create mode 100644 tests/corpus/22-binary-to-decimal.pseudo create mode 100644 tests/corpus/23-dice.pseudo create mode 100644 tests/corpus/24-string-builtins.pseudo create mode 100644 tests/corpus/25-nested-collections.pseudo create mode 100644 tests/corpus/26-swap-byref.pseudo create mode 100644 tests/corpus/27-quantifiers.pseudo create mode 100644 tests/corpus/28-float-trap.pseudo create mode 100644 tests/corpus/29-early-exit-flag.pseudo create mode 100644 tests/corpus/30-state-machine.pseudo create mode 100644 tests/corpus/31-edges.pseudo create mode 100644 tests/corpus/32-stops.pseudo create mode 100644 tests/corpus/33-stops-div.pseudo create mode 100644 tests/corpus/34-stops-depth.pseudo create mode 100644 tests/corpus/35-stops-unset.pseudo create mode 100644 tests/corpus/36-stops-counter.pseudo create mode 100644 tests/corpus/37-static-errors.pseudo create mode 100644 tests/corpus/38-continue.pseudo create mode 100644 tests/corpus/39-constants-codons.pseudo create mode 100644 tests/corpus/40-text-builtins.pseudo create mode 100644 tests/corpus/41-reserved-name.pseudo create mode 100644 tests/corpus/42-numerics.pseudo create mode 100644 tests/corpus/43-parallel-map.pseudo create mode 100644 tests/corpus/44-parallel-race.pseudo create mode 100644 tests/corpus/45-parallel-neighbour-race.pseudo create mode 100644 tests/corpus/46-projectile.pseudo create mode 100644 tests/corpus/47-binomial-and-ph.pseudo create mode 100644 tests/corpus/48-declare-with-value.pseudo create mode 100644 tests/course-css.test.mjs create mode 100644 tests/curriculum.test.mjs create mode 100644 tests/editor.test.mjs create mode 100644 tests/exercises.test.mjs create mode 100644 tests/fuzz.test.mjs create mode 100644 tests/hardware.test.mjs create mode 100644 tests/helpers/sync-programs.mjs create mode 100644 tests/listings.test.mjs create mode 100644 tests/matho.test.mjs create mode 100644 tests/mojo-check.test.mjs create mode 100644 tests/mojo-run.test.mjs create mode 100644 tests/mojo.test.mjs create mode 100644 tests/practices-switch.test.mjs create mode 100644 tests/practices.test.mjs create mode 100644 tests/pseudo-declare-init.test.mjs create mode 100644 tests/quarto-gallery.test.mjs create mode 100644 tests/quarto-render.test.mjs create mode 100644 tests/quarto.test.mjs create mode 100644 tests/quarto/harness.lua create mode 100644 tests/reference.test.mjs create mode 100644 tests/runview.test.mjs create mode 100644 tests/services.test.mjs create mode 100644 tests/snapshots/practices.json create mode 100644 tests/snapshots/sync-mojo/best-position.mojo create mode 100644 tests/snapshots/sync-mojo/binary-search.mojo create mode 100644 tests/snapshots/sync-mojo/count-base-proved.mojo create mode 100644 tests/snapshots/sync-mojo/count-base.mojo create mode 100644 tests/snapshots/sync-mojo/edit-distance.mojo create mode 100644 tests/snapshots/sync-mojo/first-unknown.mojo create mode 100644 tests/snapshots/sync-mojo/gc-fraction.mojo create mode 100644 tests/snapshots/sync-mojo/hamming.mojo create mode 100644 tests/snapshots/sync-mojo/kmers.mojo create mode 100644 tests/snapshots/sync-mojo/match-off-by-one.mojo create mode 100644 tests/snapshots/sync-mojo/match-proved.mojo create mode 100644 tests/snapshots/sync-mojo/match-reset.mojo create mode 100644 tests/snapshots/sync-mojo/match.mojo create mode 100644 tests/snapshots/sync-mojo/revcomp.mojo create mode 100644 tests/snapshots/sync-mojo/tally.mojo create mode 100644 tests/snapshots/sync-mojo/translate-codons.mojo create mode 100644 tests/state.test.mjs create mode 100644 tests/sync-coverage.test.mjs create mode 100644 tests/sync-hub.test.mjs create mode 100644 tests/sync-lingo.test.mjs create mode 100644 tests/sync-matho.test.mjs create mode 100644 tests/sync-mojo.test.mjs create mode 100644 tests/sync-speco.test.mjs create mode 100644 tests/tasks.test.mjs create mode 100644 tests/versions.test.mjs create mode 100644 tsconfig.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0a4cb20 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,100 @@ +# EditorConfig: https://editorconfig.org +# In VS Code, install the "EditorConfig for VS Code" extension (EditorConfig.EditorConfig). + +root = true + +# Defaults for every file +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +# Python +[*.{py,pyi}] +indent_size = 4 +max_line_length = 88 + +# Mojo (`mojo format` is Black-style, 88 columns; the fire emoji extension is also valid) +[*.{mojo,🔥}] +indent_size = 4 +max_line_length = 88 + +# Rust (rustfmt defaults: 4 spaces, 100 columns) +[*.rs] +indent_size = 4 +max_line_length = 100 + +# Cargo manifests and rustfmt config +[{Cargo.toml,Cargo.lock,rustfmt.toml,.rustfmt.toml,clippy.toml}] +indent_size = 4 + +# Mojo project manifest +[{mojoproject.toml,pixi.toml,pixi.lock}] +indent_size = 4 + +# YAML +[*.{yml,yaml}] +indent_size = 2 + +# JSON and friends +[*.{json,jsonc,json5}] +indent_size = 2 + +# Web +[*.{js,jsx,mjs,cjs,ts,tsx,css,scss,less,html,vue,svelte}] +indent_size = 2 + +# Config formats +[*.{toml,ini,cfg}] +indent_size = 4 + +[*.xml] +indent_size = 2 + +# Markdown: trailing spaces are significant (hard line breaks) +[*.{md,markdown}] +indent_size = 2 +trim_trailing_whitespace = false + +# typst +[*.{typ}] +indent_size = 4 +trim_trailing_whitespace = false + +# Shell scripts +[*.{sh,bash,zsh}] +indent_size = 2 + +# Makefiles require tabs +[{Makefile,makefile,*.mk}] +indent_style = tab + +# Go uses tabs +[*.go] +indent_style = tab + +# Windows-only scripts need CRLF +[*.{bat,cmd,ps1}] +end_of_line = crlf + +# Dockerfiles +[{Dockerfile,Dockerfile.*,*.dockerfile}] +indent_size = 4 + +# Terraform +[*.{tf,tfvars,hcl}] +indent_size = 2 + +# Don't touch these +[LICENSE*] +insert_final_newline = false + +[*.{diff,patch}] +trim_trailing_whitespace = false + +[*.min.{js,css}] +insert_final_newline = unset +trim_trailing_whitespace = unset diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..997504b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# SCM syntax highlighting & preventing 3-way merges +pixi.lock merge=binary linguist-language=YAML linguist-generated=true -diff diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..a131a04 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,75 @@ +# Programming+ on Gitea Actions, with a runner that has no container image: +# the act_runner runs jobs directly on the droplet's shell ("host mode"). +# +# Runner setup, once, on the droplet (docs/deploy.md): +# - node >= 20, git, rsync installed; a `deploy` user that can write /srv/www +# - act_runner registered with the host-mode label this file's `runs-on` names: +# act_runner register --instance https://git.example --token ... --labels "quarto-deploy:host" +# (the `:host` suffix is what makes jobs run on the machine instead of in docker) +# +# Every push and pull request builds and tests. A push to main also publishes +# the site to /srv/www/ as an atomic release (scripts/deploy.sh). +# +# Repository → Settings → Actions → Variables (all optional): +# SITE_SLUG the directory under /srv/www (defaults to the repository name) +# SITE_URL e.g. https://pplus.scient.ing, turns on the smoke test +name: Build, test, deploy +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: deploy-${{ gitea.ref }} + cancel-in-progress: true + +jobs: + site: + # The host-mode label from the runner registration. Jobs run as the + # runner's user, in a fresh working directory, with the host's node. + runs-on: quarto-deploy + steps: + # actions/checkout needs node on the host, which the job needs anyway. + - uses: actions/checkout@v4 + + - name: Toolchain on the host + run: | + node --version + npm --version + git --version + command -v rsync >/dev/null || echo "rsync missing: local deploys fall back to cp, SSH deploys need it" + + - run: npm ci + - run: npm test + + # The same check as `pixi run mojo-status-strict`: offline, from the stored godbolt answers. + - name: Our Mojo programs pass + run: | + if command -v python3 >/dev/null; then python3 scripts/mojo/corpus.py status --strict + else echo "python3 missing: corpus status skipped"; fi + + - name: Assemble the site + run: scripts/assemble.sh + env: + GITHUB_SHA: ${{ gitea.sha }} + + - name: Publish to /srv/www + if: gitea.event_name != 'pull_request' && gitea.ref == 'refs/heads/main' + env: + SLUG: ${{ vars.SITE_SLUG || gitea.event.repository.name }} + GITHUB_SHA: ${{ gitea.sha }} + run: scripts/deploy.sh "$SLUG" + + - name: Smoke test + if: gitea.event_name != 'pull_request' && gitea.ref == 'refs/heads/main' && vars.SITE_URL != '' + env: + SITE_URL: ${{ vars.SITE_URL }} + GITHUB_SHA: ${{ gitea.sha }} + run: | + sleep 2 + live=$(curl -fsS "$SITE_URL/VERSION") + case "$live" in + "${GITHUB_SHA:0:12}"*) echo "live site is at $live" ;; + *) echo "live site reports '$live', expected ${GITHUB_SHA:0:12}" >&2; exit 1 ;; + esac diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4118958 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +site/ +node_modules/ +.DS_Store +dist/ +patches/ +# pixi environments +.pixi/* +!.pixi/config.toml + +# Python +__pycache__/ +*.pyc +# the Quarto example site's output and Quarto's own state +quarto/_site/ +quarto/.quarto/ +quarto/_extensions/pplus/engine/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..66a5c44 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,58 @@ +# AGENTS.md + +Instructions for coding agents (and people) changing Programming+. Read this first, then the [README](README.md) for what the app is and where things are. When this file and a task's instructions disagree, the task wins; say so in your summary. + +## Build, test, and the gate + +```bash +pixi run test # build, then every test (node --test against dist/, the corpus pipeline's Python tests included) +pixi run ci # the gate: every test, and no Mojo program of ours failing +``` + +Without pixi (a sandbox with only Node and Python): + +```bash +tsc -p tsconfig.json && node --test tests/*.test.mjs +python3 scripts/mojo/corpus.py status --strict +``` + +**Finish every change with the gate green.** The baseline passes completely; there is no known failure to work around. If a test fails, fix the cause or stop and report it. Do not skip, loosen, or delete a test to get green. + +The full suite takes about two minutes. While iterating, build and run one file: `tsc -p tsconfig.json && node --test tests/state.test.mjs`. + +## Hard rules + +1. **Do not edit generated files by hand.** `src/mojo/generated/*` and `quarto/_extensions/pplus/syntax/mojo.xml` come from the corpus pipeline (`pixi run mojo-emit`, `mojo-status`, `play`). `quarto/_extensions/pplus/pplus-views.css` comes from `styles.css`, and `pplus-hw.css` and `course/*.css` beside it from `styles/course/` (`pixi run quarto-css`; a test fails while they are out of date, so run it after changing a rule the views use). `mojo/corpus/` comes from `mojo-harvest`. `mojo/golden/` holds godbolt's answers and comes only from `mojo-verify`. +2. **Do not edit a `.mojo` file's text unless the task needs it.** A stored godbolt answer is keyed by the whole source, header comments included, so any edit (even to a comment) makes the program unverified until it is asked again on the network. If you add or change one, say in your summary that it needs `pixi run mojo-verify-item '/'`. +3. **Never claim Mojo compiles, runs, or prints something without the real compiler's answer.** Mojo is pinned to 1.1.0. The checker may never report an error on a program the compiler accepts, and the interpreter must print exactly what godbolt printed or decline; `tests/mojo-check.test.mjs` and `tests/mojo-run.test.mjs` hold them to that. Every Mojo construct you write into the app must pass `checkMojo`, and every standard-library name must exist in `src/mojo/generated/stdlib.ts` or `types.ts`. +4. **No new dependencies.** TypeScript is the only npm package. There is no bundler, no framework, and no runtime dependency; the corpus pipeline is Python's standard library only. CodeMirror is vendored as one built module (`src/vendor/`), rebuilt only by `scripts/vendor/codemirror.sh`. +5. **You have no network** in most sandboxes. Godbolt (`mojo-verify`, Compile & run) and GitHub (`mojo-harvest`, `mojo-fetch`) need one. Never fake their results; leave those steps to the owner and list them. +6. **Keep the workspace working while you change it.** Code panes are always the CodeMirror editor (`Editor` in `src/ui/editor.ts`, over the vendored `src/vendor/codemirror.js`), never a ``; + if (this.namespaceURI === SVG_NS && !this.childNodes.length) return open + '/>'; + return `${open}>${super.serialize()}`; + } +} +const BOOL_ATTR: Record = { hidden: true, open: true, disabled: true, readonly: true, checked: true, selected: true, multiple: true, required: true }; + +/* ---------- selectors ---------- */ + +type Matcher = (e: SElement) => boolean; +const compiled = new Map(); + +function compile(sel: string): Matcher { + const hit = compiled.get(sel); + if (hit) return hit; + const alts = sel.split(',').map((s) => s.trim()).filter(Boolean).map(descendant); + const m: Matcher = (e) => alts.some((a) => a(e)); + compiled.set(sel, m); + return m; +} + +/** `a b c`: c, inside a b, inside an a. */ +function descendant(s: string): Matcher { + if (/[>+~]/.test(s.replace(/\[[^\]]*\]/g, ''))) throw new Error(`the render document does not handle the selector "${s}" (only the descendant combinator)`); + const parts = s.split(/\s+(?![^\[]*\])/).filter(Boolean).map(compound); + const last = parts.pop()!; + return (e) => { + if (!last(e)) return false; + let k = parts.length - 1; + for (let a = e.parentElement; a && k >= 0; a = a.parentElement) if (parts[k](a)) k--; + return k < 0; + }; +} + +function compound(s: string): Matcher { + const tests: Matcher[] = []; + const re = /^([a-zA-Z][\w-]*|\*)|\.([\w-]+)|#([\w-]+)|\[([\w-]+)(?:([\^$*]?=)"?([^"\]]*)"?)?\]/g; + let m: RegExpExecArray | null; + let pos = 0; + while ((m = re.exec(s))) { + if (m.index !== pos) break; + pos = re.lastIndex; + const [, tag, cls, id, attr, op, val] = m; + if (tag && tag !== '*') tests.push((e) => e.localName.toLowerCase() === tag.toLowerCase()); + else if (cls) tests.push((e) => e.classList.contains(cls)); + else if (id) tests.push((e) => e.getAttribute('id') === id); + else if (attr) tests.push((e) => { + const v = e.getAttribute(attr); + if (v === null) return false; + if (!op) return true; + return op === '=' ? v === val : op === '^=' ? v.startsWith(val) : op === '$=' ? v.endsWith(val) : v.includes(val); + }); + } + if (pos !== s.length) throw new Error(`the render document does not handle the selector "${s}"`); + return (e) => tests.every((t) => t(e)); +} + +/* ---------- the document, and the globals ---------- */ + +export class SDocument extends SFragment { + readonly documentElement = new SElement('html'); + readonly head = new SElement('head'); + readonly body = new SElement('body'); + constructor() { super(); this.nodeType = 9; this.appendChild(this.documentElement); this.documentElement.append(this.head, this.body); } + createElement(tag: string): SElement { return new SElement(tag); } + createElementNS(ns: string | null, tag: string): SElement { return new SElement(tag, ns); } + createTextNode(s: string): SText { return new SText(String(s)); } + createComment(s: string): SComment { return new SComment(String(s)); } + createDocumentFragment(): SFragment { return new SFragment(); } + getElementById(id: string): SElement | null { return this.querySelector('#' + id); } + execCommand(): boolean { return false; } + get activeElement(): null { return null; } +} + +const queued: Array<() => void> = []; + +/** Run what the views put off to the next frame or a timer (a view that measures before drawing), until none is left. */ +export function flushQueued(rounds = 8): void { + for (let i = 0; i < rounds && queued.length; i++) for (const fn of queued.splice(0)) { try { fn(); } catch { /* a view's late refinement, not its output */ } } +} + +let installed: SDocument | null = null; + +/** + * Give this process a `document` (and the few other browser globals the views reach for). Does nothing where a + * real document exists, so the same render code runs in the app's gallery and under `quarto render`. + */ +export function installDocument(): boolean { + const g = globalThis as any; + if (g.document && !installed) return false; + if (installed) return true; + installed = new SDocument(); + const store = new Map(); + g.document = installed; + g.Node = SNode; g.Element = SElement; g.HTMLElement = SElement; g.SVGElement = SElement; g.Text = SText; g.DocumentFragment = SFragment; + g.localStorage ??= { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, String(v)), removeItem: (k: string) => void store.delete(k), clear: () => store.clear(), key: (i: number) => [...store.keys()][i] ?? null, get length() { return store.size; } }; + g.requestAnimationFrame ??= (fn: (t: number) => void) => { queued.push(() => fn(0)); return queued.length; }; + g.cancelAnimationFrame ??= () => { /* queued work runs at most once */ }; + g.ResizeObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } }; + g.IntersectionObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } }; + g.MutationObserver ??= class { observe() { /* nothing changes */ } disconnect() { /* nothing changes */ } takeRecords() { return []; } }; + g.getComputedStyle ??= () => ({ getPropertyValue: () => '' }); + g.matchMedia ??= () => ({ matches: false, addEventListener() { /* static */ }, removeEventListener() { /* static */ }, addListener() { /* static */ }, removeListener() { /* static */ } }); + // a window whose timers are queued with the animation frames: the render reads the views once, after flushQueued() + g.window ??= g; + if (g.window === g) { + g.innerWidth ??= 1200; g.innerHeight ??= 800; g.devicePixelRatio ??= 1; + g.addEventListener ??= () => { /* nothing fires */ }; g.removeEventListener ??= () => { /* nothing fires */ }; + g.location ??= { href: 'https://pplus.invalid/', hash: '', search: '', origin: 'https://pplus.invalid' }; + } + return true; +} + +/** The HTML of what a view built: an element's children, as markup. */ +export function htmlOf(node: unknown): string { + if (node instanceof SNode) return node.serialize(); + return (node as any).innerHTML as string; +} diff --git a/src/quarto/machine.ts b/src/quarto/machine.ts new file mode 100644 index 0000000..d671ae4 --- /dev/null +++ b/src/quarto/machine.ts @@ -0,0 +1,194 @@ +/** + * The machine, rendered with the page: the Hardware area's board views (registers, memory, the stack, the caches, + * virtual memory, the pipeline, the out-of-order core, the encoding...) over an x86-64 run, for the Quarto + * extension's `pplus-hw` shortcodes. + * + * The views are the course's own (src/engines/asm86/views.js and hwviews.js), mounted exactly as the board mounts + * them (`mountView`, `courseViews` in core/hardware.ts) and drawn at every step of the run. A page cannot run them, + * so each card keeps what it drew at each step: the distinct drawings once, and which one each step shows. pplus.js + * steps through them; render.mjs compresses them (they repeat from step to step, so deflate makes a run of a + * hundred steps a few kilobytes per card). The step the page opens on is in the markup itself, so the page reads, + * prints and works without script. + */ +import { el, add } from '../ui/dom.js'; +import type { Session } from '../core/session.js'; +import { BOARD_VIEWS, BOARD_PRESETS, boardFrame, boardView, courseViews, parseMachine, machineLabel, machineName, type BoardViewId } from '../core/hardware.js'; +import { mountView } from '../ui/hw/board.js'; +import { machineView } from '../ui/views/panels.js'; +import { highlighted, freeze } from './render.js'; + +/** + * The machine's views as the shortcodes name them: `pplus-hw-`. The name is the board's id, except where a + * shortcode of that name already means something else (the ALU is `bits` on the board, the whole core `machine`). + */ +export const HW_NAMES: Record = { + code: 'code', explain: 'explain', registers: 'registers', flags: 'flags', address: 'address', memory: 'memory', stack: 'stack', + dataflow: 'dataflow', alu: 'bits', branches: 'branches', vectors: 'vectors', + lines: 'lines', cache: 'cache', hierarchy: 'hierarchy', paging: 'paging', + pipeline: 'pipeline', uops: 'uops', timeline: 'timeline', bottleneck: 'bottleneck', counters: 'counters', + chip: 'machine', core: 'core', encoding: 'encoding', +}; + +/** The board's arrangements a page can ask for (`preset=`), without the Mojo one (the machine cards only). */ +export const HW_PRESETS = BOARD_PRESETS.filter((p) => p.id !== 'mojo').map((p) => ({ id: p.id, label: p.label, blurb: p.blurb, views: p.items.map((x) => x.id).filter((id) => boardView(id)!.needs === 'asm') })); + +/** A view by its shortcode name or its board id. */ +export function hwView(name: string): BoardViewId | null { + const n = name.trim().toLowerCase(); + if (HW_NAMES[n]) return HW_NAMES[n]; + const v = boardView(n); + return v && v.needs === 'asm' ? v.id : null; +} + +/** What pplus.js reads: for each card, its distinct drawings, and which one each step shows. */ +export interface HwData { + count: number; + t: number; + /** Per step: the line of the instruction about to run (`n`) and of the one that just ran (`l`), and that instruction's text. */ + steps: Array<{ n: number | null; l: number | null; x: string }>; + cards: Array<{ id: string; frames: string[]; at: number[] }>; + /** Steps drawn: every one, or every `stride`-th when the run is longer than `max`. */ + shown: number[]; +} + +export interface HwRequest { views?: string[]; preset?: string; t?: number; max?: number; listing?: boolean; stepper?: boolean } + +export function machineBoard(session: Session, req: HwRequest): { node: HTMLElement; markdown: string; warnings: string[]; data: HwData | null } { + const warnings: string[] = []; + session.state.lang = 'asm'; + // the views asked for, in order; unknown ones are reported, and paging turns virtual memory on + let ids: BoardViewId[] = []; + if (req.views?.length) { + for (const v of req.views) { const id = hwView(v); if (id) { if (!ids.includes(id)) ids.push(id); } else warnings.push(`hw: no machine view "${v}"; the views are ${Object.keys(HW_NAMES).join(', ')}`); } + } + if (!ids.length) ids = (HW_PRESETS.find((p) => p.id === req.preset) ?? HW_PRESETS[0]).views; + if (req.preset && !req.views?.length && !HW_PRESETS.some((p) => p.id === req.preset)) warnings.push(`hw: no preset "${req.preset}"; the presets are ${HW_PRESETS.map((p) => p.id).join(', ')}`); + if (ids.includes('paging') && !parseMachine(session.state.machine).paging) session.state.machine = machineName({ preset: parseMachine(session.state.machine).preset, paging: true }); + + const tr = session.trace(); + const trace = tr && tr.lang === 'asm' ? (tr.raw as any)?.trace : null; + if (!session.source('asm').trim()) { + const why = 'The machine views run an x86-64 file (asm=, with its setup=). For a Mojo program, `pixi run quarto-export` writes the compiler\'s x86-64 and setup beside the page.'; + return { node: el('div', {}, el('p', { class: 'pplus-err' }, why)), markdown: `*${why}*`, warnings: [...warnings, 'hw: no x86-64 file (asm=)'], data: null }; + } + if (!trace) { + const why = session.runError ?? session.diagnostics('asm').find((d) => d.severity === 'error')?.message ?? 'The x86-64 file does not assemble.'; + return { node: el('div', {}, el('p', { class: 'pplus-err' }, `It does not run: ${why}`)), markdown: `*It does not run: ${why}*`, warnings: [...warnings, `hw: ${why}`], data: null }; + } + + const machine = parseMachine(session.state.machine); + const count: number = trace.count; + const max = Math.max(10, Math.min(req.max ?? 400, 5000)); + const stride = Math.max(1, Math.ceil(count / max)); + const shown: number[] = []; + for (let t = 0; t <= count; t += stride) shown.push(t); + if (shown[shown.length - 1] !== count) shown.push(count); + const t0 = Math.max(0, Math.min(req.t ?? 0, count)); + // the step the page opens on is one of those drawn + const open = shown.reduce((best, t) => (Math.abs(t - t0) < Math.abs(best - t0) ? t : best), shown[0]); + const stepper = req.stepper !== false && count > 0; + + const lineOf = (instr: any) => (instr && typeof instr.lineNo === 'number' ? instr.lineNo + 1 : null); + const steps = shown.map((t) => { const f = boardFrame(trace, t); return { n: lineOf(f.next), l: lineOf(f.last?.instr), x: String(f.last?.instr?.text ?? '').trim().replace(/\s+/g, ' ') }; }); + + const cards: HwData['cards'] = []; + const grid = el('div', { class: 'pplus-hw-grid' }); + // the listing stands beside the cards (sticky while they scroll), unless the machine-code card is one of them + let listing: HTMLElement | null = null; + if (req.listing !== false && !ids.includes('code')) { + const code = highlighted(session.source('asm'), 'asm', { numbers: true }); + const at = steps[shown.indexOf(open)]; + for (const ln of [...code.querySelectorAll('.pplus-ln')]) { + const n = Number(ln.getAttribute('data-line')); + if (n === at.n) ln.classList.add('is-next'); + if (n === at.l) ln.classList.add('is-last'); + } + listing = el('section', { class: 'pplus-hw-card pplus-hw-listing', 'data-hw': 'listing' }, el('div', { class: 'pplus-hw-title' }, 'x86-64'), code); + } + for (const id of ids) { + const def = boardView(id)!; + const card = el('section', { class: `pplus-hw-card pplus-hw-${id}${def.wide ? ' is-wide' : ''}`, 'data-hw': id, title: def.blurb }); + add(grid, card); + if (id === 'counters') { + // the run's totals: the same at every step + const box = el('div', { class: 'view view-asm' }); + machineView(session, box); + freeze(box); + add(card, el('div', { class: 'pplus-hw-title' }, def.label), box); + continue; + } + const spec = id === 'lines' ? { name: 'lines', options: {} } : courseViews([{ id }], trace, machine)[0]; + if (!spec) continue; + const view = mountView(spec.name, trace, spec.options); + const frames: string[] = []; + const index = new Map(); + const at: number[] = []; + let first = ''; + for (const t of stepper ? shown : [open]) { + view.update(boardFrame(trace, t)); + const html = inert(view.node.outerHTML); + if (!index.has(html)) { index.set(html, frames.length); frames.push(html); } + at.push(index.get(html)!); + if (t === open) first = html; + } + if (view.node.classList.contains('has-failed')) warnings.push(`hw: the ${def.label} view failed on this run`); + const holder = el('div', { class: 'a86 board-a86', 'data-hw-frame': '' }); + // the drawing for the step the page opens on: the course view's own markup. In a browser (the gallery) it goes + // in directly; the small document has no parser, so there it is spliced into the serialized page (spliceFrames) + if (typeof DOMParser !== 'undefined') holder.innerHTML = first; + else (holder as any).__html = first; + add(card, holder); + cards.push({ id, frames, at }); + } + + const data: HwData = { count, t: open, steps, cards, shown }; + const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label); + const node = el('div', { 'data-count': String(count), 'data-t': String(open) }, + stepper ? el('div', { class: 'pplus-steps-bar' }, + el('span', { class: 'pplus-chip pplus-chip-asm' }, 'x86-64'), + btn('first', '⏮', 'First step'), btn('back', '◀', 'Back one step'), btn('next', '▶', 'One step'), btn('last', '⏭', 'Last step'), btn('play', 'Play', 'Play the run'), + el('input', { type: 'range', class: 'pplus-steps-slider', min: '0', max: String(shown.length - 1), value: String(shown.indexOf(open)), 'aria-label': 'step' }), + el('span', { class: 'pplus-steps-count' }, `${open} / ${count}`)) : null, + el('div', { class: 'pplus-hw-now' }, nowText(steps[shown.indexOf(open)], open), el('span', { class: 'pplus-muted pplus-hw-machine' }, ` · ${machineLabel(session.state.machine)} machine`)), + el('div', { class: `pplus-hw-body${listing ? ' has-listing' : ''}` }, listing, grid), + stride > 1 ? el('p', { class: 'pplus-note' }, `The run takes ${count} steps; every ${stride}${stride === 2 ? 'nd' : stride === 3 ? 'rd' : 'th'} is drawn (max="${max}").`) : null, + stepper ? el('script', { type: 'application/json', class: 'pplus-hw-data' }, JSON.stringify(data).replace(/]*>[\s\S]*?<\/button>/g, '').replace(/]*>[\s\S]*?<\/select>/g, '').replace(/]*>/g, ''); +} + +export const nowText = (s: { x: string } | undefined, t: number): string => (t === 0 ? 'Before the first instruction.' : `Step ${t}: ${s?.x ?? ''}`); + +/** Put each card's drawing for the opening step into the serialized markup (see machineBoard). */ +export function spliceFrames(html: string, node: HTMLElement): string { + const holders = [...node.querySelectorAll('[data-hw-frame]')]; + let i = 0; + return html.replace(/
<\/div>/g, (m) => { + const h = holders[i++] as any; + return h?.__html ? m.replace('>
', `>${h.__html}`) : m; + }); +} + +/** In a format other than HTML: the registers the run wrote, at the step shown, and what each view is. */ +function machineMarkdown(ids: BoardViewId[], trace: any, t: number): string { + const f = boardFrame(trace, t); + const regs = new Set(); + for (const s of trace.steps.slice(0, t)) for (const r of s.diff?.regs ?? []) regs.add(r.name); + const hex = (v: unknown) => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } }; + const rows = [...regs].map((r) => `| ${r} | ${hex(f.state.regs[r])} |`); + return [`*The machine at step ${t} of ${trace.count}${f.last ? `, after \`${String(f.last.instr.text).trim().replace(/\s+/g, ' ')}\`` : ''}.*`, '', + rows.length ? ['| register | value |', '|---|---|', ...rows].join('\n') : '', + '', `*Drawn in the HTML version of this page: ${ids.map((id) => boardView(id)!.label).join(', ')}.*`].join('\n'); +} + +export const HW_VIEW_LIST = BOARD_VIEWS.filter((v) => v.needs === 'asm'); diff --git a/src/quarto/program.ts b/src/quarto/program.ts new file mode 100644 index 0000000..07ea49e --- /dev/null +++ b/src/quarto/program.ts @@ -0,0 +1,71 @@ +/** + * A program file as a Quarto page keeps it beside the .qmd: which pane it fills, the header lines the page's + * checker reads (`// CALL:`, `// INPUT:`, `// EXPECT:` ...), and the text a reader is shown, without them. + * + * The rules are the shortcode's (quarto/_extensions/pplus/pplus.lua) and scripts/check-pages.mjs's: + * lingo, pseudo, speco `// KEY: value` anywhere in the file + * matho (.tex) `% KEY: value` + * Mojo the leading block of `# key: value` comments (mojo/local/'s corpus header, or + * `# EXPECT:` lines); a `# note:` further down belongs to the program + * DOM-free; tests/quarto-render.test.mjs checks it. + */ +import type { LangId } from '../core/types.js'; + +export interface ProgramHeader { + call?: string; + input: string[]; + expect: string[]; + errors?: number; + stops?: string; + questions: string[]; +} + +/** The pane a file fills, from its extension. */ +export function langOfFile(name: string): LangId | null { + const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase(); + switch (ext) { + case 'lingo': return 'lingo'; + case 'tex': case 'matho': return 'matho'; + case 'pseudo': return 'pseudo'; + case 'speco': return 'speco'; + case 'mojo': case '🔥': return 'mojo'; + case 'asm': case 's': return 'asm'; + default: return null; + } +} + +// `# expect-stdout:` is the corpus header's spelling of EXPECT (mojo/local/, mojo/stress/), so an exported program keeps its check +const HEADER = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT|EXPECT|ERRORS|QUESTION|STOPS|expect-stdout):\s?(.*)$/; + +/** The header lines of a program file (the same lines scripts/check-pages.mjs reads). */ +export function programHeader(text: string): ProgramHeader { + const h: ProgramHeader = { input: [], expect: [], questions: [] }; + for (const line of text.split('\n')) { + const m = HEADER.exec(line); + if (!m) continue; + const v = m[2]; + if (m[1] === 'CALL') h.call = v.trim(); + else if (m[1] === 'INPUT') h.input.push(v); + else if (m[1] === 'EXPECT' || m[1] === 'expect-stdout') h.expect.push(v); + else if (m[1] === 'ERRORS') h.errors = Number(v); + else if (m[1] === 'QUESTION') h.questions.push(v.trim()); + else if (m[1] === 'STOPS') h.stops = v.trim(); + } + return h; +} + +/** The file as a page shows it and a pane holds it: the header lines removed, blank lines trimmed at both ends. */ +export function listingText(text: string, lang: LangId): string { + const out: string[] = []; + let head = lang === 'mojo'; + for (const line of text.replace(/\r\n?/g, '\n').split('\n')) { + if (head) { + if (/^#\s*[\w-]+:/.test(line)) continue; + if (!line.trim() && !out.length) continue; + head = false; + } + if (lang !== 'mojo' && /^\s*(?:\/\/|%)\s*[A-Z]+:/.test(line)) continue; + out.push(line); + } + return out.join('\n').replace(/^\n+/, '').replace(/\n+$/, ''); +} diff --git a/src/quarto/render.ts b/src/quarto/render.ts new file mode 100644 index 0000000..1bcb7be --- /dev/null +++ b/src/quarto/render.ts @@ -0,0 +1,508 @@ +/** + * The static views of the Quarto extension: a program from the files beside a page, run by the app's own engines + * when the page is rendered, and drawn by the app's own views (src/ui/views/) as HTML that needs no iframe and no + * network. `quarto render` reaches this through quarto/_extensions/pplus/render.mjs, under the small document of + * ./dom.ts; the app's "With Quarto" gallery (src/ui/quarto.ts) calls it in the browser, with the real one, so the + * gallery shows exactly what a page gets. + * + * run what the program prints (and returns), checked against its EXPECT lines + * steps the listing with a stepper: every step, the line it ran, the values after it (pplus.js steps it) + * table the table of values: a column per step that changed something, a row per name + * flow the flowchart of the routine, shaded by how often each line ran + * data the data-flow graph of the routine + * life each Mojo value's lifetime: made, copied, moved, destroyed + * proof the claims of the speco (or the pseudo's ENSUREs), proved, broken or open + * tests the fuzzer's report for every routine + * check the checker's findings for each file, on its own lines + * translate the procedure in every notation the hub can write it in, Mojo generated from the pseudo + * machine the x86-64 run on the model machine: instructions, cycles, cache misses + * hw the Hardware area's board over an x86-64 run: registers, memory, caches, pipeline, the core..., + * steppable (./machine.ts) + * + * Every view returns HTML for an HTML page and Markdown for any other format (a PDF, a Word file), so a page + * renders everywhere; the Markdown says plainly what only the HTML can show. + */ +import { el, add } from '../ui/dom.js'; +import { Session } from '../core/session.js'; +import { emptyState, type PlayState } from '../core/state.js'; +import { LANG_NAMES, type LangId } from '../core/types.js'; +import { SERVICES } from '../services/index.js'; +import { SyncHub, mojoFromPseudo, LINKED } from '../sync/hub.js'; +import { runColumns, defaultFollow, runRows, valuesAt, type RunRow } from '../core/runview.js'; +import { familyOf } from '../ui/stepkinds.js'; +import { flowView, dataFlowView, traceTableView } from '../ui/views/viz.js'; +import { problemsView, proofView, machineView } from '../ui/views/panels.js'; +import { testsView } from '../ui/views/tests.js'; +import { lifetimesView } from '../ui/views/lifetimes.js'; +import { MOJO_VERSION } from '../mojo/generated/pin.js'; +import { listingText, programHeader, type ProgramHeader } from './program.js'; +import { machineBoard, spliceFrames } from './machine.js'; + +export const STATIC_VIEWS = ['run', 'steps', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'check', 'translate', 'machine', 'hw'] as const; +export type StaticView = typeof STATIC_VIEWS[number]; +export const isStaticView = (v: unknown): v is StaticView => (STATIC_VIEWS as readonly string[]).includes(v as string); + +const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm']; + +/** What a page asks for: one view of the program in `files` (each file's text as it is on disk, header and all). */ +export interface RenderRequest { + view: StaticView; + files: Partial>; + /** The pane the run reads (default: the first of lingo, matho, pseudo, mojo, asm given; speco runs as its pseudo). */ + lang?: LangId; + /** The call, and the lines INPUT reads; by default the files' own `// CALL:` and `// INPUT:` lines. */ + call?: string | null; + input?: string[]; + setup?: string; + machine?: string; + /** The step a stepper starts on, and where the flowchart and the table of values stop (default: the end). */ + t?: number; + title?: string; + /** translate: the notations to show (default: every one the procedure has, and Mojo). */ + to?: LangId[]; + /** steps: the most steps kept for the stepper (default 400). */ + max?: number; + /** steps, table: the variables to show, as written in the program (default: the routine that does the most work). */ + follow?: string[]; + /** hw: the machine views to show (their shortcode names or board ids), or a preset of the board (regs, caches, pipeline, chip). */ + hw?: string[]; + preset?: string; + /** hw: false leaves out the x86-64 listing; stepper false draws only the step `t`. */ + listing?: boolean; + stepper?: boolean; + /** A run of the Mojo file by a real compiler (render.mjs does it when `mojo` is on the PATH). */ + compiled?: { stdout: string; stderr: string; status: number | null; version: string } | null; +} + +export interface TranslatedPane { lang: LangId; label: string; text: string; authored: boolean; generated: boolean; note?: string; /** For a generated pane: the notation it was written from. */ from?: LangId } + +export interface RenderResult { + view: StaticView; + /** The language that ran or was drawn. */ + lang: LangId | null; + /** The view as an element of whichever document is installed, and as markup. */ + node: HTMLElement; + html: string; + markdown: string; + /** Things the author should know (stderr in `quarto render`): a run that does not print its EXPECT lines, a missing piece. */ + warnings: string[]; + /** run: what the program printed against what its EXPECT lines say. */ + expect?: { want: string[]; got: string[]; ok: boolean }; + /** translate: each notation's text. */ + panes?: TranslatedPane[]; +} + +/* ------------------------------------------------------------------ */ +/* The session */ +/* ------------------------------------------------------------------ */ + +interface Prepared { session: Session; header: ProgramHeader; given: LangId[]; sources: Partial> } + +function prepare(req: RenderRequest): Prepared { + const sources: Partial> = {}; + const given: LangId[] = []; + for (const l of PANES) { + const text = req.files[l]; + if (typeof text !== 'string') continue; + sources[l] = listingText(text, l); + given.push(l); + } + const runnable = (['lingo', 'matho', 'pseudo', 'mojo', 'asm'] as LangId[]).find((l) => given.includes(l)) ?? given[0] ?? 'pseudo'; + const lang = req.lang && given.includes(req.lang) ? req.lang : runnable; + // the header of the file that runs comes first; another file's fills in what it leaves out + const order = [lang, ...given.filter((l) => l !== lang)]; + const header: ProgramHeader = { input: [], expect: [], questions: [] }; + for (const l of order) { + const h = programHeader(req.files[l] ?? ''); + header.call ??= h.call; header.errors ??= h.errors; header.stops ??= h.stops; + if (!header.input.length) header.input = h.input; + if (!header.expect.length) header.expect = h.expect; + header.questions.push(...h.questions); + } + const state: PlayState = { ...emptyState(), sources, lang, view: 'trace' }; + const call = req.call !== undefined ? req.call : header.call; + if (call) state.call = call; + const input = req.input ?? header.input; + if (input.length) state.input = input.join('\n'); + if (req.setup) state.setup = listingText(req.setup, 'asm'); + if (req.machine) state.machine = req.machine; + if (typeof req.t === 'number' && req.t >= 0) state.t = Math.floor(req.t); + if (req.title) state.title = req.title; + return { session: new Session(state), header, given, sources }; +} + +/* ------------------------------------------------------------------ */ +/* Small pieces */ +/* ------------------------------------------------------------------ */ + +/** Code, highlighted by the pane's own highlighter, one `.pplus-ln` per line (`data-line` is 1-based). */ +export function highlighted(text: string, lang: LangId, opts: { numbers?: boolean } = {}): HTMLElement { + const svc = SERVICES[lang]; + const rows = text.split('\n'); + const doc = svc.tokenizeLines ? svc.tokenizeLines(text) : null; + const pre = el('pre', { class: `pplus-code lang-${lang}` }); + rows.forEach((line, i) => { + const ln = el('span', { class: 'pplus-ln', 'data-line': String(i + 1) }); + if (opts.numbers) add(ln, el('span', { class: 'pplus-lno', 'aria-hidden': 'true' }, String(i + 1))); + const toks = doc ? doc[i] ?? [] : svc.tokenize ? svc.tokenize(line) : [{ text: line, cls: '' }]; + for (const t of toks) add(ln, t.cls ? el('span', { class: t.cls }, t.text) : t.text); + if (!line) add(ln, ' '); + add(pre, ln); + if (i < rows.length - 1) add(pre, '\n'); + }); + return pre; +} + +const chip = (lang: LangId) => el('span', { class: `pplus-chip pplus-chip-${lang}` }, LANG_NAMES[lang]); + +function head(...parts: Array): HTMLElement { + return el('div', { class: 'pplus-head' }, ...parts); +} + +/** A view built for a screen, made for a page: controls that need the app (buttons, inputs, menus) are taken out, and a link-styled line reference becomes plain text. */ +export function freeze(root: Element): void { + for (const s of [...root.querySelectorAll('select')]) { + const opt = (s as HTMLSelectElement).options[(s as HTMLSelectElement).selectedIndex] ?? (s as HTMLSelectElement).options[0]; + s.replaceWith(el('span', { class: 'pplus-picked' }, opt?.textContent ?? '')); + } + for (const b of [...root.querySelectorAll('button')]) { + if (b.classList.contains('linkish')) b.replaceWith(el('span', { class: b.className.replace('linkish', 'pplus-ref') }, b.textContent ?? '')); + else if (b.classList.contains('btn-option')) b.replaceWith(el('span', { class: 'pplus-option' }, b.textContent ?? '')); + else if (b.classList.contains('life-mark')) b.replaceWith(el('span', { class: b.className, title: b.getAttribute('title') ?? '', style: b.getAttribute('style') ?? '' })); + else b.remove(); + } + for (const i of [...root.querySelectorAll('input')]) i.remove(); + for (const l of [...root.querySelectorAll('.tool-label')]) l.remove(); + // what the app says about stepping, which a page does not do + for (const x of [...root.querySelectorAll('.fuzz-bar, .viz-step-note')]) x.remove(); + for (const x of [...root.querySelectorAll('[title=""]')]) x.removeAttribute('title'); +} + +const mdEscape = (s: string) => s.replace(/\|/g, '\\|').replace(/\n/g, ' '); +const fence = (text: string, cls = '') => { const ticks = /```/.test(text) ? '````' : '```'; return `${ticks}${cls}\n${text}\n${ticks}`; }; +function mdTable(headRow: string[], rows: string[][]): string { + return [`| ${headRow.map(mdEscape).join(' | ')} |`, `|${headRow.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map((c) => mdEscape(c || ' ')).join(' | ')} |`)].join('\n'); +} + +function result(view: StaticView, lang: LangId | null, node: HTMLElement, markdown: string, warnings: string[] = [], extra: Partial = {}): RenderResult { + node.classList.add('pplus-static', `pplus-v-${view}`); + node.setAttribute('data-pplus-view', view); + return { view, lang, node, html: node.outerHTML, markdown, warnings, ...extra }; +} + +/** A view of the app's, drawn into a fresh element and frozen for the page. */ +function appView(draw: (host: HTMLElement) => unknown, cls: string): HTMLElement { + const host = el('div', { class: `view ${cls}` }); + draw(host); + freeze(host); + return host; +} + +const noHooks = { reveal: () => { /* a page has no editor to move */ }, fix: () => { /* nor one to fix */ } }; + +/* ------------------------------------------------------------------ */ +/* The views */ +/* ------------------------------------------------------------------ */ + +export function renderStatic(req: RenderRequest): RenderResult { + if (!isStaticView(req.view)) throw new Error(`unknown view "${req.view}": the static views are ${STATIC_VIEWS.join(', ')}`); + const p = prepare(req); + if (!p.given.length) return result(req.view, null, el('div', {}, el('p', { class: 'pplus-note' }, 'No program: give a file (pseudo=, lingo=, matho=, speco=, mojo= or asm=).')), '*No program was given.*', ['no program file was given']); + switch (req.view) { + case 'run': return runOf(p, req); + case 'steps': return stepsOf(p, req); + case 'table': return tableOf(p); + case 'flow': case 'data': return graphOf(p, req.view); + case 'life': return lifeOf(p); + case 'proof': return proofOf(p); + case 'tests': return testsOf(p); + case 'check': return checkOf(p); + case 'translate': return translateOf(p, req); + case 'machine': return machineOf(p); + case 'hw': return hwOf(p, req); + } +} + +/* ---------- run ---------- */ + +function runOf(p: Prepared, req: RenderRequest): RenderResult { + const { session, header } = p; + const warnings: string[] = []; + const lang = session.traceLang(); + const trace = session.trace(); + const call = lang !== 'mojo' && lang !== 'asm' ? session.callText() : null; + const node = el('div', {}); + const compiled = lang === 'mojo' ? req.compiled ?? null : null; + let got: string[]; + let who: string; + if (compiled) { + got = compiled.stdout.replace(/\n$/, '').split('\n').filter((l, i, a) => !(a.length === 1 && l === '')); + who = `${compiled.version}, on the machine that rendered this page`; + } else { + got = trace ? [...trace.output] : []; + who = lang === 'mojo' ? `Programming+'s Mojo interpreter (modeled on Mojo ${MOJO_VERSION}; not the compiler)` : lang === 'asm' ? 'the model x86-64 machine' : `Programming+'s ${LANG_NAMES[lang]} interpreter`; + } + add(node, head(chip(lang), call ? el('code', { class: 'pplus-call' }, call) : null, el('span', { class: 'pplus-muted' }, trace ? `${trace.count} step${trace.count === 1 ? '' : 's'}` : ''), el('span', { class: 'pplus-spacer' }), el('span', { class: 'pplus-muted pplus-who' }, who))); + if (!trace && !compiled) { + const why = session.runError ?? (session.allDiagnostics().find((d) => d.severity === 'error')?.message ? `It does not run yet: ${session.allDiagnostics().find((d) => d.severity === 'error')!.message}` : 'There is nothing to run.'); + add(node, el('p', { class: 'pplus-err' }, why)); + warnings.push(`run: ${why}`); + return result('run', lang, node, `*${why}*`, warnings); + } + add(node, el('pre', { class: 'pplus-out' }, got.length ? got.join('\n') : el('span', { class: 'pplus-muted' }, '(printed nothing)'))); + let errText: string | null = null; + if (compiled && compiled.status !== 0) errText = `exited with status ${compiled.status}${compiled.stderr.trim() ? `: ${compiled.stderr.trim().split('\n').slice(0, 6).join('\n')}` : ''}`; + else if (!compiled && trace?.error) errText = `stopped${trace.error.line ? ` at line ${trace.error.line}` : ''}: ${trace.error.message}`; + if (errText) add(node, el('p', { class: header.stops ? 'pplus-note' : 'pplus-err' }, `The run ${errText}`)); + if (trace?.truncated) add(node, el('p', { class: 'pplus-note' }, 'The run was cut short after the step limit.')); + let expect: RenderResult['expect']; + if (header.expect.length) { + const ok = JSON.stringify(got) === JSON.stringify(header.expect); + expect = { want: header.expect, got, ok }; + add(node, el('div', { class: `pplus-expect ${ok ? 'is-ok' : 'is-bad'}` }, ok + ? `✓ prints the ${header.expect.length} line${header.expect.length === 1 ? '' : 's'} its EXPECT header says` + : el('span', {}, '✗ does not print what its EXPECT header says. Expected:', el('pre', { class: 'pplus-out' }, header.expect.join('\n'))))); + if (!ok) warnings.push(`run: printed ${JSON.stringify(got)}, its EXPECT lines say ${JSON.stringify(header.expect)}`); + } + if (compiled && trace && JSON.stringify(trace.output) !== JSON.stringify(got)) warnings.push('run: Programming+\'s Mojo interpreter printed something else than the compiler; the page shows the compiler\'s output'); + const md = [`${LANG_NAMES[lang]}${call ? ` \`${call}\`` : ''}, run by ${who}:`, '', fence(got.join('\n') || '(printed nothing)'), errText ? `\n*The run ${errText}*` : ''].join('\n'); + return result('run', lang, node, md, warnings, { expect }); +} + +/* ---------- steps ---------- */ + +/** The stepper's data, read by pplus.js: one row per step, and a value per followed variable after it. */ +export interface StepsData { + lang: LangId; + count: number; + t: number; + cols: Array<{ label: string; type: string }>; + /** l: the line the step ran; x: what it did; f: its kind (write, decision, loop, call, return, io, life, error); w: what it wrote; c: each column's value after it (null: not in scope); cw: the columns it wrote; o: what it printed. */ + rows: Array<{ l: number | null; x: string; f: string; w: string[]; c: Array; cw: number[]; o: string[] }>; + /** The values before the first step. */ + c0: Array; + error: string | null; + truncated: boolean; +} + +const hex = (v: unknown): string => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } }; + +function stepsData(session: Session, req: RenderRequest): StepsData | null { + const trace = session.trace(); + if (!trace) return null; + const max = Math.max(10, Math.min(req.max ?? 400, 5000)); + const n = Math.min(trace.count, max); + if (trace.lang === 'asm') { + const steps = trace.steps as any[]; + const states = trace.states as any[]; + const regs: string[] = []; + for (const s of steps.slice(0, n)) for (const r of s.diff?.regs ?? []) if (!regs.includes(r.name)) regs.push(r.name); + const at = (i: number) => regs.map((r) => (states[i]?.regs?.[r] !== undefined ? hex(states[i].regs[r]) : null)); + return { + lang: 'asm', count: n, t: Math.min(req.t ?? 0, n), cols: regs.map((r) => ({ label: r, type: 'register' })), c0: at(0), + rows: steps.slice(0, n).map((s, i) => { + const wrote = (s.diff?.regs ?? []).map((r: any) => r.name); + return { l: s.instr.lineNo + 1, x: s.instr.text, f: s.branch ? 'decision' : wrote.length ? 'write' : 'other', w: [...wrote, ...(s.diff?.mem?.length ? ['memory'] : [])], c: at(i + 1), cw: wrote.map((r: string) => regs.indexOf(r)), o: s.diff?.out ? [s.diff.out] : [] }; + }), + error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n, + }; + } + const cols = runColumns(trace); + let follow = defaultFollow(cols, 6); + if (req.follow?.length) { + const want = req.follow.map((f) => f.toLowerCase()); + const picked = cols.filter((c) => want.includes(c.name.toLowerCase()) || want.includes(c.key.toLowerCase())).map((c) => c.key); + if (picked.length) follow = picked; + } + const byKey = new Map(cols.map((c) => [c.key, c])); + const many = new Set(follow.map((k) => k.split('.')[0])).size > 1; + const rows: RunRow[] = runRows(trace, follow, 0, n); + // what the run prints after its last step (a call's result, "F returned 3") belongs to that step + const printed = rows.reduce((k, r) => k + r.printed.length, 0); + if (n === trace.count && rows.length && printed < trace.output.length) rows[rows.length - 1].printed.push(...trace.output.slice(printed)); + return { + lang: trace.lang, count: n, t: Math.min(req.t ?? 0, n), + cols: follow.map((k) => { const c = byKey.get(k)!; return { label: many ? `${c.fn}.${c.name}` : c.name, type: c.type }; }), + c0: valuesAt(trace, follow, 0).map((v) => v.text), + rows: rows.map((r) => ({ l: r.line, x: r.text, f: familyOf({ kind: r.kind, text: r.text, writes: r.writes }, trace.lang), w: r.writes, c: follow.map((k) => r.cells[k]?.text ?? null), cw: follow.map((k, i) => (r.cells[k]?.wrote ? i : -1)).filter((i) => i >= 0), o: r.printed })), + error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n, + }; +} + +/** The stepper's panels at position `t` (after t steps), drawn the way pplus.js redraws them; also the page without script. */ +export function stepsPanel(data: StepsData, t: number): { now: string; vals: Array; wrote: number[]; out: string[]; next: number | null; last: number | null } { + const last = t > 0 ? data.rows[t - 1] : null; + const next = t < data.count ? data.rows[t] : null; + const out = data.rows.slice(0, t).flatMap((r) => r.o); + const now = t === 0 ? (data.count ? 'Before the first step.' : 'The program takes no steps.') : `Step ${t}: ${last!.x}${last!.w.length ? ` — writes ${last!.w.join(', ')}` : ''}`; + return { now, vals: last ? last.c : data.c0, wrote: last ? last.cw : [], out, next: next?.l ?? null, last: last?.l ?? null }; +} + +function stepsOf(p: Prepared, req: RenderRequest): RenderResult { + const { session } = p; + const data = stepsData(session, req); + const lang = session.traceLang(); + if (!data) { + const why = session.runError ?? 'It does not run yet; the check view lists what the checker found.'; + return result('steps', lang, el('div', {}, el('p', { class: 'pplus-err' }, why)), `*${why}*`, [`steps: ${why}`]); + } + const source = session.source(data.lang); + const t = data.t; + const at = stepsPanel(data, t); + const code = highlighted(source, data.lang, { numbers: true }); + for (const ln of [...code.querySelectorAll('.pplus-ln')]) { + const n = Number(ln.getAttribute('data-line')); + if (n === at.next) ln.classList.add('is-next'); + if (n === at.last) ln.classList.add('is-last'); + } + const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label); + const vars = el('table', { class: 'pplus-vars' }); + data.cols.forEach((c, i) => add(vars, el('tr', { class: at.wrote.includes(i) ? 'is-wrote' : '' }, el('th', { title: c.type }, c.label), el('td', { 'data-col': String(i) }, at.vals[i] ?? '—')))); + const json = JSON.stringify(data).replace(/ c.label)], data.rows.slice(0, 60).map((r, i) => [String(i + 1), String(r.l ?? ''), r.x, ...r.c.map((v) => v ?? '')]))].join('\n') + (data.count > 60 ? `\n\n*…and ${data.count - 60} more steps in the HTML version.*` : ''); + return result('steps', data.lang, node, md); +} + +/* ---------- table, flow, data, life ---------- */ + +function tableOf(p: Prepared): RenderResult { + const { session } = p; + const node = appView((h) => traceTableView(session, h), 'view-table'); + const trace = session.trace(); + let md = '*The table of values needs a run that works.*'; + if (trace && trace.lang !== 'asm') { + const follow = defaultFollow(runColumns(trace), 8); + const rows = runRows(trace, follow, 0, trace.count, { onlyWrites: true }).slice(0, 80); + md = mdTable(['step', 'line', ...follow.map((k) => k.slice(k.indexOf('.') + 1)), 'printed'], rows.map((r) => [String(r.step + 1), String(r.line ?? ''), ...follow.map((k) => (r.cells[k]?.wrote ? r.cells[k].text ?? '' : '')), r.printed.join(' ⏎ ')])); + } + return result('table', trace?.lang ?? session.traceLang(), node, md); +} + +function graphOf(p: Prepared, view: 'flow' | 'data'): RenderResult { + const { session } = p; + // the flowchart and the data flow draw the pseudo (or the Mojo); a lingo or matho program is drawn as its pseudo + if (session.state.lang !== 'mojo') session.state.lang = 'pseudo'; + const node = appView((h) => (view === 'flow' ? flowView(session, h) : dataFlowView(session, h)), view === 'flow' ? 'view-flow' : 'view-data'); + const what = view === 'flow' ? 'flowchart' : 'data-flow graph'; + return result(view, session.state.lang, node, `*The ${what} of this procedure is drawn in the HTML version of this page.*`); +} + +function lifeOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'mojo'; + const node = appView((h) => lifetimesView(session, h), 'view-life'); + const warnings = p.given.includes('mojo') ? [] : ['life: lifetimes are drawn for a Mojo file (mojo=)']; + return result('life', 'mojo', node, '*Each value\'s lifetime is drawn in the HTML version of this page.*', warnings); +} + +/* ---------- proof, tests, check ---------- */ + +function proofOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'pseudo'; + const node = appView((h) => proofView(session, h, noHooks), 'view-proof'); + const pr = session.proof(); + const md = pr ? [`**${pr.report.counts.proved} proved, ${pr.report.counts.broken} broken, ${pr.report.counts.open} open.**`, '', ...pr.report.units.flatMap((u) => u.obligations.map((o) => `- ${o.status}: ${o.label} (line ${(o as any).specoLine ?? (o as any).pseudoLine ?? o.line})`))].join('\n') : '*The proof needs pseudocode that parses.*'; + return result('proof', 'pseudo', node, md, pr && pr.report.counts.broken ? [`proof: ${pr.report.counts.broken} claim(s) broken`] : []); +} + +function testsOf(p: Prepared): RenderResult { + const { session } = p; + if (session.state.lang !== 'mojo') session.state.lang = 'pseudo'; + const node = appView((h) => testsView(session, h, noHooks), 'view-tests'); + const reps = session.tests(); + const md = reps.length ? reps.map((r) => `- \`${r.name}\`: ${r.failures.length ? `${r.failures.length} way(s) to fail, e.g. \`${r.failures[0].call}\`: ${r.failures[0].message}` : 'no failures'} on ${r.checked} generated inputs`).join('\n') : '*Nothing to test: generated-input testing needs a routine.*'; + return result('tests', session.state.lang, node, md); +} + +function checkOf(p: Prepared): RenderResult { + const { session, given } = p; + // only the files the page gave: a notation the hub filled in is not the author's to answer for + const view = Object.create(session) as Session; + (view as any).allDiagnostics = () => given.flatMap((l) => session.diagnostics(l)); + const node = appView((h) => problemsView(view, h, noHooks), 'view-problems'); + const diags = given.flatMap((l) => session.diagnostics(l)); + const md = diags.length ? diags.map((d) => `- **${d.severity}**, ${LANG_NAMES[d.lang]} line ${d.line}: ${d.message}`).join('\n') : '*The checker has nothing to report.*'; + return result('check', given[0] ?? null, node, md); +} + +/* ---------- translate ---------- */ + +const LABEL: Record = { lingo: 'lingo', matho: 'matho', pseudo: 'pseudo', speco: 'speco', mojo: 'Mojo', asm: 'x86-64' }; + +function translateOf(p: Prepared, req: RenderRequest): RenderResult { + const { sources, given, header } = p; + const warnings: string[] = []; + const call = req.call !== undefined ? req.call : header.call ?? null; + const linkedGiven = given.filter((l) => (LINKED as readonly string[]).includes(l)); + const panes: TranslatedPane[] = []; + let hub: { sources: Partial>; stale: Partial>; mojo: string; lead: LangId } | null = null; + if (linkedGiven.length) { + // the first file the page gave leads, as if typed into its pane; the notations it was not given follow from it + // (a file the page gives is always shown as written) + const lead = linkedGiven.includes(req.lang as any) ? req.lang! : linkedGiven[0]; + const r = new SyncHub({ lingo: '', matho: '', pseudo: '', speco: '' }, undefined, { call }).edit(lead as any, sources[lead] ?? ''); + hub = { sources: r.sources, stale: r.stale, mojo: r.mojo.source, lead }; + } + const want = req.to?.length ? req.to : [...LINKED, 'mojo'] as LangId[]; + for (const l of want) { + if (given.includes(l)) { panes.push({ lang: l, label: LABEL[l], text: sources[l] ?? '', authored: true, generated: false }); continue; } + if (l === 'mojo') { + const text = hub?.mojo ?? (hub?.sources.pseudo ? mojoFromPseudo(hub.sources.pseudo, call).source : ''); + if (text.trim()) panes.push({ lang: 'mojo', label: 'Mojo', text, authored: false, generated: true, from: 'pseudo', note: 'Generated from the pseudo: a literal translation, not reviewed for Mojo best practices.' }); + continue; + } + if (!hub || !(LINKED as readonly string[]).includes(l)) continue; + const text = hub.sources[l] ?? ''; + const stale = hub.stale[l]; + if (stale) { panes.push({ lang: l, label: LABEL[l], text: '', authored: false, generated: false, note: stale }); continue; } + if (text.trim()) panes.push({ lang: l, label: LABEL[l], text, authored: false, generated: true, from: hub.lead }); + } + // the notations the page gave first, as written; then what was made from them + panes.sort((a, b) => Number(b.authored) - Number(a.authored)); + if (!panes.some((x) => x.text.trim())) warnings.push('translate: nothing to show; give a lingo, matho, pseudo or speco file'); + const node = el('div', { class: 'pplus-translate-grid' }); + for (const pane of panes) { + add(node, el('div', { class: `pplus-pane pplus-pane-${pane.lang}` }, + el('div', { class: 'pplus-pane-head' }, chip(pane.lang), pane.authored ? el('span', { class: 'pplus-muted' }, 'as written') : pane.generated ? el('span', { class: 'pplus-tag-generated' }, 'generated') : null), + pane.text ? highlighted(pane.text, pane.lang) : null, + pane.note ? el('p', { class: pane.text ? 'pplus-muted pplus-small' : 'pplus-note' }, pane.text ? pane.note : `Cannot be written in ${pane.label}: ${pane.note}`) : null)); + } + const md = panes.map((x) => `**${x.label}**${x.generated ? ' (generated)' : ''}\n\n${x.text ? fence(x.text, x.lang === 'matho' ? 'latex' : x.lang) : `*${x.note}*`}`).join('\n\n'); + return result('translate', panes[0]?.lang ?? null, node, md, warnings, { panes }); +} + +/* ---------- machine ---------- */ + +function machineOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'asm'; + const node = appView((h) => machineView(session, h), 'view-asm'); + const rows = [...node.querySelectorAll('.perf-tbl tr')].map((tr) => [...tr.children].map((c) => (c.textContent ?? '').trim())); + const md = rows.length ? mdTable(['', 'value'], rows) : '*The machine view needs an x86-64 file that assembles (asm=).*'; + return result('machine', 'asm', node, md, p.given.includes('asm') ? [] : ['machine: the machine view needs an x86-64 file (asm=)']); +} + +/* ---------- hw: the machine board ---------- */ + +function hwOf(p: Prepared, req: RenderRequest): RenderResult { + const b = machineBoard(p.session, { views: req.hw, preset: req.preset, t: req.t, max: req.max, listing: req.listing, stepper: req.stepper }); + const r = result('hw', 'asm', b.node, b.markdown, b.warnings); + return { ...r, html: spliceFrames(r.html, b.node) }; +} diff --git a/src/quarto/shortcodes.ts b/src/quarto/shortcodes.ts new file mode 100644 index 0000000..09fda8b --- /dev/null +++ b/src/quarto/shortcodes.ts @@ -0,0 +1,139 @@ +/** + * The shortcodes of the Quarto extension (quarto/_extensions/pplus/pplus.lua), as data: what each is called, what + * it shows, and the options it reads. The app's "With Quarto" gallery (src/ui/quarto.ts) is written from this, + * scripts/check-pages.mjs reads it to know a shortcode when it sees one, and tests/quarto.test.mjs holds it to the + * names pplus.lua returns. DOM-free. + */ +import type { LangId } from '../core/types.js'; +import type { StaticView, RenderRequest } from './render.js'; +import { listingText } from './program.js'; +import { emptyState, type PlayState } from '../core/state.js'; +import { boardView } from '../core/hardware.js'; +import { HW_NAMES } from './machine.js'; + +export type ShortcodeKind = 'rendered' | 'machine' | 'live' | 'text'; + +export interface ShortcodeDef { + name: string; + kind: ShortcodeKind; + /** rendered: the view render.ts draws; live: the embed view (or `any`, chosen by view=). */ + view?: StaticView | 'playground' | 'any'; + /** machine: the board view it shows (its pplus-hw-), or none for the whole board. */ + hw?: string; + title: string; + summary: string; + /** The options it reads besides the shared ones (SHARED_OPTIONS). */ + options: string[]; +} + +/** Read by every shortcode that names program files. */ +export const SHARED_OPTIONS = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm', 'setup', 'lang', 'call', 'input', 'machine', 't', 'title', 'caption', 'collapse', 'area'] as const; + +/** Read by every rendered view (the machine's too). */ +export const RENDERED_OPTIONS = ['code', 'numbers', 'live', 'height', 'column'] as const; + +export const SHORTCODES: ShortcodeDef[] = [ + { name: 'pplus-run', kind: 'rendered', view: 'run', title: 'Run it', summary: 'What the program prints and returns, checked against its EXPECT lines. A Mojo file runs on the real compiler when the machine that renders has one.', options: ['compiler'] }, + { name: 'pplus-steps', kind: 'rendered', view: 'steps', title: 'Step through it', summary: 'The listing beside a stepper: every step, the line it ran, what it wrote, the values after it, and what was printed so far. The run is in the page; a small script moves through it.', options: ['follow', 'max'] }, + { name: 'pplus-table', kind: 'rendered', view: 'table', title: 'Table of values', summary: 'The table you would draw by hand: a column per step that changed something, a row per name.', options: [] }, + { name: 'pplus-flow', kind: 'rendered', view: 'flow', title: 'Flowchart', summary: 'The routine as a flowchart, laid out from its structure; each box shaded by how often its line ran, each arrow labeled with how often it was taken.', options: [] }, + { name: 'pplus-dataflow', kind: 'rendered', view: 'data', title: 'Data flow', summary: 'Which names feed which: the parameters on the left, what leaves on the right, an arrow for each assignment.', options: [] }, + { name: 'pplus-lifetimes', kind: 'rendered', view: 'life', title: 'Lifetimes', summary: 'Each Mojo value from the step it is made to the step it is destroyed or moved out of, with every copy and move on the way.', options: [] }, + { name: 'pplus-proof', kind: 'rendered', view: 'proof', title: 'Proof', summary: 'Every claim the specification makes (ENSURE, INVARIANT, a .speco file woven in): proved, broken by a run, or open.', options: [] }, + { name: 'pplus-tests', kind: 'rendered', view: 'tests', title: 'Generated tests', summary: 'The fuzzer\'s report for each routine: what each input must do, how the inputs were made, every failure shrunk to the smallest input, every case run.', options: [] }, + { name: 'pplus-check', kind: 'rendered', view: 'check', title: 'The checker', summary: 'What Programming+ finds in each file before anything runs, on the file\'s own lines, with a link to the guide.', options: [] }, + { name: 'pplus-translate', kind: 'rendered', view: 'translate', title: 'Every notation', summary: 'One file in, the procedure in every notation out: lingo, matho, pseudo, speco, and Mojo generated from the pseudo (and labeled so). As tabs, columns, or the app\'s panes.', options: ['to', 'layout'] }, + { name: 'pplus-machine', kind: 'rendered', view: 'machine', title: 'The machine', summary: 'An x86-64 run on the model machine: instructions, cycles on an in-order and an out-of-order core, cache misses, branches, and what bounds it.', options: [] }, + { name: 'pplus-view', kind: 'rendered', view: undefined, title: 'Any view by name', summary: 'Any of the rendered views, chosen with view= (run, steps, table, flow, data, life, proof, tests, check, translate, machine).', options: ['view'] }, + { name: 'pplus-hw', kind: 'machine', view: 'hw', title: 'The machine board', summary: 'The Hardware area\'s board over an x86-64 run: the listing beside the cards of a preset (registers and memory, caches, pipeline, the whole chip) or the views you name, every one drawn at every step, with a stepper.', options: ['preset', 'views', 'listing', 'stepper', 'max'] }, + ...Object.entries(HW_NAMES).map(([name, id]): ShortcodeDef => { + const v = boardView(id)!; + return { name: `pplus-hw-${name}`, kind: 'machine', view: 'hw', hw: name, title: v.label, summary: v.blurb, options: ['listing', 'stepper', 'max'] }; + }), + { name: 'pplus-playground', kind: 'live', view: 'playground', title: 'The whole playground', summary: 'The app in the page: every pane, the stepper, every inspect tab and the dock. The reader\'s edits are kept in their browser; Reset brings the page\'s version back.', options: ['panel', 'build', 'dock', 'docktab', 'editor', 'side', 'dockheight', 'theme', 'ro', 'height', 'problem', 'state'] }, + { name: 'pplus-embed', kind: 'live', view: 'any', title: 'One live view', summary: 'One view of the app with the code it reads: trace, table, flow, data, life, problems, proof, tests, compiler, asm, or one pane.', options: ['view', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] }, + { name: 'pplus', kind: 'live', view: 'any', title: 'The original shortcode', summary: 'A live embed, a listing, or both (show=). Pages written for it keep working.', options: ['view', 'show', 'mode', 'text', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] }, + { name: 'pplus-listing', kind: 'text', title: 'Listings', summary: 'The files as highlighted code blocks, without their header lines; a .tex file typeset as equations.', options: ['numbers', 'math', 'link', 'text'] }, + { name: 'pplus-tabs', kind: 'text', title: 'Tabs', summary: 'The files as a tabset, one tab per notation.', options: ['numbers', 'math'] }, + { name: 'pplus-link', kind: 'text', title: 'A link', summary: 'A link that opens the program in the app.', options: ['view', 'text'] }, +]; + +export const SHORTCODE_NAMES: readonly string[] = SHORTCODES.map((s) => s.name); + +export const OPTION_DOCS: Record = { + lingo: 'a lingo file beside the page', matho: 'a LaTeX (.tex) file of equations', pseudo: 'a pseudo file', speco: 'a speco file (the specification)', + mojo: 'a Mojo file', asm: 'an x86-64 listing', setup: 'the x86-64 setup block: registers and memory', + lang: 'the pane that runs (default: the first of lingo, matho, pseudo, mojo, asm given)', + call: 'the call to run (default: the file\'s // CALL: line)', input: 'lines INPUT reads, separated by |', machine: 'the x86-64 machine model preset', + t: 'the step the stepper starts on', title: 'a title over the view', caption: 'a sentence under it', collapse: '1 folds it into a block the reader opens', + area: 'bridge, dev or hw: where "open in the playground" goes', + code: '1 prints the program above the view', numbers: '1 numbers the listing\'s lines', live: 'click adds "make it live", which puts the live view in its place', + height: 'the live frame\'s height in px (auto: fits its content)', compiler: 'auto (the real mojo when on the PATH), on, or off', + follow: 'the variables to show, comma-separated', max: 'the most steps kept (default 400; a longer machine run is sampled)', to: 'the notations to show, comma-separated', + layout: 'tabs (default), columns, or grid', + preset: 'the board\'s arrangement: regs (default), caches, pipeline or chip', views: 'the machine views to show, comma-separated (registers, memory, cache, pipeline, chip...)', + listing: '0 leaves out the x86-64 listing', column: 'Quarto\'s column for the figure: body, page (pplus-hw\'s default), screen...', stepper: '0 draws only step t, without a stepper', view: 'which view', panel: 'the tab the playground opens on', build: 'O0 (as written) or default (as mojo build does)', + dock: 'open or closed', docktab: 'the dock\'s tab', editor: 'the editor column\'s share of the width', side: 'the variables panel\'s share', dockheight: 'the editors\' share of the height', + theme: 'light or dark (default: follow the page)', ro: '1: read-only, nothing saved', showcall: '0 hides the run box', split: 'the code\'s share of the frame', + problem: 'a catalog problem instead of files', state: 'a state from the playground\'s Share dialog', show: 'embed, listing or both', mode: 'link: only a link', text: 'the link\'s text', math: '0 prints a .tex file as code', link: '1 adds a link to the app', +}; + +/** The shortcode as a page writes it. */ +export function shortcodeText(name: string, attrs: Record): string { + const parts = Object.entries(attrs).map(([k, v]) => `${k}="${v.replace(/"/g, '"')}"`); + return `{{< ${name}${parts.length ? ' ' + parts.join(' ') : ''} >}}`; +} + +const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm']; +const list = (s: string | undefined) => (s ? s.split(/[\s,]+/).filter(Boolean) : undefined); + +/** + * What a rendered shortcode asks render.ts for, given its options and the files beside the page (by name): the + * same request pplus.lua builds, for the gallery to draw what a page would get. + */ +export function requestFor(view: StaticView, attrs: Record, files: Record): RenderRequest { + const req: RenderRequest = { view, files: {} }; + for (const p of PANES) if (attrs[p] && files[attrs[p]] !== undefined) req.files[p] = files[attrs[p]]; + if (attrs.lang) req.lang = attrs.lang as LangId; + if (attrs.call) req.call = attrs.call; + if (attrs.input) req.input = attrs.input.split('|'); + if (attrs.setup && files[attrs.setup] !== undefined) req.setup = files[attrs.setup]; + if (attrs.machine) req.machine = attrs.machine; + if (attrs.t && Number.isFinite(Number(attrs.t))) req.t = Number(attrs.t); + if (attrs.title) req.title = attrs.title; + if (attrs.max && Number.isFinite(Number(attrs.max))) req.max = Number(attrs.max); + if (attrs.views) req.hw = list(attrs.views); + if (attrs.preset) req.preset = attrs.preset; + if (attrs.listing === '0') req.listing = false; + if (attrs.stepper === '0') req.stepper = false; + req.follow = list(attrs.follow); + req.to = list(attrs.to) as LangId[] | undefined; + return req; +} + +/** The state a live shortcode puts in its iframe's URL: the same one pplus.lua writes. */ +export function liveStateFor(attrs: Record, files: Record): PlayState { + const s = emptyState(); + let first: LangId | null = null; + let call: string | undefined; let input: string[] | undefined; + for (const p of PANES) { + const text = attrs[p] ? files[attrs[p]] : undefined; + if (text === undefined) continue; + s.sources[p] = listingText(text, p); + first ??= p; + for (const line of text.split('\n')) { + const m = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT):\s?(.*)$/.exec(line); + if (m?.[1] === 'CALL') call ??= m[2].trim(); + if (m?.[1] === 'INPUT') (input ??= []).push(m[2]); + } + } + s.lang = (attrs.lang as LangId) || first || 'pseudo'; + s.view = 'trace'; + if (attrs.setup && files[attrs.setup] !== undefined) s.setup = files[attrs.setup]; + const c = attrs.call ?? call; + if (c) s.call = c; + if (attrs.input) s.input = attrs.input.split('|').join('\n'); else if (input) s.input = input.join('\n'); + if (attrs.title) s.title = attrs.title; + if (attrs.t) s.t = Number(attrs.t); + return s; +} diff --git a/src/services/asm.ts b/src/services/asm.ts new file mode 100644 index 0000000..69996d1 --- /dev/null +++ b/src/services/asm.ts @@ -0,0 +1,152 @@ +/** + * x86-64: wraps the course's asm86 simulator. `parse` assembles, `run` + * executes with a setup block (registers, memory, stdin) in the sandbox's + * syntax, and the trace carries per-instruction diffs plus the hardware + * model (caches, pipeline, out-of-order core) lazily through `raw.hardware`. + */ +import { assemble, run as runAsm, AsmError } from '../engines/asm86/interp.js'; +import { hardwareFor } from '../engines/asm86/machine.js'; +import { MACHINE_PRESETS, machineName, machineSpec, parseMachine } from '../core/hardware.js'; +import type { Diagnostic, LanguageService, Parsed, RunOptions, Trace } from '../core/types.js'; + +export type AsmProgram = any; +export type AsmState = any; +export type AsmStep = any; + +export interface AsmSetup { registers: Record; memory: any[]; flags: Record; stdin: string } + +function num(tok: string): bigint { + const t = tok.trim(); + if (/^'.'$/.test(t)) return BigInt(t.charCodeAt(1)); + if (/^-?(0x[0-9a-f_]+|0b[01_]+|\d[\d_]*)$/i.test(t)) { + const neg = t.startsWith('-'); + const v = BigInt(t.replace(/^-/, '').replace(/_/g, '')); + return neg ? -v : v; + } + throw new Error(`"${t}" is not a number`); +} + +function unquote(s: string): string { + const m = /^"((?:[^"\\]|\\.)*)"$/.exec(s.trim()); + if (!m) throw new Error(`expected text in double quotes, found ${s.trim()}`); + return m[1].replace(/\\n/g, '\n').replace(/\\t/g, '\t').replace(/\\"/g, '"').replace(/\\\\/g, '\\'); +} + +/** The sandbox's setup language: `rdi = 0x1000`, `memory 0x1000 "GATTACA"`, `stdin "..."`, `flags CF ZF`. */ +export function parseSetup(text: string): AsmSetup { + const out: AsmSetup = { registers: {}, memory: [], flags: {}, stdin: '' }; + String(text || '').split('\n').forEach((raw, i) => { + const line = raw.replace(/(^|\s)(#|;|\/\/).*$/, '').trim(); + if (!line) return; + try { + let m: RegExpExecArray | null; + if ((m = /^([a-z][a-z0-9]*)\s*=\s*(.+)$/i.exec(line))) { + out.registers[m[1].toLowerCase()] = num(m[2]); + } else if ((m = /^memory\s+(\S+)\s+(.*)$/i.exec(line))) { + const addr = Number(num(m[1])); + const rest = m[2].trim(); + const name = `m${out.memory.length}_${addr.toString(16)}`; + const label = `0x${addr.toString(16)}`; + let r: RegExpExecArray | null; + if (rest.startsWith('"')) out.memory.push({ name, label, addr, text: unquote(rest) }); + else if ((r = /^bytes\s+(.*)$/i.exec(rest))) out.memory.push({ name, label, addr, bytes: r[1].trim().split(/[\s,]+/).map((b) => Number(BigInt.asUintN(8, num(b)))) }); + else if ((r = /^qwords\s+(.*)$/i.exec(rest))) { + const bytes: number[] = []; + for (const q of r[1].trim().split(/[\s,]+/)) { let v = BigInt.asUintN(64, num(q)); for (let k = 0; k < 8; k++) { bytes.push(Number(v & 0xffn)); v >>= 8n; } } + out.memory.push({ name, label, addr, bytes }); + } else if ((r = /^zero\s+(\S+)$/i.exec(rest))) out.memory.push({ name, label, addr, size: Number(num(r[1])) }); + else throw new Error('after the address, write "text", bytes ..., qwords ..., or zero n'); + } else if ((m = /^stdin\s+(.*)$/i.exec(line))) { + out.stdin = unquote(m[1]); + } else if ((m = /^flags\s+(.*)$/i.exec(line))) { + for (const f of m[1].split(/[\s,]+/)) { + if (!['ZF', 'SF', 'CF', 'OF', 'PF'].includes(f.toUpperCase())) throw new Error(`no flag named ${f}`); + out.flags[f.toUpperCase()] = true; + } + } else throw new Error('not a setup line (register = value, memory addr ..., stdin "...", flags ...)'); + } catch (e: any) { + throw new Error(`setup line ${i + 1}: ${e.message}`); + } + }); + return out; +} + +export function parseAsm(source: string): Parsed { + try { + const program = assemble(source); + const diagnostics: Diagnostic[] = []; + for (const l of program.lines || []) { + if (l.error) diagnostics.push({ lang: 'asm', severity: 'error', id: 'assemble', line: (l.lineNo ?? 0) + 1, col: 1, message: String(l.error) }); + } + return { program, diagnostics, ok: diagnostics.length === 0 }; + } catch (e: any) { + const line = e?.line != null ? e.line + 1 : e?.lineNo != null ? e.lineNo + 1 : 1; + const message = String(e.message).replace(/^line \d+:\s*/, ''); + return { program: null, diagnostics: [{ lang: 'asm', severity: 'error', id: e instanceof AsmError ? e.kind || 'assemble' : 'assemble', line, col: 1, message }], ok: false }; + } +} + +/** The machine presets; a state's `machine` may add `+paging` to one (core/hardware.ts). */ +export const MACHINES = MACHINE_PRESETS; + +export function runAsmProgram(parsed: Parsed, options: RunOptions): Trace { + if (!parsed.program || !parsed.ok) throw new Error('The listing has a line the assembler refused; fix it before running.'); + const setup = parseSetup(options.setup || ''); + const machine = machineName(parseMachine(options.machine)); + // the hardware model reads the machine from the trace's spec, so the board's views and the counters agree on it + const spec = { program: parsed.program, registers: setup.registers, memory: setup.memory, flags: setup.flags, stdin: setup.stdin, maxSteps: options.maxSteps ?? 20000, machine: machineSpec(machine) }; + const tr: any = runAsm(spec); + const hits = new Map(); + for (const instr of parsed.program.instrs) { const n = tr.hits[instr.index] || 0; if (n) hits.set(instr.lineNo + 1, n); } + const err = tr.stats.error || tr.stats.fault; + const output: string[] = []; + if (tr.stats.output) output.push(tr.stats.output); + output.push(`rax = ${tr.stats.result} (0x${BigInt.asUintN(64, tr.stats.result).toString(16)})`); + if (tr.stats.exitCode != null) output.push(`exit code ${tr.stats.exitCode}`); + return { + lang: 'asm', + steps: tr.steps, + states: tr.states, + count: tr.count, + output, + error: err ? { kind: err.kind || 'fault', message: err.message || String(err), line: err.lineNo != null ? err.lineNo + 1 : null } : null, + truncated: !!tr.stats.truncated, + hits, + raw: { trace: tr, machine, hardware: () => hardwareFor(tr) }, + }; +} + +const MNEMONIC = /^(mov|movabs|movzx|movsx|movsxd|lea|add|sub|adc|sbb|inc|dec|imul|mul|div|idiv|cqo|cdq|cdqe|and|or|xor|shl|sal|shr|sar|rol|ror|cmp|test|bt|stc|clc|cmc|push|pop|leave|jmp|j[a-z]{1,3}|cmov[a-z]{1,3}|set[a-z]{1,3}|call|ret|syscall|neg|not|xchg|popcnt|tzcnt|lzcnt|bsf|bsr|nop|movdq[ua]|movd|movq|pcmpeqb|pmovmskb|pand|por|pxor|psubb|paddb)$/i; +const REG = /^(r(ax|bx|cx|dx|si|di|bp|sp|8|9|1[0-5])|e(ax|bx|cx|dx|si|di|bp|sp)|r(8|9|1[0-5])[dwb]|[abcd][xlh]|[sd]il?|[bs]pl?|xmm\d{1,2}|rip)$/i; + +export function tokenizeAsm(line: string): Array<{ text: string; cls: string }> { + const out: Array<{ text: string; cls: string }> = []; + const re = /([;#].*$|\/\/.*$)|('.'|"(?:[^"\\]|\\.)*")|(\b0x[0-9a-f]+\b|\b\d+\b)|(\.?[A-Za-z_$][\w$.]*:)|(\.?[A-Za-z_$][\w$.]*)|(\s+)|(.)/g; + let m: RegExpExecArray | null; + let first = true; + while ((m = re.exec(line))) { + const [text, c, s, n, lbl, w] = m; + let cls = ''; + if (c) cls = 'tok-comment'; + else if (s) cls = 'tok-string'; + else if (n) cls = 'tok-number'; + else if (lbl) cls = 'tok-label'; + else if (w) { + if (first && MNEMONIC.test(w)) cls = 'tok-keyword'; + else if (REG.test(w)) cls = 'tok-builtin'; + else if (/^(byte|word|dword|qword|xmmword|ptr)$/i.test(w)) cls = 'tok-op'; + else cls = 'tok-name'; + first = false; + } + out.push({ text, cls }); + } + return out; +} + +export const asmService: LanguageService = { + id: 'asm', + name: 'x86-64', + parse: parseAsm, + run: runAsmProgram, + tokenize: tokenizeAsm, +}; diff --git a/src/services/godbolt.ts b/src/services/godbolt.ts new file mode 100644 index 0000000..2f1fce2 --- /dev/null +++ b/src/services/godbolt.ts @@ -0,0 +1,243 @@ +/** + * Compiler Explorer (godbolt.org): the real Mojo compiler behind the Compile + * button. Programming+ ships no compiler and never says a program compiles + * without asking one. + * + * One request compiles, returns the listing, and runs the program (what the + * corpus calls mode "both"; probes/godbolt-asm-and-run confirmed one request + * returns both). The body is the one scripts/mojo/mojocorpus/godbolt.py + * sends, and tests/mojo.test.mjs compares the two, so the button and the + * corpus can never ask different questions. + * + * What the probes taught us about Mojo 1.1.0 on godbolt, which shapes this file: + * - godbolt runs `mojo build --emit=asm -o /app/output.s /app/example.mojo` + * and passes no Intel-syntax flag, so the listing is AT&T (see src/mojo/att.ts); + * - errors arrive as `:LINE:COL: error: ...`, then the source line, a + * caret line, and sometimes a fix-it line (the replacement or insertion); + * - the user's own functions are labelled "example::name(args)", and only an + * unoptimised build (-O0) keeps them out of line; + * - with --debug-level=line-tables (probes/godbolt-line-tables*), instructions + * carry source lines, at no cost in compile time; but instructions inlined + * from the standard library carry lines of the library's own files (print's + * default arguments point at line 218 of io.mojo), so a line is the + * program's only when godbolt says it comes from the program's file. + */ +import type { Diagnostic, QuickFix } from '../core/types.js'; +import { GODBOLT_BASE, GODBOLT_COMPILER, MOJO_VERSION } from '../mojo/generated/pin.js'; + +/** How the program is built: as written (every function kept, -O0) or as `mojo build` does by default. */ +export type BuildLevel = 'O0' | 'default'; +/** Line tables on both: they map instructions to lines and cost nothing in compile time (probes/godbolt-line-tables*). */ +export const BUILD_ARGS: Record = { O0: '-O0 --debug-level=line-tables', default: '--debug-level=line-tables' }; + +const ASM_FILTERS = { binary: false, execute: false, intel: true, demangle: true, labels: true, libraryCode: false, directives: true, commentOnly: true, trim: true }; + +/** The request body, field for field what the Python harness sends in mode "both". */ +export function mojoRequestBody(source: string, stdin = '', args = ''): Record { + return { + source, + options: { + userArguments: args, + executeParameters: { args: [], stdin }, + compilerOptions: { executorRequest: false, skipAsm: false }, + filters: { ...ASM_FILTERS, execute: true }, + tools: [], + libraries: [], + }, + lang: 'mojo', + allowStoreCodeDebug: false, + }; +} + +export function mojoRequestUrl(base = GODBOLT_BASE, compiler = GODBOLT_COMPILER): string { + return `${base.replace(/\/+$/, '')}/api/compiler/${encodeURIComponent(compiler)}/compile`; +} + +/** + * One listing line. `line` is a line of the program, when the instruction came + * from it; `from` says where an instruction inlined from elsewhere (the standard + * library) came from, so it is never mistaken for a line of the program. + */ +export interface AsmLine { text: string; line: number | null; from?: { file: string; line: number } } + +/** + * Which file a source line belongs to. Accepts each way godbolt can mark the + * program's own file: `mainsource: true`, no file named, or the input file's + * name (`inputFilename`, example.mojo). + */ +export function sourceOf(src: any, inputFile = 'example.mojo'): Pick { + if (!src || typeof src.line !== 'number') return { line: null }; + const file: string | null = src.file ? String(src.file) : null; + const base = file ? file.split('/').pop()! : null; + const main = src.mainsource === true || (src.mainsource !== false && (!file || base === inputFile)); + return main ? { line: src.line } : { line: null, from: { file: base ?? '?', line: src.line } }; +} + +/** One answer, in the shape the Python harness normalises to. */ +export interface Answer { + compiled: boolean; + buildStderr: string; + executed: boolean; + exitCode: number | null; + stdout: string; + stderr: string; + timedOut: boolean; + asm: AsmLine[]; +} + +const joinLines = (xs: unknown): string => (Array.isArray(xs) ? xs.map((l: any) => (typeof l === 'string' ? l : l?.text ?? '')).join('\n') : ''); + +export function normaliseAnswer(data: any): Answer { + const exe = data?.execResult ?? {}; + return { + compiled: data?.code === 0, + buildStderr: joinLines(data?.stderr), + executed: !!exe.didExecute, + exitCode: typeof exe.code === 'number' ? exe.code : null, + stdout: joinLines(exe.stdout), + stderr: joinLines(exe.stderr), + timedOut: !!exe.timedOut, + asm: Array.isArray(data?.asm) ? data.asm.filter((a: any) => a && typeof a === 'object').map((a: any) => ({ text: String(a.text ?? ''), ...sourceOf(a.source, data?.inputFilename || 'example.mojo') })) : [], + }; +} + +/* --------------------------------------------------------------------------- + * Compiler diagnostics + * ------------------------------------------------------------------------- */ + +const HEAD = /^:(\d+):(\d+): (error|warning|note|remark): (.*)$/; +const ORIGIN = `the Mojo ${MOJO_VERSION} compiler`; + +interface RawDiag { severity: string; line: number; col: number; message: string; excerpt: string; caret: string; fixit: string | null } + +function readRaw(stderr: string): RawDiag[] { + const lines = stderr.split('\n'); + const out: RawDiag[] = []; + for (let i = 0; i < lines.length; i++) { + const m = HEAD.exec(lines[i]); + if (!m) continue; + const d: RawDiag = { severity: m[3], line: Number(m[1]), col: Number(m[2]), message: m[4], excerpt: '', caret: '', fixit: null }; + const body: string[] = []; + for (let j = i + 1; j < lines.length && !HEAD.test(lines[j]) && !/^\S.*: (error|warning): /.test(lines[j]); j++) body.push(lines[j]); + d.excerpt = body[0] ?? ''; + d.caret = body[1] ?? ''; + if (body[2] !== undefined && body[2].trim() && /^[ ~^]*$/.test(d.caret)) d.fixit = body[2]; + out.push(d); + } + return out; +} + +/** The fix a caret line and a fix-it line describe: a replacement under a range, else an insertion. */ +function fixOf(d: RawDiag): QuickFix | null { + if (d.fixit == null) return null; + const start = d.caret.search(/[\^~]/); + if (start < 0) return null; + const end = d.caret.replace(/\s+$/, '').length; // one past the last ^ or ~ + const at = d.fixit.search(/\S/); + const text = d.fixit.trim(); + if (at === start && end - start > 1) return { label: `Replace with ${text}`, line: d.line, col: start + 1, endCol: end + 1, text }; + return { label: `Insert ${text}`, line: d.line, col: at + 1, endCol: at + 1, text }; +} + +/** + * The compiler's messages as diagnostics on the Mojo pane. Notes stay + * notes; notes that carry a fix-it become the choices of a question on the + * error they follow ("consider transferring the value with '^'" or "you can + * copy it explicitly with '.copy()'"); an error's own fix-it is its fix. + */ +export function compilerDiagnostics(stderr: string): Diagnostic[] { + const out: Diagnostic[] = []; + let parent: Diagnostic | null = null; + for (const d of readRaw(stderr)) { + const sev = d.severity === 'remark' ? 'note' : d.severity as 'error' | 'warning' | 'note'; + const diag: Diagnostic = { lang: 'mojo', severity: sev, id: 'compiler', line: d.line, col: d.col, message: d.message, origin: ORIGIN }; + const fix = fixOf(d); + if (sev === 'note' && parent) { + if (fix) { + parent.question ??= { text: 'The compiler suggests:', options: [] }; + parent.question.options.push({ ...fix, label: d.message.replace(/^consider /, '').replace(/^you can /, '') }); + } + out.push(diag); + continue; + } + if (fix) diag.fix = fix; + out.push(diag); + if (sev !== 'note') parent = diag; + } + return out; +} + +/* --------------------------------------------------------------------------- + * The listing, as functions + * ------------------------------------------------------------------------- */ + +export type FunctionKind = 'user' | 'entry' | 'library' | 'data'; +export interface ListingFunction { label: string; name: string; kind: FunctionKind; lines: AsmLine[] } + +const TYPE_NAMES: Record = { int: 'Int', uint: 'UInt', bool: 'Bool', float64: 'Float64', float32: 'Float32', float16: 'Float16', int8: 'Int8', int16: 'Int16', int32: 'Int32', int64: 'Int64', uint8: 'UInt8', uint16: 'UInt16', uint32: 'UInt32', uint64: 'UInt64' }; + +/** `"example::add(::SIMD[DType.int, 1],::SIMD[DType.int, 1])"` reads as `add(Int, Int)`. */ +export function demangle(label: string): string { + let s = label.replace(/^"|"$/g, '').replace(/^example::/, ''); + s = s.replace(/::SIMD\[DType\.(\w+), 1\]/g, (_, t: string) => TYPE_NAMES[t] ?? `Scalar[${t}]`); + s = s.replace(/(^|[(,\s\[])::/g, '$1'); + return s.replace(/,(?=\S)/g, ', '); +} + +function kindOf(label: string): FunctionKind { + if (label.startsWith('"example::') || label.startsWith('example::')) return 'user'; + if (label === 'main') return 'entry'; + if (/^(static_string_\w+|\.L\.str[\w.]*)$/.test(label)) return 'data'; // a read-only string, not code + return 'library'; +} + +const LABEL = /^(?:"((?:[^"\\]|\\.)*)"|([A-Za-z_.$][\w.$@]*)):\s*$/; + +/** Split the listing at each function label; local labels (.LBB2_2) stay inside their function. */ +export function listingFunctions(asm: AsmLine[]): ListingFunction[] { + const out: ListingFunction[] = []; + let cur: ListingFunction | null = null; + for (const a of asm) { + const m = LABEL.exec(a.text.trim()); + if (m && !(m[2] ?? '').startsWith('.L')) { + const label = m[1] !== undefined ? `"${m[1]}"` : m[2]; + cur = { label, name: m[1] !== undefined ? demangle(label) : label, kind: kindOf(m[1] !== undefined ? m[1] : label), lines: [] }; + out.push(cur); + continue; + } + if (!cur) continue; + if (!a.text.trim() || /^\s*\.(type|size|section|globl|p2align|cfi_\w+|file|loc|text|data)\b/.test(a.text)) continue; + cur.lines.push(a); + } + return out.filter((f) => f.lines.length); +} + +/* --------------------------------------------------------------------------- + * Asking + * ------------------------------------------------------------------------- */ + +export interface CompileOutcome { answer: Answer | null; error: string | null; seconds: number } + +/** Ask godbolt. A network or HTTP failure is an outcome to show, not an exception. */ +export async function compileMojo(source: string, opts: { stdin?: string; level?: BuildLevel; signal?: AbortSignal; timeoutMs?: number } = {}): Promise { + const t0 = Date.now(); + const ctl = new AbortController(); + const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? 60000); + opts.signal?.addEventListener('abort', () => ctl.abort()); + try { + const res = await fetch(mojoRequestUrl(), { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify(mojoRequestBody(source, opts.stdin ?? '', BUILD_ARGS[opts.level ?? 'O0'])), + signal: ctl.signal, + }); + if (res.status === 429) return { answer: null, error: 'godbolt.org is rate-limiting requests from here. Wait a minute and compile again.', seconds: (Date.now() - t0) / 1000 }; + if (!res.ok) return { answer: null, error: `godbolt.org answered ${res.status} ${res.statusText}.`, seconds: (Date.now() - t0) / 1000 }; + return { answer: normaliseAnswer(await res.json()), error: null, seconds: (Date.now() - t0) / 1000 }; + } catch (e: any) { + const msg = e?.name === 'AbortError' ? 'godbolt.org did not answer in time.' : `Could not reach godbolt.org (${e?.message || e}).`; + return { answer: null, error: msg, seconds: (Date.now() - t0) / 1000 }; + } finally { + clearTimeout(timer); + } +} diff --git a/src/services/index.ts b/src/services/index.ts new file mode 100644 index 0000000..478fe49 --- /dev/null +++ b/src/services/index.ts @@ -0,0 +1,18 @@ +import type { LangId, LanguageService } from '../core/types.js'; +import { lingoService } from './lingo.js'; +import { mathoService } from './matho.js'; +import { pseudoService } from './pseudo.js'; +import { specoService } from './speco.js'; +import { asmService } from './asm.js'; +import { mojoService } from './mojo.js'; + +export const SERVICES: Record> = { + lingo: lingoService, + matho: mathoService, + pseudo: pseudoService, + speco: specoService, + mojo: mojoService, + asm: asmService, +}; + +export const LANG_ORDER: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm']; diff --git a/src/services/lingo.ts b/src/services/lingo.ts new file mode 100644 index 0000000..47e3c9f --- /dev/null +++ b/src/services/lingo.ts @@ -0,0 +1,102 @@ +/** + * lingo: the controlled-English service. Wraps `readSteps` from the course's + * english.js. Today the engine lowers English to pseudocode *text* and + * re-parses it; this adapter exposes that as `lower(..., 'pseudo')` with the + * engine's own line map, and runs English programs through the pseudocode + * service so the trace is the same shape. + */ +import { readSteps, SENTENCE_FORMS } from '../engines/pseudo/english.js'; +import type { Diagnostic, LanguageService, Lowered, Parsed, RunOptions, Trace } from '../core/types.js'; +import { toDiagnostic, studyOf, runPseudo, defaultCall as pseudoDefaultCall } from './pseudo.js'; + +export type Reading = any; + +export function readLingo(source: string): Parsed { + const r = readSteps(source); + const diagnostics: Diagnostic[] = r.diags.map((d: any) => toDiagnostic(d, 'lingo')); + return { program: r, diagnostics, ok: !!r.ok }; +} + +export function lowerLingo(parsed: Parsed, target: string): Lowered | null { + const r = parsed.program; + if (!r || !r.pseudo) return null; + const lowered: Lowered = { + target: 'pseudo', + source: r.pseudo, + // lineMap[i] describes pseudocode line i+1 and names the English line it came from + map: (r.lineMap || []).map((m: any, i: number) => ({ from: m?.line ?? 0, to: i + 1 })).filter((m: { from: number }) => m.from > 0), + notes: [], + }; + if (target === 'pseudo') return lowered; + return null; +} + +/** Run an English program: lower it, then run the pseudocode with the English line numbers mapped back. */ +export function runLingo(parsed: Parsed, options: RunOptions): Trace { + const low = lowerLingo(parsed, 'pseudo'); + if (!low) throw new Error('The steps do not read yet; answer the questions in the problems panel first.'); + const st = studyOf(low.source); + if (!st.ok) throw new Error('The pseudocode these steps became has an error: ' + (st.diagnostics.find((d) => d.severity === 'error')?.message || '')); + // The call in the toolbar usually names the pseudocode pane's routine; aim it at the English routine instead. + let call = options.call ?? null; + const subs: Map = st.program.program.subs; + const main = parsed.program.main; + const m = call ? /^\s*([A-Za-z_]\w*)\s*\((.*)\)\s*$/s.exec(call) : null; + if (m && main && !subs.has(m[1].toUpperCase())) { + const sub = subs.get(String(main.pseudo).toUpperCase()); + const argc = m[2].trim() ? m[2].split(/,(?![^\[\]{}()]*[\]})])/).length : 0; + call = sub && sub.params.length === argc ? `${sub.name}(${m[2]})` : null; + } + const tr = runPseudo(st, { ...options, call: call ?? pseudoDefaultCall(st.program) }); + const toEnglish = new Map(low.map.map((m) => [m.to, m.from])); + const hits = new Map(); + for (const [line, n] of tr.hits) { const e = toEnglish.get(line); if (e) hits.set(e, (hits.get(e) || 0) + n); } + return { + ...tr, + lang: 'lingo', + hits, + steps: tr.steps.map((s: any) => ({ ...s, pseudoLine: s.line, line: toEnglish.get(s.line) ?? s.line })), + error: tr.error ? { ...tr.error, line: tr.error.line != null ? toEnglish.get(tr.error.line) ?? tr.error.line : null } : null, + }; +} + +export function defaultCallLingo(parsed: Parsed): string | null { + const low = lowerLingo(parsed, 'pseudo'); + if (!low) return null; + const st = studyOf(low.source); + return st.ok ? pseudoDefaultCall(st.program) : null; +} + +const STEP_WORDS = /^(to|start|let|set|make|add|append|put|insert|subtract|increase|decrease|multiply|double|halve|count|remove|sort|swap|show|print|check|if|otherwise|for|repeat|while|until|stop|skip|the answer|example)\b/i; + +export function tokenizeLingo(line: string): Array<{ text: string; cls: string }> { + const out: Array<{ text: string; cls: string }> = []; + const re = /("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)?')|(\b\d+(?:\.\d+)?\b)|(\b[A-Za-z][A-Za-z0-9_]*\b)|(\s+)|(.)/g; + let m: RegExpExecArray | null; + let first = true; + while ((m = re.exec(line))) { + const [text, s, n, w] = m; + let cls = ''; + if (s) cls = 'tok-string'; + else if (n) cls = 'tok-number'; + else if (w) { + if (first && STEP_WORDS.test(line.trim())) cls = 'tok-keyword'; + else if (/^[A-Z]/.test(w) || w.length === 1) cls = 'tok-name'; + first = false; + } + out.push({ text, cls }); + } + return out; +} + +export const sentenceForms: Array<{ job: string; example: string }> = (SENTENCE_FORMS as any[]).map((f) => ({ job: f.job || f.label || '', example: f.example || f.text || String(f) })); + +export const lingoService: LanguageService = { + id: 'lingo', + name: 'lingo', + parse: readLingo, + run: runLingo, + lower: lowerLingo, + defaultCall: defaultCallLingo, + tokenize: tokenizeLingo, +}; diff --git a/src/services/matho.ts b/src/services/matho.ts new file mode 100644 index 0000000..1b42eb2 --- /dev/null +++ b/src/services/matho.ts @@ -0,0 +1,1199 @@ +/** + * matho: equations, written in LaTeX. + * + * A student pastes the formula from the paper or the textbook, written the + * way they would write it in a LaTeX document, and the pane becomes pseudo: + * one FUNCTION per equation, sums and products as accumulator loops, cases + * as IF/ELSE, Greek letters as names, subscripts as list positions. + * + * \bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i + * + * FUNCTION X_BAR(N : INTEGER, X : LIST OF FLOAT) RETURNS FLOAT + * DECLARE Total : FLOAT + * Total <- 0.0 + * FOR I <- 0 TO N + * Total <- Total + X[I] + * NEXT I + * RETURN 1 / N * Total + * ENDFUNCTION + * + * The reader knows a deliberate subset of mathematics: arithmetic, fractions, + * roots, powers, e^x, |x|, floors and ceilings, sums and products with + * bounds or over a set, binomial coefficients, factorials, the usual + * functions (sin, cos, tan, exp, ln, log), max and min, dot products and + * norms of vectors, piecewise definitions with \begin{cases}, and + * references to equations defined higher up. Anything else (integrals, + * limits, infinity, derivatives) is refused with a sentence that says what + * finite procedure to write instead, because a procedure is what a program + * is, and that is the lesson. + * + * The decisions a translation has to make (which letters are whole numbers, + * which are lists, where a 1-based sum meets a 0-based list) are reported + * as notes on the equation's line, so nothing is decided silently. + */ +import type { Diagnostic, LanguageService, Lowered, Parsed, RunOptions, Trace } from '../core/types.js'; +import { studyOf, runPseudo, defaultCall as pseudoDefaultCall } from './pseudo.js'; +import { reservedNames } from '../core/reference.js'; + +/* ------------------------------------------------------------------ */ +/* Tokens */ +/* ------------------------------------------------------------------ */ + +type Tok = { t: 'cmd' | 'num' | 'id' | 'sym' | 'text' | 'end'; v: string; pos: number }; + +const TEXT_CMDS = new Set(['text', 'mathrm', 'operatorname', 'textrm', 'mathit', 'mbox']); +const SKIP_CMDS = new Set([',', ';', ':', '!', ' ', 'quad', 'qquad', 'displaystyle', 'nonumber', 'left', 'right', 'big', 'Big', 'bigg', 'Bigg', 'limits', 'nolimits', 'cdots', 'dots', 'ldots']); + +function tokenize(src: string): { toks: Tok[]; error: string | null } { + const toks: Tok[] = []; + let i = 0; + let error: string | null = null; + const n = src.length; + while (i < n) { + const ch = src[i]; + if (ch === '%') { while (i < n && src[i] !== '\n') i++; continue; } + if (/\s/.test(ch)) { i++; continue; } + if (ch === '\\') { + const m = /^\\([A-Za-z]+|.)/.exec(src.slice(i)); + if (!m) { i++; continue; } + const name = m[1]; + i += m[0].length; + if (SKIP_CMDS.has(name)) continue; + if (TEXT_CMDS.has(name)) { + // \text{...}: the braces hold words, not maths + let j = i; while (j < n && /\s/.test(src[j])) j++; + if (src[j] === '{') { + let depth = 0; let k = j; + for (; k < n; k++) { if (src[k] === '{') depth++; else if (src[k] === '}') { depth--; if (depth === 0) break; } } + toks.push({ t: 'text', v: src.slice(j + 1, k).trim(), pos: i - m[0].length }); + i = k + 1; + continue; + } + } + if (name === 'label') { // \label{...} is for the document, not the maths + const close = src.indexOf('}', i); i = close < 0 ? n : close + 1; continue; + } + toks.push({ t: 'cmd', v: name, pos: i - m[0].length }); + continue; + } + if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(src[i + 1] || ''))) { + const m = /^[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?|^[0-9]+\./.exec(src.slice(i))!; + toks.push({ t: 'num', v: m[0], pos: i }); + i += m[0].length; + continue; + } + if (/[A-Za-z]/.test(ch)) { toks.push({ t: 'id', v: ch, pos: i }); i++; continue; } + if ('{}()[]^_+-*/=<>,|!&:;\'.'.includes(ch)) { toks.push({ t: 'sym', v: ch, pos: i }); i++; continue; } + if ('·×÷'.includes(ch)) { toks.push({ t: 'cmd', v: ch === '·' || ch === '×' ? 'cdot' : 'div', pos: i }); i++; continue; } + if ('≤≥≠'.includes(ch)) { toks.push({ t: 'cmd', v: ch === '≤' ? 'le' : ch === '≥' ? 'ge' : 'ne', pos: i }); i++; continue; } + if (ch === 'π') { toks.push({ t: 'cmd', v: 'pi', pos: i }); i++; continue; } + if (ch === '∑') { toks.push({ t: 'cmd', v: 'sum', pos: i }); i++; continue; } + if (ch === '∏') { toks.push({ t: 'cmd', v: 'prod', pos: i }); i++; continue; } + if (ch === '√') { toks.push({ t: 'cmd', v: 'sqrt', pos: i }); i++; continue; } + if (ch === '∈') { toks.push({ t: 'cmd', v: 'in', pos: i }); i++; continue; } + if (ch === '$') { i++; continue; } + if (!error) error = `The character ${JSON.stringify(ch)} is not part of the mathematics this reader knows.`; + i++; + } + toks.push({ t: 'end', v: '', pos: n }); + return { toks, error }; +} + +/* ------------------------------------------------------------------ */ +/* Syntax tree */ +/* ------------------------------------------------------------------ */ + +type Decor = 'bar' | 'hat' | 'vec' | 'tilde' | 'bold' | null; + +export type Expr = + | { k: 'num'; v: string } + | { k: 'var'; name: string; decor: Decor; sub: Expr | null; subText: string | null; pos: number } + | { k: 'bin'; op: '+' | '-' | '*' | '/' | 'mod'; l: Expr; r: Expr } + | { k: 'neg'; e: Expr } + | { k: 'pow'; b: Expr; e: Expr } + | { k: 'call'; fn: string; args: Expr[]; pos: number } + | { k: 'sqrt'; e: Expr; n: Expr | null } + | { k: 'abs'; e: Expr } + | { k: 'norm'; e: Expr } + | { k: 'floor'; e: Expr } + | { k: 'ceil'; e: Expr } + | { k: 'big'; op: 'sum' | 'prod'; idx: string; lo: Expr | null; hi: Expr | null; over: Expr | null; body: Expr; pos: number } + | { k: 'binom'; n: Expr; m: Expr } + | { k: 'fact'; e: Expr } + | { k: 'pi' } + | { k: 'cases'; arms: Array<{ value: Expr; cond: Cond | null }> } + | { k: 'dot'; l: Expr; r: Expr }; + +export type Cond = + | { k: 'cmp'; op: '<' | '<=' | '>' | '>=' | '==' | '!='; l: Expr; r: Expr } + | { k: 'and'; l: Cond; r: Cond } + | { k: 'or'; l: Cond; r: Cond } + | { k: 'not'; c: Cond }; + +export interface Equation { + /** 1-based line of the source where the equation starts. */ + line: number; + source: string; + lhs: Expr | null; + rhs: Expr; +} + +export interface MathoProgram { + equations: Equation[]; + pseudo: string; + /** pseudo line (1-based) → equation index */ + lineMap: number[]; + /** Name and parameters of every function the pseudo defines, in order. */ + defs: Array<{ name: string; params: Array<{ name: string; type: string }>; line: number }>; +} + +class ParseError extends Error { constructor(msg: string, public pos: number, public id = 'matho-syntax') { super(msg); } } + +const GREEK: Record = { + alpha: 'Alpha', beta: 'Beta', gamma: 'Gamma', delta: 'Delta', epsilon: 'Epsilon', varepsilon: 'Epsilon', zeta: 'Zeta', eta: 'Eta', theta: 'Theta', vartheta: 'Theta', + iota: 'Iota', kappa: 'Kappa', lambda: 'Lambda', mu: 'Mu', nu: 'Nu', xi: 'Xi', rho: 'Rho', varrho: 'Rho', sigma: 'Sigma', tau: 'Tau', upsilon: 'Upsilon', phi: 'Phi', varphi: 'Phi', + chi: 'Chi', psi: 'Psi', omega: 'Omega', Gamma: 'GammaU', Delta: 'DeltaU', Theta: 'ThetaU', Lambda: 'LambdaU', Xi: 'XiU', Pi: 'PiU', Sigma: 'SigmaU', Phi: 'PhiU', Psi: 'PsiU', Omega: 'OmegaU', ell: 'Ell', hbar: 'HBar', +}; +const FUNCS: Record = { sin: 'SIN', cos: 'COS', tan: 'TAN', exp: 'EXP', ln: 'LOG', log: 'LOG10', sqrt: 'SQRT', max: 'MAX', min: 'MIN', arctan: 'ATAN', atan: 'ATAN', abs: 'ABS' }; +const REFUSED: Record = { + int: 'An integral has no finite procedure behind it. Write the sum it approximates instead: \\sum_{i=0}^{n-1} f(a + i \\, h) \\, h with a step h, which becomes a loop.', + iint: 'A double integral has no finite procedure behind it. Write it as nested sums over a grid of steps.', + oint: 'A contour integral has no finite procedure behind it. Write it as a sum over the points of the path.', + infty: 'A program cannot run to infinity. Give the sum or product an upper bound, such as n, and make n a parameter.', + lim: 'A limit is not a procedure. Pick a small step or a large n and write what the expression is there.', + partial: 'A derivative is not a procedure. Write the difference quotient it approximates: (f(x + h) - f(x)) / h for a step h.', + nabla: 'A gradient is not a procedure. Write one difference quotient per coordinate.', + prime: 'A derivative is not a procedure. Write the difference quotient it approximates.', + forall: 'A statement about all values is a specification, not a procedure. Put it in the speco pane as an ENSURE.', + exists: 'A statement about some value is a specification, not a procedure. Put it in the speco pane, or write the loop that searches for the value.', + cup: 'Set union is not a single step in pseudo. Write the loop that ADDs each member of one SET to the other.', + cap: 'Set intersection is not a single step in pseudo. Write the loop that keeps the members found in both.', + to: 'An arrow is not an operation. Write the value the expression becomes.', + rightarrow: 'An arrow is not an operation. Write the value the expression becomes.', + approx: 'Write = and the expression you actually want computed; a program cannot be approximately equal.', + propto: 'Proportionality leaves the constant out. Name the constant and write = with it in.', + sim: 'A distribution symbol is not a procedure. Write RANDN() or RAND(x) for the sample you want drawn.', +}; + +/* ------------------------------------------------------------------ */ +/* Parser */ +/* ------------------------------------------------------------------ */ + +class Parser { + toks: Tok[]; + i = 0; + /** While the left side is being read, `f(x)` defines f even if f is new. */ + private lhsMode = false; + /** How many \| ... \| norms are open, so that the closing \| is not read as a new factor. */ + private normOpen = 0; + /** Functions defined by earlier equations, by their LaTeX name key. */ + constructor(toks: Tok[], private knownFns: Set) { this.toks = toks; } + + get tok(): Tok { return this.toks[this.i]; } + peek(k = 1): Tok { return this.toks[Math.min(this.i + k, this.toks.length - 1)]; } + next(): Tok { return this.toks[this.i++]; } + isSym(v: string): boolean { return this.tok.t === 'sym' && this.tok.v === v; } + isCmd(v: string): boolean { return this.tok.t === 'cmd' && this.tok.v === v; } + expectSym(v: string, what: string): void { + if (!this.isSym(v)) throw new ParseError(`Expected ${JSON.stringify(v)} ${what}, but found ${this.describe(this.tok)}.`, this.tok.pos); + this.next(); + } + describe(t: Tok): string { return t.t === 'end' ? 'the end of the equation' : t.t === 'cmd' ? `\\${t.v}` : t.t === 'text' ? `the text "${t.v}"` : JSON.stringify(t.v); } + + /** The whole equation: `lhs = rhs`, `rhs`, or cases. */ + equation(): { lhs: Expr | null; rhs: Expr } { + if (this.tok.t === 'end') throw new ParseError('The equation is empty.', 0); + this.lhsMode = true; + const first = this.expr(); + this.lhsMode = false; + if (this.isSym('=') || this.isCmd('equiv') || (this.isSym(':') && this.peek().t === 'sym' && this.peek().v === '=')) { + if (this.isSym(':')) this.next(); + this.next(); + const rhs = this.exprOrCases(); + if (this.isSym('=')) throw new ParseError('A chain of equalities (a = b = c) is a statement, not a definition. Keep the two sides you want computed, and put the rest in a comment.', this.tok.pos, 'matho-chain'); + this.endOrError(); + return { lhs: first, rhs }; + } + this.endOrError(); + return { lhs: null, rhs: first }; + } + + private endOrError(): void { + if (this.tok.t !== 'end') { + const t = this.tok; + if (t.t === 'sym' && (t.v === '<' || t.v === '>')) throw new ParseError('A comparison on its own is a condition, not a value. Use it inside \\begin{cases} ... \\end{cases}, or in the speco pane.', t.pos, 'matho-condition'); + throw new ParseError(`Did not expect ${this.describe(t)} here.`, t.pos); + } + } + + private exprOrCases(): Expr { + if (this.isCmd('begin')) return this.cases(); + return this.expr(); + } + + private cases(): Expr { + this.next(); // \begin + const env = this.braceText(); + if (env !== 'cases') throw new ParseError(`\\begin{${env}} is not something this reader knows; only \\begin{cases} is.`, this.tok.pos, 'matho-command'); + const arms: Array<{ value: Expr; cond: Cond | null }> = []; + for (; ;) { + const value = this.expr(); + let cond: Cond | null = null; + if (this.isSym('&')) { + this.next(); + cond = this.condition(); + } + arms.push({ value, cond }); + if (this.isCmd('\\')) { this.next(); if (this.isCmd('end')) break; continue; } + if (this.isCmd('end')) break; + throw new ParseError(`Expected \\\\ between the cases or \\end{cases}, but found ${this.describe(this.tok)}.`, this.tok.pos); + } + this.next(); // \end + const close = this.braceText(); + if (close !== 'cases') throw new ParseError(`\\begin{cases} was closed by \\end{${close}}.`, this.tok.pos); + if (!arms.some((a) => a.cond === null)) throw new ParseError('The cases need a last line with no condition (write "& \\text{otherwise}"), so that every input has a value.', this.tok.pos, 'matho-cases-otherwise'); + if (arms.findIndex((a) => a.cond === null) !== arms.length - 1) throw new ParseError('The case with no condition ("otherwise") has to be the last one.', this.tok.pos, 'matho-cases-otherwise'); + return { k: 'cases', arms }; + } + + private braceText(): string { + this.expectSym('{', 'after \\begin or \\end'); + let s = ''; + while (!this.isSym('}') && this.tok.t !== 'end') s += this.next().v; + this.expectSym('}', 'to close the environment name'); + return s; + } + + /** A condition in a cases arm: `\text{if } x < 0`, `x \ge 0 \text{ and } y > 0`, `0 \le x < 1`, `\text{otherwise}`. */ + private condition(): Cond | null { + if (this.tok.t === 'text') { + const w = this.tok.v.toLowerCase().replace(/[^a-z]/g, ''); + if (w === 'otherwise' || w === 'else') { this.next(); return null; } + if (w === 'if' || w === 'when' || w === 'for' || w === 'where') this.next(); + } + return this.orCond(); + } + private orCond(): Cond { + let l = this.andCond(); + while (this.isCmd('lor') || this.isCmd('vee') || (this.tok.t === 'text' && /^or$/i.test(this.tok.v.trim()))) { this.next(); l = { k: 'or', l, r: this.andCond() }; } + return l; + } + private andCond(): Cond { + let l = this.cmp(); + while (this.isCmd('land') || this.isCmd('wedge') || this.isSym(',') || (this.tok.t === 'text' && /^and$/i.test(this.tok.v.trim()))) { this.next(); l = { k: 'and', l, r: this.cmp() }; } + return l; + } + private cmpOp(): '<' | '<=' | '>' | '>=' | '==' | '!=' | null { + const t = this.tok; + if (t.t === 'sym') { + if (t.v === '<') { this.next(); if (this.isSym('=')) { this.next(); return '<='; } return '<'; } + if (t.v === '>') { this.next(); if (this.isSym('=')) { this.next(); return '>='; } return '>'; } + if (t.v === '=') { this.next(); if (this.isSym('=')) this.next(); return '=='; } + if (t.v === '!' && this.peek().t === 'sym' && this.peek().v === '=') { this.next(); this.next(); return '!='; } + } + if (t.t === 'cmd') { + const m: Record = { le: '<=', leq: '<=', leqslant: '<=', ge: '>=', geq: '>=', geqslant: '>=', ne: '!=', neq: '!=', lt: '<', gt: '>' }; + if (m[t.v]) { this.next(); return m[t.v]; } + } + return null; + } + private cmp(): Cond { + const l = this.expr(); + const op = this.cmpOp(); + if (!op) throw new ParseError(`A condition needs a comparison (<, \\le, =, \\ne, ...) after ${this.describe(this.toks[this.i - 1])}.`, this.tok.pos, 'matho-condition'); + const r = this.expr(); + let c: Cond = { k: 'cmp', op, l, r }; + // a chain such as 0 \le x < 1 + const op2 = this.cmpOp(); + if (op2) { const r2 = this.expr(); c = { k: 'and', l: c, r: { k: 'cmp', op: op2, l: r, r: r2 } }; } + return c; + } + + /* ---- expressions ---- */ + + expr(): Expr { + let l = this.term(); + for (; ;) { + if (this.isSym('+')) { this.next(); l = { k: 'bin', op: '+', l, r: this.term() }; } + else if (this.isSym('-')) { this.next(); l = { k: 'bin', op: '-', l, r: this.term() }; } + else if (this.isCmd('pm') || this.isCmd('mp')) throw new ParseError('\\pm gives two values; a function returns one. Write the + version and the - version as two equations.', this.tok.pos, 'matho-pm'); + else break; + } + return l; + } + + private startsFactor(t: Tok): boolean { + if (t.t === 'num' || t.t === 'id' || t.t === 'text') return true; + if (t.t === 'sym') return t.v === '(' || t.v === '{' || t.v === '['; + if (t.t === 'cmd' && t.v === '|') return this.normOpen === 0; + if (t.t === 'cmd') return !['cdot', 'times', 'div', 'bmod', 'mod', 'le', 'leq', 'ge', 'geq', 'ne', 'neq', 'lt', 'gt', 'land', 'lor', 'end', '\\', 'equiv', 'in', 'pm', 'mp', 'right', 'rfloor', 'rceil', 'rvert', 'rVert', 'rangle'].includes(t.v); + return false; + } + + private term(): Expr { + let l = this.unary(); + for (; ;) { + if (this.isCmd('cdot') || this.isCmd('times') || this.isSym('*')) { + const dotted = this.isCmd('cdot'); + this.next(); + const r = this.unary(); + l = dotted && isVector(l) && isVector(r) ? { k: 'dot', l, r } : { k: 'bin', op: '*', l, r }; + } else if (this.isSym('/') || this.isCmd('div')) { this.next(); l = { k: 'bin', op: '/', l, r: this.unary() }; } + else if (this.isCmd('bmod') || this.isCmd('mod')) { this.next(); l = { k: 'bin', op: 'mod', l, r: this.unary() }; } + else if (this.startsFactor(this.tok) && !(this.tok.t === 'sym' && this.tok.v === '[' && false)) { + // juxtaposition is multiplication: 2 \pi r, m v^2, \frac{1}{n} \sum ... + l = { k: 'bin', op: '*', l, r: this.unary() }; + } else break; + } + return l; + } + + private unary(): Expr { + if (this.isSym('-')) { this.next(); return { k: 'neg', e: this.unary() }; } + if (this.isSym('+')) { this.next(); return this.unary(); } + return this.postfix(); + } + + /** An atom with its subscripts, superscripts, and factorials. */ + private postfix(): Expr { + let e = this.atom(); + for (; ;) { + if (this.isSym('^')) { + this.next(); + const ex = this.scriptArg(); + if (e.k === 'var' && e.name === 'e' && !e.sub && !e.decor) e = { k: 'call', fn: 'EXP', args: [ex], pos: e.pos }; + else e = { k: 'pow', b: e, e: ex }; + } else if (this.isSym('_')) { + this.next(); + if (e.k !== 'var' || e.sub) throw new ParseError('A subscript belongs on a name: x_i, v_{\\max}, a_{i+1}.', this.tok.pos, 'matho-subscript'); + const save = this.i; + const argToks = this.scriptTokens(); + const text = argToks.every((t) => t.t === 'id' || t.t === 'text' || t.t === 'num') ? argToks.map((t) => t.v).join('') : null; + this.i = save; + e = { ...e, sub: this.scriptArg(), subText: text }; + } else if (this.isSym('!')) { this.next(); e = { k: 'fact', e }; } + else if (this.isSym('\'')) throw new ParseError(REFUSED.prime, this.tok.pos, 'matho-refused'); + else break; + } + return e; + } + + /** The tokens of the next `{...}` group or single token, without consuming them. */ + private scriptTokens(): Tok[] { + const out: Tok[] = []; + if (this.isSym('{')) { + let depth = 0; + for (let j = this.i; j < this.toks.length; j++) { + const t = this.toks[j]; + if (t.t === 'sym' && t.v === '{') { depth++; if (depth === 1) continue; } + if (t.t === 'sym' && t.v === '}') { depth--; if (depth === 0) break; } + out.push(t); + } + } else out.push(this.tok); + return out; + } + + private scriptArg(): Expr { + if (this.isSym('{')) { this.next(); const e = this.expr(); this.expectSym('}', 'to close the group'); return e; } + // a single token: x^2, x_i, e^x, \sum_i + const t = this.tok; + if (t.t === 'num' || t.t === 'id' || t.t === 'cmd' || t.t === 'text') return this.atom(); + throw new ParseError(`Expected a group in braces or a single symbol after ${this.describe(this.toks[this.i - 1])}.`, t.pos); + } + + private atom(): Expr { + const t = this.tok; + if (t.t === 'num') { this.next(); return { k: 'num', v: t.v }; } + if (t.t === 'id') { + this.next(); + // f(x) where f names an earlier equation: a call + if (this.isSym('(') && (this.knownFns.has(t.v) || this.lhsMode)) return this.callArgs(t.v, t.pos); + return { k: 'var', name: t.v, decor: null, sub: null, subText: null, pos: t.pos }; + } + if (t.t === 'text') { + this.next(); + const name = t.v.replace(/\s+/g, '_'); + if (this.isSym('(') && (this.knownFns.has(name) || this.lhsMode)) return this.callArgs(name, t.pos); + return { k: 'var', name, decor: null, sub: null, subText: null, pos: t.pos }; + } + if (t.t === 'sym') { + if (t.v === '(' || t.v === '[') { + this.next(); + const e = this.expr(); + this.expectSym(t.v === '(' ? ')' : ']', 'to close the bracket'); + return e; + } + if (t.v === '{') { this.next(); const e = this.expr(); this.expectSym('}', 'to close the group'); return e; } + if (t.v === '|') { this.next(); const e = this.expr(); this.expectSym('|', 'to close the absolute value'); return { k: 'abs', e }; } + throw new ParseError(`Did not expect ${this.describe(t)} here.`, t.pos); + } + if (t.t === 'cmd') return this.command(); + throw new ParseError('The equation ends too early.', t.pos); + } + + private callArgs(fn: string, pos: number): Expr { + this.expectSym('(', 'after the function name'); + const args: Expr[] = []; + if (!this.isSym(')')) { args.push(this.expr()); while (this.isSym(',')) { this.next(); args.push(this.expr()); } } + this.expectSym(')', 'to close the arguments'); + return { k: 'call', fn, args, pos }; + } + + private group(what: string): Expr { + this.expectSym('{', what); + const e = this.expr(); + this.expectSym('}', 'to close the group'); + return e; + } + + private command(): Expr { + const t = this.next(); + const c = t.v; + if (REFUSED[c]) throw new ParseError(REFUSED[c], t.pos, 'matho-refused'); + if (GREEK[c]) return { k: 'var', name: '\\' + c, decor: null, sub: null, subText: null, pos: t.pos }; + if (c === 'pi') return { k: 'pi' }; + if (c === 'frac' || c === 'dfrac' || c === 'tfrac') { const n = this.group('for the top of the fraction'); const d = this.group('for the bottom of the fraction'); return { k: 'bin', op: '/', l: n, r: d }; } + if (c === 'sqrt') { + let n: Expr | null = null; + if (this.isSym('[')) { this.next(); n = this.expr(); this.expectSym(']', 'to close the root index'); } + return { k: 'sqrt', e: this.group('for what the root is taken of'), n }; + } + if (c === 'binom' || c === 'dbinom' || c === 'tbinom') return { k: 'binom', n: this.group('for the top of the binomial'), m: this.group('for the bottom of the binomial') }; + if (c === 'bar' || c === 'overline' || c === 'hat' || c === 'vec' || c === 'tilde' || c === 'mathbf' || c === 'boldsymbol') { + const decor: Decor = c === 'overline' ? 'bar' : c === 'mathbf' || c === 'boldsymbol' ? 'bold' : (c as Decor); + const inner = this.group(`for what \\${c} applies to`); + if (inner.k !== 'var' || inner.sub) throw new ParseError(`\\${c} goes over a single name: \\${c}{x}.`, t.pos, 'matho-decor'); + return { ...inner, decor }; + } + if (c === 'sum' || c === 'prod') return this.bigOp(c, t.pos); + if (c === 'lfloor') { const e = this.expr(); if (!this.isCmd('rfloor')) throw new ParseError('\\lfloor needs a matching \\rfloor.', this.tok.pos); this.next(); return { k: 'floor', e }; } + if (c === 'lceil') { const e = this.expr(); if (!this.isCmd('rceil')) throw new ParseError('\\lceil needs a matching \\rceil.', this.tok.pos); this.next(); return { k: 'ceil', e }; } + if (c === 'lvert') { const e = this.expr(); if (!this.isCmd('rvert')) throw new ParseError('\\lvert needs a matching \\rvert.', this.tok.pos); this.next(); return { k: 'abs', e }; } + if (c === 'lVert' || c === '|') { + this.normOpen++; + const e = this.expr(); + this.normOpen--; + if (!(this.isCmd('rVert') || this.isCmd('|'))) throw new ParseError('\\lVert (or \\|) needs a matching \\rVert (or \\|).', this.tok.pos); + this.next(); + return { k: 'norm', e }; + } + if (c === 'langle') { const l = this.expr(); this.expectSym(',', 'between the two vectors of the inner product'); const r = this.expr(); if (!this.isCmd('rangle')) throw new ParseError('\\langle needs a matching \\rangle.', this.tok.pos); this.next(); return { k: 'dot', l, r }; } + if (c === 'log' && this.isSym('_')) { + this.next(); + const base = this.scriptArg(); + const arg = this.funcArg(); + if (base.k === 'num' && base.v === '10') return { k: 'call', fn: 'LOG10', args: [arg], pos: t.pos }; + if (base.k === 'num' && base.v === '2') return { k: 'call', fn: 'LOG2', args: [arg], pos: t.pos }; + if (base.k === 'var' && base.name === 'e' && !base.sub) return { k: 'call', fn: 'LOG', args: [arg], pos: t.pos }; + return { k: 'bin', op: '/', l: { k: 'call', fn: 'LOG', args: [arg], pos: t.pos }, r: { k: 'call', fn: 'LOG', args: [base], pos: t.pos } }; + } + if (FUNCS[c]) { + if (this.isSym('^')) { + // \sin^2 x + this.next(); + const p = this.scriptArg(); + const arg = this.funcArg(); + return { k: 'pow', b: { k: 'call', fn: FUNCS[c], args: [arg], pos: t.pos }, e: p }; + } + if (c === 'max' || c === 'min') { + this.expectSym('(', `after \\${c}`); + const args = [this.expr()]; + while (this.isSym(',')) { this.next(); args.push(this.expr()); } + this.expectSym(')', `to close \\${c}`); + return { k: 'call', fn: FUNCS[c], args, pos: t.pos }; + } + return { k: 'call', fn: FUNCS[c], args: [this.funcArg()], pos: t.pos }; + } + if (c === 'begin') throw new ParseError('\\begin{cases} can only be the whole right-hand side of an equation.', t.pos, 'matho-cases-place'); + if (c === 'mathbb' || c === 'mathcal') { const inner = this.group(`for \\${c}`); return inner; } + throw new ParseError(`\\${c} is not a command this reader knows. It knows arithmetic, \\frac, \\sqrt, powers, e^x, |x|, \\lfloor \\rfloor, \\sum, \\prod, \\binom, n!, \\sin \\cos \\tan \\exp \\ln \\log, \\max \\min, \\vec and \\|v\\|, \\begin{cases}, and Greek letters.`, t.pos, 'matho-command'); + } + + /** What a function such as \sin applies to: a bracketed argument, or the next power. */ + private funcArg(): Expr { + if (this.isSym('(')) { this.next(); const e = this.expr(); this.expectSym(')', 'to close the argument'); return e; } + if (this.isSym('{')) return this.group(''); + return this.postfix(); + } + + private bigOp(op: 'sum' | 'prod', pos: number): Expr { + let idx: string | null = null; + let lo: Expr | null = null; + let hi: Expr | null = null; + let over: Expr | null = null; + for (let k = 0; k < 2; k++) { + if (this.isSym('_')) { + this.next(); + const braced = this.isSym('{'); + if (braced) this.next(); + const v = this.tok; + if (v.t !== 'id' && !(v.t === 'cmd' && GREEK[v.v])) throw new ParseError(`\\${op} needs an index letter under it: \\${op}_{i=0}^{n-1}.`, v.pos, 'matho-sum-index'); + this.next(); + idx = v.t === 'id' ? v.v : '\\' + v.v; + if (this.isSym('=')) { this.next(); lo = this.expr(); } + else if (this.isCmd('in')) { this.next(); over = this.expr(); } + if (braced) this.expectSym('}', 'to close the index'); + } else if (this.isSym('^')) { + this.next(); + hi = this.scriptArg(); + } + } + if (!idx) throw new ParseError(`\\${op} needs an index letter under it: \\${op}_{i=0}^{n-1}.`, pos, 'matho-sum-index'); + if (hi && !lo && !over) throw new ParseError(`\\${op}_{${idx}} has an upper bound but no lower one: write \\${op}_{${idx}=0}^{...}.`, pos, 'matho-sum-bounds'); + const body = this.term(); + return { k: 'big', op, idx, lo, hi, over, body, pos }; + } +} + +function isVector(e: Expr): boolean { return e.k === 'var' && (e.decor === 'vec' || e.decor === 'bold') && !e.sub; } + +/* ------------------------------------------------------------------ */ +/* Lowering */ +/* ------------------------------------------------------------------ */ + +type PType = 'INTEGER' | 'FLOAT' | 'LIST OF FLOAT' | 'LIST OF LIST OF FLOAT'; + +interface Param { key: string; name: string; type: PType; roles: Set<'index' | 'bound' | 'list' | 'matrix' | 'vector' | 'plain'> } + +interface Def { key: string; fnName: string; params: Param[]; } + +const RESERVED = new Set(reservedNames().map((r) => r.term.toUpperCase())); + +/** A variable's key: its base name plus decoration plus a non-index subscript. */ +function varKey(v: Extract, indexSub: boolean): string { + return `${v.decor ?? ''}:${v.name}:${indexSub ? '' : (v.subText ?? '')}`; +} + +function baseWord(name: string): string { + if (name.startsWith('\\')) return GREEK[name.slice(1)] ?? name.slice(1); + if (name.length === 1) return name.toUpperCase(); + return name.split(/[_\s]+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(''); +} + +/** `x` → X, `\sigma` → Sigma, `\bar{x}` → XBar, `v_{max}` → VMax, `x_0` → X0. */ +function pseudoName(v: Extract, indexSub: boolean): string { + let s = baseWord(v.name); + if (v.decor === 'bar') s += 'Bar'; + else if (v.decor === 'hat') s += 'Hat'; + else if (v.decor === 'tilde') s += 'Tilde'; + if (!indexSub && v.subText) { + const sub = v.subText.replace(/^\\/, ''); + s += GREEK[sub] ?? (sub.charAt(0).toUpperCase() + sub.slice(1)); + } + if (!/^[A-Za-z_]\w*$/.test(s)) s = s.replace(/\W/g, '_'); + if (RESERVED.has(s.toUpperCase())) s += 'Val'; + return s; +} + +/** The function name an equation's left side gives: `f` → F, `\bar{x}` → X_BAR, `E_k` → E_K, `\sigma^2` → SIGMA_SQUARED. */ +function functionName(lhs: Expr): string { + let squared = false; + let e = lhs; + if (e.k === 'pow' && e.e.k === 'num' && e.e.v === '2') { squared = true; e = e.b; } + if (e.k === 'fact' && e.e.k === 'var') return 'FACTORIAL'; + if (e.k === 'call' && Object.values(FUNCS).includes(e.fn)) return [e.fn, ...e.args.map((a) => (a.k === 'var' ? baseWord(a.name).toUpperCase() : 'OF'))].join('_'); + if (e.k === 'call') e = { k: 'var', name: e.fn, decor: null, sub: null, subText: null, pos: e.pos }; + if (e.k !== 'var') return 'VALUE'; + const parts = [baseWord(e.name).toUpperCase()]; + if (e.decor === 'bar') parts.push('BAR'); else if (e.decor === 'hat') parts.push('HAT'); else if (e.decor === 'tilde') parts.push('TILDE'); + if (e.subText) parts.push((GREEK[e.subText.replace(/^\\/, '')] ?? e.subText).toUpperCase()); + if (squared) parts.push('SQUARED'); + let s = parts.join('_').replace(/\W/g, '_'); + if (RESERVED.has(s)) s += '_FN'; + return s; +} + +class Lowerer { + diagnostics: Diagnostic[] = []; + defs = new Map(); + lines: string[] = []; + lineMap: number[] = []; + outDefs: MathoProgram['defs'] = []; + + private note(line: number, id: string, message: string): void { this.diagnostics.push({ lang: 'matho', severity: 'note', id, line, message }); } + private warn(line: number, id: string, message: string): void { this.diagnostics.push({ lang: 'matho', severity: 'warning', id, line, message }); } + + lower(eqs: Equation[]): void { + eqs.forEach((eq, k) => { + const start = this.lines.length; + this.one(eq, k); + for (let i = start; i < this.lines.length; i++) this.lineMap[i] = k; + }); + } + + private one(eq: Equation, k: number): void { + const { lhs, rhs } = eq; + // --- the function's own name and explicit arguments + let fnName = lhs ? functionName(lhs) : (k === 0 ? 'VALUE' : `VALUE_${k + 1}`); + const explicit: Array> = []; + let lhsIndex: Extract | null = null; + const lhsIsBuiltin = lhs?.k === 'call' && Object.values(FUNCS).includes(lhs.fn); + if (lhs?.k === 'call' && !lhsIsBuiltin) for (const a of lhs.args) { if (a.k !== 'var' || a.sub) { this.warn(eq.line, 'matho-lhs-args', `The arguments on the left side should be plain names, as in f(x, y); ${describeExpr(a)} was ignored.`); continue; } explicit.push(a); } + if (lhs?.k === 'var' && lhs.sub && lhs.sub.k === 'var' && mentionsSub(rhs, lhs.sub.name)) { lhsIndex = lhs.sub; fnName = functionName({ ...lhs, sub: null, subText: null }); } + if (lhs && lhs.k !== 'var' && lhs.k !== 'call' && !(lhs.k === 'pow' && lhs.b.k === 'var') && !(lhs.k === 'fact' && lhs.e.k === 'var')) this.warn(eq.line, 'matho-lhs', `The left side ${describeExpr(lhs)} is an expression, not a name, so the function is called ${fnName}.`); + if (this.defs.has(fnName)) { let n = 2; while (this.defs.has(`${fnName}_${n}`)) n++; fnName = `${fnName}_${n}`; } + + // --- parameters: explicit first, then the free names of the right side + const params: Param[] = []; + const byKey = new Map(); + const bound = new Set(); // index names bound by sums in scope while walking + const indexNames = new Set(); // every index letter in this equation (sums + lhs index) + collectIndices(rhs, indexNames); + if (lhsIndex) indexNames.add(lhsIndex.name); + const add = (v: Extract, role: 'index' | 'bound' | 'plain'): Param => { + const indexSub = !!v.sub && isIndexExpr(v.sub, indexNames); + const key = varKey(v, indexSub); + let p = byKey.get(key); + if (!p) { + p = { key, name: pseudoName(v, indexSub), type: 'FLOAT', roles: new Set() }; + let n = 2; const base = p.name; while ([...byKey.values()].some((q) => q.name === p!.name) || p.name.toUpperCase() === fnName) p.name = `${base}${n++}`; + if (p.name !== base) this.note(eq.line, 'matho-case', `${describeExpr(v)} and ${p.name.toUpperCase() === fnName || base.toUpperCase() === fnName ? `the function ${fnName}` : base} are different symbols in mathematics but would be the same name in pseudo, so ${describeExpr(v)} became ${p.name}.`); + byKey.set(key, p); params.push(p); + } + p.roles.add(role); + if (indexSub && v.sub) p.roles.add(subDepth(v.sub) === 2 ? 'matrix' : 'list'); + if (isVector(v)) p.roles.add('vector'); + return p; + }; + if (lhsIndex) { const p = add(lhsIndex, 'index'); p.type = 'INTEGER'; } + for (const a of explicit) add(a, 'plain'); + const walk = (e: Expr, inBound: boolean, inIndex: boolean): void => { + switch (e.k) { + case 'var': + if (bound.has(e.name) && !e.sub && !e.decor) return; + if (e.name === 'e' && !e.sub && !e.decor) { /* Euler's e on its own is a name; a note is given at emit time */ } + if (this.defs.has(functionName(e)) && !e.sub) { // a reference to an earlier equation: its parameters join ours + const d = this.defs.get(functionName(e))!; + for (const q of d.params) { const p = byKey.get(q.key) ?? (byKey.set(q.key, { ...q, roles: new Set(q.roles) }).get(q.key)!); if (!params.includes(p)) params.push(p); } + return; + } + add(e, inBound ? 'bound' : inIndex ? 'index' : 'plain'); + if (e.sub) walk(e.sub, false, true); + return; + case 'num': case 'pi': return; + case 'bin': if (e.op === 'mod') { walk(e.l, true, false); walk(e.r, true, false); return; } walk(e.l, inBound, inIndex); walk(e.r, inBound, inIndex); return; + case 'dot': walk(e.l, false, false); walk(e.r, false, false); return; + case 'fact': walk(e.e, true, false); return; + case 'neg': case 'abs': case 'norm': case 'floor': case 'ceil': walk(e.e, inBound, inIndex); return; + case 'sqrt': walk(e.e, false, false); if (e.n) walk(e.n, true, false); return; + case 'pow': walk(e.b, inBound, inIndex); walk(e.e, inBound, inIndex); return; + case 'call': + if (this.defs.has(functionName({ k: 'var', name: e.fn, decor: null, sub: null, subText: null, pos: e.pos }))) { + const d = this.defs.get(functionName({ k: 'var', name: e.fn, decor: null, sub: null, subText: null, pos: e.pos }))!; + // explicit arguments cover the first parameters; the rest join ours + for (const q of d.params.slice(e.args.length)) { const p = byKey.get(q.key) ?? (byKey.set(q.key, { ...q, roles: new Set(q.roles) }).get(q.key)!); if (!params.includes(p)) params.push(p); } + } + for (const a of e.args) walk(a, false, false); + return; + case 'binom': walk(e.n, true, false); walk(e.m, true, false); return; + case 'big': + if (e.lo) walk(e.lo, true, false); + if (e.hi) walk(e.hi, true, false); + if (e.over) { if (e.over.k === 'var' && !e.over.sub) add(e.over, 'plain').roles.add('vector'); else walk(e.over, false, false); } + { const was = bound.has(e.idx); bound.add(e.idx); walk(e.body, false, false); if (!was) bound.delete(e.idx); } + return; + case 'cases': + for (const a of e.arms) { walk(a.value, false, false); if (a.cond) walkCond(a.cond); } + return; + } + }; + const walkCond = (c: Cond): void => { if (c.k === 'cmp') { walk(c.l, false, false); walk(c.r, false, false); } else if (c.k === 'not') walkCond(c.c); else { walkCond(c.l); walkCond(c.r); } }; + walk(rhs, false, false); + + // --- types from roles + for (const p of params) { + if (p.roles.has('matrix')) p.type = 'LIST OF LIST OF FLOAT'; + else if (p.roles.has('list') || p.roles.has('vector')) p.type = 'LIST OF FLOAT'; + else if (p.roles.has('index') || p.roles.has('bound')) p.type = 'INTEGER'; + else if (p.type !== 'INTEGER') p.type = 'FLOAT'; + } + // the explicit arguments keep their order; anything else the right side needs is appended, with a note + const explicitKeys = new Set(explicit.map((a) => varKey(a, false))); + if (lhs?.k === 'call' && !lhsIsBuiltin) { + const extra = params.filter((p) => !explicitKeys.has(p.key) && !lhsIndex); + if (extra.length) this.note(eq.line, 'matho-extra-params', `${extra.map((p) => p.name).join(', ')} ${extra.length === 1 ? 'is' : 'are'} used on the right side but ${extra.length === 1 ? 'is not an argument' : 'are not arguments'} of ${describeExpr(lhs)}, so ${extra.length === 1 ? 'it became an extra parameter' : 'they became extra parameters'} of ${fnName}.`); + } + for (const p of params) { + if (p.type === 'LIST OF FLOAT' && p.roles.has('list')) this.note(eq.line, 'matho-list', `${p.name} is indexed, so it is a LIST OF FLOAT, and the subscript is a position in it.`); + if (p.type === 'LIST OF LIST OF FLOAT') this.note(eq.line, 'matho-matrix', `${p.name} has two indices, so it is a LIST OF LIST OF FLOAT: a list of rows.`); + if (p.type === 'INTEGER' && p.roles.has('bound') && !p.roles.has('index')) this.note(eq.line, 'matho-bound', `${p.name} counts something (it bounds a sum or product, or sits in a binomial coefficient), so it is an INTEGER.`); + } + + // --- emit + const ctx: EmitCtx = { params: byKey, indexNames, defs: this.defs, decls: [], used: new Set(params.map((p) => p.name)), shifts: new Map(), shifted: new Set(), notes: [], line: eq.line, bound: new Map(), loopDepth: 0, hoisted: new Map(), prelude: [] }; + if (lhsIndex) ctx.bound.set(lhsIndex.name, byKey.get(varKey(lhsIndex, false))!.name); + const body: string[] = []; + let ret: string[] = []; + if (rhs.k === 'cases') { + ret = this.emitCases(rhs, ctx, body, 1); + } else { + const expr = emitExpr(rhs, ctx, body, 1); + ret = [` RETURN ${expr}`]; + } + const head = `FUNCTION ${fnName}(${params.map((p) => `${p.name} : ${p.type}`).join(', ')}) RETURNS FLOAT`; + this.lines.push(`// ${eq.source.replace(/\s+/g, ' ').trim()}`); + this.lines.push(head); + for (const d of ctx.decls) this.lines.push(` DECLARE ${d.name} : ${d.type}`); + this.lines.push(...ctx.prelude, ...body, ...ret, 'ENDFUNCTION', ''); + for (const n of ctx.notes) this.note(eq.line, n.id, n.message); + this.defs.set(fnName, { key: fnName, fnName, params }); + this.outDefs.push({ name: fnName, params: params.map((p) => ({ name: p.name, type: p.type })), line: eq.line }); + } + + private emitCases(e: Extract, ctx: EmitCtx, out: string[], indent: number): string[] { + const pad = ' '.repeat(indent); + const lines: string[] = []; + e.arms.forEach((arm, i) => { + const last = i === e.arms.length - 1; + if (!last) { + const cond = emitCond(arm.cond!, ctx, out, indent); + lines.push(`${pad}${i === 0 ? 'IF' : 'ELSEIF'} ${cond} THEN`); + } else lines.push(`${pad}ELSE`); + const inner: string[] = []; + const v = emitExpr(arm.value, ctx, inner, indent + 1); + lines.push(...inner, `${pad} RETURN ${v}`); + }); + lines.push(`${pad}ENDIF`); + return lines; + } +} + +interface EmitCtx { + params: Map; + indexNames: Set; + defs: Map; + decls: Array<{ name: string; type: string }>; + used: Set; + /** index letter → how many to subtract when it indexes a list (a sum from 1) */ + shifts: Map; + /** index letters whose shift was actually used on a subscript */ + shifted: Set; + notes: Array<{ id: string; message: string }>; + line: number; + /** index letter → its pseudo name, while in scope */ + bound: Map; + /** how many sum/product loops the emitter is inside */ + loopDepth: number; + /** calls of earlier equations that do not change inside a loop, computed once before it: call text → local name */ + hoisted: Map; + /** the lines that compute the hoisted values, placed before the body */ + prelude: string[]; +} + +function fresh(ctx: EmitCtx, base: string): string { + const taken = (x: string) => ctx.used.has(x) || RESERVED.has(x.toUpperCase()) || ctx.defs.has(x.toUpperCase()); + let name = base; + if (taken(name) && !taken(`${base}Val`)) name = `${base}Val`; + let n = 2; + while (taken(name)) name = `${base}${n++}`; + ctx.used.add(name); + return name; +} + +function mentionsSub(e: Expr, idx: string): boolean { + let found = false; + const w = (x: Expr): void => { + if (found) return; + switch (x.k) { + case 'var': if (x.sub && subMentions(x.sub, idx)) found = true; return; + case 'bin': case 'dot': w(x.l); w(x.r); return; + case 'neg': case 'abs': case 'norm': case 'floor': case 'ceil': case 'fact': w(x.e); return; + case 'sqrt': w(x.e); return; + case 'pow': w(x.b); w(x.e); return; + case 'call': x.args.forEach(w); return; + case 'binom': w(x.n); w(x.m); return; + case 'big': w(x.body); return; + case 'cases': x.arms.forEach((a) => w(a.value)); return; + default: return; + } + }; + w(e); + return found; +} + +function subMentions(sub: Expr, idx: string): boolean { + switch (sub.k) { + case 'var': return !sub.sub && sub.name === idx; + case 'bin': return subMentions(sub.l, idx) || subMentions(sub.r, idx); + case 'neg': return subMentions(sub.e, idx); + default: return false; + } +} + +function collectIndices(e: Expr, out: Set): void { + switch (e.k) { + case 'big': out.add(e.idx); collectIndices(e.body, out); if (e.lo) collectIndices(e.lo, out); if (e.hi) collectIndices(e.hi, out); return; + case 'bin': case 'dot': collectIndices(e.l, out); collectIndices(e.r, out); return; + case 'neg': case 'abs': case 'norm': case 'floor': case 'ceil': case 'fact': collectIndices(e.e, out); return; + case 'sqrt': collectIndices(e.e, out); return; + case 'pow': collectIndices(e.b, out); collectIndices(e.e, out); return; + case 'call': e.args.forEach((a) => collectIndices(a, out)); return; + case 'binom': collectIndices(e.n, out); collectIndices(e.m, out); return; + case 'cases': e.arms.forEach((a) => collectIndices(a.value, out)); return; + case 'var': if (e.sub) collectIndices(e.sub, out); return; + default: return; + } +} + +/** Is a subscript a position (built from index letters and numbers) rather than a label such as max or 0? */ +function isIndexExpr(e: Expr, indexNames: Set): boolean { + switch (e.k) { + case 'var': return !e.sub && !e.decor && indexNames.has(e.name); + case 'num': return false; + case 'bin': return (e.op === '+' || e.op === '-' || e.op === '*') && (isIndexExpr(e.l, indexNames) || isIndexExpr(e.r, indexNames)) && (isIndexExpr(e.l, indexNames) || e.l.k === 'num') && (isIndexExpr(e.r, indexNames) || e.r.k === 'num'); + case 'neg': return isIndexExpr(e.e, indexNames); + default: return false; + } +} + +/** `a_{ij}` is two indices when the subscript is two index letters juxtaposed. */ +function subDepth(sub: Expr): number { + if (sub.k === 'bin' && sub.op === '*' && sub.l.k === 'var' && sub.r.k === 'var' && !sub.l.sub && !sub.r.sub) return 2; + return 1; +} + +function describeExpr(e: Expr): string { + switch (e.k) { + case 'num': return e.v; + case 'var': return (e.decor ? `\\${e.decor}{${e.name}}` : e.name) + (e.subText ? `_{${e.subText}}` : e.sub ? '_{...}' : ''); + case 'call': return `${e.fn}(${e.args.map(describeExpr).join(', ')})`; + case 'pow': return `${describeExpr(e.b)}^{${describeExpr(e.e)}}`; + case 'bin': return `${describeExpr(e.l)} ${e.op} ${describeExpr(e.r)}`; + default: return `a ${e.k}`; + } +} + +const PREC: Record = { '+': 6, '-': 6, '*': 7, '/': 7, mod: 7, '^': 9 }; + +function emitExpr(e: Expr, ctx: EmitCtx, out: string[], indent: number): string { + const pad = ' '.repeat(indent); + const wrapIf = (s: string, child: Expr, parentPrec: number, right = false): string => { + if (child.k === 'bin') { const p = PREC[child.op]; if (p < parentPrec || (p === parentPrec && right)) return `(${s})`; } + if (child.k === 'neg' && parentPrec >= 7) return `(${s})`; + return s; + }; + switch (e.k) { + case 'num': return e.v; + case 'pi': return 'PI()'; + case 'var': { + if (!e.sub && !e.decor && ctx.bound.has(e.name)) return ctx.bound.get(e.name)!; + const fnName = functionName(e); + if (!e.sub && ctx.defs.has(fnName)) { const d = ctx.defs.get(fnName)!; return hoist(ctx, `${d.fnName}(${d.params.map((p) => ctx.params.get(p.key)?.name ?? p.name).join(', ')})`, pseudoName(e, false)); } + const indexSub = !!e.sub && isIndexExpr(e.sub, ctx.indexNames); + const p = ctx.params.get(varKey(e, indexSub)); + const name = p ? p.name : pseudoName(e, indexSub); + if (e.name === 'e' && !e.sub && !e.decor && !ctx.notes.some((n) => n.id === 'matho-euler')) ctx.notes.push({ id: 'matho-euler', message: 'A plain e is a name here (E), not Euler\'s number; write e^{x} for EXP(x), or EXP(1) for the constant.' }); + if (!indexSub || !e.sub) return name; + if (subDepth(e.sub) === 2 && e.sub.k === 'bin') return `${name}[${emitIndex(e.sub.l, ctx, out, indent)}][${emitIndex(e.sub.r, ctx, out, indent)}]`; + return `${name}[${emitIndex(e.sub, ctx, out, indent)}]`; + } + case 'bin': { + const p = PREC[e.op]; + const l = wrapIf(emitExpr(e.l, ctx, out, indent), e.l, p); + const r = wrapIf(emitExpr(e.r, ctx, out, indent), e.r, p, true); + return `${l} ${e.op === 'mod' ? 'MOD' : e.op} ${r}`; + } + case 'dot': return `DOT(${emitExpr(e.l, ctx, out, indent)}, ${emitExpr(e.r, ctx, out, indent)})`; + case 'neg': { const s = emitExpr(e.e, ctx, out, indent); return `-${e.e.k === 'bin' ? `(${s})` : s}`; } + case 'pow': { + const b = emitExpr(e.b, ctx, out, indent); + const x = emitExpr(e.e, ctx, out, indent); + const bs = e.b.k === 'bin' || e.b.k === 'neg' || e.b.k === 'pow' ? `(${b})` : b; + if (e.e.k === 'bin' && e.e.op === '/' && e.e.l.k === 'num' && e.e.l.v === '1' && e.e.r.k === 'num' && e.e.r.v === '2') return `SQRT(${b})`; + const xs = e.e.k === 'bin' || e.e.k === 'neg' ? `(${x})` : x; + return `${bs} ^ ${xs}`; + } + case 'call': { + const fnName = functionName({ k: 'var', name: e.fn, decor: null, sub: null, subText: null, pos: e.pos }); + if (ctx.defs.has(fnName)) { + const d = ctx.defs.get(fnName)!; + const args = e.args.map((a) => emitExpr(a, ctx, out, indent)); + const rest = d.params.slice(e.args.length).map((p) => ctx.params.get(p.key)?.name ?? p.name); + const text = `${d.fnName}(${[...args, ...rest].join(', ')})`; + const usesIndex = [...ctx.bound.values()].some((n) => new RegExp(`\\b${n}\\b`).test(args.join(','))); + return usesIndex ? text : hoist(ctx, text, baseWord(e.fn)); + } + if (e.fn === 'ATAN') return `ATAN2(${emitExpr(e.args[0], ctx, out, indent)}, 1)`; + return `${e.fn}(${e.args.map((a) => emitExpr(a, ctx, out, indent)).join(', ')})`; + } + case 'sqrt': { + const x = emitExpr(e.e, ctx, out, indent); + if (!e.n) return `SQRT(${x})`; + return `${e.e.k === 'bin' || e.e.k === 'neg' ? `(${x})` : x} ^ (1 / ${emitExpr(e.n, ctx, out, indent)})`; + } + case 'abs': return `ABS(${emitExpr(e.e, ctx, out, indent)})`; + case 'norm': return `NORM_OF(${emitExpr(e.e, ctx, out, indent)})`; + case 'floor': return `FLOOR(${emitExpr(e.e, ctx, out, indent)})`; + case 'ceil': return `CEIL(${emitExpr(e.e, ctx, out, indent)})`; + case 'binom': return `CHOOSE(${emitExpr(e.n, ctx, out, indent)}, ${emitExpr(e.m, ctx, out, indent)})`; + case 'fact': { + // n! as a product loop + const n = emitExpr(e.e, ctx, out, indent); + const acc = fresh(ctx, 'Factorial'); + const k = fresh(ctx, 'K'); + ctx.decls.push({ name: acc, type: 'FLOAT' }); + out.push(`${pad}${acc} <- 1.0`, `${pad}FOR ${k} <- 2 TO ${e.e.k === 'num' || e.e.k === 'var' ? n : `(${n})`} + 1`, `${pad} ${acc} <- ${acc} * ${k}`, `${pad}NEXT ${k}`); + if (!ctx.notes.some((x) => x.id === 'matho-factorial')) ctx.notes.push({ id: 'matho-factorial', message: `${describeExpr(e.e)}! became a product loop, ${acc}, run before the RETURN.` }); + return acc; + } + case 'big': { + const isSum = e.op === 'sum'; + const acc = fresh(ctx, isSum ? 'Total' : 'Product'); + ctx.decls.push({ name: acc, type: 'FLOAT' }); + const idxName = fresh(ctx, baseWord(e.idx)); + out.push(`${pad}${acc} <- ${isSum ? '0.0' : '1.0'}`); + const inner: string[] = []; + let shift = 0; + if (e.over) { + out.push(`${pad}FOR EACH ${idxName} IN ${emitExpr(e.over, ctx, out, indent)}`); + } else { + const lo = e.lo ? emitExpr(e.lo, ctx, out, indent) : '0'; + let hi: string; + if (!e.hi) { + // no upper bound: the length of the list the index walks + const list = listIndexedBy(e.body, e.idx, ctx); + if (!list) throw new ParseError(`\\${e.op}_{${e.idx}} has no upper bound and ${e.idx} indexes no list, so the reader cannot tell how many passes to make. Write \\${e.op}_{${e.idx}=0}^{n-1}.`, e.pos, 'matho-sum-bounds'); + hi = `LENGTH(${list})`; + ctx.notes.push({ id: 'matho-sum-length', message: `\\${e.op}_{${e.idx}} has no bounds, so the loop runs over every position of ${list}.` }); + } else hi = inclusiveToExclusive(e.hi, ctx, out, indent); + if (e.lo && e.lo.k === 'num' && e.lo.v === '1' && e.hi && (e.hi.k === 'var' || (e.hi.k === 'bin' && e.hi.op !== '-'))) shift = 1; + out.push(`${pad}FOR ${idxName} <- ${lo} TO ${hi}`); + } + const wasBound = ctx.bound.get(e.idx); + const wasShift = ctx.shifts.get(e.idx); + ctx.bound.set(e.idx, idxName); + if (shift) ctx.shifts.set(e.idx, shift); else ctx.shifts.delete(e.idx); + ctx.loopDepth++; + const body = emitExpr(e.body, ctx, inner, indent + 1); + ctx.loopDepth--; + if (shift && ctx.shifted.has(e.idx)) ctx.notes.push({ id: 'matho-one-based', message: `The ${isSum ? 'sum' : 'product'} runs from ${e.idx} = 1, and lists in pseudo start at position 0, so a subscript ${e.idx} became a position ${idxName} - 1.` }); + ctx.shifted.delete(e.idx); + if (wasBound === undefined) ctx.bound.delete(e.idx); else ctx.bound.set(e.idx, wasBound); + if (wasShift === undefined) ctx.shifts.delete(e.idx); else ctx.shifts.set(e.idx, wasShift); + const needsParens = e.body.k === 'bin' && (isSum ? e.body.op === '+' || e.body.op === '-' : e.body.op !== '*'); + out.push(...inner, `${pad} ${acc} <- ${acc} ${isSum ? '+' : '*'} ${needsParens ? `(${body})` : body}`, `${pad}NEXT ${idxName}`); + return acc; + } + case 'cases': throw new ParseError('\\begin{cases} can only be the whole right-hand side of an equation.', 0, 'matho-cases-place'); + } +} + +/** Inside a loop, a value that does not change from pass to pass is computed once, before the loop. */ +function hoist(ctx: EmitCtx, callText: string, nameHint: string): string { + if (ctx.loopDepth === 0) return callText; + const have = ctx.hoisted.get(callText); + if (have) return have; + const local = fresh(ctx, nameHint); + ctx.decls.push({ name: local, type: 'FLOAT' }); + ctx.prelude.push(` ${local} <- ${callText}`); + ctx.hoisted.set(callText, local); + ctx.notes.push({ id: 'matho-hoist', message: `${callText} does not change from one pass of the loop to the next, so it is computed once, as ${local}, before the loop.` }); + return local; +} + +/** A subscript as a list position, with the 1-based shift applied to bare index letters. */ +function emitIndex(e: Expr, ctx: EmitCtx, out: string[], indent: number): string { + const s = emitExpr(e, ctx, out, indent); + if (e.k === 'var' && !e.sub && ctx.shifts.get(e.name)) { ctx.shifted.add(e.name); return `${s} - ${ctx.shifts.get(e.name)}`; } + if (e.k === 'bin') { + // i+1 with a shift of 1 is just I + const shiftOf = (x: Expr): number => x.k === 'var' && !x.sub ? ctx.shifts.get(x.name) ?? 0 : 0; + const sh = shiftOf(e.l) || shiftOf(e.r); + if (sh) { + ctx.shifted.add(e.l.k === 'var' && shiftOf(e.l) ? e.l.name : (e.r as any).name); + if (e.op === '+' && e.r.k === 'num' && Number(e.r.v) === sh) return emitExpr(e.l, ctx, out, indent); + return `${s} - ${sh}`; + } + } + return s; +} + +/** The upper bound of a sum is inclusive; FOR ... TO is exclusive. `n-1` → N, `n` → N + 1, `5` → 6. */ +function inclusiveToExclusive(hi: Expr, ctx: EmitCtx, out: string[], indent: number): string { + if (hi.k === 'bin' && hi.op === '-' && hi.r.k === 'num' && hi.r.v === '1') return emitExpr(hi.l, ctx, out, indent); + if (hi.k === 'num' && /^\d+$/.test(hi.v)) return String(Number(hi.v) + 1); + const s = emitExpr(hi, ctx, out, indent); + return hi.k === 'bin' ? `${s} + 1` : `${s} + 1`; +} + +function listIndexedBy(body: Expr, idx: string, ctx: EmitCtx): string | null { + let found: string | null = null; + const w = (e: Expr): void => { + if (found) return; + switch (e.k) { + case 'var': if (e.sub && e.sub.k === 'var' && e.sub.name === idx) { const p = ctx.params.get(varKey(e, true)); found = p ? p.name : pseudoName(e, true); } return; + case 'bin': case 'dot': w(e.l); w(e.r); return; + case 'neg': case 'abs': case 'norm': case 'floor': case 'ceil': case 'fact': case 'sqrt': w(e.e); return; + case 'pow': w(e.b); w(e.e); return; + case 'call': e.args.forEach(w); return; + case 'big': w(e.body); return; + default: return; + } + }; + w(body); + return found; +} + +function emitCond(c: Cond, ctx: EmitCtx, out: string[], indent: number): string { + switch (c.k) { + case 'cmp': return `${emitExpr(c.l, ctx, out, indent)} ${c.op} ${emitExpr(c.r, ctx, out, indent)}`; + case 'and': return `${emitCond(c.l, ctx, out, indent)} AND ${emitCond(c.r, ctx, out, indent)}`; + case 'or': return `(${emitCond(c.l, ctx, out, indent)}) OR (${emitCond(c.r, ctx, out, indent)})`; + case 'not': return `NOT (${emitCond(c.c, ctx, out, indent)})`; + } +} + +/* ------------------------------------------------------------------ */ +/* Splitting a document into equations */ +/* ------------------------------------------------------------------ */ + +const WRAPPERS = /\\\[|\\\]|\\begin\{(?:equation|align|gather|eqnarray|math|displaymath)\*?\}|\\end\{(?:equation|align|gather|eqnarray|math|displaymath)\*?\}|\$\$|\\nonumber|\\notag/g; + +/** Lines that belong together: an equation continues while braces or a cases block are open, or the next line starts with an operator or `=`. */ +export function splitEquations(src: string): Array<{ line: number; text: string }> { + const lines = src.split('\n'); + const out: Array<{ line: number; text: string }> = []; + let cur: { line: number; text: string } | null = null; + let depth = 0; + let inCases = 0; + const flush = () => { if (cur && cur.text.trim()) out.push(cur); cur = null; }; + lines.forEach((raw, i) => { + let line = raw.replace(/%.*$/, '').replace(WRAPPERS, ' '); + if (!line.trim()) { if (depth <= 0 && inCases <= 0) flush(); return; } + // an unclosed brace keeps the equation open, unless the next line plainly starts a new one (a fresh `=` outside any cases) + const freshEquation = depth > 0 && inCases <= 0 && /^[^=&]*[A-Za-z}]\s*=/.test(line) && !/^\s*(?:&\s*)?=/.test(line); + const continues = !freshEquation && (depth > 0 || inCases > 0 || /^\s*(?:&\s*)?(?:=|\+|-|\\cdot|\\times)/.test(line) || (cur && /(?:=|\+|-|\\cdot|\\times|\\frac|\\left\(|\{)\s*$/.test(cur.text))); + if (freshEquation) depth = 0; + if (!continues) flush(); + if (inCases <= 0 && !/\\begin\{cases\}/.test(line)) line = line.replace(/&/g, ' '); // alignment marks outside cases + if (!cur) cur = { line: i + 1, text: line }; + else cur.text += '\n' + line; + for (const ch of line) { if (ch === '{') depth++; else if (ch === '}') depth--; } + inCases += (line.match(/\\begin\{cases\}/g) || []).length - (line.match(/\\end\{cases\}/g) || []).length; + }); + flush(); + // a trailing \\ ends an equation in align; drop it + for (const e of out) e.text = e.text.replace(/\\\\\s*$/, '').replace(/^\s*&/, ''); + return out; +} + +/* ------------------------------------------------------------------ */ +/* The service */ +/* ------------------------------------------------------------------ */ + +export function parseMatho(source: string): Parsed { + const diagnostics: Diagnostic[] = []; + const equations: Equation[] = []; + const known = new Set(); + for (const chunk of splitEquations(source)) { + const { toks, error } = tokenize(chunk.text); + if (error) diagnostics.push({ lang: 'matho', severity: 'error', id: 'matho-character', line: chunk.line, message: error }); + const p = new Parser(toks, known); + try { + const eq = p.equation(); + equations.push({ line: chunk.line, source: chunk.text, lhs: eq.lhs, rhs: eq.rhs }); + if (eq.lhs?.k === 'call') known.add(eq.lhs.fn); + if (eq.lhs?.k === 'var' && !eq.lhs.sub && !eq.lhs.decor && eq.lhs.name.length === 1) known.add(eq.lhs.name); + } catch (e: any) { + if (e instanceof ParseError) { + const before = chunk.text.slice(0, e.pos); + const line = chunk.line + (before.match(/\n/g) || []).length; + const col = before.length - before.lastIndexOf('\n'); + diagnostics.push({ lang: 'matho', severity: 'error', id: e.id, line, col, message: e.message, guide: e.id === 'matho-refused' ? 'matho-what-a-program-can-be' : undefined }); + } else throw e; + } + } + const low = new Lowerer(); + try { + low.lower(equations); + } catch (e: any) { + if (e instanceof ParseError) { + const eq = equations[Math.min(low.outDefs.length, equations.length - 1)]; + diagnostics.push({ lang: 'matho', severity: 'error', id: e.id, line: eq ? eq.line : 1, message: e.message }); + return { program: { equations, pseudo: '', lineMap: [], defs: [] }, diagnostics, ok: false }; + } + throw e; + } + diagnostics.push(...low.diagnostics); + const pseudo = low.lines.join('\n').replace(/\n+$/, '\n'); + // a translation that does not read as pseudo is a bug in the reader; surface it rather than hide it + const st = studyOf(pseudo); + for (const d of st.diagnostics.filter((x) => x.severity === 'error')) { + const k = low.lineMap[d.line - 1] ?? 0; + diagnostics.push({ lang: 'matho', severity: 'error', id: 'matho-pseudo', line: equations[k]?.line ?? 1, message: `The pseudo this became does not read (line ${d.line}: ${d.message}). The translation is too literal here; open the pseudo pane and finish it by hand.` }); + } + return { program: { equations, pseudo, lineMap: low.lineMap, defs: low.outDefs }, diagnostics, ok: !diagnostics.some((d) => d.severity === 'error') && equations.length > 0 }; +} + +export function lowerMatho(parsed: Parsed, target: string): Lowered | null { + const p = parsed.program; + if (!p || !p.pseudo || target !== 'pseudo') return null; + return { + target: 'pseudo', + source: p.pseudo, + map: p.lineMap.map((k, i) => ({ from: p.equations[k]?.line ?? 0, to: i + 1 })).filter((m) => m.from > 0), + notes: [], + }; +} + +/** A call that fits the last function: lists of four values, n = 4, indices 1, other numbers 2.0. */ +export function defaultCallMatho(parsed: Parsed): string | null { + const p = parsed.program; + if (!p || !p.defs.length) return null; + const d = p.defs[p.defs.length - 1]; + const sample = (q: { name: string; type: string }): string => { + if (q.type === 'LIST OF FLOAT') return '[1.0, 2.0, 3.0, 4.0]'; + if (q.type === 'LIST OF LIST OF FLOAT') return '[[1.0, 2.0], [3.0, 4.0]]'; + if (q.type === 'INTEGER') return /^(N|M|Len|Count)/.test(q.name) ? '4' : '1'; + return /^(X|T|P|Q|Prob|Theta|Alpha)\d*$/.test(q.name) ? '0.5' : '2.0'; + }; + // when a matrix is passed, its bounds are 2 + const hasMatrix = d.params.some((q) => q.type === 'LIST OF LIST OF FLOAT'); + return `${d.name}(${d.params.map((q) => (hasMatrix && q.type === 'INTEGER' ? '2' : sample(q))).join(', ')})`; +} + +export function runMatho(parsed: Parsed, options: RunOptions): Trace { + const low = lowerMatho(parsed, 'pseudo'); + if (!low) throw new Error('The equations do not translate yet; see the problems view.'); + const st = studyOf(low.source); + if (!st.ok) throw new Error('The pseudo these equations became has an error: ' + (st.diagnostics.find((d) => d.severity === 'error')?.message || '')); + const tr = runPseudo(st, { ...options, call: options.call ?? defaultCallMatho(parsed) ?? pseudoDefaultCall(st.program) }); + const toMatho = new Map(low.map.map((m) => [m.to, m.from])); + const hits = new Map(); + for (const [line, n] of tr.hits) { const e = toMatho.get(line); if (e) hits.set(e, (hits.get(e) || 0) + n); } + return { + ...tr, + lang: 'matho', + hits, + steps: tr.steps.map((s: any) => ({ ...s, pseudoLine: s.line, line: toMatho.get(s.line) ?? s.line })), + error: tr.error ? { ...tr.error, line: tr.error.line != null ? toMatho.get(tr.error.line) ?? tr.error.line : null } : null, + }; +} + +export function tokenizeMatho(line: string): Array<{ text: string; cls: string }> { + const out: Array<{ text: string; cls: string }> = []; + const re = /(%.*$)|(\\[A-Za-z]+|\\.)|(\d+(?:\.\d+)?)|([A-Za-z])|([{}])|(\s+)|(.)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(line))) { + const [text, c, cmd, n, w, br] = m; + let cls = ''; + if (c) cls = 'tok-comment'; + else if (cmd) cls = REFUSED[cmd.slice(1)] ? 'tok-error' : GREEK[cmd.slice(1)] ? 'tok-name' : 'tok-keyword'; + else if (n) cls = 'tok-number'; + else if (w) cls = 'tok-name'; + else if (br) cls = 'tok-punct'; + out.push({ text, cls }); + if (c) break; + } + return out; +} + +export const mathoService: LanguageService = { + id: 'matho', + name: 'matho', + parse: parseMatho, + run: runMatho, + lower: lowerMatho, + defaultCall: defaultCallMatho, + tokenize: tokenizeMatho, +}; diff --git a/src/services/mojo.ts b/src/services/mojo.ts new file mode 100644 index 0000000..81849f1 --- /dev/null +++ b/src/services/mojo.ts @@ -0,0 +1,32 @@ +/** + * The Mojo pane's language service: highlighting (src/mojo/tokenize), and what + * Programming+ can say before compiling (src/mojo/check: removed syntax, then + * the parser and the structure and name checks, each in the compiler's words, + * scored against godbolt in tests/mojo-check.test.mjs). Nothing runs here yet: + * Mojo runs on the real compiler through the Compile button (src/services/godbolt), + * and Programming+'s own stepping arrives with the interpreter in Stage 3. + */ +import type { LanguageService, Parsed } from '../core/types.js'; +import { tokenizeMojo, tokenizeMojoLine } from '../mojo/tokenize.js'; +import { checkMojo } from '../mojo/check.js'; +import type { Module } from '../mojo/parse.js'; + +export interface MojoProgram { source: string; module: Module } + +export function parseMojo(source: string): Parsed { + const { diagnostics, module } = checkMojo(source); + return { program: { source, module }, diagnostics, ok: !diagnostics.some((d) => d.severity === 'error') }; +} + +/** Whether the program reads standard input, which is when the input box is shown. */ +export function mojoReadsInput(source: string): boolean { + return /\binput\s*\(/.test(source.replace(/#.*$/gm, '')); +} + +export const mojoService: LanguageService = { + id: 'mojo', + name: 'Mojo', + parse: parseMojo, + tokenize: tokenizeMojoLine, + tokenizeLines: tokenizeMojo, +}; diff --git a/src/services/pseudo-study.ts b/src/services/pseudo-study.ts new file mode 100644 index 0000000..9f58d50 --- /dev/null +++ b/src/services/pseudo-study.ts @@ -0,0 +1,175 @@ +/** + * The app's reading of pseudo: the engine's `study()` (src/engines/pseudo/study.js), with one form added. + * + * DECLARE Total : INTEGER <- 0 + * + * declares a name and gives it its starting value on one line, the way Mojo writes `var total: Int = 0`. The + * two-line form (DECLARE, then an assignment) still reads as before. The engine's parser holds one statement per + * line and stays unchanged (AGENTS.md, rule 1), so this module does what `study()` does, in its order (parse, + * check, analyze, coach), with one step between parse and check: + * + * 1. Each line that is `DECLARE : <- ` has its `<- ` blanked out with spaces, so + * the engine parses a plain DECLARE and every column on the line stays where it was. + * 2. The value is parsed on its own (`parseExpression`), its positions moved onto that line, and an ordinary + * `Assign` is put right after the `Declare` in the tree. It carries `withDeclare: true`, and the `Declare` + * carries it as `init`, so a translator can write the pair as one line (pseudo-to-mojo does). + * + * From then on everything (the checker, the data flow, the coach, the interpreter, the verifier, the fuzzer, the + * translators) sees a DECLARE and an assignment on the same line, and the run shows the declaration and the + * value it starts with as two steps of that line. + */ +import { parse, parseExpression } from '../engines/pseudo/parse.js'; +import { check } from '../engines/pseudo/check.js'; +import { analyze } from '../engines/pseudo/analyze.js'; +import { coach } from '../engines/pseudo/coach.js'; + +const RANK: Record = { error: 0, warning: 1, note: 2 }; + +/** One `DECLARE x : T <- value` line, as found in the source. */ +export interface DeclareInit { + line: number; + /** The names before the colon, as written. */ + names: string[]; + /** 1-based columns: the arrow, and the first character of the value. */ + arrowCol: number; + valueCol: number; + /** The value's text, without a trailing comment. */ + value: string; +} + +/** Where a `//` comment starts on a line, outside any string or character literal (-1 if none). */ +function commentStart(line: string): number { + let quote: string | null = null; + for (let i = 0; i < line.length; i++) { + const c = line[i]; + if (quote) { if (c === '\\') i++; else if (c === quote) quote = null; continue; } + if (c === '"' || c === "'") quote = c; + else if (c === '/' && line[i + 1] === '/') return i; + } + return -1; +} + +/** The first `<-` on a line outside literals, before `end` (-1 if none). */ +function arrowAt(line: string, end: number): number { + let quote: string | null = null; + for (let i = 0; i < end; i++) { + const c = line[i]; + if (quote) { if (c === '\\') i++; else if (c === quote) quote = null; continue; } + if (c === '"' || c === "'") quote = c; + else if (c === '<' && line[i + 1] === '-') return i; + } + return -1; +} + +/** + * The `DECLARE ... : type <- value` lines of a source, and the source with each `<- value` blanked out. A DECLARE + * with an arrow and no colon before it is left as written: the engine already explains that one. + */ +export function splitDeclareInits(source: string): { source: string; inits: DeclareInit[] } { + const lines = String(source ?? '').replace(/\r\n?/g, '\n').split('\n'); + const inits: DeclareInit[] = []; + lines.forEach((text, i) => { + const head = /^(\s*)DECLARE\b/i.exec(text); + if (!head) return; + const cut = commentStart(text); + const end = cut < 0 ? text.length : cut; + const arrow = arrowAt(text, end); + if (arrow < 0) return; + const colon = text.indexOf(':', head[0].length); + if (colon < 0 || colon > arrow) return; + const names = text.slice(head[0].length, colon).split(',').map((n) => n.trim()).filter(Boolean); + const raw = text.slice(arrow + 2, end); + const lead = raw.length - raw.trimStart().length; + inits.push({ line: i + 1, names, arrowCol: arrow + 1, valueCol: arrow + 3 + lead, value: raw.trim() }); + lines[i] = text.slice(0, arrow) + ' '.repeat(end - arrow) + text.slice(end); + }); + return { source: lines.join('\n'), inits }; +} + +/** Move a parsed expression from line 1 of its own text onto `line`, starting at column `col`. */ +function place(node: any, line: number, col: number): void { + if (!node || typeof node !== 'object') return; + if (Array.isArray(node)) { for (const x of node) place(x, line, col); return; } + for (const [k, v] of Object.entries(node)) { + if (k === 'line' && typeof v === 'number') node.line = line; + else if ((k === 'col' || k.endsWith('Col')) && typeof v === 'number') node[k] = v + col - 1; + else if (k === 'end' && typeof v === 'number') node.end = v + col - 1; + else if (v && typeof v === 'object') place(v, line, col); + } +} + +/** Put `assign` right after the Declare on `line`, wherever in the tree that Declare sits. */ +function spliceAfterDeclare(node: any, line: number, make: (decl: any) => any, seen = new Set()): boolean { + if (!node || typeof node !== 'object' || seen.has(node)) return false; + seen.add(node); + if (Array.isArray(node)) { + const i = node.findIndex((s) => s && s.kind === 'Declare' && s.line === line); + if (i >= 0) { node.splice(i + 1, 0, make(node[i])); return true; } + return node.some((x) => spliceAfterDeclare(x, line, make, seen)); + } + return Object.values(node).some((v) => spliceAfterDeclare(v, line, make, seen)); +} + +const diag = (severity: string, code: string, line: number, col: number, message: string, extra: object = {}) => + ({ severity, code, line, col, message, ...extra }); + +/** + * What the engine's `study(source, options)` returns, for a source that may also declare and assign on one line. + * `source` is the source as written; `parsed` is the engine's parse of the blanked source, with the assignments + * put in. + */ +export function studyPseudo(source: string, options: { coach?: boolean; strict?: boolean } = {}): any { + const original = String(source ?? ''); + const { source: blanked, inits } = splitDeclareInits(original); + const parsed: any = parse(blanked); + const extra: any[] = []; + for (const it of inits) { + if (it.names.length !== 1) { + extra.push(diag('error', 'declare-init-names', it.line, it.arrowCol, `A DECLARE with a starting value names one variable, as in DECLARE ${it.names[0] || 'Total'} : INTEGER <- 0. Give ${it.names.slice(1).join(', ')} a line of its own.`, { guide: 'declaring' })); + continue; + } + if (!it.value) { + extra.push(diag('error', 'declare-init-empty', it.line, it.arrowCol, `The declaration of ${it.names[0]} has nothing on the right of its arrow. Write its starting value, as in DECLARE ${it.names[0]} : INTEGER <- 0, or leave the arrow off.`, { guide: 'declaring' })); + continue; + } + const p: any = parseExpression(it.value); + const errs = (p.diags as any[]).filter((d) => d.severity === 'error'); + if (errs.length || !p.expr) { + for (const d of errs.length ? errs : [diag('error', 'expected', 1, 1, 'The starting value is not an expression.')]) extra.push({ ...d, line: it.line, col: (d.col ?? 1) + it.valueCol - 1 }); + continue; + } + place(p.expr, it.line, it.valueCol); + const name = it.names[0]; + const nameCol = original.split('\n')[it.line - 1].indexOf(name) + 1; + spliceAfterDeclare(parsed.ast, it.line, (decl) => { + const assign = { kind: 'Assign', line: it.line, col: nameCol, target: { kind: 'Name', name, line: it.line, col: nameCol }, value: p.expr, withDeclare: true }; + decl.init = assign; + return assign; + }); + } + if (extra.length) parsed.diags = [...parsed.diags, ...extra].sort((a: any, b: any) => a.line - b.line || a.col - b.col); + + // from here on, exactly what study() does (src/engines/pseudo/study.js) + const { program, diags } = check(parsed); + const errors = diags.filter((d: any) => d.severity === 'error'); + let analysis = null; + let coached: any[] = []; + const structural = parsed.diags.some((d: any) => d.severity === 'error' && ['missing-closer', 'stray-closer', 'next-mismatch'].includes(d.code)); + if (!structural) { + try { + analysis = analyze(program); + if (options.coach !== false) coached = coach(program, analysis, options); + } catch (err) { + if (options.strict) throw err; + analysis = null; + } + } + const all = [...diags, ...coached].map(reword).sort((a: any, b: any) => a.line - b.line || RANK[a.severity] - RANK[b.severity] || (a.col || 0) - (b.col || 0)); + return { source: original, parsed, program, analysis, diags: all, errors: errors.map(reword), blanks: program.blanks, ok: errors.length === 0 }; +} + +/** The engine's advice that a declaration "gives no value" is out of date once one can: say what the form is. */ +function reword(d: any): any { + if (d.code === 'declare-assign') return { ...d, message: 'A declaration needs its type before a starting value: DECLARE Total : INTEGER <- 0, or DECLARE Total : INTEGER and then Total <- 0 on the next line.' }; + return d; +} diff --git a/src/services/pseudo.ts b/src/services/pseudo.ts new file mode 100644 index 0000000..2b835d6 --- /dev/null +++ b/src/services/pseudo.ts @@ -0,0 +1,192 @@ +/** + * The pseudocode service: wraps the course's parse/check/coach/interp/ + * translate/vcgen/testing modules behind the LanguageService interface. + * The engine modules are vendored unchanged under ../engines/pseudo. + */ +import { studyPseudo as study } from './pseudo-study.js'; +import { run as runProgram, evaluateConstant, valueFits } from '../engines/pseudo/interp.js'; +import { parseExpression, sourceOf } from '../engines/pseudo/parse.js'; +import { verify } from '../engines/pseudo/vcgen.js'; +import { checkProperties } from '../engines/pseudo/testing.js'; +import { typeName, PArray, formatValue, KEYWORDS, BUILTINS } from '../engines/pseudo/lang.js'; +import type { Diagnostic, LanguageService, Parsed, ProofReport, PropertyReport, RunOptions, Trace } from '../core/types.js'; + +/* The engine's own shapes, typed loosely: they are JavaScript. */ +export type Study = any; +export type PseudoState = any; +export type PseudoStep = any; + +export function toDiagnostic(d: any, lang: 'pseudo' | 'lingo' = 'pseudo'): Diagnostic { + const out: Diagnostic = { + lang, + severity: d.severity, + id: d.code || d.id || 'diag', + line: d.line ?? 1, + col: d.col ?? 1, + message: d.message, + }; + if (d.guide) out.guide = d.guide; + if (d.fix && d.fix.col != null) out.fix = { label: 'Fix', line: d.fix.line ?? d.line, col: d.fix.col, endCol: d.fix.endCol ?? null, text: d.fix.text }; + if (d.question?.options?.length) { + out.question = { + text: d.question.prompt || d.question.text || 'Which did you mean?', + options: d.question.options.map((o: any) => { + const r = o.replace || o.insert || {}; + return { label: o.label, line: r.line ?? d.line, col: r.col ?? d.col ?? 1, endCol: o.insert ? r.col ?? d.col ?? 1 : (r.endCol ?? null), text: r.text ?? '' }; + }), + }; + } + return out; +} + +export function studyOf(source: string): Parsed { + const s = study(source, { coach: true }); + return { program: s, diagnostics: s.diags.map((d: any) => toDiagnostic(d)), ok: s.ok }; +} + +function resolveCall(program: any, call: string) { + const p = parseExpression(call); + if (p.diags.some((d: any) => d.severity === 'error') || p.expr.kind !== 'CallExpr') throw new Error(`"${call}" is not a call. Write the subroutine's name and its arguments, as in COUNT_BASE('A', "GATTACA").`); + const sub = program.subs.get(p.expr.name.toUpperCase()); + if (!sub) throw new Error(`The program has no FUNCTION or PROCEDURE called ${p.expr.name}.`); + if (p.expr.args.length !== sub.params.length) throw new Error(`${sub.name} takes ${sub.params.length} value(s), and the call gives ${p.expr.args.length}.`); + const args = p.expr.args.map((a: any, i: number) => { + let v = evaluateConstant(program, a); + const t = sub.params[i].type; + if (t.k === 'ARRAY' && Array.isArray(v)) { const arr = new PArray([v.length]); arr.data = v; v = arr; } + if (t.k === 'SET' && Array.isArray(v)) v = new Set(v); + if (!valueFits(t, v)) throw new Error(`Parameter ${sub.params[i].name} of ${sub.name} is ${typeName(t)}, and the call gives ${sourceOf(a)}.`); + return v; + }); + return { name: sub.name, args, text: call }; +} + +export function defaultCall(s: Study): string | null { + const program = s?.program; + if (!program) return null; + if (program.main?.body?.length) return null; + const subs = [...program.subs.values()] as any[]; + const sub = subs.find((x) => x.kind === 'Function') || subs[0]; + if (!sub) return null; + const sample = (t: any): string => { + switch (t?.k) { + case 'STRING': return '"GATTACA"'; + case 'CHAR': return "'A'"; + case 'INTEGER': return '3'; + case 'FLOAT': return '0.5'; + case 'BOOL': return 'TRUE'; + case 'LIST': return t.of?.k === 'STRING' ? '["GATTACA", "GGC"]' : t.of?.k === 'FLOAT' ? '[0.5, 1.5]' : '[12, 30, 25, 8]'; + default: return '[]'; + } + }; + return `${sub.name}(${sub.params.map((p: any) => sample(p.type)).join(', ')})`; +} + +export function runPseudo(parsed: Parsed, options: RunOptions): Trace { + const s = parsed.program; + if (!s || !parsed.ok) throw new Error('The program has errors; fix them before running.'); + const text = options.call ?? defaultCall(s); + const call = text ? resolveCall(s.program, text) : null; + const tr = runProgram(s.program, { call, input: options.input || [], maxSteps: options.maxSteps ?? 20000, contracts: true, seed: 1 }); + const output = tr.output.slice(); + if (call && tr.result !== undefined && !tr.error) output.push(`${call.name} returned ${formatValue(tr.result)}`); + return { + lang: 'pseudo', + steps: tr.steps, + states: tr.states, + count: tr.count, + output, + error: tr.error ? { kind: tr.error.kind, message: tr.error.message, line: tr.error.line } : null, + truncated: !!tr.truncated, + hits: tr.hits, + raw: tr, + }; +} + +export function provePseudo(parsed: Parsed): ProofReport { + const s = parsed.program; + if (!s || !parsed.ok) return { units: [], counts: { proved: 0, broken: 0, open: 0, total: 0 } }; + const r = verify(s.program, { budgetMs: 3000 }); + // Cross-check unproved obligations against generated inputs: an obligation + // a run breaks is "broken", the rest stay "open". + const brokenKeys = new Set(); + for (const sub of s.program.subs.values()) { + try { + const pr = checkProperties(s.program, sub.name, { count: 150 }); + for (const f of pr.failures) brokenKeys.add(`${f.kind}@${f.line}`); + } catch { /* a subroutine whose parameters cannot be generated */ } + } + const units = r.units.map((u: any) => ({ + name: u.name, kind: u.kind, line: u.line, partial: !!u.partial, + inferred: (u.inferred || []).flatMap((x: any) => (typeof x === 'string' ? [x] : (x.facts || []).map((f: string) => `line ${x.line}: ${f}`))), + notes: (u.notes || []).map((n: any) => n.text || String(n)), + obligations: u.obligations.map((o: any) => { + const status: 'proved' | 'broken' | 'open' = o.status === 'proved' ? 'proved' : brokenKeys.has(`${kindKey(o.kind)}@${o.line}`) ? 'broken' : 'open'; + return { + kind: o.kind, label: o.label, line: o.line, col: o.col, paths: o.paths, + status: u.partial && status === 'proved' ? 'open' : status, + facts: o.shown?.facts || [], goal: o.shown?.goal || '', reason: o.shown?.reason, + }; + }), + })); + const all = units.flatMap((u: any) => u.obligations); + return { + units, + counts: { + proved: all.filter((o: any) => o.status === 'proved').length, + broken: all.filter((o: any) => o.status === 'broken').length, + open: all.filter((o: any) => o.status === 'open').length, + total: all.length, + }, + }; +} + +/** The verifier's obligation kinds vs. the runtime error kinds `checkProperties` reports. */ +function kindKey(k: string): string { + return ({ index: 'index', key: 'key', slice: 'index', divide: 'divide', require: 'require', ensure: 'ensure', assert: 'assert', 'invariant-init': 'invariant', 'invariant-keep': 'invariant', 'decreases-bound': 'decreases', 'decreases-step': 'decreases' } as Record)[k] || k; +} + +export function propertiesPseudo(parsed: Parsed, name?: string): PropertyReport[] { + const s = parsed.program; + if (!s || !parsed.ok) return []; + const subs = [...s.program.subs.values()] as any[]; + const targets = name ? subs.filter((x) => x.name.toUpperCase() === name.toUpperCase()) : subs; + return targets.map((sub) => { + const pr = checkProperties(s.program, sub.name, { count: 300 }); + return { + name: sub.name, checked: pr.checked, problem: pr.problem, + failures: pr.failures.map((f: any) => ({ call: f.call, message: f.message, line: f.line, kind: f.kind })), + }; + }); +} + +const KW = new Set(KEYWORDS as Iterable); +const BI = new Set(Object.keys(BUILTINS || {})); + +export function tokenizePseudo(line: string): Array<{ text: string; cls: string }> { + const out: Array<{ text: string; cls: string }> = []; + const re = /(\/\/.*$)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)?')|(\b\d+(?:\.\d+)?(?:e-?\d+)?\b)|(\b[A-Za-z_][A-Za-z0-9_]*\b)|(<-|==|!=|<=|>=|[-+*\/^&<>=()[\]{}:,.])|(\s+)|(.)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(line))) { + const [text, c, s, n, w, op] = m; + let cls = ''; + if (c) cls = 'tok-comment'; + else if (s) cls = 'tok-string'; + else if (n) cls = 'tok-number'; + else if (w) cls = KW.has(w) ? 'tok-keyword' : BI.has(w) ? 'tok-builtin' : /^[A-Z][A-Z0-9_]*$/.test(w) && KW.has(w.toUpperCase()) ? 'tok-keyword' : 'tok-name'; + else if (op) cls = 'tok-op'; + out.push({ text, cls }); + } + return out; +} + +export const pseudoService: LanguageService = { + id: 'pseudo', + name: 'pseudocode', + parse: studyOf, + run: runPseudo, + prove: provePseudo, + checkProperties: propertiesPseudo, + defaultCall: (p) => defaultCall(p.program), + tokenize: tokenizePseudo, +}; diff --git a/src/services/speco.ts b/src/services/speco.ts new file mode 100644 index 0000000..0e77127 --- /dev/null +++ b/src/services/speco.ts @@ -0,0 +1,413 @@ +/** + * speco: the specification language, as a standalone document. + * + * Today the course's contracts (REQUIRE, ENSURE, INVARIANT, DECREASES, + * ASSERT) can only live inside pseudocode. This service lets a student write + * them in their own pane, in math notation, and weaves them into the + * pseudocode before handing it to the verifier. It is the seam the review + * recommended: the spec is written before the algorithm, rendered as + * mathematics, and proved against whatever pseudocode is in the next pane. + * + * SPEC COUNT_BASE(B, T) + * ENSURE RESULT = |{ k ∈ [0, |T|) : T[k] = B }| + * LOOP FOR I + * INVARIANT Total = |{ k ∈ [0, I) : T[k] = B }| + * + * Math symbols are accepted and lowered to the notation's ASCII spelling: + * ∀ ∃ Σ ∈ ∧ ∨ ¬ ≤ ≥ ≠ = |…| → FORALL EXISTS SUM IN AND OR NOT <= >= != == LENGTH(…) + * and the reverse direction renders a pseudocode program's contracts as a + * speco document, so existing examples show up in the pane. + */ +import type { Diagnostic, LanguageService, Lowered, Parsed, ProofReport } from '../core/types.js'; +import { studyOf, provePseudo } from './pseudo.js'; +import { SPECO_SYMBOLS } from '../core/reference.js'; + +export interface SpecLoop { selector: string; /** 1-based line of the LOOP header in the speco source */ line?: number; lines: Array<{ kind: 'INVARIANT' | 'DECREASES'; text: string; line: number }> } +export interface SpecUnit { + name: string; + params: string[]; + line: number; + requires: Array<{ text: string; line: number }>; + ensures: Array<{ text: string; line: number }>; + decreases: { text: string; line: number } | null; + loops: SpecLoop[]; +} +export interface SpecDoc { units: SpecUnit[]; diagnostics: Diagnostic[] } + +/* ------------------------------------------------------------------ */ +/* Math notation <-> the notation's ASCII */ +/* ------------------------------------------------------------------ */ + +/** `|X|` → `LENGTH(X)`, with nesting. */ +function lowerBars(s: string): string { + // Treat | as an opening bar when the previous significant char is an operator or start, else closing. + let out = ''; + let open = 0; + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (ch !== '|') { out += ch; continue; } + const trimmed = out.replace(/\s+$/, ''); + const prev = trimmed.slice(-1); + const afterOperator = prev === '' || /[(\[{,:=<>+\-*\/^&]/.test(prev) || /\b(AND|OR|NOT|IN|FORALL|EXISTS|SUM)$/i.test(trimmed); + if (afterOperator || open === 0) { out += 'LENGTH('; open++; } + else { out += ')'; open--; } + } + while (open-- > 0) out += ')'; + return out; +} + +export function toAscii(expr: string): string { + let s = expr; + for (const sym of SPECO_SYMBOLS) { + if (sym.math.length !== 1 || sym.math === '=') continue; // single symbols; = and |X| and words are handled below + s = s.split(sym.math).join(` ${sym.ascii} `); + } + s = s.replace(/∑/g, ' SUM ').replace(/×/g, ' * ').replace(/÷/g, ' / ').replace(/→/g, ' -> '); + s = lowerBars(s); + s = s.replace(/\bresult\b/g, 'RESULT').replace(/([A-Za-z_]\w*)₀/g, 'OLD($1)'); + // a single = that is not part of ==, <=, >=, != becomes == + s = s.replace(/(^|[^=<>!])=(?!=)/g, '$1=='); + // a symbol written just inside a bracket, (∀ K ...), is padded like any other; the padding is not part of the claim + return s.replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').trim(); +} + +/** The notation's ASCII rendered as mathematics, for display. */ +export function toMath(expr: string): string { + let s = ' ' + expr + ' '; + // LENGTH(X) → |X|, matching the closing paren while skipping half-open ranges such as [0, N) + const closeOf = (text: string, open: number): number => { + const stack: string[] = []; + for (let j = open; j < text.length; j++) { + const ch = text[j]; + if (ch === '(' || ch === '[' || ch === '{') stack.push(ch); + else if (ch === ')' || ch === ']' || ch === '}') { + stack.pop(); + if (!stack.length) return j; + } + } + return -1; + }; + for (; ;) { + const i = s.search(/\bLENGTH\s*\(/); + if (i < 0) break; + const open = s.indexOf('(', i); + const j = closeOf(s, open); + if (j < 0) break; + s = s.slice(0, i) + '|' + s.slice(open + 1, j) + '|' + s.slice(j + 1); + } + for (const sym of SPECO_SYMBOLS) { + if (sym.math.length !== 1) continue; + s = sym.ascii.match(/^[A-Z]+$/) ? s.replace(new RegExp(`\\b${sym.ascii}\\b`, 'g'), sym.math) : s.split(sym.ascii).join(sym.math); + } + return s.replace(/\bRESULT\b/g, 'result').replace(/\bOLD\(([^)]*)\)/g, '$1₀').replace(/\s+/g, ' ').trim(); +} + +/* ------------------------------------------------------------------ */ +/* Parsing a speco document */ +/* ------------------------------------------------------------------ */ + +export function parseSpec(source: string): SpecDoc { + const units: SpecUnit[] = []; + const diagnostics: Diagnostic[] = []; + const lines = source.replace(/\r\n?/g, '\n').split('\n'); + let unit: SpecUnit | null = null; + let loop: SpecLoop | null = null; + const say = (line: number, message: string, id = 'spec') => diagnostics.push({ lang: 'speco', severity: 'error', id, line, col: 1, message }); + lines.forEach((raw, i) => { + const line = i + 1; + const text = raw.replace(/\/\/.*$/, '').trim(); + if (!text) return; + let m: RegExpExecArray | null; + if ((m = /^SPEC\s+([A-Za-z_]\w*)\s*(?:\(([^)]*)\))?\s*$/i.exec(text))) { + unit = { name: m[1].toUpperCase(), params: (m[2] || '').split(',').map((p) => p.trim().split(/\s*:\s*/)[0]).filter(Boolean), line, requires: [], ensures: [], decreases: null, loops: [] }; + units.push(unit); loop = null; return; + } + if (!unit) { say(line, 'A speco document starts with SPEC (), naming the routine these claims are about.', 'no-spec'); return; } + if ((m = /^LOOP\s+(.+)$/i.exec(text))) { loop = { selector: m[1].trim(), line, lines: [] }; unit.loops.push(loop); return; } + if ((m = /^(REQUIRE|ENSURE|INVARIANT|DECREASES|ASSERT)\s+(.+)$/i.exec(text))) { + const kind = m[1].toUpperCase(); + const body = toAscii(m[2]); + if (kind === 'REQUIRE') { if (loop) say(line, 'REQUIRE belongs to the routine, above any LOOP.'); else unit.requires.push({ text: body, line }); } + else if (kind === 'ENSURE') { if (loop) say(line, 'ENSURE belongs to the routine, above any LOOP.'); else unit.ensures.push({ text: body, line }); } + else if (kind === 'INVARIANT') { if (!loop) say(line, 'INVARIANT needs a LOOP line above it saying which loop it describes: LOOP FOR I, LOOP WHILE, or LOOP 1.'); else loop.lines.push({ kind: 'INVARIANT', text: body, line }); } + else if (kind === 'DECREASES') { if (loop) loop.lines.push({ kind: 'DECREASES', text: body, line }); else unit.decreases = { text: body, line }; } + else say(line, 'ASSERT lives in the pseudocode, at the line it is about; speco holds REQUIRE, ENSURE, INVARIANT and DECREASES.'); + return; + } + say(line, `Not a speco line. Each line is SPEC, LOOP, REQUIRE, ENSURE, INVARIANT or DECREASES followed by a claim.`, 'unknown-line'); + }); + return { units, diagnostics }; +} + +/* ------------------------------------------------------------------ */ +/* Weaving a spec into pseudocode, and extracting one back out */ +/* ------------------------------------------------------------------ */ + +export interface Woven { source: string; map: Array<{ from: number; to: number }>; diagnostics: Diagnostic[] } + +export interface WeaveOptions { + /** + * Replace mode: for each SPEC unit, the routine's existing REQUIRE / ENSURE / DECREASES and the INVARIANT / + * DECREASES of every loop the unit selects are removed first, so the pseudocode says what the speco says and + * nothing else about those routines and loops. Without it (the default, used by the proof view) the claims are + * only inserted, and what is already there is kept and never duplicated. + */ + replace?: boolean; +} + +/** The line index of the loop a `LOOP ` line names, among the loops of a routine, or -1. */ +function findLoop(lines: string[], loopLines: number[], selector: string): number { + let m: RegExpExecArray | null; + if ((m = /^(\d+)$/.exec(selector))) return loopLines[Number(m[1]) - 1] ?? -1; + if ((m = /^FOR\s+EACH\s+(\w+)/i.exec(selector))) return loopLines.find((i) => new RegExp(`^\\s*FOR\\s+EACH\\s+${m![1]}\\b`, 'i').test(lines[i])) ?? -1; + if ((m = /^FOR\s+(\w+)/i.exec(selector))) return loopLines.find((i) => new RegExp(`^\\s*FOR\\s+${m![1]}\\b`, 'i').test(lines[i])) ?? -1; + if (/^WHILE/i.test(selector)) return loopLines.find((i) => /^\s*WHILE\b/i.test(lines[i])) ?? -1; + if (/^REPEAT/i.test(selector)) return loopLines.find((i) => /^\s*REPEAT\b/i.test(lines[i])) ?? -1; + return -1; +} + +/** Where a routine starts and ends, and where its loops are, in a program's lines. */ +function locate(lines: string[], name: string): { head: number; end: number; loops: number[] } | null { + const head = lines.findIndex((l) => new RegExp(`^\\s*(FUNCTION|PROCEDURE)\\s+${name}\\b`, 'i').test(l)); + if (head < 0) return null; + let end = lines.length; + for (let i = head + 1; i < lines.length; i++) if (/^\s*(ENDFUNCTION|ENDPROCEDURE)\b/i.test(lines[i])) { end = i; break; } + const loops: number[] = []; + for (let i = head + 1; i < end; i++) if (/^\s*(FOR|WHILE|REPEAT)\b/i.test(lines[i])) loops.push(i); + return { head, end, loops }; +} + +/** Insert the spec's claims into the pseudocode under the routines and loops they name (or, in replace mode, put them in place of what is there). */ +export function weave(pseudo: string, spec: SpecDoc, options: WeaveOptions = {}): Woven { + let lines = pseudo.replace(/\r\n?/g, '\n').split('\n'); + const diagnostics: Diagnostic[] = []; + const inserts: Array<{ after: number; text: string; from: number }> = []; + if (options.replace) { + // Remove first, against the original lines, so the indices the insertions use are those of the program that is left. + const drop = new Set(); + for (const u of spec.units) { + const at = locate(lines, u.name); + if (!at) continue; + for (let i = at.head + 1; i < at.end && /^\s*(REQUIRE|ENSURE|DECREASES)\b/i.test(lines[i]); i++) drop.add(i); + for (const lp of u.loops) { + const target = findLoop(lines, at.loops, lp.selector); + if (target < 0) continue; + for (let i = target + 1; i < at.end && /^\s*(INVARIANT|DECREASES)\b/i.test(lines[i]); i++) drop.add(i); + } + } + lines = lines.filter((_, i) => !drop.has(i)); + } + for (const u of spec.units) { + const at = locate(lines, u.name); + if (!at) { diagnostics.push({ lang: 'speco', severity: 'error', id: 'no-routine', line: u.line, col: 1, message: `The pseudocode has no FUNCTION or PROCEDURE called ${u.name}.` }); continue; } + const { head, end } = at; + const indent = (lines[head].match(/^\s*/)?.[0].length ?? 0) + 4; + const norm = (t: string) => t.replace(/\s+/g, '').toUpperCase(); + const has = (from: number, to: number, kind: string, text: string) => { + for (let i = from; i < to; i++) { const m = new RegExp(`^\\s*${kind}\\s+(.+)$`, 'i').exec(lines[i]); if (m && norm(m[1]) === norm(text)) return true; } + return false; + }; + // existing contracts directly under the header keep their order: REQUIRE, then ENSURE + let afterReq = head; let afterEns = head; + for (let i = head + 1; i < end; i++) { + if (/^\s*REQUIRE\b/i.test(lines[i])) { afterReq = i; afterEns = i; } + else if (/^\s*ENSURE\b/i.test(lines[i])) afterEns = i; + else if (/^\s*DECREASES\b/i.test(lines[i])) afterEns = i; + else break; + } + for (const r of u.requires) if (!has(head, end, 'REQUIRE', r.text)) inserts.push({ after: afterReq, text: ' '.repeat(indent) + 'REQUIRE ' + r.text, from: r.line }); + for (const e of u.ensures) if (!has(head, end, 'ENSURE', e.text)) inserts.push({ after: afterEns, text: ' '.repeat(indent) + 'ENSURE ' + e.text, from: e.line }); + if (u.decreases && !has(head, afterEns + 1, 'DECREASES', u.decreases.text)) inserts.push({ after: afterEns, text: ' '.repeat(indent) + 'DECREASES ' + u.decreases.text, from: u.decreases.line }); + // loops + for (const lp of u.loops) { + const target = findLoop(lines, at.loops, lp.selector); + if (target < 0) { diagnostics.push({ lang: 'speco', severity: 'error', id: 'no-loop', line: lp.line ?? lp.lines[0]?.line ?? u.line, col: 1, message: `${u.name} has no loop matching "LOOP ${lp.selector}". Write LOOP FOR I, LOOP WHILE, or LOOP for the n-th loop.` }); continue; } + const li = (lines[target].match(/^\s*/)?.[0].length ?? 0) + 4; + // existing INVARIANT lines, then an existing DECREASES, directly under the loop header + let afterInv = target; let hasDec = -1; + for (let i = target + 1; i < end; i++) { + if (/^\s*INVARIANT\b/i.test(lines[i])) afterInv = i; + else if (/^\s*DECREASES\b/i.test(lines[i])) { hasDec = i; break; } + else break; + } + const invs = lp.lines.filter((l) => l.kind === 'INVARIANT' && !has(target, hasDec >= 0 ? hasDec : afterInv + 1, 'INVARIANT', l.text)); + const decs = lp.lines.filter((l) => l.kind === 'DECREASES'); + for (const l of invs) inserts.push({ after: afterInv, text: ' '.repeat(li) + 'INVARIANT ' + l.text, from: l.line }); + for (const l of decs) { + if (hasDec >= 0) { if (norm(lines[hasDec].replace(/^\s*DECREASES\s+/i, '')) !== norm(l.text)) diagnostics.push({ lang: 'speco', severity: 'warning', id: 'decreases-twice', line: l.line, col: 1, message: `This loop already has DECREASES in the pseudocode; the speco line is ignored.` }); continue; } + inserts.push({ after: afterInv, text: ' '.repeat(li) + 'DECREASES ' + l.text, from: l.line }); + } + } + } + // apply bottom-up so indices stay valid; keep insertion order among equal anchors + inserts.sort((a, b) => b.after - a.after); + const out = lines.slice(); + const origin: Array = lines.map(() => null); + let i = 0; + while (i < inserts.length) { + let j = i; + while (j < inserts.length && inserts[j].after === inserts[i].after) j++; + const group = inserts.slice(i, j); // same anchor, in document order + out.splice(inserts[i].after + 1, 0, ...group.map((g) => g.text)); + origin.splice(inserts[i].after + 1, 0, ...group.map((g) => g.from)); + i = j; + } + const map = origin.map((from, idx) => (from ? { from, to: idx + 1 } : null)).filter((x): x is { from: number; to: number } => !!x); + return { source: out.join('\n'), map, diagnostics }; +} + +/** The contracts already inside a pseudocode program, as a speco document. */ +export function extractSpec(pseudo: string): string { + const lines = pseudo.replace(/\r\n?/g, '\n').split('\n'); + const out: string[] = []; + let inUnit = false; + let loopIndex = 0; + let pendingLoop: string | null = null; + for (const raw of lines) { + const t = raw.trim(); + let m: RegExpExecArray | null; + if ((m = /^(FUNCTION|PROCEDURE)\s+([A-Za-z_]\w*)\s*(?:\(([^)]*)\))?/i.exec(t))) { + if (inUnit && out[out.length - 1] !== '') out.push(''); + const params = (m[3] || '').split(',').map((p) => p.trim().replace(/^BY(REF|VAL)\s+/i, '').split(/\s*:\s*/)[0]).filter(Boolean); + out.push(`SPEC ${m[2].toUpperCase()}(${params.join(', ')})`); + inUnit = true; loopIndex = 0; pendingLoop = null; continue; + } + if (!inUnit) continue; + if (/^(ENDFUNCTION|ENDPROCEDURE)\b/i.test(t)) { inUnit = false; continue; } + if ((m = /^FOR\s+EACH\s+(\w+)/i.exec(t))) { loopIndex++; pendingLoop = `FOR EACH ${m[1]}`; continue; } + if ((m = /^FOR\s+(\w+)/i.exec(t))) { loopIndex++; pendingLoop = `FOR ${m[1]}`; continue; } + if (/^WHILE\b/i.test(t)) { loopIndex++; pendingLoop = loopIndex === 1 ? 'WHILE' : String(loopIndex); continue; } + if (/^REPEAT\b/i.test(t)) { loopIndex++; pendingLoop = loopIndex === 1 ? 'REPEAT' : String(loopIndex); continue; } + if ((m = /^(REQUIRE|ENSURE)\s+(.+)$/i.exec(t))) { out.push(` ${m[1].toUpperCase()} ${toMath(m[2])}`); continue; } + if ((m = /^(INVARIANT|DECREASES)\s+(.+)$/i.exec(t))) { + if (pendingLoop) { out.push(` LOOP ${pendingLoop}`); pendingLoop = null; out.push(` ${m[1].toUpperCase()} ${toMath(m[2])}`); } + else if (out.length && /^\s{8}(INVARIANT|DECREASES)/.test(out[out.length - 1])) out.push(` ${m[1].toUpperCase()} ${toMath(m[2])}`); + else out.push(` ${m[1].toUpperCase()} ${toMath(m[2])}`); + continue; + } + if (t && !/^\/\//.test(t)) pendingLoop = pendingLoop && /^(INVARIANT|DECREASES)/i.test(t) ? pendingLoop : null; + } + const text = out.join('\n').trim(); + // drop SPEC headers that gathered no claims + return text.split(/\n(?=SPEC )/).filter((block) => block.split('\n').length > 1).join('\n\n').trim(); +} + +/* ------------------------------------------------------------------ */ +/* Pseudo as the authority: the speco that follows it, orphans kept */ +/* ------------------------------------------------------------------ */ + +export interface Reconciled { source: string; diagnostics: Diagnostic[] } + +const KEPT = '// kept: '; + +/** + * The speco that follows a pseudocode program: `extractSpec(pseudo)`, plus every claim the previous speco made + * about a routine or loop the pseudocode no longer has. Those are kept (never dropped) under a `// kept:` + * comment that says why, and reported on their line in the speco returned. They stay until the routine or loop + * comes back (the claims then belong to it again, even when the pseudocode has not written them yet) or the + * student deletes them. A claim about something the pseudocode does have is the pseudocode's: changing or + * deleting a contract in the pseudocode changes the speco. + * + * Fixed point: `reconcileSpec(pseudo, reconcileSpec(pseudo, previous).source).source` is the same text. + */ +export function reconcileSpec(pseudo: string, previous: string): Reconciled { + const lines = pseudo.replace(/\r\n?/g, '\n').split('\n'); + const prev = parseSpec(previous); + const prevLines = previous.replace(/\r\n?/g, '\n').split('\n'); + const wasKept = (line: number | undefined) => line !== undefined && /^\s*\/\/ kept:/.test(prevLines[line - 2] ?? ''); + interface Row { t: string; note?: string } + const row = (t: string, note?: string): Row => ({ t, note }); + const fresh = extractSpec(pseudo); + const blocks: Array<{ name: string; rows: Row[] }> = fresh + ? fresh.split(/\n(?=SPEC )/).map((b) => ({ name: /^SPEC\s+(\w+)/.exec(b)![1].toUpperCase(), rows: b.split('\n').map((t) => row(t)) })) + : []; + const head = (u: SpecUnit): Row[] => { + const o = [row(`SPEC ${u.name}(${u.params.join(', ')})`)]; + for (const r of u.requires) o.push(row(` REQUIRE ${toMath(r.text)}`)); + for (const e of u.ensures) o.push(row(` ENSURE ${toMath(e.text)}`)); + if (u.decreases) o.push(row(` DECREASES ${toMath(u.decreases.text)}`)); + return o; + }; + const loopRows = (lp: SpecLoop): Row[] => [row(` LOOP ${lp.selector}`), ...lp.lines.map((l) => row(` ${l.kind} ${toMath(l.text)}`))]; + const orphans: Row[][] = []; + for (const u of prev.units) { + const at = locate(lines, u.name); + if (!at) { + const why = `The pseudocode has no FUNCTION or PROCEDURE called ${u.name}, so these claims have nothing to be about. They are kept here until it comes back.`; + const [first, ...rest] = [...head(u), ...u.loops.flatMap(loopRows)]; + orphans.push([row(`${KEPT}the pseudocode has no FUNCTION or PROCEDURE called ${u.name}`), { t: first.t, note: why }, ...rest]); + continue; + } + let block = blocks.find((b) => b.name === u.name); + if (!block) { + // no contracts in the pseudocode for it: they were deleted there, unless this spec was only waiting for the routine to return + // (or only a loop of it was: then the unit comes back with just that loop) + if (wasKept(u.line)) block = { name: u.name, rows: head(u) }; + else if (u.loops.some((lp) => wasKept(lp.line))) block = { name: u.name, rows: [row(`SPEC ${u.name}(${u.params.join(', ')})`)] }; + else continue; + blocks.push(block); + } + // the loops the pseudocode has, as the extracted block names them + const claimed = new Set(); + for (const r of block.rows) { const m = /^\s{4}LOOP (.+)$/.exec(r.t); if (m) claimed.add(findLoop(lines, at.loops, m[1].trim())); } + for (const lp of u.loops) { + const target = findLoop(lines, at.loops, lp.selector); + if (target < 0) { + const why = `${u.name} has no loop matching "LOOP ${lp.selector}", so these claims have nothing to be about. They are kept here until the loop comes back.`; + const [first, ...rest] = loopRows(lp); + block.rows.push(row(` ${KEPT}${u.name} has no loop matching "LOOP ${lp.selector}"`), { t: first.t, note: why }, ...rest); + } else if (!claimed.has(target) && wasKept(lp.line)) { + block.rows.push(...loopRows(lp)); + claimed.add(target); + } + } + } + const out: Row[] = []; + [...blocks.map((b) => b.rows), ...orphans].forEach((b, i) => { if (i) out.push(row('')); out.push(...b); }); + const diagnostics: Diagnostic[] = []; + out.forEach((r, i) => { if (r.note) diagnostics.push({ lang: 'speco', severity: 'warning', id: 'spec-orphan', line: i + 1, col: 1, message: r.note }); }); + return { source: out.map((r) => r.t).join('\n'), diagnostics }; +} + +/* ------------------------------------------------------------------ */ +/* The service */ +/* ------------------------------------------------------------------ */ + +export interface SpecoProgram { spec: SpecDoc; source: string } + +export function parseSpeco(source: string): Parsed { + const spec = parseSpec(source); + return { program: { spec, source }, diagnostics: spec.diagnostics, ok: spec.diagnostics.every((d) => d.severity !== 'error') }; +} + +/** Prove a pseudocode program against this spec. Obligation lines are reported in speco's numbering where a claim came from speco. */ +export function proveAgainst(parsed: Parsed, pseudo: string): { report: ProofReport; woven: Woven; study: Parsed } { + const woven = weave(pseudo, parsed.program!.spec); + const st = studyOf(woven.source); + const report = provePseudo(st); + const back = new Map(woven.map.map((m) => [m.to, m.from])); + for (const u of report.units) for (const o of u.obligations) { + const from = back.get(o.line); + (o as any).pseudoLine = o.line; + (o as any).specoLine = from ?? null; + } + return { report, woven, study: st }; +} + +export function tokenizeSpeco(line: string): Array<{ text: string; cls: string }> { + const out: Array<{ text: string; cls: string }> = []; + const re = /(\/\/.*$)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)?')|(\b\d+(?:\.\d+)?\b)|(\b(?:SPEC|LOOP|REQUIRE|ENSURE|INVARIANT|DECREASES|FORALL|EXISTS|SUM|IN|AND|OR|NOT|RESULT|OLD|LENGTH|SORTED|FOR|EACH|WHILE|REPEAT)\b)|([∀∃Σ∑∈∧∨¬≤≥≠|])|(\b[A-Za-z_]\w*\b)|(\s+)|(.)/g; + let m: RegExpExecArray | null; + while ((m = re.exec(line))) { + const [text, c, s, n, kw, sym, w] = m; + out.push({ text, cls: c ? 'tok-comment' : s ? 'tok-string' : n ? 'tok-number' : kw ? 'tok-keyword' : sym ? 'tok-op' : w ? 'tok-name' : '' }); + } + return out; +} + +export const specoService: LanguageService = { + id: 'speco', + name: 'speco', + parse: parseSpeco, + tokenize: tokenizeSpeco, +}; diff --git a/src/sync/compare.ts b/src/sync/compare.ts new file mode 100644 index 0000000..e3afb09 --- /dev/null +++ b/src/sync/compare.ts @@ -0,0 +1,48 @@ +/** + * Comparing what two programs print, by value rather than by text, for the + * tests that hold a translation to the program it came from (pseudo run vs. + * the generated Mojo run, pseudo vs. the pseudo that lingo or matho lowers + * to). DOM-free, and only the tests import it. + * + * The notation and Mojo print the same value differently: TRUE and True, a + * string with or without quotes, 3 and 3.0, a map's keys smallest first or in + * insertion order. `canonical` erases exactly those differences and no others. + */ +import { PArray, PRecord } from '../engines/pseudo/lang.js'; + +/** A value from the pseudo interpreter, as Mojo's print shows it. */ +export function formatAsMojo(v: any): string { + if (v === undefined || v === null) return 'None'; + if (typeof v === 'boolean') return v ? 'True' : 'False'; + if (typeof v === 'number') return Number.isInteger(v) ? String(v) : String(v); + if (typeof v === 'string') return v; + if (Array.isArray(v)) return `[${v.map(formatAsMojo).join(', ')}]`; + if (v instanceof PArray) { + if (v.dims.length === 2) { + const rows: string[] = []; + for (let r = 0; r < v.dims[0]; r++) rows.push(`[${v.data.slice(r * v.dims[1], (r + 1) * v.dims[1]).map(formatAsMojo).join(', ')}]`); + return `[${rows.join(', ')}]`; + } + return `[${v.data.map(formatAsMojo).join(', ')}]`; + } + if (v instanceof Set) return `{${[...v].map(formatAsMojo).join(', ')}}`; + if (v instanceof Map) return `{${[...v].map(([k, x]) => `${formatAsMojo(k)}: ${formatAsMojo(x)}`).join(', ')}}`; + if (v instanceof PRecord) return `${v.typeName}(${[...v.fields].map(([, x]) => formatAsMojo(x)).join(', ')})`; + return String(v); +} + +/** Text with the print differences between the notation and Mojo erased. */ +export function canonical(text: string): string { + return text + .replace(/\r/g, '') + .replace(/["']/g, '') + .replace(/\bTRUE\b/g, 'True') + .replace(/\bFALSE\b/g, 'False') + .replace(/\{([^{}[\]]*)\}/g, (_m, inner: string) => `{${inner.split(', ').sort().join(', ')}}`) + .replace(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/gi, (m) => String(Number(m))) + .split('\n').map((l) => l.trimEnd()).join('\n') + .trim(); +} + +/** Do two printed outputs say the same thing? */ +export function sameOutput(a: string, b: string): boolean { return canonical(a) === canonical(b); } diff --git a/src/sync/header.ts b/src/sync/header.ts new file mode 100644 index 0000000..d00be7c --- /dev/null +++ b/src/sync/header.ts @@ -0,0 +1,6 @@ +/** + * The first line of every generated Mojo source (restructure plan, section 2.4). It travels with the + * code, so copying the text out keeps the warning. It lives in its own module so the translator + * (which never applies best-practice rewrites) has no reason to mention them. + */ +export const GENERATED_HEADER = '# Generated by Programming+ from pseudo. Not reviewed for Mojo best practices.'; diff --git a/src/sync/hub.ts b/src/sync/hub.ts new file mode 100644 index 0000000..297d7ab --- /dev/null +++ b/src/sync/hub.ts @@ -0,0 +1,338 @@ +/** + * The sync hub (restructure plan, section 2.3). Pseudo is the hub: lingo and matho lower to it, lingo and + * matho are generated from it, contracts live in it and speco is the lens on them, and Mojo is produced from + * it and never the other way. The hub is pure: no DOM, no localStorage, a function of the texts it is given. + * + * The rules, each pinned by tests/sync-hub.test.mjs: + * 1. The pane you edit is the authority. An edit produces a new pseudo (directly, or by lowering) and the + * other linked panes are regenerated from it. The pane that was edited is never rewritten. + * 2. Contracts ride along. Lingo and matho cannot say them, so the speco is woven into the pseudo that an + * edit in English or equations produces; when the authority is speco, its contracts replace the pseudo's + * and lingo and matho (which ignore contracts) follow. + * 3. An authority with errors changes nothing: every other pane keeps its text and is marked stale. + * 4. A language that cannot say the program keeps its last text, marked stale with the reason. + * 5. Mojo comes only from pseudo, as a literal translation, and is computed here, not stored. + * 6. Opening a problem rewrites nothing: `fill` generates only the linked panes that are empty. + * 7. Line maps compose through the hub: `relate` answers "which lines of that pane match this line here". + */ +import type { Diagnostic, LangId } from '../core/types.js'; +import { readLingo, lowerLingo } from '../services/lingo.js'; +import { parseMatho, lowerMatho } from '../services/matho.js'; +import { studyOf, defaultCall } from '../services/pseudo.js'; +import { parseSpec, weave, extractSpec, reconcileSpec } from '../services/speco.js'; +import { pseudoToLingo } from './pseudo-to-lingo.js'; +import { pseudoToMatho } from './pseudo-to-matho.js'; +import { pseudoToMojo } from './pseudo-to-mojo.js'; +import type { LineMap, NameMap } from './types.js'; + +/** The four languages that are kept in step with each other. Mojo and x86-64 are not linked. */ +export const LINKED = ['lingo', 'matho', 'pseudo', 'speco'] as const; +export type Linked = (typeof LINKED)[number]; +export const isLinked = (l: string): l is Linked => (LINKED as readonly string[]).includes(l); + +/** What `PlayState.sync` holds: which pane the others follow, and why any pane is not in step. */ +export interface SyncInfo { + authority: Linked; + stale?: Partial>; + names?: NameMap; +} + +export type Sources = Partial>; + +/** Line maps, kept per pane. `up[l][i]` is the line of pane `l` that pseudo line `i+1` was lowered from; `down[l][i]` is the pseudo line that line `i+1` of pane `l` was generated from. */ +export interface HubMaps { + up: Partial>; + down: Partial>; +} + +export interface MojoDerived { source: string; map: LineMap; diagnostics: Diagnostic[] } + +export interface HubResult { + sources: Sources; + authority: Linked; + stale: Partial>; + names: NameMap; + maps: HubMaps; + /** The literal Mojo for the pseudo now in play. */ + mojo: MojoDerived; + /** Panes that changed text because of this edit (never the one that was edited). */ + changed: Linked[]; +} + +const nonBlank = (s: string | undefined): boolean => !!(s ?? '').trim(); +const firstError = (ds: Diagnostic[]): Diagnostic | undefined => ds.find((d) => d.severity === 'error'); +const reasonOf = (lang: Linked, d: Diagnostic | undefined): string => { + if (!d) return `${lang} does not read yet`; + const where = lang === 'speco' ? `${lang} line ${d.line} has a problem` : `${lang} line ${d.line} does not read yet`; + return `${where} (${d.message.replace(/\s+/g, ' ').trim()})`; +}; +const unsupportedReason = (lang: Linked, ds: Diagnostic[]): string => (ds[0]?.message ?? `${lang} has no form for this program`).replace(/\s+/g, ' ').trim(); + +/** A `{from,to}` list as a LineMap over `n` output lines. */ +function pairsToMap(pairs: Array<{ from: number; to: number }>, n: number): LineMap { + const out: LineMap = Array.from({ length: n }, () => null); + for (const p of pairs) if (p.to >= 1 && p.to <= n && p.from > 0) out[p.to - 1] = p.from; + return out; +} + +/** + * The student's spelling of equation names, so a round trip through pseudo restores `\overline{x}` rather than + * the default `\bar{x}`. Keyed by the pseudo name the reader gave the function. Only a bare name on the left + * side is recorded; a function written f(x, y) is spelled by the generator itself. + */ +export function namesFromMatho(source: string): NameMap { + const parsed = parseMatho(source); + const p = parsed.program; + const names: NameMap = {}; + if (!p) return names; + for (const def of p.defs) { + const eq = p.equations.find((e) => e.line === def.line); + if (!eq) continue; + const at = eq.source.indexOf('='); + const lhs = (at > 0 ? eq.source.slice(0, at) : '').trim(); + if (lhs && !lhs.includes('(') && /^\\|^[A-Za-z]/.test(lhs)) names[def.name.toUpperCase()] = lhs; + } + return names; +} + +/** Carry a map made against a program without contracts across a weave that inserted `inserted` lines (1-based, in the woven program). */ +function shiftUp(map: LineMap | undefined, inserted: Set, wovenLines: number): LineMap | undefined { + if (!map) return map; + const out: LineMap = []; + let k = 0; + for (let i = 1; i <= wovenLines; i++) out.push(inserted.has(i) ? null : (map[k++] ?? null)); + return out; +} + +export class SyncHub { + private sources: Sources; + private info: SyncInfo | undefined; + private maps: HubMaps = { up: {}, down: {} }; + private call: string | null; + + /** `sources` are the texts as the state holds them; `info` is what the state remembers of earlier edits. */ + constructor(sources: Sources, info?: SyncInfo, opts: { call?: string | null } = {}) { + this.sources = { ...sources }; + this.info = info ? { authority: info.authority, stale: { ...(info.stale ?? {}) }, names: { ...(info.names ?? {}) } } : undefined; + this.call = opts.call ?? null; + } + + /* ---------- opening: rule 6 ---------- */ + + /** + * The panes as they should be shown when a problem opens: what is written stays as written, and a linked pane + * that is empty is generated from the pseudo (which is itself lowered from the English or equations when it is + * missing). Nothing that has text is touched, so an authored exercise is shown exactly as its author wrote it. + */ + fill(): { sources: Sources; stale: Partial>; maps: HubMaps } { + const out: Sources = { ...this.sources }; + const stale: Partial> = {}; + const maps: HubMaps = { up: {}, down: {} }; + if (!nonBlank(out.pseudo)) { + const low = this.lowerOne('lingo', out.lingo) ?? this.lowerOne('matho', out.matho); + if (low && 'pseudo' in low) { out.pseudo = low.pseudo; maps.up[low.lang] = low.map; } + } + const P = out.pseudo ?? ''; + if (nonBlank(P)) { + if (!nonBlank(out.lingo)) { + const r = pseudoToLingo(P); + if ('unsupported' in r) stale.lingo = unsupportedReason('lingo', r.unsupported); + else { out.lingo = r.source; maps.down.lingo = r.map; } + } + if (!nonBlank(out.matho)) { + const r = this.generateMatho(P, namesFromMatho(out.matho ?? '')); + if ('unsupported' in r) stale.matho = unsupportedReason('matho', r.unsupported); + else { out.matho = r.source; maps.down.matho = r.map; } + } + if (!nonBlank(out.speco)) { + const s = extractSpec(P); + if (s) out.speco = s; + } + } + return { sources: out, stale, maps }; + } + + private lowerOne(lang: 'lingo' | 'matho', text: string | undefined): { lang: 'lingo' | 'matho'; pseudo: string; map: LineMap } | null { + if (!nonBlank(text)) return null; + if (lang === 'lingo') { + const parsed = readLingo(text!); + const low = parsed.ok ? lowerLingo(parsed, 'pseudo') : null; + return low ? { lang, pseudo: low.source, map: pairsToMap(low.map, low.source.split('\n').length) } : null; + } + const parsed = parseMatho(text!); + const low = parsed.ok ? lowerMatho(parsed, 'pseudo') : null; + return low ? { lang, pseudo: low.source, map: pairsToMap(low.map, low.source.split('\n').length) } : null; + } + + private generateMatho(P: string, names: NameMap) { + const merged = { ...(this.info?.names ?? {}), ...names }; + const r = pseudoToMatho(P, { names: merged }); + // a spelling that does not lower back to the function is not trusted; fall back to the default spelling + if ('unsupported' in r && Object.keys(merged).length) return pseudoToMatho(P); + return r; + } + + /* ---------- an edit: rules 1 to 5 ---------- */ + + edit(lang: Linked, text: string): HubResult { + const prior: Sources = { ...this.sources }; + const stale: Partial> = { ...(this.info?.stale ?? {}) }; + delete stale[lang]; + const names: NameMap = { ...(this.info?.names ?? {}) }; + this.sources[lang] = text; + this.info = { authority: lang, stale, names }; + // the maps of the authority are about to be remade; the others' stay until they are regenerated + delete this.maps.down[lang]; + delete this.maps.up[lang]; + + const others = LINKED.filter((l) => l !== lang); + const failWith = (reason: string): HubResult => { + for (const l of others) stale[l] = reason; + return this.result(prior); + }; + + // 1. the pseudo this edit comes to + let P: string; + let upMap: LineMap | undefined; + let specoMap: Array<{ from: number; to: number }> = []; + if (!nonBlank(text)) { + P = ''; + } else if (lang === 'pseudo') { + const st = studyOf(text); + if (!st.ok) return failWith(reasonOf('pseudo', firstError(st.diagnostics))); + P = text; + } else if (lang === 'lingo') { + const parsed = readLingo(text); + const low = parsed.ok ? lowerLingo(parsed, 'pseudo') : null; + if (!low) return failWith(reasonOf('lingo', firstError(parsed.diagnostics))); + P = low.source; upMap = pairsToMap(low.map, P.split('\n').length); + } else if (lang === 'matho') { + const parsed = parseMatho(text); + const low = parsed.ok ? lowerMatho(parsed, 'pseudo') : null; + if (!low) return failWith(reasonOf('matho', firstError(parsed.diagnostics))); + P = low.source; upMap = pairsToMap(low.map, P.split('\n').length); + const nm = namesFromMatho(text); + for (const k of Object.keys(names)) delete names[k]; + Object.assign(names, nm); + } else { + // speco: its contracts replace the pseudo's, in the pseudo the other panes follow + const spec = parseSpec(text); + const bad = firstError(spec.diagnostics); + if (bad) return failWith(reasonOf('speco', bad)); + const base = this.sources.pseudo ?? ''; + if (nonBlank(base)) { const w = weave(base, spec, { replace: true }); P = w.source; specoMap = w.map; } else P = base; + } + + // 2. contracts ride along: an English or equation edit weaves the speco into the pseudo it produced + if (lang === 'lingo' || lang === 'matho') { + const spec = nonBlank(this.sources.speco) ? parseSpec(this.sources.speco!) : null; + if (spec && !firstError(spec.diagnostics) && spec.units.length && nonBlank(P)) { + const w = weave(P, spec); + if (w.source !== P) { + const inserted = new Set(w.map.map((m) => m.to)); + upMap = shiftUp(upMap, inserted, w.source.split('\n').length); + P = w.source; + } + } + } + + // 3. regenerate the other panes from P + this.sources.pseudo = lang === 'pseudo' ? text : P; + if (lang !== 'pseudo') { delete stale.pseudo; } + if (upMap) this.maps.up[lang] = upMap; + if (lang === 'speco' && specoMap.length) this.maps.up.speco = pairsToMap(specoMap.map((m) => ({ from: m.to, to: m.from })), (text || '').split('\n').length); + const empty = !nonBlank(P); + if (lang !== 'lingo') { + if (empty) { this.sources.lingo = ''; delete stale.lingo; delete this.maps.down.lingo; } + else { + const r = pseudoToLingo(P); + if ('unsupported' in r) stale.lingo = unsupportedReason('lingo', r.unsupported); + else { this.sources.lingo = r.source; delete stale.lingo; this.maps.down.lingo = r.map; } + } + } + if (lang !== 'matho') { + if (empty) { this.sources.matho = ''; delete stale.matho; delete this.maps.down.matho; } + else { + const r = this.generateMatho(P, {}); + if ('unsupported' in r) stale.matho = unsupportedReason('matho', r.unsupported); + else { this.sources.matho = r.source; delete stale.matho; this.maps.down.matho = r.map; } + } + } + if (lang !== 'speco') { + // the contracts the pseudo holds, with every claim about something it no longer has kept (stage 7) + const r = reconcileSpec(P, this.sources.speco ?? ''); + this.sources.speco = r.source; + delete stale.speco; + } + delete this.maps.down.pseudo; + return this.result(prior); + } + + private result(prior: Sources): HubResult { + const stale = this.info!.stale ?? {}; + const P = this.sources.pseudo ?? ''; + const mojo = this.mojo(P); + if (!('unsupported' in mojo)) this.maps.down.mojo = mojo.map; else delete this.maps.down.mojo; + const changed = LINKED.filter((l) => l !== this.info!.authority && (this.sources[l] ?? '') !== (prior[l] ?? '')); + return { + sources: { ...this.sources }, authority: this.info!.authority, stale: { ...stale }, names: { ...(this.info!.names ?? {}) }, + maps: { up: { ...this.maps.up }, down: { ...this.maps.down } }, + mojo: mojoDerived(mojo), changed, + }; + } + + private mojo(P: string) { return nonBlank(P) ? pseudoToMojo(P, { call: callFor(P, this.call) }) : { source: '', map: [], notes: [] as Diagnostic[] }; } + + /* ---------- rule 7: line maps compose through the hub ---------- */ + + /** The lines of pane `to` that match line `line` of pane `from`, going through the pseudo. */ + static relate(maps: HubMaps, from: LangId, line: number, to: LangId): number[] { + if (from === to) return [line]; + const pseudoLines = toPseudoLines(maps, from, line); + if (to === 'pseudo') return pseudoLines; + const out = new Set(); + for (const p of pseudoLines) for (const l of fromPseudoLines(maps, to, p)) out.add(l); + return [...out].sort((a, b) => a - b); + } +} + +function mojoDerived(r: ReturnType | { source: string; map: LineMap; notes: Diagnostic[] }): MojoDerived { + return 'unsupported' in r ? { source: '', map: [], diagnostics: r.unsupported } : { source: r.source, map: r.map, diagnostics: r.notes }; +} + +/** Pseudo lines for a line of pane `from`. */ +function toPseudoLines(maps: HubMaps, from: LangId, line: number): number[] { + if (from === 'pseudo') return [line]; + if (from !== 'lingo' && from !== 'matho' && from !== 'speco' && from !== 'mojo') return []; + const out: number[] = []; + const up = from === 'mojo' ? undefined : maps.up[from]; + const down = maps.down[from]; + if (up) up.forEach((src, i) => { if (src === line) out.push(i + 1); }); + else if (down) { const p = down[line - 1]; if (p) out.push(p); } + return out; +} + +/** Lines of pane `to` that were made from, or lowered into, pseudo line `p`. */ +function fromPseudoLines(maps: HubMaps, to: LangId, p: number): number[] { + if (to === 'pseudo') return [p]; + if (to !== 'lingo' && to !== 'matho' && to !== 'speco' && to !== 'mojo') return []; + const out: number[] = []; + const down = maps.down[to]; + const up = to === 'mojo' ? undefined : maps.up[to]; + if (down) down.forEach((src, i) => { if (src === p) out.push(i + 1); }); + else if (up) { const s = up[p - 1]; if (s) out.push(s); } + return out; +} + +/** Literal Mojo for a pseudo program, for callers outside an edit (the session's memo). */ +export function mojoFromPseudo(pseudo: string, call: string | null): MojoDerived { + if (!nonBlank(pseudo)) return { source: '', map: [], diagnostics: [] }; + return mojoDerived(pseudoToMojo(pseudo, { call: callFor(pseudo, call) })); +} + +/** The call that becomes `main`: the one the student set, else the one the pseudo's own routines suggest. */ +function callFor(pseudo: string, call: string | null): string | null { + if (call && call.trim()) return call; + const st = studyOf(pseudo); + return st.program ? defaultCall(st.program) : null; +} diff --git a/src/sync/pseudo-to-lingo.ts b/src/sync/pseudo-to-lingo.ts new file mode 100644 index 0000000..73b3fb5 --- /dev/null +++ b/src/sync/pseudo-to-lingo.ts @@ -0,0 +1,543 @@ +/** + * Pseudo to lingo: the English steps a student could have written to get this pseudo. + * + * The generator writes only the sentence forms the reader (src/engines/pseudo/english.js, + * `readSteps`; the table is SENTENCE_FORMS) lowers back to the same program: + * + * FUNCTION COUNT_BASE(B, T) To count base for B and T: + * Total <- 0 Start with Total at 0. + * Total <- Total + 1 Add 1 to Total. + * FOR I <- 0 TO N For each i from 0 up to but not including N: + * FOR EACH C IN T For each letter c of T: + * IF ... ELSEIF ... ELSE If ...: / Otherwise, if ...: / Otherwise: + * RETURN V The answer is V. (Stop and answer V. when not last) + * + * It never writes English that reads as something else. Whatever the generator wrote is read + * back with `readSteps` before it is returned; if the reader does not accept it, or finds a + * different routine than the pseudo has, the answer is `unsupported`, with the reader's own + * message on the pseudo line it concerns. Anything without an English form (records, PARALLEL + * FOR, REPEAT, steps outside a routine, most built-ins) is `unsupported` too, one diagnostic + * per construct, naming it and its line. + * + * Contracts (REQUIRE, ENSURE, INVARIANT, DECREASES) are not in English; they ride along in + * speco (section 2.3 of the plan). `//` comments are carried across on their lines; the + * lowering strips them, so they are the one thing a round trip does not bring back. + */ +import { studyPseudo as study } from '../services/pseudo-study.js'; +import { readSteps } from '../engines/pseudo/english.js'; +import { walkStatements, walkExpr, statementExprs } from '../engines/pseudo/analyze.js'; +import { toDiagnostic } from '../services/pseudo.js'; +import type { Diagnostic } from '../core/types.js'; +import type { LineMap } from './types.js'; + +export interface LingoResult { source: string; map: LineMap; notes: Diagnostic[] } + +/** A construct English has no sentence for. Collected per statement; the generator goes on to find the rest. */ +class NoForm extends Error { + constructor(public what: string, public line: number) { super(what); } +} + +interface Line { text: string; from: number | null } + +/** A type as the reader's "X is a ..." sentence says it, or null when English has no words for it. */ +function kindWords(t: any): string | null { + const one: Record = { INTEGER: 'a whole number', FLOAT: 'a decimal number', BOOL: 'yes or no', CHAR: 'a letter', STRING: 'a text' }; + const many: Record = { INTEGER: 'whole numbers', FLOAT: 'decimal numbers', CHAR: 'letters', STRING: 'texts' }; + if (!t) return null; + if (one[t.k]) return one[t.k]; + if ((t.k === 'LIST' || t.k === 'ARRAY') && t.dims !== 2 && many[t.of?.k]) return `a list of ${many[t.of.k]}`; + return null; +} + +/** A type reduced to what has to agree between the pseudo's and the reader's idea of an input. */ +function typeKey(t: any): string { + if (!t || t.k === 'ANY') return 'ANY'; + if (t.k === 'LIST' || t.k === 'ARRAY') return `LIST<${typeKey(t.of)}>`; + if (t.k === 'SET') return `SET<${typeKey(t.of)}>`; + if (t.k === 'HASHMAP') return `MAP<${typeKey(t.key)},${typeKey(t.val)}>`; + if (t.k === 'LETTER') return 'CHAR'; + return t.k; +} + +const up = (s: unknown): string => String(s).toUpperCase(); + +/* Precedence levels, loosest first. Open phrases (ones that read an open-ended value after them) get their own level. */ +const OR = 0, AND = 1, NOT = 2, CMP = 3, ADD = 4, MUL = 5, NEG = 6, ATOM = 7; + +interface Text { s: string; p: number; open?: boolean } + +class Gen { + out: Line[] = []; + problems: Diagnostic[] = []; + notes: Diagnostic[] = []; + srcLines: string[]; + comments = new Map(); + usedComments = new Set(); + /** Lower-case names already introduced in the routine being written. */ + known = new Set(); + curLine = 1; + subs: Map; + + constructor(private program: any, private source: string, private withKinds = false) { + this.srcLines = source.split('\n'); + for (const c of program.comments || []) this.comments.set(c.line, c); + this.subs = program.subs; + } + + fail(what: string, line = this.curLine): never { throw new NoForm(what, line); } + unsupported(what: string, line: number): void { + this.problems.push({ lang: 'lingo', severity: 'warning', id: 'lingo-no-form', line, message: `English has no sentence for ${what}, so the lingo pane keeps its last good text.` }); + } + + /* ---------- names ---------- */ + /** A pseudo name as the words a student would write: Word_Count -> "Word Count". */ + nameText(n: string): string { return String(n).split('_').filter(Boolean).join(' '); } + + emit(indent: number, text: string, from: number | null): void { this.out.push({ text: `${' '.repeat(indent)}${text}`, from }); } + + leadingComments(line: number, indent: number): void { + for (const [l, c] of this.comments) { + if (l >= line || this.usedComments.has(l) || !c.standalone) continue; + this.usedComments.add(l); + this.emit(indent, `// ${c.text}`, l); + } + } + trailing(line: number): string { + const c = this.comments.get(line); + if (!c || c.standalone || this.usedComments.has(line)) return ''; + this.usedComments.add(line); + return ` // ${c.text}`; + } + + /* ---------- program ---------- */ + run(): LingoResult | null { + const p = this.program; + for (const c of p.constants.values()) this.unsupported('a CONSTANT', c.line); + for (const d of p.defines.values()) this.unsupported('a DEFINE set', d.line); + for (const t of p.types.values()) this.unsupported('a record type', t.node.line); + if (p.main.body.length) this.unsupported('steps outside a routine (every English step belongs to a routine)', p.main.body[0].line); + let first = true; + for (const sub of p.subs.values()) { + if (!first) this.emit(0, '', null); + first = false; + this.routine(sub); + } + this.leadingComments(Infinity, 0); + if (this.problems.length) return null; + while (this.out.length && !this.out[this.out.length - 1].text.trim()) this.out.pop(); + return { source: this.out.map((l) => l.text).join('\n') + '\n', map: this.out.map((l) => l.from), notes: this.notes }; + } + + routine(sub: any): void { + const s = sub.node; + this.curLine = s.line; + this.leadingComments(s.line, 0); + this.known = new Set(); + try { + const params = sub.params.map((p: any) => { + if (p.mode === 'BYREF') this.fail('a BYREF parameter', s.line); + if (!/^[A-Za-z]$/.test(p.name) && !/^[A-Z][a-z0-9]+$/.test(p.name)) this.fail(`the parameter ${p.name}, which English can only take as a single letter or a Capitalized word`, s.line); + this.known.add(p.name.toLowerCase()); + return p.name; + }); + const words = String(sub.name).split('_').filter(Boolean).map((w: string) => w.toLowerCase()); + if (!words.length) this.fail('a routine with no name', s.line); + const list = params.length > 1 ? `${params.slice(0, -1).join(', ')} and ${params[params.length - 1]}` : params[0]; + this.emit(0, `To ${words.join(' ')}${params.length ? ` for ${list}` : ''}:${this.trailing(s.line)}`, s.line); + } catch (e) { + if (!(e instanceof NoForm)) throw e; + this.unsupported(e.what, e.line); + return; + } + this.earlyInits(sub); + this.block(s.body, 1, { top: true, loops: 0 }, sub); + if (this.withKinds) this.kindLines(sub); + } + + /** + * English names a value where a step first gives it one, and the name is known only inside the block of + * that step. A value the pseudo declares up top, first sets inside a branch or loop, and uses outside it + * therefore gets a starting value at the top of the routine ("Start with Partner at ''."), so the later + * sentences can name it. It is the one place the English holds a value the pseudo leaves unset. + */ + earlyInits(sub: any): void { + const declared = new Map(); + walkStatements(sub.node.body, (st: any) => { + if (st.kind === 'Declare' && ['INTEGER', 'FLOAT', 'BOOL', 'STRING', 'CHAR'].includes(st.resolved?.k)) for (const n of st.names) declared.set(up(n.name), { type: st.resolved, line: st.line, name: n.name }); + return undefined; + }); + if (!declared.size) return; + const first = new Map(); // name -> the block path of its first assignment + const outside = new Set(); + const readsOf = (e: any, path: string) => walkExpr(e, (x: any) => { if (x.kind === 'Name') note(up(x.name), path); return undefined; }); + const note = (name: string, path: string) => { + const f = first.get(name); + if (f === undefined) return; + if (!path.startsWith(f)) outside.add(name); + }; + const visit = (body: any[], path: string) => { + body.forEach((st: any, i: number) => { + const here = `${path}/${i}`; + const inner = (b: any[], k: string) => visit(b, `${here}:${k}`); + for (const e of statementExprs(st)) readsOf(e, path); + if ((st.kind === 'Assign' || st.kind === 'Input') && st.target.kind === 'Name') { + const n = up(st.target.name); + if (declared.has(n) && !first.has(n)) first.set(n, path); + } + if (st.kind === 'If') { st.branches.forEach((b: any, k: number) => inner(b.body, `b${k}`)); if (st.elseBody) inner(st.elseBody, 'e'); } + else if (st.kind === 'Case') { st.arms.forEach((a: any, k: number) => inner(a.body, `a${k}`)); if (st.otherwise) inner(st.otherwise, 'o'); } + else if (['For', 'ForEach', 'While', 'Repeat'].includes(st.kind)) inner(st.body, 'l'); + }); + }; + visit(sub.node.body, 'r'); + for (const [name, at] of first) { + if (at === 'r' || !outside.has(name)) continue; + const info = declared.get(name)!; + const value = info.type.k === 'INTEGER' ? '0' : info.type.k === 'FLOAT' ? '0.0' : info.type.k === 'BOOL' ? 'false' : info.type.k === 'STRING' ? '""' : "' '"; + this.emit(1, `Start with ${this.nameText(info.name)} at ${value}.`, info.line); + this.notes.push({ lang: 'lingo', severity: 'note', id: 'lingo-early-start', line: info.line, message: `${info.name} is first set inside a branch or loop and used after it, and English can name a value only where a step first gives it one. The English starts it at ${value} at the top of the routine; the pseudo leaves it unset until then.` }); + this.known.add(String(info.name).toLowerCase()); + } + } + + /** "X is a whole number." after the routine: what each input is, when its steps do not settle it. */ + kindLines(sub: any): void { + const lines: string[] = []; + for (const p of sub.params) { + const k = kindWords(p.type); + if (!k) { this.unsupported(`the kind of the input ${p.name} (${p.type?.k})`, sub.node.line); return; } + const have = this.kindOf.get(String(p.name).toLowerCase()); + if (have && have !== k) { this.unsupported(`the input ${p.name}, which two routines give different kinds (English keeps one kind per name)`, sub.node.line); return; } + this.kindOf.set(String(p.name).toLowerCase(), k); + lines.push(`${p.name} is ${k}.`); + } + if (!lines.length) return; + this.emit(0, '', null); + for (const l of lines) this.emit(0, l, sub.node.line); + } + + kindOf = new Map(); + + block(body: any[], d: number, ctx: { top: boolean; loops: number }, sub: any): void { + const before = this.out.length; + body.forEach((st, i) => { + this.curLine = st.line ?? this.curLine; + this.leadingComments(st.line, d); + try { this.stmt(st, d, ctx, sub, i === body.length - 1); } catch (e) { + if (!(e instanceof NoForm)) throw e; + this.unsupported(e.what, e.line); + } + }); + void before; + } + + /* ---------- statements ---------- */ + stmt(s: any, d: number, ctx: { top: boolean; loops: number }, sub: any, last: boolean): void { + const tr = () => this.trailing(s.line); + const E = (e: any) => this.ex(e).s; + switch (s.kind) { + case 'Declare': { + const t = s.resolved; + for (const n of s.names) { + if (t.k === 'LIST' || t.k === 'ARRAY') { this.emit(d, `Start with an empty list called ${this.nameText(n.name)}.${tr()}`, s.line); if (t.k === 'ARRAY') this.fail('a fixed-length ARRAY', s.line); } + else if (t.k === 'SET') this.emit(d, `Start with an empty set called ${this.nameText(n.name)}.${tr()}`, s.line); + else if (t.k === 'HASHMAP') { + if (t.val?.k !== 'INTEGER') this.fail('a HASHMAP whose values are not counts', s.line); + this.emit(d, `Start with an empty tally called ${this.nameText(n.name)}.${tr()}`, s.line); + } else if (t.k === 'RECORD') this.fail('a record', s.line); + // a number, text, or yes-or-no value is introduced by the step that first gives it a value + if (['LIST', 'ARRAY', 'SET', 'HASHMAP'].includes(t.k)) this.known.add(String(n.name).toLowerCase()); + } + return; + } + case 'Assign': this.assign(s, d, ctx, tr()); return; + case 'Output': { + // "Show a, b" prints a, a space, then b: the pseudo's OUTPUT a, " ", b. Values with nothing between them have no English. + const vals: any[] = []; + s.values.forEach((v: any, i: number) => { + if (i % 2 === 1) { if (!(v.kind === 'Str' && v.value === ' ')) this.fail('an OUTPUT of several values with no single space between them (English puts one space between the values it shows)', s.line); } else vals.push(v); + }); + if (s.values.length % 2 === 0) this.fail('an OUTPUT that ends with a space', s.line); + this.emit(d, `Show ${vals.map(E).join(', ')}.${tr()}`, s.line); + return; + } + case 'Input': this.fail('INPUT', s.line); return; + case 'If': { + s.branches.forEach((b: any, i: number) => { + this.emit(d, `${i ? 'Otherwise, if' : 'If'} ${E(b.cond)}:${i ? this.trailing(b.line) : tr()}`, b.line); + this.block(b.body, d + 1, { ...ctx, top: false }, sub); + }); + if (s.elseBody) { this.emit(d, 'Otherwise:', s.elseLine); this.block(s.elseBody, d + 1, { ...ctx, top: false }, sub); } + return; + } + case 'For': { + const v = this.nameText(s.var); + const lo = E(s.start); const hi = E(s.stop); + const step = s.step ? this.stepOf(s.step) : 1; + if (s.parallel) this.fail('PARALLEL FOR', s.line); + this.known.add(String(s.var).toLowerCase()); + let range: string; + if (step === 1) range = `from ${lo} up to but not including ${hi}`; + else if (step > 1) range = `from ${lo} up to but not including ${hi}, counting by ${step}`; + else if (step === -1) range = `from ${lo} down to but not including ${hi}`; + else range = `from ${lo} down to but not including ${hi}, counting by ${-step}`; + this.emit(d, `For each ${v} ${range}:${tr()}`, s.line); + this.block(s.body, d + 1, { top: false, loops: ctx.loops + 1 }, sub); + return; + } + case 'ForEach': { + const it = s.iterable; + const v = this.nameText(s.var); + this.known.add(String(s.var).toLowerCase()); + if (it.type?.k === 'STRING') this.emit(d, `For each letter ${v} of ${this.closed(it)}:${tr()}`, s.line); + else if (it.type?.k === 'LIST' || it.type?.k === 'ARRAY') this.emit(d, `For each item ${v} of ${this.closed(it)}:${tr()}`, s.line); + else this.fail('FOR EACH over this kind of collection', s.line); + this.block(s.body, d + 1, { top: false, loops: ctx.loops + 1 }, sub); + return; + } + case 'While': + this.emit(d, `Repeat while ${E(s.cond)}:${tr()}`, s.line); + this.block(s.body, d + 1, { top: false, loops: ctx.loops + 1 }, sub); + return; + case 'Repeat': this.fail('REPEAT ... UNTIL, which English reads as a loop that tests first', s.line); return; + case 'Case': { + if (!s.arms.length) this.fail('a CASE with only an OTHERWISE', s.line); + const subj = this.ex(s.subject); + const subjS = this.wrap(subj, ADD); + s.arms.forEach((a: any, i: number) => { + const conds = a.labels.map((l: any) => (l.value ? `${subjS} is ${this.wrap(this.ex(l.value), ADD)}` : `${subjS} is at least ${this.wrap(this.ex(l.low), ADD)} and ${subjS} is less than ${this.wrap(this.ex(l.high), ADD)}`)); + this.emit(d, `${i ? 'Otherwise, if' : 'If'} ${conds.join(' or ')}:`, a.line); + this.block(a.body, d + 1, { ...ctx, top: false }, sub); + }); + if (s.otherwise) { this.emit(d, 'Otherwise:', s.otherwiseLine); this.block(s.otherwise, d + 1, { ...ctx, top: false }, sub); } + return; + } + case 'Break': this.emit(d, `Stop the loop.${tr()}`, s.line); return; + case 'Continue': this.emit(d, `Skip to the next position.${tr()}`, s.line); return; + case 'Return': { + if (!s.value) { + if (ctx.loops > 0) this.fail('a RETURN with no value inside a loop', s.line); + this.emit(d, `Stop.${tr()}`, s.line); + return; + } + const late = ctx.top && last && ctx.loops === 0; + this.emit(d, `${late ? 'The answer is' : 'Stop and answer'} ${E(s.value)}.${tr()}`, s.line); + return; + } + case 'Call': this.emit(d, `${this.routineText(s)}.${tr()}`, s.line); return; + case 'BuiltinCall': this.builtinStep(s, d, tr()); return; + case 'Assert': this.emit(d, `Check that ${E(s.expr)}.${tr()}`, s.line); return; + case 'BlankStmt': this.fail('a blank to fill in', s.line); return; + default: this.fail(`a ${s.kind} step`, s.line); + } + } + + stepOf(e: any): number { + if (e.kind === 'Num' && Number.isInteger(e.value) && e.value !== 0) return e.value; + if (e.kind === 'Unary' && e.op === '-' && e.arg.kind === 'Num' && Number.isInteger(e.arg.value) && e.arg.value > 0) return -e.arg.value; + return this.fail('a loop step that is not a whole number written out', e.line ?? this.curLine); + } + + sameName(a: any, b: any): boolean { return a?.kind === 'Name' && b?.kind === 'Name' && up(a.name) === up(b.name); } + + assign(s: any, d: number, ctx: { top: boolean; loops: number }, tr: string): void { + const t = s.target; + const v = s.value; + const E = (e: any) => this.ex(e).s; + if (t.kind === 'Name') { + const name = this.nameText(t.name); + const key = String(t.name).toLowerCase(); + if (v.kind === 'Binary' && this.sameName(v.left, t) && v.op === '+' && this.known.has(key) && t.type?.k !== 'STRING' && t.type?.k !== 'CHAR') { this.emit(d, `Add ${E(v.right)} to ${name}.${tr}`, s.line); return; } + if (v.kind === 'Binary' && this.sameName(v.left, t) && v.op === '-' && this.known.has(key)) { this.emit(d, `Subtract ${E(v.right)} from ${name}.${tr}`, s.line); return; } + if (v.kind === 'Binary' && this.sameName(v.left, t) && v.op === '&' && this.known.has(key)) { this.emit(d, `Add ${E(v.right)} to the end of ${name}.${tr}`, s.line); return; } + if (v.kind === 'ListLit' && v.items.length === 0) { this.emit(d, `Set ${name} to an empty list.${tr}`, s.line); this.known.add(key); return; } + const fresh = !this.known.has(key); + this.known.add(key); + if (t.type?.k === 'FLOAT' && v.type?.k === 'INTEGER' && v.kind !== 'Num') this.fail('a whole-number value given to a FLOAT, which English would keep a whole number', s.line); + const value = t.type?.k === 'FLOAT' && v.kind === 'Num' && !/[.e]/.test(String(v.value)) ? `${v.value}.0` : E(v); + this.emit(d, fresh && ctx.top ? `Start with ${name} at ${value}.${tr}` : `Set ${name} to ${value}.${tr}`, s.line); + return; + } + if (t.kind === 'Index' && t.indices.length === 1 && t.target.kind === 'Name') { + const tt = t.target.type?.k; + if (tt === 'LIST' || tt === 'ARRAY') { this.emit(d, `Set the item of ${this.nameText(t.target.name)} at ${E(t.indices[0])} to ${E(v)}.${tr}`, s.line); return; } + if (tt === 'HASHMAP') { this.emit(d, `Set the count for ${E(t.indices[0])} in ${this.nameText(t.target.name)} to ${E(v)}.${tr}`, s.line); return; } + } + this.fail('a change to this part of a value', s.line); + } + + builtinStep(s: any, d: number, tr: string): void { + const [a, b] = s.args; + const E = (e: any) => this.ex(e).s; + switch (s.name) { + case 'APPEND': if (a.kind === 'Name') { this.emit(d, `Add ${E(b)} to ${this.nameText(a.name)}.${tr}`, s.line); return; } break; + case 'ADD': if (a.kind === 'Name') { this.emit(d, `Add ${E(b)} to ${this.nameText(a.name)}.${tr}`, s.line); return; } break; + case 'SORT': if (a.kind === 'Name') { this.emit(d, `Sort ${this.nameText(a.name)}.${tr}`, s.line); return; } break; + default: break; + } + this.fail(`${s.name}(...)`, s.line); + } + + /** A routine call as a step or value: the routine's own words, with the arguments where its inputs stand. */ + routineText(c: any): string { + const sub = this.subs.get(up(c.name)); + if (!sub) this.fail(`a call of ${c.name}`, this.curLine); + const words = String(sub.name).split('_').filter(Boolean).map((w: string) => w.toLowerCase()); + const args = c.args.map((a: any) => this.closed(a)); + const list = args.length > 1 ? `${args.slice(0, -1).join(', ')} and ${args[args.length - 1]}` : args[0]; + return `${words.join(' ')}${args.length ? ` for ${list}` : ''}`; + } + + /* ---------- expressions ---------- */ + /** An expression as a primary: wrapped in parentheses unless it already is one. */ + closed(e: any): string { + const t = this.ex(e); + return t.p >= ATOM && !t.open ? t.s : `(${t.s})`; + } + + wrap(t: Text, min: number): string { return t.p >= min && !(t.open && min > CMP) ? t.s : `(${t.s})`; } + + /** + * English for an expression. `p` is how tightly the text binds; `open` marks a phrase that reads a + * value after it ("the letter of T at i + 1"), which must be parenthesized before anything follows. + */ + ex(e: any, arg = false): Text { + void arg; + switch (e.kind) { + case 'Num': { const t = String(e.value); return { s: e.float && !/[.e]/.test(t) ? `${t}.0` : t, p: ATOM }; } + case 'Str': return { s: `"${String(e.value).replace(/"/g, '')}"`, p: ATOM }; + case 'Char': return { s: `'${e.value}'`, p: ATOM }; + case 'Bool': return { s: e.value ? 'true' : 'false', p: ATOM }; + case 'Name': return { s: this.nameText(e.name), p: ATOM }; + case 'Unary': + if (e.op === 'NOT' && e.arg.kind === 'Binary' && e.arg.op === 'IN') return { s: this.membership(e.arg, true), p: CMP }; + if (e.op === 'NOT') return { s: `not ${this.wrap(this.ex(e.arg), ATOM)}`, p: NOT }; + return { s: `-${this.wrap(this.ex(e.arg), ATOM)}`, p: NEG }; + case 'Binary': return this.binary(e); + case 'Chain': { + // a < b < c: each pair is a test + const parts: string[] = []; + e.operands.slice(1).forEach((o: any, i: number) => parts.push(this.binary({ kind: 'Binary', op: e.ops[i], left: e.operands[i], right: o }).s)); + return { s: parts.map((x) => `(${x})`).join(' and '), p: AND }; + } + case 'Index': return this.index(e); + case 'CallExpr': return this.callExpr(e); + case 'Quant': { + if (e.q !== 'FORALL' || e.domain.kind !== 'Range') this.fail(`${e.q} written this way`, this.curLine); + const v = this.nameText(e.var); + return { s: `for every ${v} from ${this.ex(e.domain.lo).s} up to but not including ${this.ex(e.domain.hi).s}, ${this.ex(e.body).s}`, p: OR - 1, open: true }; + } + default: return this.fail(`a ${e.kind} value`, this.curLine); + } + } + + binary(e: any): Text { + const op = e.op; + const l = this.ex(e.left); const r = this.ex(e.right); + switch (op) { + case 'AND': return { s: `${this.wrap(l, AND)} and ${this.wrap(r, AND + 1)}`, p: AND }; + case 'OR': return { s: `${this.wrap(l, OR)} or ${this.wrap(r, OR + 1)}`, p: OR }; + case '==': case '!=': case '<': case '<=': case '>': case '>=': { + const word = { '==': 'is', '!=': 'is not', '<': 'is less than', '<=': 'is at most', '>': 'is more than', '>=': 'is at least' }[op as string]; + return { s: `${this.wrap(l, ADD)} ${word} ${this.wrap(r, ADD)}`, p: CMP }; + } + case 'IN': return { s: this.membership(e, false), p: CMP }; + case '+': case '-': return { s: `${this.operand(l, ADD)} ${op} ${this.operand(r, ADD + 1)}`, p: ADD }; + case '&': return { s: `${this.operand(l, ADD)} joined with ${this.operand(r, ADD + 1)}`, p: ADD }; + case '*': return { s: `${this.operand(l, MUL)} * ${this.operand(r, MUL + 1)}`, p: MUL }; + case '/': return { s: `${this.operand(l, MUL)} / ${this.operand(r, MUL + 1)}`, p: MUL }; + case 'DIV': return { s: `(${this.operand(l, MUL)} / ${this.operand(r, MUL + 1)} rounded down)`, p: ATOM }; + case 'MOD': return { s: `${this.operand(l, MUL)} % ${this.operand(r, MUL + 1)}`, p: MUL }; + case '^': return this.fail('a power', this.curLine); + default: return this.fail(`the operator ${op}`, this.curLine); + } + } + + /** x is in S, x is a key of M, x is not in S, and a value inside a range. */ + membership(e: any, negated: boolean): string { + const x = this.wrap(this.ex(e.left), ADD); + if (e.right.kind === 'Range') { + const lo = this.wrap(this.ex(e.right.lo), ADD); const hi = this.wrap(this.ex(e.right.hi), ADD); + return negated ? `(${x} is less than ${lo} or ${x} is at least ${hi})` : `(${x} is at least ${lo} and ${x} is less than ${hi})`; + } + const k = e.right.type?.k; + if (k !== 'SET' && k !== 'HASHMAP' && k !== 'LIST') this.fail('IN on this kind of value', this.curLine); + return `${x} is ${negated ? 'not ' : ''}${k === 'HASHMAP' ? 'a key of' : 'in'} ${this.closed(e.right)}`; + } + + /** An operand of arithmetic: open phrases are parenthesized so they cannot swallow what follows. */ + operand(t: Text, min: number): string { return t.open || t.p < min ? `(${t.s})` : t.s; } + + index(e: any): Text { + const t = e.target; + if (e.indices.length === 1) { + const k = this.ex(e.indices[0]); + const idx = k.p >= ADD && !k.open ? k.s : `(${k.s})`; + if (t.type?.k === 'STRING') return { s: `the letter of ${this.closed(t)} at ${idx}`, p: ATOM, open: true }; + if (t.type?.k === 'LIST' || t.type?.k === 'ARRAY') return { s: `the item of ${this.closed(t)} at ${idx}`, p: ATOM, open: true }; + if (t.type?.k === 'HASHMAP') return { s: `the count for ${idx} in ${this.closed(t)}`, p: ATOM }; + } + return this.fail('this kind of position', this.curLine); + } + + callExpr(e: any): Text { + if (!e.builtin) return { s: `the result of ${this.routineText(e)}`, p: ATOM, open: true }; + const [a, b, c] = e.args; + // the reader takes "of A and B" and "of X" as one value each, so anything with an operator in it is parenthesized + const arg = (x: any) => this.closed(x); + const sum = (x: any) => { const t = this.ex(x); return t.p >= ADD && !t.open ? t.s : `(${t.s})`; }; + switch (e.builtin) { + case 'LENGTH': return { s: `the length of ${this.closed(a)}`, p: ATOM }; + case 'MIN': if (e.args.length === 2) return { s: `the smaller of ${arg(a)} and ${arg(b)}`, p: ATOM, open: true }; break; + case 'MAX': if (e.args.length === 2) return { s: `the larger of ${arg(a)} and ${arg(b)}`, p: ATOM, open: true }; break; + case 'ABS': return { s: `the absolute value of ${arg(a)}`, p: ATOM, open: true }; + case 'SQRT': return { s: `the square root of ${arg(a)}`, p: ATOM, open: true }; + case 'SLICE': if (a.type?.k === 'STRING') return { s: `the part of ${this.closed(a)} from ${sum(b)} up to but not including ${sum(c)}`, p: ATOM, open: true }; break; + default: break; + } + return this.fail(`the built-in ${e.builtin}`, this.curLine); + } +} + +/** + * Generate lingo from pseudo. `unsupported` when the pseudo has errors, when part of it has no English + * form, or when what was written does not read back as the same routines. + */ +export function pseudoToLingo(pseudo: string): LingoResult | { unsupported: Diagnostic[] } { + const st: any = study(pseudo, { coach: false }); + if (!st.ok || !st.program) { + const errors = (st.diags as any[]).filter((d) => d.severity === 'error').map((d) => toDiagnostic(d)); + return { unsupported: errors.length ? errors : [{ lang: 'pseudo', severity: 'error', id: 'lingo-no-program', line: 1, message: 'The pseudo does not read yet, so there is nothing to put into English.' }] }; + } + const program = st.program; + if (!program.subs.size && !program.main.body.length) return { unsupported: [{ lang: 'lingo', severity: 'warning', id: 'lingo-no-form', line: 1, message: 'There is no routine to put into English.' }] }; + const wanted = [...program.subs.values()] as any[]; + let last: { unsupported: Diagnostic[] } | null = null; + // First the terse English (the steps settle what each input is), then, if the reader read an input as + // something else, with a sentence saying what each input is. + for (const withKinds of [false, true]) { + const gen = new Gen(program, pseudo, withKinds); + const result = gen.run(); + if (!result) return { unsupported: gen.problems }; + const checked = readsBack(result, wanted); + if (!('unsupported' in checked)) return result; + last = checked; + } + return last!; +} + +/** The guarantee: what was written reads, and reads as the same routines with the same kinds of input. */ +function readsBack(result: LingoResult, wanted: any[]): { ok: true } | { unsupported: Diagnostic[] } { + const back: any = readSteps(result.source); + const bad = (back.diags as any[]).filter((d) => d.severity === 'error'); + const sameShape = back.routines.length === wanted.length && back.routines.every((r: any, i: number) => r.params.length === wanted[i].params.length + && r.params.every((p: any, j: number) => up(String(p.display).replace(/ /g, '_')) === up(wanted[i].params[j].name) && typeKey(p.type) === typeKey(wanted[i].params[j].type))); + if (back.ok && !bad.length && sameShape) return { ok: true }; + const problems: Diagnostic[] = bad.slice(0, 3).map((d: any) => ({ + lang: 'lingo' as const, severity: 'warning' as const, id: 'lingo-no-form', line: result.map[(d.line ?? 1) - 1] ?? 1, + message: `English cannot say this the way the reader needs it (${String(d.message).replace(/\s+/g, ' ').slice(0, 160)}), so the lingo pane keeps its last good text.`, + })); + if (!problems.length) problems.push({ lang: 'lingo', severity: 'warning', id: 'lingo-no-form', line: 1, message: 'The English written for this pseudo does not read back as the same routines and inputs, so the lingo pane keeps its last good text.' }); + return { unsupported: problems }; +} + diff --git a/src/sync/pseudo-to-matho.ts b/src/sync/pseudo-to-matho.ts new file mode 100644 index 0000000..3dbe748 --- /dev/null +++ b/src/sync/pseudo-to-matho.ts @@ -0,0 +1,617 @@ +/** + * Pseudo to matho: the equations a program says, written in LaTeX, for the programs that are equations. + * + * The matho reader (src/services/matho.ts) lowers an equation to one FUNCTION: a single RETURN, a sum or + * product as an accumulator loop, a piecewise definition as an IF chain, a reference to an earlier equation + * as a call. This generator recognizes exactly those shapes and writes the equation that lowers to them: + * + * FUNCTION X_BAR(N, X) \bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i + * Total <- 0.0 ; FOR I <- 0 TO N ... + * RETURN 1 / N * Total + * + * Anything else (a WHILE loop, text, a record, output, a loop that does more than add up) is `unsupported`, + * with the construct and its line: "matho has no form for a WHILE loop (line 7)". Matho is a notation for + * values, so a program that prints or reads input is not one of its equations. + * + * It never writes an equation that reads as something else. What was written is lowered again by the + * matho reader and held to the pseudo it came from: the same functions, taking the same kinds of input, giving + * the same values on sample inputs (and stopping the same way where the pseudo stops). A program that fails + * that check is `unsupported` too. + * + * Comments are not carried across: the lowering writes the equation itself as a comment above each function, + * and carrying that back would put a stale copy of the equation above the new one. + * + * Names. The reader turns `\bar{x}` into X_BAR and `\sigma` into SIGMA, so the student's spelling is not + * in the pseudo. The `NameMap` hint carries it (pseudo name, upper case, to the student's LaTeX); without a + * hint the default rules apply: SIGMA is `\sigma`, X_BAR is `\bar{x}`, a single letter is lower case, a longer + * name is `\text{...}`. + */ +import { studyPseudo as study } from '../services/pseudo-study.js'; +import { walkExpr } from '../engines/pseudo/analyze.js'; +import { studyOf, runPseudo, toDiagnostic } from '../services/pseudo.js'; +import { parseMatho } from '../services/matho.js'; +import type { Diagnostic } from '../core/types.js'; +import type { LineMap, NameMap } from './types.js'; + +export interface MathoResult { source: string; map: LineMap; notes: Diagnostic[] } + +class NoForm extends Error { + constructor(public what: string, public line: number) { super(what); } +} + +const up = (s: unknown): string => String(s).toUpperCase(); + +/* The Greek names the reader knows, by the pseudo name it gives them (src/services/matho.ts, GREEK). */ +const GREEK_LOWER: Record = { + ALPHA: 'alpha', BETA: 'beta', GAMMA: 'gamma', DELTA: 'delta', EPSILON: 'epsilon', ZETA: 'zeta', ETA: 'eta', THETA: 'theta', IOTA: 'iota', + KAPPA: 'kappa', LAMBDA: 'lambda', MU: 'mu', NU: 'nu', XI: 'xi', RHO: 'rho', SIGMA: 'sigma', TAU: 'tau', UPSILON: 'upsilon', PHI: 'phi', + CHI: 'chi', PSI: 'psi', OMEGA: 'omega', +}; +const GREEK_UPPER: Record = { + GAMMAU: 'Gamma', DELTAU: 'Delta', THETAU: 'Theta', LAMBDAU: 'Lambda', XIU: 'Xi', PIU: 'Pi', SIGMAU: 'Sigma', PHIU: 'Phi', PSIU: 'Psi', OMEGAU: 'Omega', +}; + +/** What a name looks like once the reader has made it a pseudo name (Word_Count -> WordCount): the form we spell. */ +function normal(name: string): string { + const s = String(name); + if (/^[A-Za-z]$/.test(s)) return s.toUpperCase(); + return s.split('_').filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(''); +} + +/** LaTeX for a variable called `name` in pseudo. `hint` is the student's own spelling, when it is known. */ +function spellVar(name: string, hint: string | undefined, vec: boolean, noSub = false): string { + let t: string; + const n = String(name); + if (hint) t = hint; + else if (GREEK_LOWER[up(n)]) t = `\\${GREEK_LOWER[up(n)]}`; + else if (GREEK_UPPER[up(n)]) t = `\\${GREEK_UPPER[up(n)]}`; + else { + const m = /^([A-Za-z])(Bar|Hat|Tilde)$/.exec(n) ?? /^([A-Za-z])_(BAR|HAT|TILDE)$/i.exec(n); + if (m) t = `\\${m[2].toLowerCase()}{${m[1] === 'E' ? '\\text{E}' : m[1].toLowerCase()}}`; + else if (/^[A-Za-z]$/.test(n)) t = n === 'E' || n === 'e' ? '\\text{E}' : n.toLowerCase(); + else if (!noSub && /^[A-Za-z][0-9]+$/.test(n)) t = `${n[0].toLowerCase()}_{${n.slice(1)}}`; + else t = `\\text{${normal(n)}}`; + } + return vec ? `\\vec{${t}}` : t; +} + +/** The left side of an equation for a function: a name the reader turns back into this FUNCTION name. */ +function spellFunction(fn: string, params: string[], hint: string | undefined, spell: (p: string) => string): { lhs: string; call: boolean } { + if (hint) return { lhs: hint, call: false }; + const parts = String(fn).split('_').filter(Boolean); + if (parts.length === 1) { + const w = parts[0]; + if (GREEK_LOWER[w] || GREEK_UPPER[w]) return { lhs: `\\${GREEK_LOWER[w] ?? GREEK_UPPER[w]}`, call: false }; + const base = w.length === 1 ? w.toLowerCase() : `\\text{${w.toLowerCase()}}`; + return { lhs: `${base === 'e' ? '\\text{e}' : base}(${params.map(spell).join(', ')})`, call: true }; + } + // X_BAR, SIGMA_SQUARED, COUNT_BASE: a name with a mark or a subscript, written bare + let rest = parts.slice(); + let squared = false; + if (rest.length > 1 && rest[rest.length - 1] === 'SQUARED') { squared = true; rest = rest.slice(0, -1); } + const head = rest[0]; + const base = GREEK_LOWER[head] ? `\\${GREEK_LOWER[head]}` : head.length === 1 ? head.toLowerCase() : `\\text{${head.toLowerCase()}}`; + let t = base; + const mark = rest.length === 2 && /^(BAR|HAT|TILDE)$/.test(rest[1]) && (head.length === 1 || GREEK_LOWER[head]); + if (mark) t = `\\${rest[1].toLowerCase()}{${base}}`; + else if (rest.length > 1) t = `${base}_{\\text{${rest.slice(1).map((x) => x.toLowerCase()).join(' ')}}}`; + if (squared) t = `${mark ? t : t}^2`; + return { lhs: t, call: false }; +} + +/* Precedence: how tightly a piece of LaTeX binds. A sum or product written with its bounds reads everything + after it as its body, so it is parenthesized wherever something follows it. */ +const BIG = 0, ADD = 1, NEG = 2, MUL = 3, POW = 4, ATOM = 5; +interface T { s: string; p: number } +const wrap = (t: T, min: number): string => (t.p < min ? `(${t.s})` : t.s); + +interface Scope { + /** name (upper case) -> what stands for it in the LaTeX */ + names: Map; + /** loop variables in scope, by name: the letter, and the lower bound as written */ + loops: Map; + /** the lists a loop variable indexes, in the order the reader will find them */ + letters: Set; +} + +const CMP_TEX: Record = { '<': '<', '<=': '\\le', '>': '>', '>=': '\\ge', '==': '=', '!=': '\\ne' }; +const ONE_ARG: Record = { SIN: '\\sin', COS: '\\cos', TAN: '\\tan', EXP: '\\exp', LOG: '\\ln', LOG10: '\\log' }; + +class Gen { + problems: Diagnostic[] = []; + lines: Array<{ text: string; from: number | null }> = []; + notes: Diagnostic[] = []; + /** Functions already written, with how a call of them is written. */ + written = new Map(); + curLine = 1; + vecs = new Set(); + paramNames = new Set(); + + constructor(private program: any, private hints: NameMap) { + } + + fail(what: string, line = this.curLine): never { throw new NoForm(what, line); } + unsupported(what: string, line: number): void { + this.problems.push({ lang: 'matho', severity: 'warning', id: 'matho-no-form', line, message: `matho has no form for ${what} (line ${line}), so the matho pane keeps its last good text.` }); + } + + hint(name: string): string | undefined { return this.hints[up(name)]; } + /** A function written with its inputs listed (f(x, y)) cannot list a subscripted input, so such inputs are written as plain names there. */ + noSub = false; + spell(name: string): string { return spellVar(name, this.hint(name), this.vecs.has(up(name)), this.noSub); } + + run(): MathoResult | null { + const p = this.program; + for (const c of p.constants.values()) this.unsupported('a CONSTANT', c.line); + for (const d of p.defines.values()) this.unsupported('a DEFINE set', d.line); + for (const t of p.types.values()) this.unsupported('a record type', t.node.line); + if (p.main.body.length) this.unsupported('steps outside a function (an equation is a function)', p.main.body[0].line); + let first = true; + for (const sub of p.subs.values()) { + const at = this.lines.length; + try { + const eq = this.routine(sub); + if (!first) this.lines.push({ text: '', from: null }); + first = false; + for (const l of eq) this.lines.push(l); + } catch (e) { + if (!(e instanceof NoForm)) throw e; + this.lines.length = at; + this.unsupported(e.what, e.line); + } + } + if (this.problems.length) return null; + const out = this.lines; + while (out.length && !out[out.length - 1].text.trim()) out.pop(); + return { source: out.map((l) => l.text).join('\n') + '\n', map: out.map((l) => l.from), notes: this.notes }; + } + + /* ---------- one function ---------- */ + routine(sub: any): Array<{ text: string; from: number | null }> { + const s = sub.node; + this.curLine = s.line; + if (sub.kind !== 'Function' || !sub.returns || !['INTEGER', 'FLOAT'].includes(sub.returns.k)) this.fail(sub.kind === 'Function' ? `a function that answers ${sub.returns?.k ?? 'nothing'} (equations answer numbers)` : 'a PROCEDURE', s.line); + const params: string[] = []; + this.paramNames = new Set(); + for (const p of sub.params) { + if (p.mode === 'BYREF') this.fail('a BYREF parameter', s.line); + const t = p.type; + const num = (x: any) => ['INTEGER', 'FLOAT'].includes(x?.k); + const ok = num(t) || ((t?.k === 'LIST' || t?.k === 'ARRAY') && (num(t.of) || (t.of?.k === 'LIST' && num(t.of.of)))); + if (!ok) this.fail(`the input ${p.name}, which is not a number or a list of numbers`, s.line); + if (t.k === 'ARRAY') this.fail('a fixed-length ARRAY', s.line); + params.push(p.name); + this.paramNames.add(up(p.name)); + } + // inputs used as vectors (DOT, NORM_OF) are written \vec{a} everywhere + this.vecs = new Set(); + const body = s.body.filter((st: any) => st.kind !== 'Declare'); + const scanVec = (st: any) => { + for (const e of exprsOf(st)) walkExpr(e, (x: any) => { + if (x.kind === 'CallExpr' && (x.builtin === 'DOT' || x.builtin === 'NORM_OF')) for (const a of x.args) if (a.kind === 'Name' && this.paramNames.has(up(a.name))) this.vecs.add(up(a.name)); + return undefined; + }); + }; + eachStatement(s.body, scanVec); + + this.noSub = !this.hint(sub.name) && String(sub.name).split('_').filter(Boolean).length === 1; + const scope: Scope = { names: new Map(), loops: new Map(), letters: new Set() }; + for (const p of params) scope.names.set(up(p), { s: this.spell(p), p: ATOM }); + const callee = spellFunction(sub.name, params, this.hint(sub.name), (p) => this.spell(p)); + const result = this.block(body, scope, sub, true); + this.written.set(up(sub.name), { call: callee.call, lhs: callee.lhs, params }); + const out: Array<{ text: string; from: number | null }> = []; + if (result.kind === 'value') { + out.push({ text: `${callee.lhs} = ${result.t.s}`, from: s.line }); + } else { + out.push({ text: `${callee.lhs} = \\begin{cases}`, from: s.line }); + result.arms.forEach((a, i) => { + const last = i === result.arms.length - 1; + out.push({ text: ` ${a.value.s} & ${a.cond ?? '\\text{otherwise}'}${last ? '' : ' \\\\'}`, from: a.line }); + }); + out.push({ text: '\\end{cases}', from: s.line }); + } + return out; + } + + /** + * The value a block of steps comes to. Steps before the RETURN give names to values (substituted where + * they are used) or run an accumulator loop (a sum or product). The block must end by returning, either + * one value or an IF chain whose every branch returns. + */ + block(body: any[], scope: Scope, sub: any, top: boolean): { kind: 'value'; t: T } | { kind: 'cases'; arms: Array<{ value: T; cond: string | null; line: number }> } { + const names = new Map(scope.names); + const local: Scope = { names, loops: scope.loops, letters: scope.letters }; + const assigned = new Set(); + for (let i = 0; i < body.length; i++) { + const st = body[i]; + this.curLine = st.line ?? this.curLine; + switch (st.kind) { + case 'Declare': break; + case 'Assign': { + const nxt = body[i + 1]; + if (st.target.kind !== 'Name') this.fail('a change to part of a value', st.line); + const n = up(st.target.name); + if (this.paramNames.has(n) || scope.loops.has(n)) this.fail(`a change to the input ${st.target.name} (an equation does not change its inputs)`, st.line); + if (assigned.has(n)) this.fail(`${st.target.name} set twice (an equation names a value once)`, st.line); + assigned.add(n); + if (nxt && (nxt.kind === 'For' || nxt.kind === 'ForEach') && this.accumulates(nxt, n)) { + const init = st.value; + const lit = init.kind === 'Num' ? Number(init.value) : NaN; + const op = this.accumulatorOp(nxt, n); + if (!((op === '+' && lit === 0) || (op === '*' && lit === 1))) this.fail(`${st.target.name} starting at ${init.kind === 'Num' ? init.value : 'a value that is not 0 (sum) or 1 (product)'}`, st.line); + names.set(n, this.bigOp(nxt, n, op!, local, sub)); + i++; + break; + } + names.set(n, this.ex(st.value, local)); + break; + } + case 'Return': { + if (!st.value) this.fail('a RETURN with no value', st.line); + if (i !== body.length - 1) this.fail('steps after a RETURN', body[i + 1].line); + return { kind: 'value', t: this.ex(st.value, local) }; + } + case 'If': { + if (!top) this.fail('a nested IF (a piecewise definition has one level of cases)', st.line); + const arms: Array<{ value: T; cond: string | null; line: number }> = []; + const rest = body.slice(i + 1); + for (const b of st.branches) { + const r = this.block(b.body, local, sub, false); + if (r.kind !== 'value') this.fail('a nested IF', b.line); + arms.push({ value: r.t, cond: this.cond(b.cond, local), line: b.line }); + } + let other: any[] | null = null; + if (st.elseBody) { if (rest.length) this.fail('steps after an IF that already has an ELSE', rest[0].line); other = st.elseBody; } + else if (rest.length) other = rest; + if (!other) this.fail('an IF with no ELSE and no RETURN after it (a piecewise definition has a value for every input)', st.line); + const r = this.block(other, local, sub, false); + if (r.kind !== 'value') this.fail('a nested IF', st.line); + arms.push({ value: r.t, cond: null, line: st.elseLine ?? other[0]?.line ?? st.line }); + return { kind: 'cases', arms }; + } + case 'For': case 'ForEach': + this.fail(`a loop that is not adding up or multiplying one value (${st.kind === 'For' ? 'FOR' : 'FOR EACH'})`, st.line); + break; + case 'While': this.fail('a WHILE loop', st.line); break; + case 'Repeat': this.fail('a REPEAT loop', st.line); break; + case 'Output': this.fail('OUTPUT (an equation has a value, not output)', st.line); break; + case 'Input': this.fail('INPUT', st.line); break; + case 'Case': this.fail('a CASE (write the IF chain, which becomes the cases)', st.line); break; + case 'Call': case 'BuiltinCall': this.fail('a step that only calls (an equation has a value)', st.line); break; + case 'Assert': this.fail('an ASSERT', st.line); break; + default: this.fail(`a ${st.kind} step`, st.line); + } + } + return this.fail('a function that does not end by returning a value', this.curLine); + } + + /** Is this loop `V <- V op t` and nothing that disturbs V? */ + accumulates(loop: any, v: string): boolean { return this.accumulatorOp(loop, v) !== null; } + accumulatorOp(loop: any, v: string): '+' | '*' | null { + if (loop.parallel) return null; + const body = loop.body.filter((s: any) => s.kind !== 'Declare'); + const last = body[body.length - 1]; + if (!last || last.kind !== 'Assign' || last.target.kind !== 'Name' || up(last.target.name) !== v) return null; + const x = last.value; + if (x.kind !== 'Binary' || !(x.op === '+' || x.op === '*') || x.left.kind !== 'Name' || up(x.left.name) !== v) return null; + return x.op; + } + + /** A sum or product: the loop, written with its bounds. */ + bigOp(loop: any, v: string, op: '+' | '*', scope: Scope, sub: any): T { + this.curLine = loop.line; + if (loop.kind === 'For' && loop.step) this.fail('a loop with a STEP', loop.line); + const name = up(loop.var); + if (this.paramNames.has(name) || scope.loops.has(name) || scope.names.has(name)) this.fail(`the loop counter ${loop.var}, which is already a name here`, loop.line); + const letter = this.indexLetter(loop.var); + if (!letter) this.fail(`the loop counter ${loop.var} (matho writes it as a single letter)`, loop.line); + if (scope.letters.has(letter)) this.fail(`two loops that both count with ${loop.var}`, loop.line); + const inner: Scope = { names: new Map(scope.names), loops: new Map(scope.loops), letters: new Set(scope.letters) }; + let under: string; + let shifted = false; + let lo: any = null; + if (loop.kind === 'ForEach') { + const it = loop.iterable; + if (it.kind !== 'Name' || !this.paramNames.has(up(it.name)) || !['LIST'].includes(it.type?.k)) this.fail('FOR EACH over anything but an input list', loop.line); + under = `_{${letter} \\in ${this.ex(it, scope).s}}`; + inner.names.set(name, { s: letter, p: ATOM }); + } else { + lo = loop.start; + const loT = this.ex(lo, scope); + const hiS = this.upper(loop.stop, scope); + const lit1 = lo.kind === 'Num' && Number(lo.value) === 1 && !lo.float; + const bare = hiS.bare; // LENGTH(L) with no stated bounds + if (bare) { + if (!(lo.kind === 'Num' && Number(lo.value) === 0)) this.fail('a loop over LENGTH that does not start at 0', loop.line); + under = `_{${letter}}`; + } else { + under = `_{${letter}=${loT.s}}^{${hiS.t.s}}`; + shifted = lit1 && (hiS.kind === 'var' || hiS.kind === 'bin'); + } + inner.names.set(name, { s: letter, p: ATOM }); + inner.loops.set(name, { letter, shifted, lo }); + if (bare) { + // the reader runs the loop over the first list the body indexes by this letter; it has to be the one named + inner.loops.get(name)!.lo = { bareList: hiS.list }; + } + } + inner.letters.add(letter); + const bodyAll = loop.body.filter((s: any) => s.kind !== 'Declare'); + const res = this.block([...bodyAll.slice(0, -1), { kind: 'Return', value: bodyAll[bodyAll.length - 1].value.right, line: bodyAll[bodyAll.length - 1].line }], inner, sub, false); + if (res.kind !== 'value') this.fail('a loop whose step chooses', loop.line); + if (loop.kind === 'For') { + const l = inner.loops.get(name)!; + if (l.lo?.bareList && this.firstIndexed(res.t.s, letter) !== l.lo.bareList) this.fail(`a loop over LENGTH(${l.lo.bareList}) whose body does not index ${l.lo.bareList} first`, loop.line); + } + const cmd = op === '+' ? '\\sum' : '\\prod'; + const needs = op === '+' ? res.t.p < MUL && res.t.p !== BIG : res.t.p < MUL && res.t.p !== BIG; + return { s: `${cmd}${under} ${needs ? `(${res.t.s})` : res.t.s}`, p: BIG }; + } + + indexLetter(v: string): string | null { + // the reader adds Val to a one-letter name that is a reserved word (K -> KVal); undo that + const n = /^[A-Za-z]Val$/.test(String(v)) ? String(v)[0] : String(v); + if (/^[A-Za-z]$/.test(n)) return n.toLowerCase(); + if (GREEK_LOWER[up(n)]) return `\\${GREEK_LOWER[up(n)]}`; + return null; + } + + /** The first list a body subscripts by `letter`, as the reader will find it: left to right in the LaTeX. */ + firstIndexed(tex: string, letter: string): string | null { + const esc = letter.replace(/\\/g, '\\\\'); + const m = new RegExp(`(\\\\text\\{[^}]*\\}|\\\\[A-Za-z]+(?:\\{[^}]*\\})?|[A-Za-z])_(?:\\{${esc}[^}]*\\}|${esc})`).exec(tex); + if (!m) return null; + const tok = m[1]; + for (const p of this.paramNames) if (spellVar(p, this.hints[p], this.vecs.has(p), this.noSub) === tok) return p; + return null; + } + + /** The inclusive upper bound a FOR ... TO (exclusive) comes from: N + 1 -> N, 5 -> 4, anything else -> that - 1. */ + upper(stop: any, scope: Scope): { t: T; kind: string; bare?: boolean; list?: string } { + if (stop.kind === 'CallExpr' && stop.builtin === 'LENGTH' && stop.args[0].kind === 'Name' && this.paramNames.has(up(stop.args[0].name))) { + return { t: { s: '', p: ATOM }, kind: 'length', bare: true, list: up(stop.args[0].name) }; + } + if (stop.kind === 'Binary' && stop.op === '+' && stop.right.kind === 'Num' && Number(stop.right.value) === 1) { + const t = this.ex(stop.left, scope); + return { t, kind: stop.left.kind === 'Name' ? 'var' : stop.left.kind === 'Binary' ? 'bin' : 'other' }; + } + if (stop.kind === 'Num' && Number.isInteger(Number(stop.value)) && Number(stop.value) >= 1) return { t: { s: String(Number(stop.value) - 1), p: ATOM }, kind: 'num' }; + const t = this.ex(stop, scope); + return { t: { s: `${wrap(t, ADD)}-1`, p: ADD }, kind: 'bin-' }; + } + + /* ---------- conditions ---------- */ + cond(e: any, scope: Scope): string { + const x = this.condPart(e, scope); + return x.s; + } + condPart(e: any, scope: Scope): { s: string; or: boolean } { + if (e.kind === 'Binary' && e.op === 'AND') { + const l = this.condPart(e.left, scope); const r = this.condPart(e.right, scope); + if (l.or || r.or) this.fail('an AND of an OR (matho conditions have no parentheses)', e.line ?? this.curLine); + return { s: `${l.s} \\land ${r.s}`, or: false }; + } + if (e.kind === 'Binary' && e.op === 'OR') { + const l = this.condPart(e.left, scope); const r = this.condPart(e.right, scope); + return { s: `${l.s} \\lor ${r.s}`, or: true }; + } + if (e.kind === 'Binary' && CMP_TEX[e.op]) { + if (e.left.type?.k === 'BOOL' || e.left.type?.k === 'STRING' || e.left.type?.k === 'CHAR') this.fail('a comparison of something that is not a number', e.line ?? this.curLine); + return { s: `${this.ex(e.left, scope).s} ${CMP_TEX[e.op]} ${this.ex(e.right, scope).s}`, or: false }; + } + if (e.kind === 'Chain') { + if (e.ops.length !== 2 || e.ops.some((o: string) => !CMP_TEX[o] || o === '==' || o === '!=')) this.fail('a chain of comparisons that matho cannot write', e.line ?? this.curLine); + const [a, b, c] = e.operands.map((o: any) => this.ex(o, scope).s); + return { s: `${a} ${CMP_TEX[e.ops[0]]} ${b} ${CMP_TEX[e.ops[1]]} ${c}`, or: false }; + } + return this.fail('a condition that is not a comparison of numbers (NOT, a yes-or-no value, or a test of membership)', e.line ?? this.curLine); + } + + /* ---------- expressions ---------- */ + ex(e: any, scope: Scope): T { + switch (e.kind) { + case 'Num': return { s: String(e.float && Number.isInteger(Number(e.value)) && !/[.e]/.test(String(e.value)) ? `${e.value}.0` : e.value), p: ATOM }; + case 'Name': { + const t = scope.names.get(up(e.name)); + if (!t) this.fail(`the name ${e.name}, which is not an input or a value named above`, e.line ?? this.curLine); + return t; + } + case 'Unary': { + if (e.op !== '-') this.fail(`the operator ${e.op}`, e.line ?? this.curLine); + const a = this.ex(e.arg, scope); + return { s: `-${wrap(a, POW)}`, p: NEG }; + } + case 'Binary': return this.binary(e, scope); + case 'Index': return this.index(e, scope); + case 'CallExpr': return this.call(e, scope); + default: return this.fail(`a ${e.kind === 'Str' ? 'text' : e.kind === 'Bool' ? 'yes-or-no' : e.kind} value`, e.line ?? this.curLine); + } + } + + binary(e: any, scope: Scope): T { + const l = this.ex(e.left, scope); const r = this.ex(e.right, scope); + switch (e.op) { + case '+': case '-': return { s: `${wrap(l, ADD)} ${e.op} ${wrap(r, ADD + 1)}`, p: ADD }; + case '*': return { s: `${wrap(l, MUL)} \\cdot ${wrap(r, MUL + 1)}`, p: MUL }; + case '/': return { s: `\\frac{${l.s}}{${r.s}}`, p: ATOM }; + case 'MOD': return { s: `${wrap(l, MUL)} \\bmod ${wrap(r, MUL + 1)}`, p: MUL }; + case '^': return { s: `${wrap(l, ATOM)}^{${r.s}}`, p: POW }; + case 'DIV': return this.fail('DIV (whole-number division)', e.line ?? this.curLine); + default: return this.fail(`the operator ${e.op}`, e.line ?? this.curLine); + } + } + + /** L[I] is l_i; with a sum that starts at 1, L[I - 1] is l_i, since the reader shifts the subscript. */ + index(e: any, scope: Scope): T { + const line = e.line ?? this.curLine; + // A[I][J] is an index of an index; read it as one two-index position + if (e.target.kind === 'Index' && e.target.indices.length === 1 && e.indices.length === 1) e = { ...e, target: e.target.target, indices: [e.target.indices[0], e.indices[0]] }; + if (e.target.kind !== 'Name' || !this.paramNames.has(up(e.target.name))) this.fail('an index into something that is not an input list', line); + const list = this.ex(e.target, scope); + const loopOf = (x: any) => (x.kind === 'Name' ? scope.loops.get(up(x.name)) : undefined); + if (e.indices.length === 2) { + // A[I][J] is A_{ij}, with both counters plain letters of loops that start where the reader's sums do + const [a, b] = e.indices.map(loopOf); + if (!a || !b || e.indices.some((x: any) => x.kind !== 'Name')) this.fail('a two-dimensional position that is not two loop counters', line); + if (a.shifted || b.shifted || a.letter.length !== 1 || b.letter.length !== 1) this.fail('a two-dimensional position in a loop that starts at 1', line); + return { s: `${list.s}_{${a.letter}${b.letter}}`, p: ATOM }; + } + if (e.indices.length !== 1) this.fail('a position with more than two indices', line); + const ix = e.indices[0]; + const sub = (s: string): T => ({ s: `${list.s}_{${s}}`, p: ATOM }); + // L[I] + if (ix.kind === 'Name') { + const lp = loopOf(ix); + if (!lp) this.fail(`the position ${ix.name}, which is not a loop counter (matho subscripts are loop letters)`, line); + if (lp.shifted) this.fail(`L[${ix.name}] in a loop that starts at 1 (matho counts a sum from 1 as positions 0, 1, ...; write L[${ix.name} - 1])`, line); + return sub(lp.letter); + } + if (ix.kind === 'Binary' && (ix.op === '+' || ix.op === '-') && ix.left.kind === 'Name' && ix.right.kind === 'Num' && Number.isInteger(Number(ix.right.value))) { + const lp = loopOf(ix.left); + if (!lp) this.fail('a position that is not built from a loop counter', line); + const k = Number(ix.right.value); + if (lp.shifted) { + if (ix.op === '-' && k === 1) return sub(lp.letter); + this.fail(`a position other than ${ix.left.name} - 1 in a loop that starts at 1`, line); + } + return sub(`${lp.letter}${ix.op}${k}`); + } + return this.fail('a position that is not a loop counter plus or minus a number', line); + } + + call(e: any, scope: Scope): T { + const line = e.line ?? this.curLine; + const args = () => e.args.map((a: any) => this.ex(a, scope)); + if (!e.builtin) { + const callee = this.written.get(up(e.name)); + if (!callee) this.fail(`a call of ${e.name}, which is not a function written above it`, line); + const a = args(); + if (callee.call) return { s: `${callee.lhs.replace(/\(.*$/, '')}(${a.map((x: T) => x.s).join(', ')})`, p: ATOM }; + // a function written bare is referred to by its name alone, and takes this equation's own inputs + const same = e.args.length === callee.params.length && e.args.every((x: any, i: number) => x.kind === 'Name' && up(x.name) === up(callee.params[i])); + if (!same) this.fail(`a call of ${e.name} with other values than its own inputs (matho refers to ${e.name} by name only when it is called with the same inputs)`, line); + return { s: callee.lhs, p: ATOM }; + } + const a = args(); + switch (e.builtin) { + case 'SQRT': return { s: `\\sqrt{${a[0].s}}`, p: ATOM }; + case 'ABS': return { s: `\\left|${a[0].s}\\right|`, p: ATOM }; + case 'FLOOR': return { s: `\\lfloor ${a[0].s} \\rfloor`, p: ATOM }; + case 'CEIL': return { s: `\\lceil ${a[0].s} \\rceil`, p: ATOM }; + case 'CHOOSE': return { s: `\\binom{${a[0].s}}{${a[1].s}}`, p: ATOM }; + case 'PI': return { s: '\\pi', p: ATOM }; + case 'LOG2': return { s: `\\log_{2}(${a[0].s})`, p: ATOM }; + case 'MAX': case 'MIN': return { s: `\\${e.builtin.toLowerCase()}(${a.map((x: T) => x.s).join(', ')})`, p: ATOM }; + case 'DOT': return { s: `${a[0].s} \\cdot ${a[1].s}`, p: MUL }; + case 'NORM_OF': return { s: `\\lVert ${a[0].s} \\rVert`, p: ATOM }; + default: + if (ONE_ARG[e.builtin] && a.length === 1) return { s: `${ONE_ARG[e.builtin]}(${a[0].s})`, p: ATOM }; + return this.fail(`the built-in ${e.builtin}`, line); + } + } +} + +/** Every expression a statement holds directly. */ +function exprsOf(st: any): any[] { + switch (st.kind) { + case 'Assign': return [st.value, ...(st.target?.kind === 'Index' ? [st.target] : [])]; + case 'Return': return st.value ? [st.value] : []; + case 'If': return st.branches.map((b: any) => b.cond); + case 'For': return [st.start, st.stop, ...(st.step ? [st.step] : [])]; + case 'ForEach': return [st.iterable]; + default: return []; + } +} + +function eachStatement(body: any[], f: (s: any) => void): void { + for (const st of body) { + f(st); + if (st.kind === 'If') { st.branches.forEach((b: any) => eachStatement(b.body, f)); if (st.elseBody) eachStatement(st.elseBody, f); } + else if (st.body) eachStatement(st.body, f); + } +} + +/* ---------- the check: what was written is lowered again and held to the pseudo ---------- */ + +type PType = any; +const numeric = (t: PType): string => (t?.k === 'LIST' || t?.k === 'ARRAY' ? `LIST<${numeric(t.of)}>` : t?.k === 'INTEGER' || t?.k === 'FLOAT' ? 'NUM' : String(t?.k)); + +/** Inputs for the sample runs: whole numbers small enough to index a list of four, decimals, and lists. */ +function samples(types: PType[]): string[][] { + const row = (ints: boolean, v: number[]) => `[${v.map((x) => (ints ? String(x) : x.toFixed(2).replace(/0$/, ''))).join(', ')}]`; + const make = (ints: number[][], floats: number[][], k: number) => (t: PType, i: number): string => { + const lists = (x: PType) => (x.of?.k === 'INTEGER' ? ints : floats); + if (t.k === 'INTEGER') return String([3, 2, 4, 1][(i + k) % 4]); + if (t.k === 'FLOAT') return String([2.5, 1.5, 3.25, 0.5][(i + k) % 4]); + if (t.of?.k === 'LIST') { const f = lists(t.of); return `[${[0, 1, 2, 3].map((r) => row(t.of.of?.k === 'INTEGER', f[(r + k) % f.length])).join(', ')}]`; } + return row(t.of?.k === 'INTEGER', lists(t)[k % lists(t).length]); + }; + const ints = [[4, 1, 3, 2], [1, 5, 2, 6], [3, 3, 3, 3]]; + const floats = [[2.5, 1, 4, 3.5], [0.5, 1.5, 2, 7], [1, 1, 1, 1]]; + return [0, 1, 2].map((k) => types.map(make(ints, floats, k))); +} + +function sameValue(a: string, b: string): boolean { + if (a === b) return true; + const x = Number(a); const y = Number(b); + if (Number.isNaN(x) || Number.isNaN(y)) return false; + return Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y)); +} + +function readsBack(latex: string, pseudo: string, program: any, map: LineMap): { ok: true } | { unsupported: Diagnostic[] } { + const why = (message: string, line = 1): { unsupported: Diagnostic[] } => ({ unsupported: [{ lang: 'matho', severity: 'warning', id: 'matho-no-form', line, message: `matho cannot say this as equations the way the reader needs it (${message}), so the matho pane keeps its last good text.` }] }); + const back = parseMatho(latex); + const errs = back.diagnostics.filter((d) => d.severity === 'error'); + if (errs.length || !back.ok) return why(errs[0]?.message.replace(/\s+/g, ' ').slice(0, 160) ?? 'the equations do not read', map[(errs[0]?.line ?? 1) - 1] ?? 1); + const wanted = [...program.subs.values()] as any[]; + const defs = back.program!.defs; + if (defs.length !== wanted.length) return why('the reader found a different number of functions'); + const st = studyOf(back.program!.pseudo); + if (!st.ok) return why('the pseudo the equations become does not read'); + const lowered = st.program.program.subs; + for (let i = 0; i < wanted.length; i++) { + const w = wanted[i]; const d = defs[i]; + if (up(d.name) !== up(w.name)) return why(`the function ${w.name} comes back as ${d.name}`, w.node.line); + if (d.params.length !== w.params.length) return why(`${w.name} comes back with ${d.params.length} inputs instead of ${w.params.length}`, w.node.line); + for (let j = 0; j < w.params.length; j++) { + const have = lowered.get(up(d.name))?.params[j]?.type; + const got = numeric(have); const want = numeric(w.params[j].type); + if (got !== want) return why(`the input ${w.params[j].name} of ${w.name} comes back as ${have?.k === 'LIST' ? 'a list' : 'a number'}; the reader decides what each input is from how the equation uses it`, w.node.line); + } + } + // the same values: run each function with sample inputs, in the pseudo and in what the equations became + const orig = studyOf(pseudo); + for (const w of wanted) { + const types = w.params.map((p: any) => p.type); + for (const args of samples(types)) { + const call = `${w.name}(${args.join(', ')})`; + const run = (p: any): string => { + try { const r = runPseudo(p, { call, input: [], maxSteps: 50000 }); return r.error ? `error:${r.error.kind}` : String((r.raw as any).result); } catch (e: any) { return `cannot run: ${String(e.message).slice(0, 80)}`; } + }; + const va = run(orig); const vb = run(st); + if (!sameValue(va, vb)) return why(`${call} gives ${va} in the pseudo and ${vb} as equations`, w.node.line); + } + } + return { ok: true }; +} + +/** + * Generate matho from pseudo. `unsupported` when the pseudo has errors, when part of it is not an equation + * (with the construct and its line), or when what was written does not read back as the same functions. + */ +export function pseudoToMatho(pseudo: string, hints?: { names?: NameMap }): MathoResult | { unsupported: Diagnostic[] } { + const st: any = study(pseudo, { coach: false }); + if (!st.ok || !st.program) { + const errors = (st.diags as any[]).filter((d) => d.severity === 'error').map((d) => toDiagnostic(d)); + return { unsupported: errors.length ? errors : [{ lang: 'pseudo', severity: 'error', id: 'matho-no-program', line: 1, message: 'The pseudo does not read yet, so there is nothing to write as equations.' }] }; + } + const program = st.program; + if (!program.subs.size && !program.main.body.length) return { unsupported: [{ lang: 'matho', severity: 'warning', id: 'matho-no-form', line: 1, message: 'There is no function to write as an equation.' }] }; + const gen = new Gen(program, hints?.names ?? {}); + const result = gen.run(); + if (!result) return { unsupported: gen.problems }; + const checked = readsBack(result.source, pseudo, program, result.map); + if ('unsupported' in checked) return checked; + return result; +} diff --git a/src/sync/pseudo-to-mojo.ts b/src/sync/pseudo-to-mojo.ts new file mode 100644 index 0000000..0e13b8e --- /dev/null +++ b/src/sync/pseudo-to-mojo.ts @@ -0,0 +1,908 @@ +/** + * Pseudo to Mojo 1.1.0: the one translator in the sync model that only goes one way. + * + * This is an app-owned port of the Mojo half of src/engines/pseudo/translate.js + * (the engine file is left untouched; this fork is where the app's Mojo is + * decided). What changed from the engine's version: + * + * - it writes `def main()` itself, from the program's own lines or from the + * call the student is running (COUNT_BASE('A', "GATTACA") becomes + * print(count_base("A", "GATTACA"))); + * - `raises` is inferred, transitively, so the result passes the checker; + * - imports come from the harvested standard-library index; + * - it never writes a construct the interpreter declines when a verified + * spelling exists (a fixed-length ARRAY is an append loop, not List(length=)); + * - it never invents Mojo. What has no faithful spelling (a statistic the + * standard library lacks, a blank to fill in) becomes + * `raise Error("not translated: ...")` with a diagnostic, never a value + * that looks right and is not; + * - FORALL, EXISTS, SUM, set-builder, KEYS, SORTED, SPLIT, FILL and the + * other built-ins with no one-line spelling become a short loop written + * just before the statement that uses them. + * + * The translation stays literal on purpose (`var n: Int` then `n = ...`, + * `total = total + 1`, an index loop over codepoints). Idiomatic rewrites are + * left to the optional Mojo helper under src/mojo/, so a student can see the + * difference. Nothing here may import that helper. + */ +import { studyPseudo as study } from '../services/pseudo-study.js'; +import { sourceOf, parseExpression } from '../engines/pseudo/parse.js'; +import { walkStatements, walkExpr, statementExprs, rootName } from '../engines/pseudo/analyze.js'; +import { toDiagnostic } from '../services/pseudo.js'; +import { MOJO_STD_EXPORTS } from '../mojo/generated/stdlib.js'; +import type { Diagnostic } from '../core/types.js'; +import type { LineMap } from './types.js'; + +import { GENERATED_HEADER } from './header.js'; +export { GENERATED_HEADER }; + +export interface MojoOptions { + /** The call to run, such as COUNT_BASE('A', "GATTACA"); becomes the body of `main` when the pseudo has no lines of its own. */ + call?: string | null; +} + +export interface MojoResult { source: string; map: LineMap; notes: Diagnostic[] } + +/** Every standard-library name the translator can write, with the module it comes from. A test holds each to the harvested index. */ +export const USED_STDLIB: Readonly> = { + Set: 'std.collections', sort: 'std.builtin.sort', + sqrt: 'std.math', exp: 'std.math', log: 'std.math', log2: 'std.math', log10: 'std.math', + sin: 'std.math', cos: 'std.math', tan: 'std.math', atan2: 'std.math', pi: 'std.math', + floor: 'std.math', ceil: 'std.math', comb: 'std.math', + random_float64: 'std.random', random_si64: 'std.random', +}; +/** Names the translator writes that Mojo provides without an import. */ +export const USED_PRELUDE: readonly string[] = ['Int', 'Float64', 'String', 'Bool', 'List', 'Dict', 'print', 'range', 'len', 'min', 'max', 'abs', 'round', 'input', 'atol', 'atof', 'chr', 'ord', 'Error']; + +const up = (s: unknown): string => String(s).toUpperCase(); + +/** GCCount -> gc_count, MaxOf -> max_of, I -> i, COUNT_BASE -> count_base. */ +export function snake(name: string): string { + if (/^[A-Z0-9_]+$/.test(name)) return name.toLowerCase(); + return name + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') + .replace(/([a-z0-9])([A-Z])/g, '$1_$2') + .toLowerCase(); +} + +/** Words a pseudo name must not become in Mojo: keywords, builtins the translation itself calls, and imported names. */ +const RESERVED = new Set([ + 'def', 'fn', 'struct', 'trait', 'comptime', 'alias', 'var', 'ref', 'mut', 'out', 'read', 'owned', 'inout', 'deinit', 'raises', 'raise', 'try', 'except', 'finally', 'with', 'as', 'import', 'from', + 'and', 'or', 'not', 'in', 'is', 'if', 'elif', 'else', 'for', 'while', 'break', 'continue', 'return', 'pass', 'del', 'assert', 'class', 'lambda', 'global', 'yield', 'match', 'case', 'self', + 'len', 'min', 'max', 'abs', 'round', 'print', 'range', 'input', 'sum', 'type', 'list', 'str', 'int', 'float', 'set', 'dict', 'chr', 'ord', 'pow', 'sort', 'sorted', 'copy', 'main', + 'atol', 'atof', 'floor', 'ceil', 'sqrt', 'exp', 'log', 'log2', 'log10', 'sin', 'cos', 'tan', 'atan2', 'pi', 'comb', 'true', 'false', 'none', + ...Object.keys(USED_STDLIB), +]); + +const COLLECTIONS = new Set(['LIST', 'ARRAY', 'HASHMAP', 'SET', 'RECORD']); +const isCollection = (t: any): boolean => !!t && COLLECTIONS.has(t.k); + +/** A statement or expression with no faithful Mojo spelling. Caught at the statement, which becomes a visible `raise`. */ +class Gap extends Error { } + +interface Line { text: string; from: number | null } +interface Pending { d: number; text: string } +interface Ctx { sub: any | null; owner: string } + +/** An expression made only of numeric literals: Mojo folds these at compile time. */ +function litOnly(e: any): boolean { + if (!e) return false; + if (e.kind === 'Num') return true; + if (e.kind === 'Unary') return e.op !== 'NOT' && litOnly(e.arg); + if (e.kind === 'Binary') return ['+', '-', '*'].includes(e.op) && litOnly(e.left) && litOnly(e.right); + return false; +} +function hasFloatLit(e: any): boolean { + if (!e) return false; + if (e.kind === 'Num') return !!e.float || /[.e]/.test(String(e.value)); + return hasFloatLit(e.arg) || hasFloatLit(e.left) || hasFloatLit(e.right); +} + +function key(name: string): string { return up(name); } + +/* ------------------------------------------------------------------ */ +/* Which routines raise */ +/* ------------------------------------------------------------------ */ + +/** Does a statement list contain something that raises in Mojo? `raising` is the set of subroutines already known to. */ +function bodyRaises(body: any[], raising: Set): boolean { + let hit = false; + const exprHit = (e: any) => { + walkExpr(e, (x: any) => { + if (hit) return false; + if (x.kind === 'Index' && x.target?.type?.k === 'HASHMAP') hit = true; + if (x.kind === 'CallExpr') { + if (!x.builtin && raising.has(key(x.name))) hit = true; + if (x.builtin === 'TO_INTEGER' || x.builtin === 'TO_FLOAT') hit = true; + } + return undefined; + }); + }; + walkStatements(body, (s: any) => { + if (hit) return false; + if (s.kind === 'Input' || s.kind === 'Assert' || s.kind === 'BlankStmt') hit = true; + if (s.kind === 'Call' && raising.has(key(s.name))) hit = true; + if (s.kind === 'BuiltinCall' && s.name === 'DELETE') hit = true; + for (const e of statementExprs(s)) exprHit(e); + return undefined; + }); + return hit; +} + +function inferRaising(program: any, seed: Iterable): Set { + const raising = new Set(seed); + let changed = true; + while (changed) { + changed = false; + for (const sub of program.subs.values()) { + const k = key(sub.name); + if (!raising.has(k) && bodyRaises(sub.node.body, raising)) { raising.add(k); changed = true; } + } + } + return raising; +} + +/* ------------------------------------------------------------------ */ +/* The translator */ +/* ------------------------------------------------------------------ */ + +class Gen { + out: Line[] = []; + pending: Pending[] = []; + notes = new Map(); + gaps: Diagnostic[] = []; + gapOwners = new Set(); + imports = new Set(); + names = new Map(); + commentsByLine = new Map(); + usedComments = new Set(); + hoistOK = true; + temp = 0; + curLine = 1; + srcLines: string[]; + varParams = new Map(); + /** The type an empty list literal takes from where it is going (an assignment's target, a parameter, a return type). */ + hint: any = null; + temps = new Set(); + /** Set while translating a call's own text (the argument literals), which has no type annotations. */ + constructor(private program: any, private source: string, private raising: Set, private opts: MojoOptions) { + for (const c of program.comments || []) this.commentsByLine.set(c.line, c); + this.srcLines = source.split('\n'); + for (const sub of program.subs.values()) { + const changed = this.changedIn(sub.node.body); + const assigned = this.assignedIn(sub.node.body); + this.varParams.set(key(sub.name), sub.params.map((p: any) => p.mode !== 'BYREF' && ((changed.has(up(p.name)) && isCollection(p.type)) || assigned.has(up(p.name))))); + } + } + + /* ---------- bookkeeping ---------- */ + changedIn(body: any[]): Set { + const out = new Set(); + walkStatements(body, (x: any) => { + if (x.kind === 'BuiltinCall' && x.args[0]) { const r = rootName(x.args[0]); if (r) out.add(up(r)); } + if ((x.kind === 'Assign' || x.kind === 'Input') && x.target.kind !== 'Name') { const r = rootName(x.target); if (r) out.add(up(r)); } + if (x.kind === 'Call') x.args.forEach((a: any, i: number) => { if (x.sub?.params?.[i]?.mode === 'BYREF' && a.kind !== 'Name') { const r = rootName(a); if (r) out.add(up(r)); } }); + return undefined; + }); + return out; + } + + /** Names a body gives a new value to directly (X <- ..., INPUT X, a FOR counter). */ + assignedIn(body: any[]): Set { + const out = new Set(); + walkStatements(body, (x: any) => { + if ((x.kind === 'Assign' || x.kind === 'Input') && x.target.kind === 'Name') out.add(up(x.target.name)); + if (x.kind === 'For' || x.kind === 'ForEach') out.add(up(x.var)); + return undefined; + }); + return out; + } + + withHint(t: any, fn: () => T): T { + const saved = this.hint; + this.hint = t; + try { return fn(); } finally { this.hint = saved; } + } + + note(id: string, text: string): void { + if (!this.notes.has(id)) this.notes.set(id, { lang: 'mojo', severity: 'note', id: `translate-${id}`, line: this.curLine, message: text }); + } + gap(why: string): never { throw new Gap(why); } + need(name: string): void { this.imports.add(name); } + + name(n: string): string { + const k = up(n); + const have = this.names.get(k); + if (have) return have; + let s = snake(n); + if (RESERVED.has(s)) s = `${s}_`; + this.names.set(k, s); + return s; + } + constName(n: string): string { return snake(n).toUpperCase(); } + fresh(stem: string): string { const t = `_${stem}${++this.temp}`; this.temps.add(t); return t; } + + flush(indent: number, from: number | null): void { + for (const h of this.pending) this.out.push({ text: `${' '.repeat(indent + h.d)}${h.text}`, from }); + this.pending = []; + } + emit(indent: number, text: string, from: number | null): void { + this.flush(indent, from); + this.out.push({ text: text ? `${' '.repeat(indent)}${text}` : '', from }); + } + hoist(lines: Array<[number, string]>): void { + if (!this.hoistOK) this.gap('a computed value inside a condition that is checked again each time'); + for (const [d, text] of lines) this.pending.push({ d, text }); + } + + leadingComments(line: number, indent: number): void { + for (const [l, c] of this.commentsByLine) { + if (l >= line || this.usedComments.has(l) || !c.standalone) continue; + this.usedComments.add(l); + this.emit(indent, `# ${c.text}`, l); + } + } + trailing(line: number): string { + const c = this.commentsByLine.get(line); + if (!c || c.standalone || this.usedComments.has(line)) return ''; + this.usedComments.add(line); + return ` # ${c.text}`; + } + + /* ---------- types and defaults ---------- */ + type(t: any): string { + if (!t) this.gap('a value whose type is not known'); + switch (t.k) { + case 'INTEGER': return 'Int'; + case 'FLOAT': return 'Float64'; + case 'CHAR': case 'STRING': return 'String'; + case 'BOOL': return 'Bool'; + case 'ARRAY': if (t.dims === 2) return `List[List[${this.type(t.of)}]]`; return `List[${this.type(t.of)}]`; + case 'LIST': return `List[${this.type(t.of)}]`; + case 'HASHMAP': return `Dict[${this.type(t.key)}, ${this.type(t.val)}]`; + case 'SET': this.need('Set'); return `Set[${this.type(t.of)}]`; + case 'RECORD': return t.name; + default: return this.gap(`a value of kind ${t.k}`); + } + } + + /** What a declared-but-unset value holds: the notation's collections start empty, a record starts with every field at its default. */ + defaultOf(t: any): string { + switch (t?.k) { + case 'INTEGER': return '0'; + case 'FLOAT': return '0.0'; + case 'BOOL': return 'False'; + case 'CHAR': case 'STRING': return 'String("")'; + case 'LIST': case 'HASHMAP': case 'SET': return `${this.type(t)}()`; + case 'RECORD': return `${t.name}(${t.fieldNames.map((f: string) => this.defaultOf(t.fields.get(up(f)))).join(', ')})`; + default: return this.gap('a value with no default'); + } + } + + /** A value that would share storage with its source, copied: M <- L gives M its own list. */ + copied(e: any, text: string): string { + if (!isCollection(e.type) || !(['Name', 'Field', 'Index'].includes(e.kind) || this.temps.has(text))) return text; + this.note('copy', 'In the notation, assigning or returning a collection gives a separate copy. Mojo spells that .copy(), because Mojo tracks which piece of code owns a value.'); + return `${text}.copy()`; + } + + /** An INTEGER value going where a FLOAT belongs becomes a Float64, as the notation widens it. */ + widened(target: any, e: any, text: string): string { + if (target?.k === 'FLOAT' && e?.type?.k === 'INTEGER' && e.kind !== 'Num') return `Float64(${text})`; + return text; + } + + /* ---------- program ---------- */ + run(): MojoResult { + const p = this.program; + for (const c of p.constants.values()) { + this.curLine = c.line; + this.leadingComments(c.line, 0); + this.names.set(up(c.name), this.constName(c.name)); + this.guarded(null, c.line, () => this.emit(0, `comptime ${this.constName(c.name)} = ${this.expr(c.node.value)}${this.trailing(c.line)}`, c.line)); + } + for (const d of p.defines.values()) { + this.curLine = d.line; + this.leadingComments(d.line, 0); + this.guarded(null, d.line, () => { + const vals = d.node.values.map((v: any) => this.expr(v)).join(', '); + this.emit(0, `def ${this.name(d.name)}() -> ${this.type(d.type)}:${this.trailing(d.line)}`, d.line); + this.emit(1, `return ${this.type(d.type)}(${vals})`, d.line); + }); + this.note('define', 'A DEFINE set becomes a small function that builds the Set, because Mojo has no global variables; the code calls it where the pseudo names the set.'); + this.emit(0, '', null); + this.emit(0, '', null); + } + for (const t of p.types.values()) { + this.curLine = t.node.line; + this.leadingComments(t.node.line, 0); + this.emit(0, '@fieldwise_init', t.node.line); + this.emit(0, `struct ${t.name}(Copyable, Movable):`, t.node.line); + this.note('struct', 'A record becomes a struct with fields. The traits a struct declares (Copyable, Movable) change between Mojo versions.'); + for (const f of t.fieldNames) this.guarded(null, t.node.line, () => this.emit(1, `var ${this.name(f)}: ${this.type(t.fields.get(up(f)))}`, t.node.line)); + this.emit(0, '', null); + this.emit(0, '', null); + } + for (const sub of p.subs.values()) { this.subroutine(sub); this.emit(0, '', null); this.emit(0, '', null); } + this.mainFunction(); + this.leadingComments(Infinity, 0); + return this.assemble(); + } + + assemble(): MojoResult { + const imports = new Map(); + for (const n of this.imports) { + const mod = USED_STDLIB[n]; + if (!mod) continue; + if (!imports.has(mod)) imports.set(mod, []); + imports.get(mod)!.push(n); + } + const head: Line[] = [{ text: GENERATED_HEADER, from: null }]; + for (const [mod, names] of [...imports].sort((a, b) => a[0].localeCompare(b[0]))) head.push({ text: `from ${mod} import ${names.sort().join(', ')}`, from: null }); + head.push({ text: '', from: null }); + const lines = [...head, ...this.out]; + while (lines.length && !lines[lines.length - 1].text.trim()) lines.pop(); + return { source: lines.map((l) => l.text).join('\n') + '\n', map: lines.map((l) => l.from), notes: [...this.notes.values(), ...this.gaps] }; + } + + /** Run `fn`; when it finds something with no faithful Mojo, write a visible `raise` in its place. */ + guarded(owner: string | null, line: number, fn: () => void, indent = 0): void { + const saved = this.pending.length; + try { fn(); } catch (err) { + if (!(err instanceof Gap)) throw err; + this.pending.length = saved; + const text = (this.srcLines[line - 1] ?? '').trim(); + this.gaps.push({ lang: 'mojo', severity: 'warning', id: 'translate-gap', line, message: `Programming+ could not translate this line into Mojo (${err.message}). The generated code stops here with an error instead of guessing.` }); + this.emit(indent, `# pseudo line ${line}: ${text}`, line); + this.emit(indent, `raise Error("not translated: pseudo line ${line}")`, line); + this.gapOwners.add(owner ?? 'main'); + } + } + + subroutine(sub: any): void { + const s = sub.node; + this.curLine = s.line; + this.leadingComments(s.line, 0); + const k = key(sub.name); + const flags = this.varParams.get(k) || []; + let header = ''; + try { + const params = sub.params.map((p: any, i: number) => { + const n = this.name(p.name); + if (p.mode === 'BYREF') { this.note('mut', 'BYREF becomes the mut argument convention, which lets the function change the caller\'s variable.'); return `mut ${n}: ${this.type(p.type)}`; } + if (flags[i]) { this.note('var-param', 'A parameter the procedure gives a new value to or changes is declared var, so the function owns a copy it may change; for a collection the caller passes .copy().'); return `var ${n}: ${this.type(p.type)}`; } + return `${n}: ${this.type(p.type)}`; + }).join(', '); + const ret = s.kind === 'Function' ? ` -> ${this.type(sub.returns)}` : ''; + header = `def ${this.name(sub.name)}(${params})${this.raising.has(k) ? ' raises' : ''}${ret}:`; + } catch (err) { + if (!(err instanceof Gap)) throw err; + header = `def ${this.name(sub.name)}() raises:`; + this.gaps.push({ lang: 'mojo', severity: 'warning', id: 'translate-gap', line: s.line, message: `Programming+ could not write this routine's signature in Mojo (${err.message}).` }); + this.gapOwners.add(k); + this.emit(0, `${header}${this.trailing(s.line)}`, s.line); + this.emit(1, `raise Error("not translated: pseudo line ${s.line}")`, s.line); + return; + } + this.emit(0, `${header}${this.trailing(s.line)}`, s.line); + for (const r of sub.requires) this.emit(1, `# REQUIRE ${sourceOf(r.expr)}`, r.line); + for (const e of sub.ensures) this.emit(1, `# ENSURE ${sourceOf(e.expr)}`, e.line); + const before = this.out.length; + this.block(s.body, 1, { sub, owner: k }); + if (this.out.length === before) this.emit(1, 'pass', s.line); + } + + /** `def main()`: the program's own lines, then the call the student is running. */ + mainFunction(): void { + const p = this.program; + const body = p.main.body; + const callText = (this.opts.call || '').trim(); + const mainRaises = this.raising.has('MAIN'); + if (!body.length && !callText) return; + this.emit(0, `def main()${mainRaises ? ' raises' : ''}:`, body[0]?.line ?? null); + const before = this.out.length; + if (body.length) this.block(body, 1, { sub: null, owner: 'main' }); + if (callText) this.callLine(callText, 1); + if (this.out.length === before) this.emit(1, 'pass', null); + } + + /** print(f(args)): the arguments are literals in the call's own text, written for the parameter types. */ + callLine(text: string, d: number): void { + this.guarded('main', 1, () => { + const parsed: any = parseExpression(text); + if (parsed.diags.some((x: any) => x.severity === 'error') || parsed.expr.kind !== 'CallExpr') this.gap('the call is not a call'); + const call = parsed.expr; + const sub = this.program.subs.get(up(call.name)); + if (!sub || sub.params.length !== call.args.length) this.gap('the call does not match a routine'); + const flags = this.varParams.get(key(sub.name)) || []; + const args = call.args.map((a: any, i: number) => this.literal(a, sub.params[i].type, flags[i])); + const expr = `${this.name(sub.name)}(${args.join(', ')})`; + if (sub.kind === 'Function') this.emit(d, `print(${expr})`, null); + else this.emit(d, expr, null); + }, d); + } + + /** A literal argument, in the Mojo that fits its parameter. */ + literal(e: any, t: any, owned = false): string { + switch (e.kind) { + case 'Num': { const s = String(e.value); return t?.k === 'FLOAT' && !/[.e]/.test(s) ? `${s}.0` : s; } + case 'Str': case 'Char': return JSON.stringify(e.value); + case 'Bool': return e.value ? 'True' : 'False'; + case 'Unary': if (e.op === '-') return `-${this.literal(e.arg, t)}`; break; + case 'ListLit': return `${this.type(t)}(${e.items.map((x: any) => this.literal(x, t?.of)).join(', ')})`; + case 'SetLit': this.need('Set'); return `${this.type(t)}(${e.items.map((x: any) => this.literal(x, t?.of)).join(', ')})`; + default: break; + } + void owned; + return this.gap(`the argument ${sourceOf(e)}`); + } + + block(body: any[], d: number, ctx: Ctx): void { + const before = this.out.length; + for (const s of body) this.stmt(s, d, ctx); + if (this.out.length === before) this.emit(d, 'pass', null); + } + + stmt(s: any, d: number, ctx: Ctx): void { + this.curLine = s.line ?? this.curLine; + this.leadingComments(s.line, d); + this.guarded(ctx.owner, s.line, () => this.stmtBody(s, d, ctx), d); + } + + /* ---------- statements ---------- */ + stmtBody(s: any, d: number, ctx: Ctx): void { + const tr = () => this.trailing(s.line); + switch (s.kind) { + case 'Declare': { + const t = s.resolved; + // DECLARE x : T <- value (one line in the pseudo) is one line in Mojo too: var x: T = value + if (s.init && s.names.length === 1 && t.k !== 'ARRAY' && t.k !== 'RECORD') { + const a = s.init; + const value = this.withHint(a.target.type, () => this.expr(a.value)); + const typed = ['LIST', 'HASHMAP', 'SET'].includes(t.k) ? '' : `: ${this.type(t)}`; + this.emit(d, `var ${this.name(s.names[0].name)}${typed} = ${this.widened(a.target.type, a.value, this.copied(a.value, value))}${tr()}`, s.line); + a.mergedIntoDeclare = true; + return; + } + for (const n of s.names) { + const v = this.name(n.name); + if (t.k === 'ARRAY') { this.arrayDecl(v, t, d, s.line); continue; } + if (['LIST', 'HASHMAP', 'SET'].includes(t.k) || t.k === 'RECORD') this.emit(d, `var ${v} = ${this.defaultOf(t)}${tr()}`, s.line); + else this.emit(d, `var ${v}: ${this.type(t)}${tr()}`, s.line); + if (t.k === 'RECORD') this.note('record-init', 'A struct in Mojo is created with a value for every field at once; the translation starts every field at its default, and the pseudo\'s field assignments change them afterwards.'); + } + return; + } + case 'Assign': { + if (s.mergedIntoDeclare) return; + const value = this.withHint(s.target.type, () => this.expr(s.value)); + this.emit(d, `${this.lhs(s.target)} = ${this.widened(s.target.type, s.value, this.copied(s.value, value))}${tr()}`, s.line); + return; + } + case 'Input': { + const t = s.target.type; + const read = 'input()'; + const conv = t?.k === 'INTEGER' ? `atol(${read})` : t?.k === 'FLOAT' ? `atof(${read})` : t?.k === 'BOOL' ? `${read} == "TRUE"` : read; + this.emit(d, `${this.lhs(s.target)} = ${conv}${tr()}`, s.line); + return; + } + case 'Output': { + const vals = s.values.map((v: any) => this.outputValue(v)); + this.emit(d, `print(${vals.join(', ')}${vals.length > 1 ? ', sep=""' : ''})${tr()}`, s.line); + return; + } + case 'If': { + const conds = s.branches.map((b: any, i: number) => { this.hoistOK = i === 0; try { return this.expr(b.cond); } finally { this.hoistOK = true; } }); + s.branches.forEach((b: any, i: number) => { + this.emit(d, `${i ? 'elif' : 'if'} ${conds[i]}:${i ? this.trailing(b.line) : tr()}`, b.line); + this.block(b.body, d + 1, ctx); + }); + if (s.elseBody) { this.emit(d, 'else:', s.elseLine); this.block(s.elseBody, d + 1, ctx); } + return; + } + case 'Case': { + const subj = this.expr(s.subject); + const arms = s.arms.map((a: any) => a.labels.map((l: any) => (l.value ? `${subj} == ${this.expr(l.value)}` : `${this.expr(l.low)} <= ${subj} < ${this.expr(l.high)}`)).join(' or ')); + s.arms.forEach((a: any, i: number) => { + this.emit(d, `${i ? 'elif' : 'if'} ${arms[i]}:`, a.line); + this.block(a.body, d + 1, ctx); + }); + if (s.otherwise) { this.emit(d, s.arms.length ? 'else:' : 'if True:', s.otherwiseLine); this.block(s.otherwise, d + 1, ctx); } + this.note('case', 'Mojo has no CASE statement: it becomes a chain of if and elif.'); + return; + } + case 'For': { + const i = this.name(s.var); + const a = this.expr(s.start); const b = this.expr(s.stop); + const r = s.step ? `range(${a}, ${b}, ${this.expr(s.step)})` : a === '0' ? `range(${b})` : `range(${a}, ${b})`; + for (const inv of s.invariants || []) this.emit(d, `# INVARIANT ${sourceOf(inv.expr)}`, inv.line); + if (s.parallel) this.emit(d, '# PARALLEL FOR: the passes are independent; this translation runs them one after another', s.line); + this.emit(d, `for ${i} in ${r}:${tr()}`, s.line); + this.block(s.body, d + 1, ctx); + return; + } + case 'ForEach': { + const x = this.name(s.var); + const it = s.iterable; + const coll = this.expr(it); + if (it.type?.k === 'STRING') { + const k = this.fresh(`${x}_pos`); + this.emit(d, `for ${k} in range(${coll}.count_codepoints()):${tr()}`, s.line); + this.emit(d + 1, `var ${x} = String(${coll}[codepoint=${k}])`, s.line); + } else if (it.type?.k === 'HASHMAP' || it.type?.k === 'SET') { + this.emit(d, `for ${x} in ${coll}${it.type.k === 'HASHMAP' ? '.keys()' : ''}:${tr()}`, s.line); + this.note('each-order', 'The lab visits SET members and HASHMAP keys smallest first. Mojo visits them in its own order, which the notation never promised; a program whose answer depends on that order is worth rewriting.'); + } else if (it.kind === 'Range') { + this.emit(d, `for ${x} in range(${this.expr(it.lo)}, ${this.expr(it.hi)}):${tr()}`, s.line); + } else { + // FOR EACH walks a snapshot, so a body that changes the list does not change the walk + const r = rootName(it); + const snap = r && this.changedIn(s.body).has(up(r)); + if (snap) this.note('each-snapshot', 'FOR EACH walks the collection as it was when the loop began. The body changes it, so the translation walks a copy.'); + this.emit(d, `for ${x} in ${snap ? `${coll}.copy()` : coll}:${tr()}`, s.line); + } + this.block(s.body, d + 1, ctx); + return; + } + case 'While': { + this.hoistOK = false; + let cond: string; + try { cond = this.expr(s.cond); } finally { this.hoistOK = true; } + for (const inv of s.invariants || []) this.emit(d, `# INVARIANT ${sourceOf(inv.expr)}`, inv.line); + if (s.decreases) this.emit(d, `# DECREASES ${sourceOf(s.decreases.expr)}`, s.decreases.line); + this.emit(d, `while ${cond}:${tr()}`, s.line); + this.block(s.body, d + 1, ctx); + return; + } + case 'Repeat': { + this.hoistOK = false; + let cond: string; + try { cond = this.expr(s.cond); } finally { this.hoistOK = true; } + this.emit(d, `while True:${tr()}`, s.line); + this.block(s.body, d + 1, ctx); + this.emit(d + 1, `if ${cond}:`, s.endLine); + this.emit(d + 2, 'break', s.endLine); + this.note('repeat', 'REPEAT ... UNTIL has no direct counterpart: it becomes while True, with a break at the end once the UNTIL condition holds.'); + return; + } + case 'Break': this.emit(d, `break${tr()}`, s.line); return; + case 'Continue': this.emit(d, `continue${tr()}`, s.line); return; + case 'Return': { + if (!s.value) { this.emit(d, `return${tr()}`, s.line); return; } + const v = this.copied(s.value, this.withHint(ctx.sub?.returns, () => this.expr(s.value))); + this.emit(d, `return ${this.widened(ctx.sub?.returns, s.value, v)}${tr()}`, s.line); + return; + } + case 'Call': { + const flags = this.varParams.get(key(s.name)) || []; + const args = s.args.map((a: any, i: number) => this.callArg(a, s.sub?.params?.[i], flags[i])); + this.emit(d, `${this.name(s.name)}(${args.join(', ')})${tr()}`, s.line); + return; + } + case 'BuiltinCall': this.emit(d, `${this.builtinStmt(s)}${tr()}`, s.line); return; + case 'ExprStmt': this.emit(d, `${this.expr(s.expr)}${tr()}`, s.line); return; + case 'Assert': { + const c = this.expr(s.expr); + this.emit(d, `if not (${c}):`, s.line); + this.emit(d + 1, `raise Error("ASSERT failed on pseudo line ${s.line}: ${sourceOf(s.expr).replace(/["\\]/g, '')}")`, s.line); + return; + } + case 'BlankStmt': this.gap(`a blank to fill in: <${s.text}>`); return; + default: return; + } + } + + /** DECLARE A : ARRAY[n] OF T: a list filled to its length, the way the verified programs do it (an append loop, since List(length=) is not run by the interpreter). */ + arrayDecl(v: string, t: any, d: number, line: number): void { + const dims = (t.dimExprs || []).map((x: any) => this.expr(x)); + const fill = this.defaultOf(t.of); + if (dims.length === 2) { + const row = this.fresh('row'); + this.emit(d, `var ${v} = ${this.type(t)}()`, line); + this.emit(d, `for _ in range(${dims[0]}):`, line); + this.emit(d + 1, `var ${row} = List[${this.type(t.of)}]()`, line); + this.emit(d + 1, `for _ in range(${dims[1]}):`, line); + this.emit(d + 2, `${row}.append(${fill})`, line); + this.emit(d + 1, `${v}.append(${row}^)`, line); + } else { + this.emit(d, `var ${v} = ${this.type(t)}()`, line); + this.emit(d, `for _ in range(${dims[0]}):`, line); + this.emit(d + 1, `${v}.append(${fill})`, line); + } + this.note('array', 'A fixed-length ARRAY becomes a list filled to its full length with an append loop, so every cell holds a value.'); + } + + callArg(a: any, param: any, owned: boolean | undefined): string { + const text = this.widened(param?.type, a, this.withHint(param?.type, () => this.expr(a))); + return owned ? this.copied(a, text) : text; + } + + builtinStmt(s: any): string { + const [a, b, c] = s.args.map((x: any) => this.expr(x)); + switch (s.name) { + case 'APPEND': return `${a}.append(${b})`; + case 'INSERT': return `${a}.insert(${b}, ${c})`; + case 'REMOVE': return `_ = ${a}.pop(${b})`; + case 'ADD': return `${a}.add(${b})`; + case 'DELETE': return `_ = ${a}.pop(${b})`; + case 'SORT': this.need('sort'); return `sort(${a})`; + default: return this.gap(`the built-in ${s.name}`); + } + } + + lhs(t: any): string { return this.expr(t, true); } + + outputValue(v: any): string { + if (v.type?.k === 'BOOL') return `("TRUE" if ${this.expr(v)} else "FALSE")`; + return this.expr(v); + } + + /* ---------- expressions ---------- */ + /** An iteration source for a quantifier or set builder: a range, or a collection's items. */ + domain(dom: any): string { + return dom.kind === 'Range' ? `range(${this.expr(dom.lo)}, ${this.expr(dom.hi)})` : this.expr(dom); + } + + expr(e: any, isTarget = false): string { + const P = (x: any) => (x && ['Binary', 'Chain', 'Quant', 'Unary'].includes(x.kind) ? `(${this.expr(x)})` : this.expr(x)); + switch (e.kind) { + case 'Num': { const t = String(e.value); return e.float && !/[.e]/.test(t) ? `${t}.0` : t; } + case 'Str': case 'Char': return JSON.stringify(e.value); + case 'Bool': return e.value ? 'True' : 'False'; + case 'Blank': return this.gap(`a blank to fill in: <${e.text}>`); + case 'Name': + if (e.sym?.kind === 'const') return this.constName(e.name); + if (e.sym?.kind === 'define') return `${this.name(e.name)}()`; + if (up(e.name) === 'RESULT' && e.sym?.kind === 'result') return this.gap('RESULT'); + return this.name(e.name); + case 'Unary': return e.op === 'NOT' ? `not ${P(e.arg)}` : `-${P(e.arg)}`; + case 'Binary': { + const map: Record = { AND: 'and', OR: 'or', DIV: '//', MOD: '%', '^': '**', '&': '+', IN: 'in' }; + if (e.op === '/') this.note('divide', 'In the notation, dividing by zero stops the program. In Mojo a Float64 division by zero gives inf or nan and the program goes on.'); + if (e.op === '/') return `Float64(${this.expr(e.left)}) / Float64(${this.expr(e.right)})`; + if (e.op === 'IN' && e.right.kind === 'Range') return `${this.expr(e.right.lo)} <= ${P(e.left)} < ${this.expr(e.right.hi)}`; + if (e.op === '&') { + const side = (x: any) => (x.type?.k === 'CHAR' || x.type?.k === 'STRING' ? P(x) : `String(${this.expr(x)})`); + return `${side(e.left)} + ${side(e.right)}`; + } + let left = this.sideExpr(e.left, e, 'l'); + // Mojo folds arithmetic on float literals exactly (0.1 + 0.2 == 0.3); the notation computes with Float64, so the left side is made one + if (litOnly(e.left) && litOnly(e.right) && (hasFloatLit(e.left) || hasFloatLit(e.right)) && !left.startsWith('Float64(') && ['+', '-', '*', '==', '!=', '<', '<=', '>', '>='].includes(e.op)) left = `Float64(${left})`; + return `${left} ${map[e.op] || e.op} ${this.sideExpr(e.right, e, 'r')}`; + } + case 'Chain': return e.operands.map((o: any, i: number) => (i ? `${e.ops[i - 1] === 'IN' ? 'in' : e.ops[i - 1]} ${P(o)}` : P(o))).join(' '); + case 'Index': { + const t = this.expr(e.target); + if (e.target.type?.k === 'STRING' && !isTarget) return `String(${t}[codepoint=${this.expr(e.indices[0])}])`; + if (e.indices.length === 2) return `${t}[${this.expr(e.indices[0])}][${this.expr(e.indices[1])}]`; + return `${t}[${this.expr(e.indices[0])}]`; + } + case 'Field': return `${this.expr(e.target)}.${this.name(e.field)}`; + case 'CallExpr': return this.call(e); + case 'ListLit': { + const t = e.type?.k === 'LIST' && e.type.of?.k !== 'ANY' ? e.type : this.hint?.k === 'LIST' || this.hint?.k === 'ARRAY' ? this.hint : e.type; + return `${this.type(t)}(${e.items.map((x: any) => this.withHint(t?.of, () => this.expr(x))).join(', ')})`; + } + case 'SetLit': this.need('Set'); return `${this.type(e.type?.of?.k !== 'ANY' ? e.type : this.hint)}(${e.items.map((x: any) => this.expr(x)).join(', ')})`; + case 'MapLit': return `{${e.entries.map((x: any) => `${this.expr(x.key)}: ${this.expr(x.value)}`).join(', ')}}`; + case 'Range': return `range(${this.expr(e.lo)}, ${this.expr(e.hi)})`; + case 'SetBuilder': { + const v = this.name(e.var); + const dom = this.domain(e.domain); + const t = this.fresh('set'); + this.hoistOK = false; + let body: string; + try { body = this.expr(e.body); } finally { this.hoistOK = true; } + this.hoist([[0, `var ${t} = ${this.type(e.type)}()`], [0, `for ${v} in ${dom}:`], [1, `if ${body}:`], [2, `${t}.add(${v})`]]); + this.note('comprehension', 'Mojo has no set comprehension, so a set written by rule becomes a loop, written just before the line that uses it, that fills a Set.'); + return t; + } + case 'Quant': { + const v = this.name(e.var); + const dom = this.domain(e.domain); + const t = this.fresh(e.q === 'FORALL' ? 'all' : e.q === 'EXISTS' ? 'any' : 'sum'); + const saved = this.hoistOK; + this.hoistOK = false; + let body: string; + try { body = this.expr(e.body); } finally { this.hoistOK = saved; } + if (e.q === 'FORALL') this.hoist([[0, `var ${t} = True`], [0, `for ${v} in ${dom}:`], [1, `if not (${body}):`], [2, `${t} = False`], [2, 'break']]); + else if (e.q === 'EXISTS') this.hoist([[0, `var ${t} = False`], [0, `for ${v} in ${dom}:`], [1, `if ${body}:`], [2, `${t} = True`], [2, 'break']]); + else this.hoist([[0, `var ${t} = ${e.type?.k === 'FLOAT' ? '0.0' : '0'}`], [0, `for ${v} in ${dom}:`], [1, `${t} += ${body}`]]); + this.note('quantifier', 'FORALL, EXISTS, and SUM have no one-line Mojo spelling; they become a loop, written just before the line that uses them, that sets a flag or adds to a running total.'); + return t; + } + default: return this.gap(`a ${e.kind} expression`); + } + } + + /** An operand of a binary operator: parenthesized when precedence needs it, and an Int meeting a Float64 is converted. */ + sideExpr(x: any, parent: any, side: 'l' | 'r'): string { + const BIND: Record = { OR: 1, AND: 2, '==': 4, '!=': 4, '<': 4, '<=': 4, '>': 4, '>=': 4, IN: 4, '&': 5, '+': 6, '-': 6, '*': 7, '/': 7, DIV: 7, MOD: 7, '^': 9 }; + let s = this.expr(x); + const other = side === 'l' ? parent.right : parent.left; + if (['+', '-', '*', '==', '!=', '<', '<=', '>', '>='].includes(parent.op) && x.type?.k === 'INTEGER' && other?.type?.k === 'FLOAT' && x.kind !== 'Num') s = `Float64(${s})`; + if (x.kind === 'Chain' || x.kind === 'Quant') return `(${s})`; + if (x.kind === 'Unary' && x.op === 'NOT' && BIND[parent.op] > 3) return `(${s})`; + if (x.kind !== 'Binary') return s; + const a = BIND[x.op]; const b = BIND[parent.op]; + if (a < b || (a === b && side === 'r' && !(parent.op === x.op && ['+', '*', 'AND', 'OR', '&'].includes(parent.op))) || (a === 4 && b === 4)) return `(${s})`; + return s; + } + + /** A built-in that is a short loop: write it before the statement and name its result. */ + loopResult(stem: string, type: string, init: string, lines: Array<[number, string]>): string { + const t = this.fresh(stem); + this.hoist([[0, `var ${t}${type ? `: ${type}` : ''} = ${init}`], ...lines.map(([d, x]): [number, string] => [d, x.split('$T').join(t)])]); + return t; + } + + call(e: any): string { + if (e.isOld) return this.gap('OLD(...) outside a contract'); + if (!e.builtin) { + const flags = this.varParams.get(key(e.name)) || []; + const args = e.args.map((a: any, i: number) => this.callArg(a, e.sub?.params?.[i], flags[i])); + return `${this.name(e.name)}(${args.join(', ')})`; + } + const args: string[] = e.args.map((a: any) => this.expr(a)); + const [a, b, c] = args; + const t0 = e.args[0]?.type?.k; + const math = (f: string): string => { this.need(f); return `${f}(Float64(${a}))`; }; + switch (e.builtin) { + case 'LENGTH': return t0 === 'STRING' ? `${a}.count_codepoints()` : `len(${a})`; + case 'ROWS': return `len(${a})`; + case 'COLUMNS': return `len(${a}[0])`; + case 'INT': return `Int(${a})`; + case 'ROUND': return `Int(round(${a}))`; + case 'ABS': return `abs(${a})`; + case 'MIN': case 'MAX': { + const mixed = e.type?.k === 'FLOAT' && e.args.length > 1 && e.args.some((x: any) => x.type?.k === 'INTEGER'); + return `${e.builtin.toLowerCase()}(${args.map((x, i) => (mixed ? this.widened(e.type, e.args[i], x) : x)).join(', ')})`; + } + case 'SQRT': return math('sqrt'); + case 'EXP': return math('exp'); + case 'LOG': return math('log'); + case 'LOG2': return math('log2'); + case 'LOG10': return math('log10'); + case 'SIN': return math('sin'); + case 'COS': return math('cos'); + case 'TAN': return math('tan'); + case 'ATAN2': this.need('atan2'); return `atan2(Float64(${a}), Float64(${b}))`; + case 'PI': this.need('pi'); return 'pi'; + case 'CHOOSE': this.need('comb'); return `comb(${a}, ${b})`; + case 'FLOOR': this.need('floor'); return `Int(floor(${a}))`; + case 'CEIL': this.need('ceil'); return `Int(ceil(${a}))`; + case 'RAND': this.need('random_float64'); return `random_float64() * ${a}`; + case 'RANDINT': this.need('random_si64'); return `Int(random_si64(${a}, ${b} - 1))`; + case 'SLICE': + if (t0 === 'STRING') { + // the verified programs build a piece of a String letter by letter; s[byte=a:b] counts bytes and is not run by the interpreter + const k = this.fresh('at'); + this.note('slice', 'A piece of a String is built letter by letter, which counts characters the way the notation does.'); + return this.loopResult('piece', '', 'String("")', [[0, `for ${k} in range(${b}, ${c}):`], [1, `$T += String(${a}[codepoint=${k}])`]]); + } + return `${a}[${b}:${c}]`; + case 'UPPER': return `${a}.upper()`; + case 'LOWER': return `${a}.lower()`; + case 'ORD': return `ord(${a})`; + case 'CHR': return `chr(${a})`; + case 'TO_STRING': return `String(${a})`; + case 'TO_INTEGER': return `atol(${a})`; + case 'TO_FLOAT': return t0 === 'STRING' ? `atof(${a})` : `Float64(${a})`; + case 'REPLACE': return `${a}.replace(${b}, ${c})`; + case 'JOIN': return `${b}.join(${a})`; + case 'INDEX_OF': + if (t0 === 'STRING') return `${a}.find(${b})`; + { + const i = this.fresh('i'); + return this.loopResult('at', '', '-1', [[0, `for ${i} in range(len(${a})):`], [1, `if ${a}[${i}] == ${b}:`], [2, `$T = ${i}`], [2, 'break']]); + } + case 'SPLIT': { + const p = this.fresh('piece'); + const parts = this.fresh('parts'); + this.hoist([[0, `var ${parts} = List[String]()`], [0, `for ${p} in ${a}.split(${b}):`], [1, `${parts}.append(String(${p}))`]]); + return parts; + } + case 'FILL': { + const ty = this.type(e.type?.of ?? e.args[1]?.type); + return this.loopResult('fill', '', `List[${ty}]()`, [[0, 'for _ in range(' + a + '):'], [1, `$T.append(${b})`]]); + } + case 'SUM_OF': { + const x = this.fresh('x'); + const zero = e.type?.k === 'FLOAT' ? '0.0' : '0'; + return this.loopResult('total', '', zero, [[0, `for ${x} in ${a}:`], [1, `$T += ${x}`]]); + } + case 'MEAN_OF': { + const x = this.fresh('x'); + const sum = this.loopResult('total', '', '0.0', [[0, `for ${x} in ${a}:`], [1, `$T += Float64(${x})`]]); + return `(${sum} / Float64(len(${a})))`; + } + case 'DOT': { + const i = this.fresh('i'); + return this.loopResult('dot', '', e.type?.k === 'FLOAT' ? '0.0' : '0', [[0, `for ${i} in range(len(${a})):`], [1, `$T += ${a}[${i}] * ${b}[${i}]`]]); + } + case 'VARIANCE_OF': case 'STDEV_OF': { + const x = this.fresh('x'); + const m = this.loopResult('mean', '', '0.0', [[0, `for ${x} in ${a}:`], [1, `$T += Float64(${x})`]]); + this.hoist([[0, `${m} = ${m} / Float64(len(${a}))`]]); + const v = this.loopResult('var', '', '0.0', [[0, `for ${x} in ${a}:`], [1, `$T += (Float64(${x}) - ${m}) * (Float64(${x}) - ${m})`]]); + this.hoist([[0, `${v} = ${v} / Float64(len(${a}) - 1)`]]); + this.note('statistics', 'The standard library has no variance or standard deviation, so they are written as loops: the sample variance divides by n - 1, as the notation does.'); + if (e.builtin === 'VARIANCE_OF') return v; + this.need('sqrt'); + return `sqrt(${v})`; + } + case 'NORM_OF': { + const x = this.fresh('x'); + this.need('sqrt'); + const q = this.loopResult('squares', '', '0.0', [[0, `for ${x} in ${a}:`], [1, `$T += Float64(${x}) * Float64(${x})`]]); + return `sqrt(${q})`; + } + case 'MEDIAN_OF': { + const x = this.fresh('x'); + this.need('sort'); + const of = e.args[0].type?.of; + const sorted = this.loopResult('sorted', '', `${this.type({ k: 'LIST', of })}()`, [[0, `for ${x} in ${a}:`], [1, `$T.append(${x})`]]); + this.hoist([[0, `sort(${sorted})`]]); + const mid = this.loopResult('median', '', '0.0', [ + [0, `if len(${sorted}) % 2 == 1:`], [1, `$T = Float64(${sorted}[len(${sorted}) // 2])`], + [0, 'else:'], [1, `$T = (Float64(${sorted}[len(${sorted}) // 2 - 1]) + Float64(${sorted}[len(${sorted}) // 2])) / 2.0`], + ]); + return mid; + } + case 'KEYS': { + const k = this.fresh('k'); + this.need('sort'); + const keys = this.loopResult('keys', '', `${this.type({ k: 'LIST', of: e.args[0].type.key })}()`, [[0, `for ${k} in ${a}.keys():`], [1, `$T.append(${k})`]]); + this.hoist([[0, `sort(${keys})`]]); + return keys; + } + case 'SORTED': { + const k = this.fresh('x'); + this.need('sort'); + const of = e.args[0].type?.k === 'SET' ? e.args[0].type.of : e.args[0].type?.of; + const items = this.loopResult('sorted', '', `${this.type({ k: 'LIST', of })}()`, [[0, `for ${k} in ${a}:`], [1, `$T.append(${k})`]]); + this.hoist([[0, `sort(${items})`]]); + return items; + } + default: + return this.gap(`the built-in ${e.builtin}, which Mojo's standard library has no function for`); + } + } +} + +/* ------------------------------------------------------------------ */ +/* Entry point */ +/* ------------------------------------------------------------------ */ + +/** + * Translate pseudo to Mojo. Returns `unsupported` only when the pseudo does + * not parse or check; everything else yields Mojo, with a diagnostic for each + * line that could not be translated. + */ +export function pseudoToMojo(pseudo: string, opts: MojoOptions = {}): MojoResult | { unsupported: Diagnostic[] } { + const st: any = study(pseudo, { coach: false }); + if (!st.ok || !st.program) { + const errors = (st.diags as any[]).filter((d) => d.severity === 'error').map((d) => toDiagnostic(d)); + return { unsupported: errors.length ? errors : [{ lang: 'pseudo', severity: 'error', id: 'translate-no-program', line: 1, message: 'The pseudo does not read yet, so there is nothing to translate.' }] }; + } + const program = st.program; + const callText = (opts.call || '').trim(); + const callName = callText ? /^\s*([A-Za-z_][A-Za-z0-9_]*)/.exec(callText)?.[1] : null; + // Inference, then translation; a line that could not be translated becomes a raise, so its routine raises too, and the pass is run again. + const extra = new Set(); + for (let pass = 0; ; pass++) { + const raising = inferRaising(program, extra); + if (bodyRaises(program.main.body, raising)) raising.add('MAIN'); + if (callName && raising.has(up(callName))) raising.add('MAIN'); + for (const k of extra) if (k === 'MAIN') raising.add('MAIN'); + const gen = new Gen(program, pseudo, raising, opts); + const result = gen.run(); + const fresh = [...gen.gapOwners].map(up).filter((k) => !raising.has(k === 'MAIN' ? 'MAIN' : k)); + if (!fresh.length || pass >= 3) return result; + for (const k of fresh) extra.add(k); + } +} + +/** The set of names a generated source may use from the standard library, for the grounding test. */ +export function stdlibNamesUsed(): string[] { return Object.keys(USED_STDLIB); } +export const STD_INDEX = MOJO_STD_EXPORTS; diff --git a/src/sync/types.ts b/src/sync/types.ts new file mode 100644 index 0000000..eb3afd8 --- /dev/null +++ b/src/sync/types.ts @@ -0,0 +1,36 @@ +/** + * The shapes every translator in src/sync/ shares (restructure plan, section 2.3). + * + * Pseudo is the hub: lingo, matho, and Mojo each translate to or from pseudo, + * never to each other. A translator is a pure function of text. + */ +import type { Diagnostic } from '../core/types.js'; + +/** + * Where each line of a translator's output came from. Entry `i` is the + * 1-based line of the input that output line `i + 1` was made from, or null + * for a line with no single source (a header comment, an import, a blank). + * Maps compose through the hub: lingo line -> pseudo line -> Mojo line. + */ +export type LineMap = Array; + +/** + * Spellings that the pseudo cannot hold. Matho lowers `\bar{x}` to X_BAR and + * `\sigma` to SIGMA; the map records the student's own spelling, keyed by the + * pseudo name (upper case), so a round trip restores it. + */ +export type NameMap = Record; + +/** Source in some language to pseudo. */ +export interface ToPseudo { + (source: string): { pseudo: string; map: LineMap; diagnostics: Diagnostic[]; names?: NameMap } | { error: Diagnostic[] }; +} + +/** Pseudo to some language. `unsupported` means the language cannot say this program. */ +export interface FromPseudo { + (pseudo: string, hints?: { names?: NameMap }): { source: string; map: LineMap; notes: Diagnostic[] } | { unsupported: Diagnostic[] }; +} + +export function isUnsupported(r: ReturnType): r is { unsupported: Diagnostic[] } { + return 'unsupported' in r; +} diff --git a/src/ui/dom.ts b/src/ui/dom.ts new file mode 100644 index 0000000..36a645d --- /dev/null +++ b/src/ui/dom.ts @@ -0,0 +1,60 @@ +/** Minimal DOM helpers. No framework; the app is small enough to render by hand. */ + +type Child = Node | string | number | null | undefined | false | Child[]; + +export function el(tag: K, attrs: Record = {}, ...children: Child[]): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k === 'class') node.className = String(v); + else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v); + else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v); + else if (k === 'dataset') Object.assign(node.dataset, v); + else if (k === 'value' || k === 'checked' || k === 'selected' || k === 'disabled' || k === 'readOnly') (node as any)[k] = v; + else if (k in node && typeof v !== 'string') (node as any)[k] = v; + else node.setAttribute(k, String(v)); + } + add(node, children); + return node; +} + +export function add(parent: Node, ...children: Child[]): void { + for (const c of children) { + if (c == null || c === false) continue; + if (Array.isArray(c)) add(parent, ...c); + else parent.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c); + } +} + +export function clear(node: Node): void { + while (node.firstChild) node.removeChild(node.firstChild); +} + +export function frag(...children: Child[]): DocumentFragment { + const f = document.createDocumentFragment(); + add(f, children); + return f; +} + +/** A button with the app's `btn` look; classes given in `attrs` are added to it, never in place of it. */ +export function button(label: string, onClick: (e: MouseEvent) => void, attrs: Record = {}): HTMLButtonElement { + const cls = new Set(['btn', ...String(attrs.class ?? '').split(/\s+/).filter(Boolean)]); + return el('button', { type: 'button', onClick, ...attrs, class: [...cls].join(' ') }, label); +} + +export function debounce void>(fn: T, ms: number): T { + let h: number | undefined; + return ((...a: any[]) => { clearTimeout(h); h = window.setTimeout(() => fn(...a), ms); }) as T; +} + +export async function copyText(text: string): Promise { + try { await navigator.clipboard.writeText(text); return true; } catch { + const ta = el('textarea', { value: text, style: { position: 'fixed', opacity: '0' } }); + document.body.appendChild(ta); ta.select(); + try { return document.execCommand('copy'); } finally { ta.remove(); } + } +} + +export function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] as string)); +} diff --git a/src/ui/editor.ts b/src/ui/editor.ts new file mode 100644 index 0000000..1835b14 --- /dev/null +++ b/src/ui/editor.ts @@ -0,0 +1,417 @@ +/** + * The code editor: CodeMirror 6 (vendored as src/vendor/codemirror.js) behind + * the small interface the shell and the embeds program against. What + * Programming+ adds on top of a stock editor: + * + * - highlighting from the language service's own tokenizer (the same one + * the reference and the home page use), so the editor cannot drift from + * the parser; + * - a gutter that is a teaching instrument: diagnostic marks, breakpoints, + * how often each line ran, and an arrow on the line about to run; + * - the line about to run, the line that just ran, and lines linked from + * a view, as line decorations; + * - each line's first diagnostic at the end of the line, so nothing needs a + * hover; and the reference entry for whatever the pointer rests on. + * + * Tab indents (Shift+Tab outdents), Enter follows the language's own + * indentation rule, Ctrl+/ toggles the line comment, Ctrl+Z/Y undo and redo, + * Ctrl+F searches, Ctrl+G goes to a line, Ctrl+] / Ctrl+[ indent and outdent. + */ +import { el } from './dom.js'; +import type { Diagnostic, LangId, QuickFix } from '../core/types.js'; +import { explain } from '../core/reference.js'; +import { tooltip } from './tooltip.js'; +import { + EditorView, EditorState, Decoration, type DecorationSet, StateField, StateEffect, RangeSetBuilder, RangeSet, + gutter, GutterMarker, gutterLineClass, lineNumbers, keymap, placeholder, WidgetType, Compartment, + history, historyKeymap, defaultKeymap, searchKeymap, search, highlightSelectionMatches, gotoLine, indentMore, indentLess, + bracketMatching, indentUnit, Transaction, type Extension, +} from '../vendor/codemirror.js'; + +export type Tokenizer = (line: string) => Array<{ text: string; cls: string }>; +/** A whole document at once, for languages whose strings span lines. */ +export type DocumentTokenizer = (source: string) => Array>; + +export interface EditorOptions { + tokenize?: Tokenizer; + /** Preferred over `tokenize` when given: the editor tokenizes the document, not each line alone. */ + tokenizeLines?: DocumentTokenizer; + /** The indentation for the line after `line` (Enter); the default rule is the pseudocode's. */ + nextIndent?: (line: string, step: string) => string; + /** The line comment, for Ctrl+/ (Cmd+/). */ + lineComment?: string; + readOnly?: boolean; + placeholder?: string; + onChange?: (value: string) => void; + onCursorLine?: (line: number) => void; + /** Called when the user clicks a diagnostic mark in the gutter. */ + onDiagnosticClick?: (d: Diagnostic) => void; + tabSize?: number; + /** Which language's reference explains hovered words. */ + lang?: LangId; + /** Extra explanations for hovered words (a target language's keywords, say). */ + explainWord?: (word: string, line: string) => { title: string; body: string; where?: string } | null; + /** Show each line's first diagnostic at the end of the line, so nothing needs a hover. */ + inlineMessages?: boolean; + /** A click on a line number (breakpoints). */ + onLineClick?: (line: number) => void; + /** Smaller type, for a companion or an embed. */ + compact?: boolean; +} + +export interface LineDecorations { + /** Line about to run. */ + current?: number | null; + /** Line that just ran. */ + last?: number | null; + /** How many times each line has run. */ + hits?: Map; + /** Lines linked from the other pane (hover). */ + linked?: Set; + /** Breakpoints. */ + breakpoints?: Set; +} + +/* ------------------------------------------------------------------ */ +/* State the shell pushes in: diagnostics and line decorations */ +/* ------------------------------------------------------------------ */ + +interface Extras { diagnostics: Diagnostic[]; deco: LineDecorations; inline: boolean } +const setExtras = StateEffect.define(); +const extrasField = StateField.define({ + create: () => ({ diagnostics: [], deco: {}, inline: true }), + update(v, tr) { for (const e of tr.effects) if (e.is(setExtras)) v = e.value; return v; }, +}); + +function worstOf(ds: Diagnostic[]): '' | 'error' | 'warning' | 'note' { + return ds.some((d) => d.severity === 'error') ? 'error' : ds.some((d) => d.severity === 'warning') ? 'warning' : ds.length ? 'note' : ''; +} + +function byLine(ds: Diagnostic[]): Map { + const m = new Map(); + for (const d of ds) { const a = m.get(d.line) || []; a.push(d); m.set(d.line, a); } + return m; +} + +class MessageWidget extends WidgetType { + constructor(private text: string, private cls: string) { super(); } + eq(o: MessageWidget) { return o.text === this.text && o.cls === this.cls; } + toDOM() { return el('span', { class: `ed-msg ed-msg-${this.cls}` }, this.text); } + ignoreEvent() { return true; } +} + +/** Line classes (current, last, linked, diagnostics) and the inline messages. */ +const lineDecorations = EditorView.decorations.compute([extrasField, 'doc'], (state) => { + const { diagnostics, deco, inline } = state.field(extrasField); + const lines = byLine(diagnostics); + const touched = new Set([...lines.keys()]); + if (deco.current) touched.add(deco.current); + if (deco.last) touched.add(deco.last); + for (const l of deco.linked ?? []) touched.add(l); + const items: Array<{ from: number; deco: Decoration }> = []; + for (const n of touched) { + if (n < 1 || n > state.doc.lines) continue; + const line = state.doc.line(n); + const ds = lines.get(n) || []; + const worst = worstOf(ds); + const cls = ['ed-line', worst && `ed-line-${worst}`, deco.current === n && 'ed-current', deco.last === n && 'ed-last', deco.linked?.has(n) && 'ed-linked'].filter(Boolean).join(' '); + items.push({ from: line.from, deco: Decoration.line({ class: cls }) }); + const shown = ds.filter((d) => d.severity !== 'note'); + if (inline && shown.length) { + const msg = shown[0].message.length > 110 ? shown[0].message.slice(0, 107) + '…' : shown[0].message; + items.push({ from: line.to, deco: Decoration.widget({ widget: new MessageWidget(` ◂ ${msg}${shown.length > 1 ? ` (+${shown.length - 1} more)` : ''}`, worst || 'note'), side: 1 }) }); + } + } + items.sort((a, b) => a.from - b.from || (a.deco.spec.widget ? 1 : -1)); + const b = new RangeSetBuilder(); + for (const it of items) b.add(it.from, it.from, it.deco); + return b.finish(); +}); + +/* ------------------------------------------------------------------ */ +/* Gutters */ +/* ------------------------------------------------------------------ */ + +class TextMarker extends GutterMarker { + constructor(private text: string, private cls: string, private title = '', private click?: () => void) { super(); } + eq(o: TextMarker) { return o.text === this.text && o.cls === this.cls && o.title === this.title; } + toDOM() { + const s = el('span', { class: this.cls, title: this.title }, this.text); + if (this.click) s.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); this.click!(); }); + return s; + } +} +class ClassMarker extends GutterMarker { + constructor(cls: string) { super(); this.elementClass = cls; } + eq(o: ClassMarker) { return o.elementClass === this.elementClass; } +} +const SEV_ICON: Record = { error: '●', warning: '▲', note: '○' }; + +function gutters(opts: EditorOptions): Extension { + const changed = (u: { startState: EditorState; state: EditorState }) => u.startState.field(extrasField) !== u.state.field(extrasField); + const marks = gutter({ + class: 'ed-g ed-g-marks', + lineMarker(view, line) { + const ds = byLine(view.state.field(extrasField).diagnostics).get(view.state.doc.lineAt(line.from).number) || []; + const worst = worstOf(ds); + return worst ? new TextMarker(SEV_ICON[worst], `ed-mark ed-mark-${worst}`, ds.map((d) => d.message).join('\n'), () => opts.onDiagnosticClick?.(ds[0])) : null; + }, + lineMarkerChange: changed, + }); + const numbers = lineNumbers({ + domEventHandlers: { + mousedown(view, line, e) { + if (!opts.onLineClick) return false; + (e as MouseEvent).preventDefault(); + opts.onLineClick(view.state.doc.lineAt(line.from).number); + return true; + }, + }, + }); + const hits = gutter({ + class: 'ed-g ed-g-hits', + lineMarker(view, line) { + const n = view.state.field(extrasField).deco.hits?.get(view.state.doc.lineAt(line.from).number); + return n ? new TextMarker(`×${n}`, 'ed-hits', `ran ${n} time${n === 1 ? '' : 's'}`) : null; + }, + lineMarkerChange: changed, + }); + const arrow = gutter({ + class: 'ed-g ed-g-arrow', + lineMarker(view, line) { + return view.state.field(extrasField).deco.current === view.state.doc.lineAt(line.from).number ? new TextMarker('▶', 'ed-arrow') : null; + }, + lineMarkerChange: changed, + }); + const lineClasses = gutterLineClass.compute([extrasField, 'doc'], (state) => { + const { deco } = state.field(extrasField); + const out: Array<{ from: number; m: ClassMarker }> = []; + for (const n of new Set([...(deco.breakpoints ?? []), ...(deco.current ? [deco.current] : [])])) { + if (n < 1 || n > state.doc.lines) continue; + const cls = [deco.breakpoints?.has(n) && 'ed-gbreak', deco.current === n && 'ed-gcurrent'].filter(Boolean).join(' '); + out.push({ from: state.doc.line(n).from, m: new ClassMarker(cls) }); + } + out.sort((a, b) => a.from - b.from); + return RangeSet.of(out.map((o) => o.m.range(o.from))); + }); + return [marks, numbers, hits, arrow, lineClasses]; +} + +/* ------------------------------------------------------------------ */ +/* Highlighting from the language's tokenizer */ +/* ------------------------------------------------------------------ */ + +function highlighting(opts: EditorOptions): Extension { + const tok = opts.tokenize || ((l: string) => [{ text: l, cls: '' }]); + const compute = (state: EditorState): DecorationSet => { + const b = new RangeSetBuilder(); + const doc = state.doc; + const docTokens = opts.tokenizeLines ? opts.tokenizeLines(doc.toString()) : null; + for (let i = 1; i <= doc.lines; i++) { + const line = doc.line(i); + let at = line.from; + for (const t of docTokens ? (docTokens[i - 1] ?? []) : tok(line.text)) { + const to = Math.min(line.to, at + t.text.length); + if (t.cls && to > at) b.add(at, to, Decoration.mark({ class: t.cls })); + at = to; + } + } + return b.finish(); + }; + const field = StateField.define({ + create: compute, + update: (v, tr) => (tr.docChanged ? compute(tr.state) : v), + provide: (f) => EditorView.decorations.from(f), + }); + return field; +} + +/* ------------------------------------------------------------------ */ +/* Keys */ +/* ------------------------------------------------------------------ */ + +const DEFAULT_OPENERS = /^\s*(FOR|WHILE|REPEAT|IF|ELSE|ELSEIF|CASE|FUNCTION|PROCEDURE|TYPE|LOOP|SPEC)\b.*[^:]$|:\s*$|^\s*\.?\w+:\s*$/; +const DEFAULT_CLOSERS = /^\s*(NEXT|END\w+|UNTIL)\b/; + +function keys(opts: EditorOptions): Extension { + const tab = ' '.repeat(opts.tabSize ?? 4); + const insertTab = (view: EditorView) => { + const { from, to } = view.state.selection.main; + if (from !== to) return indentMore(view); + view.dispatch(view.state.replaceSelection(tab)); + return true; + }; + const enter = (view: EditorView) => { + const { from } = view.state.selection.main; + const line = view.state.doc.lineAt(from); + const before = line.text.slice(0, from - line.from); + let indent = before.match(/^\s*/)?.[0] ?? ''; + if (opts.nextIndent) indent = opts.nextIndent(before, tab); + else if (DEFAULT_OPENERS.test(before) && !DEFAULT_CLOSERS.test(before)) indent += tab; + view.dispatch(view.state.replaceSelection('\n' + indent), { scrollIntoView: true }); + return true; + }; + const comment = (view: EditorView) => { + const mark = opts.lineComment; + if (!mark) return false; + const { from, to } = view.state.selection.main; + const first = view.state.doc.lineAt(from).number; + const last = view.state.doc.lineAt(to > from && view.state.doc.lineAt(to).from === to ? to - 1 : to).number; + const esc = mark.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const lines = []; for (let n = first; n <= last; n++) lines.push(view.state.doc.line(n)); + const all = lines.filter((l) => l.text.trim()).every((l) => new RegExp(`^\\s*${esc}`).test(l.text)); + const changes = lines.filter((l) => l.text.trim()).map((l) => { + if (all) { const m = new RegExp(`^(\\s*)${esc} ?`).exec(l.text)!; return { from: l.from + m[1].length, to: l.from + m[0].length, insert: '' }; } + const ws = l.text.match(/^\s*/)![0].length; return { from: l.from + ws, to: l.from + ws, insert: `${mark} ` }; + }); + view.dispatch({ changes }); + return true; + }; + return keymap.of([ + { key: 'Tab', run: insertTab, shift: indentLess }, + { key: 'Enter', run: enter }, + { key: 'Mod-/', run: comment }, + { key: 'Mod-]', run: indentMore }, { key: 'Mod-[', run: indentLess }, + { key: 'Mod-g', run: gotoLine }, + ...historyKeymap, ...searchKeymap, ...defaultKeymap, + ]); +} + +/* ------------------------------------------------------------------ */ +/* The editor */ +/* ------------------------------------------------------------------ */ + +export class Editor { + readonly root: HTMLElement; + private view: EditorView; + private diagnostics: Diagnostic[] = []; + private deco: LineDecorations = {}; + private inline: boolean; + private opts: EditorOptions; + private readOnlyPart = new Compartment(); + + constructor(opts: EditorOptions = {}) { + this.opts = opts; + this.inline = opts.inlineMessages !== false; + this.root = el('div', { class: 'ed' + (opts.readOnly ? ' ed-ro' : '') + (opts.compact ? ' ed-compact' : '') }); + let hoverTimer: number | undefined; + const state = EditorState.create({ + doc: '', + extensions: [ + extrasField, lineDecorations, gutters(opts), highlighting(opts), + history(), bracketMatching(), search({ top: true }), highlightSelectionMatches(), + indentUnit.of(' '.repeat(opts.tabSize ?? 4)), EditorState.tabSize.of(opts.tabSize ?? 4), + keys(opts), + opts.placeholder ? placeholder(opts.placeholder) : [], + this.readOnlyPart.of(opts.readOnly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []), + EditorView.updateListener.of((u) => { + // a change the app made to follow another pane (setSynced) is not the student typing: nothing is told + if (u.transactions.some((tr) => tr.docChanged && !tr.isUserEvent('sync'))) this.opts.onChange?.(u.state.doc.toString()); + if (u.selectionSet || u.docChanged) this.opts.onCursorLine?.(u.state.doc.lineAt(u.state.selection.main.head).number); + if (u.docChanged || u.selectionSet) tooltip.hide(); + }), + EditorView.domEventHandlers({ + mousemove: (e) => { clearTimeout(hoverTimer); hoverTimer = window.setTimeout(() => this.hover(e), 120); return false; }, + mouseleave: () => { clearTimeout(hoverTimer); tooltip.hide(); return false; }, + scroll: () => { tooltip.hide(); return false; }, + keydown: () => { tooltip.hide(); return false; }, + }), + ], + }); + this.view = new EditorView({ state, parent: this.root }); + } + + /** The word or symbol under the pointer, and its explanation if the reference has one. */ + private hover(e: MouseEvent): void { + const pos = this.view.posAtCoords({ x: e.clientX, y: e.clientY }, false); + if (pos == null) { tooltip.hide(); return; } + const line = this.view.state.doc.lineAt(pos); + const col = pos - line.from; + const text = line.text; + if (col < 0 || col >= text.length) { tooltip.hide(); return; } + const lineTokens = this.opts.tokenizeLines ? (this.opts.tokenizeLines(this.view.state.doc.toString())[line.number - 1] ?? []) : (this.opts.tokenize || ((l: string) => [{ text: l, cls: '' }]))(text); + let at = 0; let found: { text: string; cls: string } | null = null; + for (const t of lineTokens) { if (col >= at && col < at + t.text.length) { found = t; break; } at += t.text.length; } + if (!found || !found.text.trim()) { tooltip.hide(); return; } + let word = found.text; + let info: { title: string; body: string; where?: string } | null = null; + // English: the longest known phrase around the pointer wins over the single word under it + if (this.opts.lang === 'lingo') { + const words = text.split(/(\s+)/); + let p = 0; let idx = -1; + for (let i = 0; i < words.length; i++) { if (col >= p && col < p + words[i].length) { idx = i; break; } p += words[i].length; } + if (idx >= 0 && idx % 2 === 0) for (let span = 6; span >= 2 && !info; span--) for (let start = Math.max(0, idx - (span - 1) * 2); start <= idx && !info; start += 2) { + if (start + (span - 1) * 2 >= words.length) continue; + const phrase = words.slice(start, start + (span - 1) * 2 + 1).join('').replace(/[.,:;]+$/, ''); + info = explain('lingo', phrase, text); + if (info) word = phrase; + } + } + if (!info) info = this.opts.explainWord?.(word, text) || (this.opts.lang ? explain(this.opts.lang, word, text) : null); + if (!info) { tooltip.hide(); return; } + tooltip.show(e.clientX, e.clientY, info); + } + + get value(): string { return this.view.state.doc.toString(); } + set value(v: string) { + const cur = this.view.state.doc.toString(); + if (cur === v) return; + // loading text (opening a problem, Reset, a file) is not an edit: Ctrl+Z must not be able to undo the pane to empty + this.view.dispatch({ changes: { from: 0, to: cur.length, insert: v }, annotations: Transaction.addToHistory.of(false) }); + } + + /** + * Bring the text up to date with another pane, without disturbing this one: only the part that differs is + * replaced (so a cursor outside it, the scroll position and the selection stay where they are), no change is + * reported, and the update is its own undo step (the `sync` user event is not one that history joins to typing), + * so Ctrl+Z here undoes the sync and nothing the student typed elsewhere. + */ + setSynced(v: string): void { + const cur = this.view.state.doc.toString(); + if (cur === v) return; + let a = 0; + const max = Math.min(cur.length, v.length); + while (a < max && cur.charCodeAt(a) === v.charCodeAt(a)) a++; + let b = 0; + while (b < max - a && cur.charCodeAt(cur.length - 1 - b) === v.charCodeAt(v.length - 1 - b)) b++; + this.view.dispatch({ changes: { from: a, to: cur.length - b, insert: v.slice(a, v.length - b) }, userEvent: 'sync' }); + } + + focus(): void { this.view.focus(); } + + setReadOnly(ro: boolean): void { + this.view.dispatch({ effects: this.readOnlyPart.reconfigure(ro ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []) }); + this.root.classList.toggle('ed-ro', ro); + } + + setDiagnostics(d: Diagnostic[]): void { this.diagnostics = d; this.push(); } + setInlineMessages(on: boolean): void { this.inline = on; this.push(); } + /** A partial update: keys you leave out keep their value; pass null to clear one. */ + setDecorations(d: LineDecorations): void { this.deco = { ...this.deco, ...d }; this.push(); } + private push(): void { this.view.dispatch({ effects: setExtras.of({ diagnostics: this.diagnostics, deco: this.deco, inline: this.inline }) }); } + + cursorLine(): number { return this.view.state.doc.lineAt(this.view.state.selection.main.head).number; } + + /** Apply a quick fix (1-based line and cols; endCol exclusive, null = to the end of the line). */ + applyFix(f: QuickFix): void { + const doc = this.view.state.doc; + if (f.line < 1 || f.line > doc.lines) return; + const line = doc.line(f.line); + const last = doc.line(Math.min(Math.max(f.endLine ?? f.line, f.line), doc.lines)); + const from = line.from + Math.max(0, f.col - 1); + const to = f.endCol == null ? last.to : last.from + Math.max(0, f.endCol - 1); + this.view.dispatch({ changes: { from: Math.min(from, line.to), to: Math.min(Math.max(to, from), last.to), insert: f.text } }); + } + + scrollToLine(line: number): void { + const doc = this.view.state.doc; + if (line < 1 || line > doc.lines) return; + this.view.dispatch({ effects: EditorView.scrollIntoView(doc.line(line).from, { y: 'nearest', yMargin: 48 }) }); + } + + /** Kept for callers that used to force a repaint; CodeMirror repaints itself. */ + render(): void { this.view.requestMeasure(); } + + destroy(): void { this.view.destroy(); } +} + diff --git a/src/ui/embed.ts b/src/ui/embed.ts new file mode 100644 index 0000000..b707d2d --- /dev/null +++ b/src/ui/embed.ts @@ -0,0 +1,225 @@ +/** + * Embed mode: one view, no chrome, sized for an `; + // the Quarto extension's shortcode for the same state: this layout, panes, build and step, on any page + const title = this.session.state.title || PROBLEMS.find((p) => p.id === this.session.state.problem)?.title; + const shortcode = view === 'playground' + ? `{{< pplus-playground state="${blob}" height="${tall}"${title ? ` title="${title.replace(/"/g, '"')}"` : ''} >}}` + : `{{< pplus-embed state="${blob}" view="${view}"${title ? ` title="${title.replace(/"/g, '"')}"` : ''} >}}`; + add(embedRow, el('label', {}, 'embed'), el('input', { class: 'input mono', readOnly: true, value: snippet }), button('Copy', async (e) => { await copyText(snippet); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' })); + add(quartoRow, el('label', {}, 'Quarto'), el('input', { class: 'input mono', readOnly: true, value: shortcode }), button('Copy', async (e) => { await copyText(shortcode); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' }), + el('a', { class: 'small', href: '#/quarto', target: '_blank', rel: 'noopener', title: 'Every shortcode of the Quarto extension, and the views it renders into a page' }, 'more ways ↗')); + }; + embedView.addEventListener('change', renderEmbed); + renderEmbed(); + add(dlg, el('h3', {}, 'Share this exact state'), + el('p', { class: 'small muted' }, `${blob.length} characters in the link. The link carries every pane, the call, the setup, the chosen language, the layout, and the step you are on.`), + row('open in Programming+', appLink), + this.session.provenance() || this.session.compileBadge() + ? el('div', { class: 'share-row' }, el('label', {}, 'the Mojo'), el('span', { class: 'share-badges' }, ...mojoBadges(this.session)), + el('span', { class: 'small muted' }, this.session.provenance() ? 'The label stays with the Mojo wherever it is shown. ' : '', 'Compile results stay in this browser: a link never carries them.')) : null, + el('div', { class: 'share-row' }, el('label', {}, 'embed which view'), embedView), + embedRow, + quartoRow, + el('div', { class: 'share-row' }, el('label', {}, 'as a file'), el('span', { class: 'small muted' }, `${this.fileName()} holds the same state; Open… loads it back, here or on another machine.`), button('Download', () => this.download(withVersions.checked), { class: 'btn btn-small' })), + this.session.versions().length ? el('div', { class: 'share-row' }, el('label', {}, 'versions'), el('label', { class: 'small' }, withVersions, ` Include my ${this.session.versions().length} saved version${this.session.versions().length === 1 ? '' : 's'} in the file (a link never carries them)`)) : null, + el('div', { class: 'share-actions' }, button('Close', () => dlg.close(), { class: 'btn' }))); + document.body.appendChild(dlg); + dlg.addEventListener('close', () => dlg.remove()); + dlg.showModal(); + } + + /* ---------- hooks for the views ---------- */ + + private hooks(): PanelHooks { + return { + reveal: (lang, line) => { + if (lang !== this.session.state.lang) { this.session.setLang(lang); this.showPane(lang); } + const ed = this.editors.get(lang)!; + ed.scrollToLine(line); + ed.setDecorations({ linked: new Set([line]) }); + setTimeout(() => ed.setDecorations({ linked: undefined }), 1200); + }, + fix: (lang, f: QuickFix) => { this.editors.get(lang)!.applyFix(f); }, + }; + } +} diff --git a/src/ui/splitter.ts b/src/ui/splitter.ts new file mode 100644 index 0000000..c88d77a --- /dev/null +++ b/src/ui/splitter.ts @@ -0,0 +1,32 @@ +/** A draggable divider between two grid tracks. Fractions persist through `onChange`; `start` restores a + * saved fraction, while double-click still resets to `initial`. */ +import { el } from './dom.js'; + +export function splitter(opts: { container: HTMLElement; axis: 'x' | 'y'; initial: number; start?: number; min?: number; max?: number; onChange: (fraction: number) => void; apply: (fraction: number) => void }): HTMLElement { + const bar = el('div', { class: `splitter splitter-${opts.axis}`, role: 'separator', 'aria-orientation': opts.axis === 'x' ? 'vertical' : 'horizontal', tabIndex: 0, title: 'Drag to resize; double-click to reset' }); + let f = opts.start ?? opts.initial; + const clamp = (v: number) => Math.min(opts.max ?? 0.85, Math.max(opts.min ?? 0.15, v)); + opts.apply(f); + bar.addEventListener('pointerdown', (e) => { + e.preventDefault(); + bar.setPointerCapture(e.pointerId); + bar.classList.add('dragging'); + document.body.classList.add('resizing', `resizing-${opts.axis}`); + const move = (ev: PointerEvent) => { + const r = opts.container.getBoundingClientRect(); + f = clamp(opts.axis === 'x' ? (ev.clientX - r.left) / r.width : (ev.clientY - r.top) / r.height); + opts.apply(f); + }; + const stop = () => { bar.classList.remove('dragging'); document.body.classList.remove('resizing', `resizing-${opts.axis}`); bar.removeEventListener('pointermove', move); bar.removeEventListener('pointerup', stop); bar.removeEventListener('pointercancel', stop); opts.onChange(f); }; + bar.addEventListener('pointermove', move); + bar.addEventListener('pointerup', stop); + bar.addEventListener('pointercancel', stop); + }); + bar.addEventListener('dblclick', () => { f = opts.initial; opts.apply(f); opts.onChange(f); }); + bar.addEventListener('keydown', (e) => { + const step = 0.02; + if ((opts.axis === 'x' && e.key === 'ArrowLeft') || (opts.axis === 'y' && e.key === 'ArrowUp')) { f = clamp(f - step); opts.apply(f); opts.onChange(f); e.preventDefault(); } + if ((opts.axis === 'x' && e.key === 'ArrowRight') || (opts.axis === 'y' && e.key === 'ArrowDown')) { f = clamp(f + step); opts.apply(f); opts.onChange(f); e.preventDefault(); } + }); + return bar; +} diff --git a/src/ui/stepkinds.ts b/src/ui/stepkinds.ts new file mode 100644 index 0000000..805e43d --- /dev/null +++ b/src/ui/stepkinds.ts @@ -0,0 +1,36 @@ +/** + * One palette for what a step does, shared by the pseudo and Mojo interpreters' + * traces (each records a `kind` on every step) so that the trace table, the + * "next" box, the table of values and the legend all say the same thing with + * the same color. + */ +export type StepFamily = 'write' | 'decision' | 'loop' | 'call' | 'return' | 'io' | 'life' | 'error' | 'other'; + +const FAMILY: Record = { + // pseudo (src/engines/pseudo/interp.js) + assign: 'write', declare: 'write', builtin: 'write', expr: 'write', + test: 'decision', select: 'decision', check: 'decision', + next: 'loop', break: 'loop', continue: 'loop', 'loop-start': 'loop', 'loop-test': 'loop', 'loop-end': 'loop', pass: 'loop', passes: 'loop', + call: 'call', return: 'return', + input: 'io', output: 'io', + error: 'error', + // Mojo (src/mojo/interp.ts) + stmt: 'write', loop: 'loop', + raise: 'error', except: 'error', destroy: 'life', +}; + +export const FAMILY_LABEL: Record = { + write: 'writes a value', decision: 'decides (a test)', loop: 'loop control', call: 'enters a routine', return: 'returns', io: 'input or output', life: 'a value is destroyed', error: 'raises or fails', other: 'other', +}; + +/** A Mojo `stmt` that prints is really output; a step that writes nothing and tests nothing is "other". */ +export function familyOf(step: { kind?: string; text?: string; writes?: unknown[] } | null | undefined, lang?: string): StepFamily { + if (!step) return 'other'; + const k = step.kind ?? ''; + if (lang === 'mojo' && k === 'stmt' && /^\s*print\s*\(/.test(step.text ?? '')) return 'io'; + if (lang === 'mojo' && k === 'stmt' && /^\s*input\s*\(|=\s*input\s*\(/.test(step.text ?? '')) return 'io'; + if (lang === 'mojo' && k === 'stmt' && !(step.writes?.length)) return 'other'; + return FAMILY[k] ?? 'other'; +} + +export const FAMILIES: StepFamily[] = ['write', 'decision', 'loop', 'call', 'return', 'io', 'life', 'error']; diff --git a/src/ui/theme.ts b/src/ui/theme.ts new file mode 100644 index 0000000..8ad090c --- /dev/null +++ b/src/ui/theme.ts @@ -0,0 +1,69 @@ +/** Light, dark, or follow the system. Stored in this browser; `?theme=` on an embed wins. */ +export type Theme = 'light' | 'dark' | 'system'; +const KEY = 'pplus.theme'; + +/** + * The class the course stylesheets read (styles/course/README.md): they draw dark on `body.quarto-dark`, and + * follow the operating system only when the body has neither class. The app always says which, so a light app + * on a dark system never draws dark widgets. `forced` is a host page's choice (an embed's `?theme=`, or the + * Quarto extension's switch), which wins over the setting. + */ +export function themeBodyClass(setting: Theme, systemDark: boolean, forced: 'light' | 'dark' | null = null): 'quarto-light' | 'quarto-dark' { + const shown = forced ?? (setting === 'system' ? (systemDark ? 'dark' : 'light') : setting); + return shown === 'dark' ? 'quarto-dark' : 'quarto-light'; +} + +let forced: 'light' | 'dark' | null = null; + +const systemDark = (): boolean => { try { return matchMedia('(prefers-color-scheme: dark)').matches; } catch { return false; } }; + +/** Put exactly one of `quarto-light` or `quarto-dark` on ``, matching what the page shows. */ +export function syncBodyTheme(): void { + const body = typeof document !== 'undefined' ? document.body : null; + if (!body) return; + const want = themeBodyClass(currentTheme(), systemDark(), forced); + body.classList.toggle('quarto-dark', want === 'quarto-dark'); + body.classList.toggle('quarto-light', want === 'quarto-light'); +} + +let watching = false; +/** Keep the body class right from now on: once at load, and whenever the system preference changes. */ +export function watchTheme(): void { + syncBodyTheme(); + if (watching) return; + watching = true; + try { matchMedia('(prefers-color-scheme: dark)').addEventListener('change', syncBodyTheme); } catch { /* an old browser: the class follows the next change made here */ } +} + +export function currentTheme(): Theme { + try { const t = localStorage.getItem(KEY); if (t === 'light' || t === 'dark') return t; } catch { /* ignore */ } + return 'system'; +} + +export function applyTheme(t: Theme): void { + const root = document.documentElement; + forced = null; + if (t === 'system') root.removeAttribute('data-theme'); else root.setAttribute('data-theme', t); + try { if (t === 'system') localStorage.removeItem(KEY); else localStorage.setItem(KEY, t); } catch { /* ignore */ } + syncBodyTheme(); +} + +/** What the page is showing right now, resolving "system" (and a host page's forced choice). */ +export function effectiveTheme(): 'light' | 'dark' { + if (forced) return forced; + const t = currentTheme(); + if (t !== 'system') return t; + return systemDark() ? 'dark' : 'light'; +} + +export function cycleTheme(): Theme { + const next: Theme = effectiveTheme() === 'dark' ? 'light' : 'dark'; + applyTheme(next); + return next; +} + +export function forceTheme(t: 'light' | 'dark'): void { + forced = t; + document.documentElement.setAttribute('data-theme', t); + syncBodyTheme(); +} diff --git a/src/ui/tooltip.ts b/src/ui/tooltip.ts new file mode 100644 index 0000000..13c053e --- /dev/null +++ b/src/ui/tooltip.ts @@ -0,0 +1,26 @@ +/** One shared tooltip for hover explanations, positioned near the pointer. */ +import { el, clear, add } from './dom.js'; + +class Tooltip { + private node: HTMLElement | null = null; + private ensure(): HTMLElement { + if (!this.node) { this.node = el('div', { class: 'tip', role: 'tooltip', style: { display: 'none' } }); document.body.appendChild(this.node); } + return this.node; + } + show(x: number, y: number, info: { title: string; body: string; where?: string }): void { + const n = this.ensure(); + clear(n); + add(n, el('div', { class: 'tip-title' }, el('code', {}, info.title), info.where ? el('span', { class: 'tip-where' }, info.where) : null), el('div', { class: 'tip-body' }, info.body)); + n.style.display = ''; + const w = Math.min(380, window.innerWidth - 24); + n.style.maxWidth = `${w}px`; + const left = Math.min(x + 14, window.innerWidth - w - 12); + n.style.left = `${Math.max(8, left)}px`; + n.style.top = `${y + 18}px`; + const r = n.getBoundingClientRect(); + if (r.bottom > window.innerHeight - 8) n.style.top = `${Math.max(8, y - r.height - 10)}px`; + } + hide(): void { if (this.node) this.node.style.display = 'none'; } +} + +export const tooltip = new Tooltip(); diff --git a/src/ui/views/compiler.ts b/src/ui/views/compiler.ts new file mode 100644 index 0000000..fa1fd0d --- /dev/null +++ b/src/ui/views/compiler.ts @@ -0,0 +1,240 @@ +/** + * The Compiler view: what the real Mojo compiler made of the Mojo pane. + * Everything here is godbolt's answer, kept by the session with exactly the + * source, input, and build it answered; an edit since is said, not hidden. + * + * output what the program printed, its input, and how it ended + * messages the compiler's errors and notes, each a link to its line + * listing the instructions, one block per function: the student's own + * functions first, the runtime and the standard library folded + * away; Intel syntax (what the x86-64 pane reads) or godbolt's + * AT&T original; and "Open in Hardware" to step one. + */ +import { el, clear, add, button } from '../dom.js'; +import type { Session, CompileRecord } from '../../core/session.js'; +import type { AsmLine, BuildLevel, ListingFunction } from '../../services/godbolt.js'; +import { intelListing } from '../../mojo/att.js'; +import { tokenizeAsm } from '../../services/asm.js'; +import { MOJO_VERSION, GODBOLT_COMPILER } from '../../mojo/generated/pin.js'; +import type { PanelHooks } from './panels.js'; +import { generatedLabel } from '../provenance.js'; + +export interface CompilerHooks extends PanelHooks { + /** Put one function (and the user's functions it calls) in the x86-64 pane. */ + sendToAsm(functions: ListingFunction[], fn: ListingFunction): void; + /** Compile the Mojo pane now. */ + compile(): void; +} + +let syntax: 'intel' | 'att' = 'intel'; +/** By function (the listing's order) or by line (each Mojo line, then the instructions it became). */ +let layout: 'line' | 'function' = 'line'; +/** Whether to show the other build level's listing beside this one. */ +let compare = false; +/** The Mojo pane's cursor line, and the view to show it in: its instructions are highlighted. */ +let cursorLine: number | null = null; +let liveRoot: HTMLElement | null = null; +export function focusCompilerLine(line: number): void { + cursorLine = line; + if (!liveRoot) return; + let first: HTMLElement | null = null; + for (const g of liveRoot.querySelectorAll('[data-line]')) { + const on = Number(g.dataset.line) === line; + g.classList.toggle('asm-group-active', on); + if (on && !first) first = g; + } + first?.scrollIntoView({ block: 'nearest' }); +} + +/** The standard-library functions a function calls: what the x86-64 pane cannot run. */ +export function libraryCalls(fn: ListingFunction): string[] { + const out = new Set(); + for (const l of fn.lines) { + const m = /^\s*callq?\s+\*?(?:"((?:[^"\\]|\\.)*)"|(\S+))/.exec(l.text); + const raw = m && (m[1] ?? m[2]); + if (!raw || raw.startsWith('example::') || raw.startsWith('.L') || raw.startsWith('%')) continue; + const path = raw.replace(/@PLT$/, '').replace(/[\[(].*$/, '').split('::').filter(Boolean); + if (!path.length) continue; + const name = path[path.length - 1]; + out.add(path.length > 1 ? `${name} (${path.slice(0, -1).join('.')})` : name); + } + return [...out]; +} + +/** + * One function's instructions under the Mojo lines they came from, in source order. An instruction + * with no line of the program's own (inlined from the standard library, or with no line at all) + * stays with the line before it, counted as inlined. + */ +function byLine(fn: ListingFunction, rec: CompileRecord, hooks: CompilerHooks, fresh: boolean): HTMLElement { + const src = rec.source.split('\n'); + const groups = new Map; inlined: number }>(); + const rows = intelListing(fn, rec.functions); + let current: number | null = null; + rows.forEach((r, i) => { + const l = fn.lines[i]; + if (l.line != null) current = l.line; + if (current == null) return; + if (!groups.has(current)) groups.set(current, { lines: [], intel: [], inlined: 0 }); + const g = groups.get(current)!; + g.lines.push(l); g.intel.push(r.intel); + if (l.line == null && r.intel && !r.intel.endsWith(':')) g.inlined++; + }); + const box = el('div', { class: 'asm-bylines' }); + for (const [line, g] of [...groups].sort((a, b) => a[0] - b[0])) { + const n = g.intel.filter((t) => t && !t.endsWith(':')).length; + const head = el('div', { class: 'asm-group-head' }, + el('button', { type: 'button', class: 'linkish mono', disabled: !fresh, onClick: () => hooks.reveal('mojo', line) }, `line ${line}`), + el('code', { class: 'asm-group-src' }, (src[line - 1] ?? '').trim()), + el('span', { class: 'spacer' }), + el('span', { class: 'small muted' }, `${n} instruction${n === 1 ? '' : 's'}${g.inlined ? `, ${g.inlined} inlined from the standard library` : ''}`)); + add(box, el('div', { class: `asm-group${cursorLine === line ? ' asm-group-active' : ''}`, 'data-line': String(line) }, head, asmPre(g.lines, syntax === 'intel' ? g.intel : null, null))); + } + if (!groups.size) add(box, el('p', { class: 'muted small' }, 'No instruction here carries a line of your program.')); + return box; +} + +function asmPre(lines: AsmLine[], intel: Array | null, reveal: ((line: number) => void) | null): HTMLElement { + const pre = el('pre', { class: 'compile-asm' }); + const withLines = lines.some((l) => l.line != null || l.from); + lines.forEach((l, i) => { + const text = intel ? intel[i] : l.text.trim(); + if (text == null) return; + if (withLines) { + if (l.line != null) add(pre, reveal + ? el('button', { type: 'button', class: 'asm-src linkish', title: `from line ${l.line} of the Mojo pane; click to show it`, onClick: () => reveal(l.line!) }, String(l.line).padStart(4) + ' ') + : el('span', { class: 'asm-src', title: `from line ${l.line} (an earlier version of the program)` }, String(l.line).padStart(4) + ' ')); + else add(pre, el('span', { class: 'asm-src asm-src-lib', title: l.from ? `inlined from ${l.from.file}, line ${l.from.line}: standard library code, not a line of your program` : '' }, l.from ? ' · ' : ' ')); + } + const isLabel = /:$/.test(text); + const shown = isLabel ? text : ' ' + text; + if (intel) for (const t of tokenizeAsm(shown)) add(pre, t.cls ? el('span', { class: t.cls }, t.text) : t.text); + else add(pre, shown); + add(pre, '\n'); + }); + return pre; +} + +function functionBlock(fn: ListingFunction, rec: CompileRecord, hooks: CompilerHooks, open: boolean, fresh: boolean): HTMLElement { + const rows = intelListing(fn, rec.functions); + const det = el('details', { class: `asm-fn asm-fn-${fn.kind}`, open }, + el('summary', {}, el('code', {}, fn.name), el('span', { class: 'muted small' }, ` ${fn.lines.filter((l) => !/:\s*$/.test(l.text)).length} instructions`))); + const actions = el('div', { class: 'asm-fn-actions' }); + const calls = fn.kind === 'user' ? libraryCalls(fn) : []; + if (fn.kind === 'user') add(actions, button('Open in Hardware', () => hooks.sendToAsm(rec.functions, fn), { class: 'btn btn-small', title: calls.length ? `Step this function on the model machine. It calls ${calls.join(', ')}: standard-library code the model machine cannot run, so it stops there.` : 'Step this function on the model machine.' })); + if (calls.length) add(actions, el('span', { class: 'small muted' }, `calls into the standard library: ${calls.join(', ')}. The model machine stops at those.`)); + const withLines = fn.lines.some((l) => l.line != null); + add(det, actions, fn.kind === 'user' && layout === 'line' && withLines ? byLine(fn, rec, hooks, fresh) : asmPre(fn.lines, syntax === 'intel' ? rows.map((r) => r.intel) : null, fresh ? (line) => hooks.reveal('mojo', line) : null)); + return det; +} + +/** Each of the program's functions at both build levels, side by side, with their instruction counts. */ +function comparison(rec: CompileRecord, other: CompileRecord | null, pending: boolean): HTMLElement { + const box = el('div', { class: 'build-compare' }); + if (!other) { add(box, el('p', { class: 'muted small' }, pending ? 'Compiling the other build…' : 'The other build has not been compiled for this source yet.')); return box; } + const [o0, opt] = rec.level === 'O0' ? [rec, other] : [other, rec]; + const count = (f: ListingFunction | undefined) => (f ? f.lines.filter((l) => !/:\s*$/.test(l.text)).length : 0); + const users = [...new Set([...o0.functions, ...opt.functions].filter((f) => f.kind === 'user').map((f) => f.name))]; + add(box, el('p', { class: 'small muted' }, 'The same source, built as written (-O0) and optimized. What the optimizer keeps, merges, or removes is the point: a function absent from the optimized build was inlined into its callers, or computed away.')); + for (const name of users) { + const a = o0.functions.find((f) => f.name === name), b = opt.functions.find((f) => f.name === name); + // the student's main() gone from the optimized build: the program's entry point absorbed it + const entry = !b && name === 'main()' ? opt.functions.find((f) => f.label === 'main' || f.name === 'main') : undefined; + const col = (f: ListingFunction | undefined, recd: CompileRecord, label: string, note?: string) => el('div', { class: 'build-col' }, + el('div', { class: 'small' }, el('b', {}, label), ' ', el('span', { class: 'muted' }, f ? `${count(f)} instructions${note ? `: ${note}` : ''}` : 'not in this build')), + f ? asmPre(f.lines, syntax === 'intel' ? intelListing(f, recd.functions).map((r) => r.intel) : null, null) : el('p', { class: 'muted small' }, 'Inlined into its callers, or computed away.')); + add(box, el('div', { class: 'build-pair' }, el('code', {}, name), el('div', { class: 'build-cols' }, + col(a, o0, '-O0'), + entry ? col(entry, opt, 'optimized', 'main() is not a function of its own here; it, and what it calls, were inlined into the program\'s entry point, main') : col(b, opt, 'optimized')))); + } + return box; +} + +export function compilerView(session: Session, root: HTMLElement, hooks: CompilerHooks): () => void { + liveRoot = root; + function render() { + clear(root); + const last = session.lastCompile(); + const head = el('div', { class: 'compile-head' }); + add(root, head); + // the compiler's answer is about the source it was sent; if that source was generated, say so beside it + const kind = session.provenance(); + if (kind) add(head, generatedLabel(kind)); + if (session.compiling) { + add(head, el('span', { class: 'badge badge-open' }, 'compiling'), el('span', { class: 'small muted' }, `Asking godbolt.org (${GODBOLT_COMPILER}) to build and run the Mojo pane…`)); + if (!last) return; + } + if (!last) { + add(head, el('span', { class: 'small muted' }, 'Not compiled yet.'), el('span', { class: 'spacer' }), button('Compile & run', () => hooks.compile(), { class: 'btn btn-small' })); + add(root, el('p', { class: 'muted' }, `Compile & run (Ctrl+Enter) builds the Mojo pane with the real Mojo ${MOJO_VERSION} compiler on godbolt.org, runs it, and shows here what it printed, what the compiler said, and the instructions it produced. Programming+ ships no compiler of its own and never says a program compiles without asking one. The stepper beside the editor goes through it line by line in Programming+'s own interpreter, and says so when it meets something it does not model yet.`)); + return; + } + const { record: rec, fresh } = last; + const o = rec.outcome; + const a = o.answer; + if (!session.compiling) { + const badge = !a ? ['badge-broken', 'no answer'] : !a.compiled ? ['badge-broken', 'did not compile'] : a.timedOut ? ['badge-broken', 'timed out'] : !a.executed ? ['badge-open', 'compiled, did not run'] : a.exitCode === 0 ? ['badge-proved', 'ran, exit 0'] : ['badge-broken', `exited with ${a.exitCode}`]; + add(head, el('span', { class: `badge ${badge[0]}` }, badge[1]), + el('span', { class: 'small muted' }, `Mojo ${MOJO_VERSION} on godbolt.org · ${rec.level === 'O0' ? 'as written (-O0)' : 'optimized'} · ${o.seconds.toFixed(1)} s`), + el('span', { class: 'spacer' }), button('Compile again', () => hooks.compile(), { class: 'btn btn-small btn-quiet' })); + } + if (!fresh) add(root, el('p', { class: 'hint' }, 'You have edited the Mojo pane since this answer; it is the answer for the earlier version. Compile again to see the current one.')); + if (!a) { add(root, el('p', { class: 'compile-err' }, o.error || 'No answer.')); return; } + + // output + const out = el('section', { class: 'compile-section' }, el('h4', {}, 'Output')); + if (rec.stdin) add(out, el('div', { class: 'small muted' }, 'input: ', el('code', {}, rec.stdin.replace(/\n$/, '').split('\n').join(' ⏎ ')))); + if (a.executed) add(out, el('pre', { class: 'compile-std' }, a.stdout || '(no output)')); + else add(out, el('p', { class: 'muted small' }, a.compiled ? 'The program was built but not run.' : 'Nothing ran: the program did not compile.')); + if (a.stderr.trim()) add(out, el('pre', { class: 'compile-err' }, a.stderr.trim())); + add(root, out); + + // messages + if (rec.diagnostics.length) { + const sec = el('section', { class: 'compile-section' }, el('h4', {}, 'What the compiler said')); + const list = el('ul', { class: 'problems' }); + for (const d of rec.diagnostics) add(list, el('li', { class: `problem problem-${d.severity}` }, + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal('mojo', d.line), disabled: !fresh }, `line ${d.line}`), + el('span', { class: 'problem-msg' }, `${d.severity}: ${d.message}`), + d.fix && fresh ? button(d.fix.label, () => hooks.fix('mojo', d.fix!), { class: 'btn btn-small' }) : null, + ...(d.question && fresh ? d.question.options.map((opt) => button(opt.label, () => hooks.fix('mojo', opt), { class: 'btn btn-small btn-option' })) : []))); + add(sec, list); + add(root, sec); + } + + // listing + if (a.compiled && rec.functions.length) { + const sec = el('section', { class: 'compile-section' }); + const toggle = button(syntax === 'intel' ? 'Show AT&T (as godbolt sent it)' : 'Show Intel (as the x86-64 pane reads it)', () => { syntax = syntax === 'intel' ? 'att' : 'intel'; render(); }, { class: 'btn btn-small btn-quiet' }); + const other: BuildLevel = rec.level === 'O0' ? 'default' : 'O0'; + const otherRec = session.compileAt(rec.source, other); + const cmp = button(compare ? 'Hide the other build' : `Compare with ${other === 'O0' ? '-O0 (as written)' : 'the optimized build'}`, () => { + compare = !compare; + if (compare && !otherRec && fresh) void session.compile(undefined, other).then(() => render()); + render(); + }, { class: 'btn btn-small btn-quiet', disabled: !fresh && !otherRec, title: 'Compile the same source at the other level, and show each function at both' }); + const arrange = button(layout === 'line' ? 'In listing order' : 'By Mojo line', () => { layout = layout === 'line' ? 'function' : 'line'; render(); }, { class: 'btn btn-small btn-quiet', title: 'By Mojo line: each line of your program, then the instructions it became. Move the cursor in the Mojo pane to find a line here.' }); + add(sec, el('div', { class: 'compile-head' }, el('h4', {}, 'What the processor runs'), el('span', { class: 'spacer' }), cmp, arrange, toggle)); + if (compare) add(sec, comparison(rec, otherRec, session.compiling !== null)); + const user = rec.functions.filter((f) => f.kind === 'user'); + const rest = rec.functions.filter((f) => f.kind !== 'user' && f.kind !== 'data'); + if (!user.length) add(sec, el('p', { class: 'hint' }, rec.level === 'default' + ? 'The optimizer folded your functions into main, so none of them has instructions of its own here. Build "as written" in the toolbar to see each one.' + : 'None of the instructions are labelled as your functions.')); + user.forEach((f, i) => add(sec, functionBlock(f, rec, hooks, i < 3, fresh))); + if (rest.length) { + const lib = el('details', { class: 'asm-library' }, el('summary', {}, `The runtime and the standard library (${rest.length} function${rest.length === 1 ? '' : 's'})`)); + add(lib, el('p', { class: 'muted small' }, 'main is the entry point the runtime calls; it sets up the runtime and calls your main. The rest is standard library code compiled into the program: print, String, and what they use.')); + for (const f of rest) add(lib, functionBlock(f, rec, hooks, false, fresh)); + add(sec, lib); + } + add(sec, el('p', { class: 'muted small' }, syntax === 'intel' + ? 'Shown in Intel syntax, translated from godbolt\'s AT&T listing: the destination comes first. The number before an instruction is the line of your program it came from (click it); a dot marks code inlined from the standard library. Lines the x86-64 pane does not model are still shown; it refuses them when you send them there.' + : 'AT&T syntax, exactly as godbolt sent it: the destination comes last, registers start with %, constants with $.')); + add(root, sec); + } + } + const off = session.onChange(render); + render(); + return () => { off(); if (liveRoot === root) liveRoot = null; }; +} diff --git a/src/ui/views/lifetimes.ts b/src/ui/views/lifetimes.ts new file mode 100644 index 0000000..6cad78b --- /dev/null +++ b/src/ui/views/lifetimes.ts @@ -0,0 +1,75 @@ +/** + * The Lifetimes view (Stage 4): one row per value whose lifecycle can be seen, + * from the step it is made to the step it is destroyed or moved out of, with + * each copy, move, and naming on the way. It reads the lifecycle events the + * interpreter records on its steps (src/mojo/interp.ts, LifeEvent), so what it + * shows is when the compiled program does these things: a value dies at its + * last use, a move makes a new value from the old one, which ends there. + * + * Click a mark to step there; the cursor is where the stepper is. + */ +import { el, clear, add } from '../dom.js'; +import type { Session } from '../../core/session.js'; + +interface Row { id: number; label: string; names: string[]; start: number; end: number | null; endKind: 'destroyed' | 'moved' | null; movedTo?: number; from?: number; how: 'made' | 'copied' | 'moved'; marks: Array<{ step: number; kind: string; text: string }> } + +export function lifetimesView(session: Session, root: HTMLElement, opts: { goto?: (t: number) => void } = {}): () => void { + const render = () => { + clear(root); + const trace = session.trace(); + if (!trace) { add(root, el('p', { class: 'muted' }, session.runError ?? 'Step through the Mojo pane to see its values\' lifetimes here.')); return; } + if (trace.lang !== 'mojo') { add(root, el('p', { class: 'muted' }, 'Lifetimes are shown for Mojo runs: when each value is made, copied, moved, and destroyed.')); return; } + const steps = trace.steps as any[]; + const rows = new Map(); + steps.forEach((s, i) => { + for (const e of s.life ?? []) { + if (e.kind === 'made' || e.kind === 'copied' || e.kind === 'moved') { + rows.set(e.id, { id: e.id, label: e.label, names: [], start: i, end: null, endKind: null, from: e.from, how: e.kind, marks: [{ step: i, kind: e.kind, text: e.kind === 'made' ? `made: ${e.label}` : `${e.kind} from #${e.from}` }] }); + if (e.kind === 'moved' && e.from && rows.has(e.from)) { const old = rows.get(e.from)!; old.end = i; old.endKind = 'moved'; old.movedTo = e.id; old.marks.push({ step: i, kind: 'moved-out', text: `moved into #${e.id}` }); } + } else if (e.kind === 'named') { + const r = rows.get(e.id); if (r && !r.names.includes(e.name)) { r.names.push(e.name); r.marks.push({ step: i, kind: 'named', text: `named ${e.name}` }); } + } else if (e.kind === 'destroyed') { + const r = rows.get(e.id); if (r) { r.end = i; r.endKind = 'destroyed'; r.marks.push({ step: i, kind: 'destroyed', text: `destroyed (line ${s.line})` }); } + } + } + }); + if (!rows.size) { + add(root, el('p', { class: 'muted' }, 'No value in this run has a lifecycle that can be seen. Give a struct a __deinit__ (or a copy or move constructor) that prints, and each of its values gets a row here: when it is made, copied, moved, and destroyed.')); + if (trace.error) add(root, el('p', { class: 'small err' }, trace.error.message)); + return; + } + const n = Math.max(1, trace.count); + const t = Math.min(session.state.t ?? n, n); + add(root, el('p', { class: 'small muted' }, `One row per value. A move makes a new value from the old one, which ends there; a value is destroyed at its last use, not at the end of its scope.${opts.goto ? ' Click a mark to step there.' : ''}`)); + const table = el('div', { class: 'life' }); + for (const r of [...rows.values()].sort((a, b) => a.id - b.id)) { + const name = r.names.length ? r.names.join(', ') : 'temporary'; + const lane = el('div', { class: 'life-lane' }); + const left = (r.start / n) * 100, right = ((r.end ?? n) / n) * 100; + add(lane, el('div', { class: `life-bar life-bar-${r.how}${r.end === null ? ' life-bar-open' : ''}`, style: { left: `${left}%`, width: `${Math.max(0.6, right - left)}%` } })); + for (const m of r.marks) { + add(lane, el('button', { type: 'button', class: `life-mark life-mark-${m.kind}`, title: `step ${m.step + 1}: ${m.text}`, style: { left: `${(m.step / n) * 100}%` }, onClick: () => opts.goto?.(m.step + 1) })); + } + add(lane, el('div', { class: 'life-cursor', style: { left: `${(t / n) * 100}%` } })); + const ending = r.endKind === 'destroyed' ? 'destroyed' : r.endKind === 'moved' ? `moved into #${r.movedTo}` : 'alive at the end'; + const origin = r.how === 'made' ? 'made' : `${r.how} from #${r.from}`; + add(table, el('div', { class: 'life-row' }, + el('div', { class: 'life-name' }, el('span', { class: 'life-id' }, `#${r.id}`), ' ', el('b', { class: 'mono' }, name), el('div', { class: 'small muted mono' }, r.label)), + lane, + el('div', { class: 'life-sum small muted' }, `${origin} · ${ending}`))); + } + add(root, table); + add(root, el('div', { class: 'life-legend small muted' }, + el('span', { class: 'life-mark life-mark-made legend' }), ' made ', + el('span', { class: 'life-mark life-mark-copied legend' }), ' copied ', + el('span', { class: 'life-mark life-mark-moved legend' }), ' moved in ', + el('span', { class: 'life-mark life-mark-moved-out legend' }), ' moved out ', + el('span', { class: 'life-mark life-mark-named legend' }), ' named ', + el('span', { class: 'life-mark life-mark-destroyed legend' }), ' destroyed')); + if (trace.error) add(root, el('p', { class: 'small err' }, trace.error.message)); + }; + const off = session.onChange(render); + const offStep = session.onStep(render); + render(); + return () => { off(); offStep(); }; +} diff --git a/src/ui/views/panels.ts b/src/ui/views/panels.ts new file mode 100644 index 0000000..3c0744d --- /dev/null +++ b/src/ui/views/panels.ts @@ -0,0 +1,177 @@ +/** + * The non-stepping views: problems (every diagnostic, with one-click + * rewrites), proof (obligations), and machine + * (the hardware model's perf-stat numbers for an assembly run). + */ +import { machineLabel } from '../../core/hardware.js'; +import { el, clear, add, button } from '../dom.js'; +import type { Diagnostic, LangId, QuickFix } from '../../core/types.js'; +import { LANG_NAMES } from '../../core/types.js'; +import type { Session } from '../../core/session.js'; +import { toMath } from '../../services/speco.js'; + +export const GUIDE_URL = 'https://biosc1540.scient.ing/programmingplus/reference/pseudocode/'; + +export interface PanelHooks { + /** Jump the editor to a line of a language. */ + reveal(lang: LangId, line: number): void; + /** Apply a rewrite to a language's source. */ + fix(lang: LangId, f: QuickFix): void; +} + +const SEV_ICON: Record = { error: '●', warning: '▲', note: '○' }; + +export function problemsView(session: Session, root: HTMLElement, hooks: PanelHooks): () => void { + function render() { + clear(root); + const diags = session.allDiagnostics(); + if (!diags.length) { add(root, el('p', { class: 'muted' }, 'Nothing to report. The panes read cleanly.')); return; } + const list = el('ul', { class: 'problems' }); + for (const d of diags) { + const item = el('li', { class: `problem problem-${d.severity}` }); + add(item, + el('span', { class: 'problem-sev', title: d.severity }, SEV_ICON[d.severity]), + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal(d.lang, d.line) }, `${LANG_NAMES[d.lang]} ${d.line}`), + el('span', { class: 'problem-msg' }, d.message), + d.origin && d.severity === 'note' ? el('span', { class: 'problem-origin', title: 'Who says so' }, d.origin) : null, + ); + if (d.guide) add(item, el('a', { class: 'problem-guide', href: `${GUIDE_URL}#${d.guide}`, target: '_blank', rel: 'noopener' }, 'guide ↗')); + if (d.docUrl) add(item, el('a', { class: 'problem-guide', href: d.docUrl, target: '_blank', rel: 'noopener' }, 'manual ↗')); + if (d.fix) add(item, button(d.fix.label === 'Fix' ? `Fix: ${d.fix.text || 'remove'}` : d.fix.label, () => hooks.fix(d.lang, d.fix!), { class: 'btn btn-small' })); + if (d.question) { + const q = el('div', { class: 'problem-question' }, el('div', { class: 'problem-q' }, d.question.text)); + for (const o of d.question.options) add(q, button(o.label, () => hooks.fix(d.lang, o), { class: 'btn btn-small btn-option' })); + add(item, q); + } + add(list, item); + } + add(root, list); + } + const off = session.onChange(render); + render(); + return off; +} + +const STATUS_WORD: Record = { proved: 'proved', broken: 'broken by a run', open: 'open' }; + +export function proofView(session: Session, root: HTMLElement, hooks: PanelHooks): () => void { + function render() { + clear(root); + const pr = session.proof(); + if (!pr) { add(root, el('p', { class: 'muted' }, 'The proof view needs pseudocode that parses. Fix the errors in the problems view first.')); return; } + const { report } = pr; + const speco = session.parsedSpeco(); + if (speco && speco.program?.spec.units.length) add(root, el('p', { class: 'hint' }, `Proving against the ${speco.program.spec.units.length} SPEC${speco.program.spec.units.length === 1 ? '' : 'S'} in the speco pane, woven into the pseudocode.`)); + add(root, el('div', { class: 'proof-counts' }, + el('span', { class: 'badge badge-proved' }, `${report.counts.proved} proved`), + el('span', { class: 'badge badge-broken' }, `${report.counts.broken} broken`), + el('span', { class: 'badge badge-open' }, `${report.counts.open} open`), + )); + if (!report.counts.total) add(root, el('p', { class: 'muted' }, 'No claims to check. Add an ENSURE under a FUNCTION line, or a SPEC in the speco pane.')); + for (const u of report.units) { + const sec = el('details', { class: 'proof-unit', open: true }, el('summary', {}, el('b', {}, u.name), ` · ${u.obligations.length} claim${u.obligations.length === 1 ? '' : 's'}`, u.partial ? el('span', { class: 'badge badge-open' }, 'partial: not every path was examined') : null)); + if (u.inferred.length) add(sec, el('p', { class: 'muted small' }, 'Invariants the checker found on its own: ', ...u.inferred.map((x) => el('code', { class: 'math' }, toMath(String(x)), ' ')))); + for (const n of u.notes) add(sec, el('p', { class: 'muted small' }, n)); + const list = el('ul', { class: 'obligations' }); + for (const o of u.obligations) { + const where = (o as any).specoLine ? { lang: 'speco' as LangId, line: (o as any).specoLine } : { lang: 'pseudo' as LangId, line: (o as any).pseudoLine ?? o.line }; + const item = el('li', { class: `obligation ob-${o.status}` }, + el('span', { class: `badge badge-${o.status}` }, STATUS_WORD[o.status]), + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal(where.lang, where.line) }, `${LANG_NAMES[where.lang]} ${where.line}`), + el('span', {}, o.label), + ); + const det = el('details', { class: 'ob-detail' }, el('summary', {}, 'what is known, and what has to follow')); + if (o.facts.length) add(det, el('div', { class: 'small muted' }, 'Known:'), el('ul', { class: 'facts' }, ...o.facts.map((f) => el('li', { class: 'math' }, toMath(f))))); + add(det, el('div', { class: 'small muted' }, 'Must follow:'), el('div', { class: 'math goal' }, toMath(o.goal))); + if (o.reason) add(det, el('p', { class: 'small muted' }, o.reason)); + add(item, det); + add(list, item); + } + add(sec, list); + add(root, sec); + } + add(root, el('p', { class: 'small muted' }, 'Proved means: on every path the checker examined, the claim follows from what is known. Open means the checker could not finish the argument; usually a loop needs an invariant. Broken means a generated input violated it.')); + } + const off = session.onChange(render); + render(); + return off; +} + +export function machineView(session: Session, root: HTMLElement): () => void { + function render() { + clear(root); + const tr = session.state.lang === 'asm' || session.traceLang() === 'asm' ? session.trace() : null; + if (!tr || tr.lang !== 'asm') { add(root, el('p', { class: 'muted' }, 'The machine view shows the hardware model for an assembly run. Open the x86-64 pane.')); return; } + let perf: any; + try { perf = (tr.raw as any).hardware().perf(); } catch (e: any) { add(root, el('p', { class: 'muted' }, `The hardware model could not run: ${e.message}`)); return; } + const machine = (tr.raw as any).machine; + const byLine = mojoCost(session, tr); + if (byLine) add(root, byLine); + add(root, el('p', { class: 'hint' }, `Machine: ${machineLabel(machine)}. Two cycle counts are shown because the course models two cores: an in-order 5-stage pipeline and an out-of-order core. They charge memory differently, so compare each against itself across edits, not against each other.`)); + const rows: Array<[string, string]> = [ + ['instructions', String(perf.instructions)], + ['micro-ops', String(perf.uops)], + ['cycles, in-order pipeline', String(perf.cyclesInOrder)], + ['cycles, out-of-order core', String(perf.cyclesOoO)], + ['instructions per cycle (OoO)', perf.ipc?.toFixed?.(2) ?? String(perf.ipc)], + ['branches', `${perf.branches} (${perf.mispredicts} mispredicted)`], + ['L1d loads / misses', `${perf.l1dLoads} / ${perf.l1dMisses}`], + ['L1i misses', String(perf.l1iMisses)], + ['L2 misses', String(perf.l2Misses)], + ['L3 misses', String(perf.l3Misses)], + ['memory reads', String(perf.memoryReads)], + ['TLB misses', perf.tlbMisses == null ? '—' : String(perf.tlbMisses)], + ['time at this clock', `${(perf.seconds * 1e9).toFixed(0)} ns`], + ]; + const table = el('table', { class: 'tbl perf-tbl' }); + for (const [k, v] of rows) add(table, el('tr', {}, el('td', {}, k), el('td', { class: 'mono' }, v))); + add(root, table); + if (Array.isArray(perf.bounds) && perf.bounds.length) { + add(root, el('h4', {}, 'What bounds the out-of-order core'), el('ul', { class: 'bounds' }, ...perf.bounds.map((b: any) => el('li', {}, el('b', {}, b.name), ': ', el('span', { class: 'mono' }, `${b.cycles} cycles`), ' — ', b.text)))); + } + } + const off = session.onChange(render); + render(); + return off; +} + +export function diagnosticsFor(session: Session, lang: LangId): Diagnostic[] { return session.diagnostics(lang); } + +/** + * For code sent from the Compiler view (each instruction marked `; mojo line N`): what each Mojo + * line cost on the model machine, as instructions executed and in-order pipeline cycles. An + * instruction's cycles are how far it moves the finish line (its write-back after the previous + * one's), so they add up to the run's total; the first one also pays for filling the pipeline and + * fetching code not yet in the cache. + */ +function mojoCost(session: Session, tr: any): HTMLElement | null { + const asm = session.source('asm').split('\n'); + const mojoOf = (asmLine: number): number | null => { const m = /;\s*mojo line (\d+)/.exec(asm[asmLine] ?? ''); return m ? Number(m[1]) : null; }; + if (!asm.some((l) => /;\s*mojo line \d+/.test(l))) return null; + let rows: any[]; + try { rows = (tr.raw as any).hardware().pipeline().rows; } catch { return null; } + const lines = new Map(); + let prev = 0, first: number | null | undefined; + for (const r of rows) { + const ln = mojoOf(r.step?.instr?.lineNo ?? -1); + if (first === undefined) first = ln; + const e = lines.get(ln) ?? { executed: 0, cycles: 0 }; + e.executed++; e.cycles += r.E.WB - prev; prev = r.E.WB; + lines.set(ln, e); + } + const total = [...lines.values()].reduce((a, e) => a + e.cycles, 0) || 1; + const src = session.source('mojo').split('\n'); + const tbl = el('table', { class: 'tbl' }, el('tr', {}, el('th', {}, 'Mojo line'), el('th', {}, ''), el('th', {}, 'instructions run'), el('th', {}, 'cycles (in-order)'), el('th', {}, 'share'))); + for (const [ln, e] of [...lines].sort((a, b) => (a[0] ?? 1e9) - (b[0] ?? 1e9))) { + add(tbl, el('tr', {}, + el('td', { class: 'mono' }, ln == null ? '—' : String(ln)), + el('td', { class: 'mono' }, ln == null ? 'no line of the program (inlined library code, or added by the compiler)' : (src[ln - 1] ?? '').trim()), + el('td', { class: 'mono' }, String(e.executed)), + el('td', { class: 'mono' }, String(e.cycles)), + el('td', { class: 'mono' }, `${Math.round((100 * e.cycles) / total)}%`))); + } + return el('div', { class: 'cost-by-line' }, + el('h4', {}, 'What each Mojo line cost'), + el('p', { class: 'small muted' }, `On the in-order pipeline: each instruction counts the cycles it adds to the finish. ${first != null ? `The first instruction (line ${first}) also pays for filling the pipeline and fetching code not yet in the cache, which is why its line looks expensive on a short run.` : ''}`), + tbl); +} diff --git a/src/ui/views/practices.ts b/src/ui/views/practices.ts new file mode 100644 index 0000000..64984e9 --- /dev/null +++ b/src/ui/views/practices.ts @@ -0,0 +1,43 @@ +/** + * The Best practices tab (the Bridge, when the helper is on): what the rules find in the generated Mojo. Each + * finding shows the Mojo line, the pseudo line it came from, the reason, the before and after, the manual's page, + * and, where it is true, how to write the pseudo or lingo so the translator writes the better form. The Mojo here + * is read-only, so rewrites are shown, not applied; clicking a finding lights both lines. + */ +import { el, clear, add } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { RULES } from '../../mojo/practices.js'; +import type { LangId } from '../../core/types.js'; + +export interface PracticesHooks { + /** Light these lines, each in its own pane, for a moment. */ + highlight(pairs: Array<[LangId, number]>): void; +} + +export function practicesView(session: Session, root: HTMLElement, hooks: PracticesHooks): () => void { + function render() { + clear(root); + const found = session.practices(); + add(root, el('p', { class: 'hint' }, 'The Mojo here is a literal translation of your pseudo, so it keeps habits Mojo programmers drop. These notes show what they would change. The translation itself never changes, and nothing here edits your work.')); + if (!session.source('mojo').trim()) { add(root, el('p', { class: 'muted' }, 'There is no Mojo yet: it is made from the pseudo.')); return; } + if (!found.length) { add(root, el('p', { class: 'muted' }, `Nothing to suggest. ${RULES.length} checks ran on the generated Mojo and found nothing to change.`)); return; } + const list = el('ul', { class: 'practices' }); + for (const f of found) { + const pseudo = session.pseudoLinesOfMojo(f.line); + const rule = RULES.find((r) => r.id === f.rule)!; + const item = el('li', { class: 'practice', onClick: () => hooks.highlight([['mojo', f.line], ...pseudo.map((l): [LangId, number] => ['pseudo', l])]) }, + el('div', { class: 'practice-head' }, + el('strong', {}, rule.title), + el('span', { class: 'mono small muted' }, `Mojo ${f.line}${f.endLine && f.endLine !== f.line ? `–${f.endLine}` : ''}`, pseudo.length ? ` · pseudo ${pseudo[0]}${pseudo.length > 1 ? `–${pseudo[pseudo.length - 1]}` : ''}` : '')), + el('p', {}, f.message), + el('div', { class: 'practice-diff' }, el('pre', { class: 'mono practice-before', title: 'as generated' }, f.before), el('pre', { class: 'mono practice-after', title: 'as a person might write it' }, f.after)), + f.pseudoHint ? el('p', { class: 'small' }, el('b', {}, 'In the pseudo: '), f.pseudoHint) : null, + el('p', { class: 'small' }, el('a', { href: f.docUrl, target: '_blank', rel: 'noopener' }, 'The Mojo manual ↗'))); + add(list, item); + } + add(root, list); + } + const off = session.onChange((what) => { if (what === 'source' || what === 'state') render(); }); + render(); + return off; +} diff --git a/src/ui/views/run.ts b/src/ui/views/run.ts new file mode 100644 index 0000000..e028113 --- /dev/null +++ b/src/ui/views/run.ts @@ -0,0 +1,205 @@ +/** + * The Run view: the whole run read top to bottom, one row per step, with a column for each variable the student + * follows (its value after the step: written now in color, carried over faded, out of scope blank) and the + * lifecycle of the value it names marked in the same cell. Above the rows, the followed variables as they stand + * at the stepper's position, with a ruler for strings and lists and a grid for tables. Click a row to step there. + * + * It replaces the Variables panel, the trace table, the table of values and the lifetimes: the data is + * core/runview.ts, the stepper is the one docked under the editor (it moves this view through session.onStep). + */ +import { el, add, clear } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { runColumns, runRows, defaultFollow, valuesAt, type RunColumn, type RunRow, type LifeKind } from '../../core/runview.js'; +import { familyOf, FAMILY_LABEL } from '../stepkinds.js'; + +export interface RunHooks { + goto(t: number): void; + /** The followed variables kept for this area (null: not chosen yet), and where a new choice is kept. */ + follow(): string[] | null; + setFollow(keys: string[]): void; +} + +const LIFE_MARK: Record = { made: '●', copied: '⧉', 'moved-in': '⇢', 'moved-out': '⇥', destroyed: '✕' }; +/** Every step is drawn while the run is this short; a longer one shows a window around the stepper. */ +const ALL_UP_TO = 800; +const WINDOW = 300; +/** The types whose value is drawn with a ruler of cells (rulerCells in core/runview.ts), pseudo's and Mojo's. */ +const RULED = /^(STRING|LIST\b|String|List\[)/; + +export function runView(session: Session, root: HTMLElement, hooks: RunHooks): () => void { + let onlyWrites = false; + let built: { trace: any; key: string; cols: RunColumn[]; follow: string[] } | null = null; + let rowEls = new Map(); + let windowAt = 0; + const head = el('div', { class: 'run-head' }); + const now = el('div', { class: 'run-now' }); + const scroll = el('div', { class: 'run-scroll' }); + clear(root); + add(root, head, now, scroll); + + const t = () => session.state.t ?? 0; + + function followed(cols: RunColumn[]): string[] { + const keys = new Set(cols.map((c) => c.key)); + const kept = (hooks.follow() ?? []).filter((k) => keys.has(k)); + return kept.length || hooks.follow()?.length === 0 ? kept : defaultFollow(cols); + } + + function short(text: string, n = 22): string { return text.length > n ? `${text.slice(0, n - 1)}…` : text; } + + let picking = false; + + function renderHead(cols: RunColumn[], follow: string[]) { + clear(head); + const order = (keys: string[]) => keys.sort((a, b) => cols.findIndex((x) => x.key === a) - cols.findIndex((x) => x.key === b)); + const set = (keys: string[]) => { hooks.setFollow(order(keys)); build(true); }; + const where = (c: RunColumn) => (c.fn === 'main' ? 'the main program' : c.fn); + const multi = new Set(cols.map((c) => c.fn)).size > 1; + const chips = el('div', { class: 'run-follow' }, el('span', { class: 'run-follow-label' }, 'Follow')); + for (const k of follow) { + const c = cols.find((x) => x.key === k)!; + add(chips, el('span', { class: 'run-chip on', title: `${c.name}${c.type ? ` (${c.type})` : ''} in ${where(c)}` }, + multi ? el('span', { class: 'run-chip-fn' }, `${c.fn === 'main' ? 'main' : c.fn}.`) : null, c.name, + el('button', { type: 'button', class: 'run-chip-x', title: `Stop following ${c.name}`, 'aria-label': `stop following ${c.name}`, onClick: () => set(follow.filter((x) => x !== k)) }, '×'))); + } + if (!follow.length) add(chips, el('span', { class: 'small muted' }, 'nothing yet')); + add(chips, el('button', { type: 'button', class: 'run-chip run-chip-add' + (picking ? ' open' : ''), 'aria-expanded': picking, title: 'Choose the variables to follow', onClick: () => { picking = !picking; renderHead(cols, follow); } }, picking ? 'done' : '+ variables')); + const filter = el('label', { class: 'run-filter small', title: 'Hide the steps that change nothing, print nothing and end nothing' }, + el('input', { type: 'checkbox', checked: onlyWrites, onChange: (e: Event) => { onlyWrites = (e.target as HTMLInputElement).checked; build(true); } }), ' only steps that change something'); + add(head, chips, filter); + if (!picking) return; + // the picker: every variable of the run, by routine; clicking one follows it or stops following it + const picker = el('div', { class: 'run-picker' }); + const byFn = new Map(); + for (const c of cols) byFn.set(c.fn, [...(byFn.get(c.fn) ?? []), c]); + for (const [fn, list] of byFn) { + add(picker, el('div', { class: 'run-picker-row' }, + el('span', { class: 'run-fn' }, fn === 'main' ? 'main program' : fn), + ...list.map((c) => { + const on = follow.includes(c.key); + return el('button', { + type: 'button', class: 'run-chip' + (on ? ' on' : ''), 'aria-pressed': on, + title: `${c.name}${c.type ? ` (${c.type})` : ''}: ${c.writes ? `written by ${c.writes} step${c.writes === 1 ? '' : 's'}` : 'never written after it is made'}`, + onClick: () => set(on ? follow.filter((k) => k !== c.key) : [...follow, c.key]), + }, c.name, c.writes ? el('sup', {}, String(c.writes)) : null); + }), + el('button', { type: 'button', class: 'linkish small', onClick: () => set([...new Set([...follow, ...list.filter((c) => c.name !== 'self').map((c) => c.key)])]) }, 'all'))); + } + add(picker, el('div', { class: 'run-picker-row' }, el('button', { type: 'button', class: 'linkish small', onClick: () => set(defaultFollow(cols)) }, 'back to the suggested ones'), el('button', { type: 'button', class: 'linkish small', onClick: () => set([]) }, 'none'))); + add(head, picker); + } + + function renderNow(trace: any, follow: string[], cols: RunColumn[]) { + clear(now); + if (!follow.length) { add(now, el('p', { class: 'small muted' }, 'Choose variables to follow above: each gets a column of its values, step by step.')); return; } + const at = valuesAt(trace, follow, t()); + const rows = (trace.steps as any[]); + const next = rows[t()]; + const readNext = new Set((next?.reads ?? []).map((r: any) => r.name)); + const last = rows[t() - 1]; + const wroteLast = new Set((last?.writes ?? []).map((w: any) => w.name)); + for (const v of at) { + const c = cols.find((x) => x.key === v.key)!; + const box = el('div', { class: 'run-var' + (wroteLast.has(c.name) && v.inScope ? ' run-var-wrote' : '') + (readNext.has(c.name) && v.inScope ? ' run-var-read' : '') }, + el('span', { class: 'run-var-name mono' }, c.name), v.type ? el('span', { class: 'run-var-type' }, v.type) : null, + el('span', { class: 'run-var-value mono', title: v.text ?? '' }, v.inScope ? (v.text ?? el('i', { class: 'muted' }, 'no value yet')) : el('i', { class: 'muted' }, 'not in scope'))); + if (v.inScope && v.ruler) { + const reads = (next?.reads ?? []).filter((r: any) => r.name === c.name && r.path).map((r: any) => Number(r.path[0])); + const writes = (last?.writes ?? []).filter((w: any) => w.name === c.name && w.path).map((w: any) => Number(w.path[0])); + const r = el('div', { class: 'ruler' }); + v.ruler.forEach((x, i) => add(r, el('span', { class: 'ruler-cell' + (reads.includes(i) ? ' read' : '') + (writes.includes(i) ? ' wrote' : '') }, el('b', {}, x === ' ' ? '␣' : x), el('i', {}, String(i))))); + add(box, r); + } else if (v.inScope && v.grid) { + const g = el('table', { class: 'run-grid' }); + const at = (list: any[], kind: string) => new Set(list.filter((a: any) => a.name === c.name && a.path?.length === 2).map((a: any) => `${a.path[0]},${a.path[1]}`)); + const wrote = at(last?.writes ?? [], 'w'), reads = at(next?.reads ?? [], 'r'); + v.grid.forEach((row, i) => add(g, el('tr', {}, el('th', {}, String(i)), ...row.map((x, j) => el('td', { class: (wrote.has(`${i},${j}`) ? 'wrote' : '') + (reads.has(`${i},${j}`) ? ' read' : '') }, x))))); + add(box, g); + } else if (RULED.test(c.type) && (!v.inScope || v.text == null)) { + // a string or list out of scope, or with no value yet: the same height as with its ruler, so the boxes + // under and beside it do not move when it gets one + add(box, el('div', { class: 'ruler ruler-placeholder', 'aria-hidden': 'true' }, el('span', { class: 'ruler-cell' }, el('b', {}, '\u00a0'), el('i', {}, '0')))); + } + add(now, box); + } + // while one run is stepped the panel never gets shorter (a table, or a value that wraps, can still grow it once) + if (heldFor !== trace) { heldFor = trace; now.style.minHeight = ''; } + const h = now.offsetHeight; + if (h > (Number.parseFloat(now.style.minHeight) || 0)) now.style.minHeight = `${h}px`; + } + let heldFor: any = null; + + function cell(row: RunRow, key: string): HTMLElement { + const c = row.cells[key]; + const td = el('td', { class: 'run-cell mono' + (c.wrote ? ' wrote' : '') + (c.read ? ' read' : '') + (c.text == null ? ' out' : '') }); + for (const m of c.life) add(td, el('span', { class: `run-life run-life-${m.kind}`, title: m.text }, LIFE_MARK[m.kind])); + if (c.at.length) add(td, el('span', { class: 'run-at', title: `this step wrote ${c.at.map((x) => `[${x}]`).join(' and ')}` }, c.at.map((x) => `[${x}]`).join(' '), ' ')); + if (c.text != null) add(td, el('span', { title: c.text }, short(c.text))); + return td; + } + + function build(force = false) { + const trace = session.trace(); + if (!trace) { clear(head); clear(now); clear(scroll); add(scroll, el('p', { class: 'muted run-empty' }, session.runError || 'Nothing to run yet.')); built = null; return; } + if (trace.lang === 'asm') { clear(head); clear(now); clear(scroll); add(scroll, el('p', { class: 'muted run-empty' }, 'The machine\'s run is drawn on the board: registers, memory and the rest.')); built = null; return; } + const cols = runColumns(trace); + const follow = followed(cols); + const key = JSON.stringify([follow, onlyWrites, windowAt]); + if (!force && built?.trace === trace && built.key === key) { mark(); return; } + built = { trace, key, cols, follow }; + renderHead(cols, follow); + clear(scroll); + rowEls = new Map(); + const n = trace.count; + let from = 0, to = n; + if (n > ALL_UP_TO) { from = Math.max(0, Math.min(windowAt - WINDOW / 2, n - WINDOW)); to = Math.min(n, from + WINDOW); } + const rows = runRows(trace, follow, from, to, { onlyWrites }); + const thead = el('thead', {}, el('tr', {}, el('th', { class: 'run-no' }, '#'), el('th', { class: 'run-line' }, 'line'), el('th', { class: 'run-what' }, 'what ran'), + ...follow.map((k) => { const c = cols.find((x) => x.key === k)!; return el('th', { class: 'run-colhead mono', title: `${c.name} in ${c.fn === 'main' ? 'the main program' : c.fn}` }, c.name); }))); + const tbody = el('tbody'); + const jump = (label: string, at: number) => el('tr', { class: 'run-more' }, el('td', { colspan: 3 + follow.length }, el('button', { type: 'button', class: 'linkish', onClick: () => { windowAt = at; build(true); } }, label))); + if (from > 0) add(tbody, jump(`… ${from} earlier steps: show them`, from)); + for (const r of rows) { + const fam = familyOf((trace.steps as any[])[r.step], trace.lang); + const what = el('td', { class: 'run-what mono' }, el('span', { class: 'run-indent', style: { width: `${Math.min(r.depth, 6) * 10}px` } }), r.text); + if (r.otherLife.length) add(what, el('div', { class: 'run-note' }, r.otherLife.join(' · '))); + if (r.printed.length) add(what, el('div', { class: 'run-note run-printed' }, `prints ${r.printed.map((x) => JSON.stringify(x)).join(', ')}`)); + const tr = el('tr', { class: `run-row k-${fam}`, title: FAMILY_LABEL[fam], onClick: () => hooks.goto(r.step + 1) }, + el('td', { class: 'run-no muted' }, el('span', { class: `k-dot k-${fam}` }), String(r.step + 1)), el('td', { class: 'run-line mono muted' }, r.line == null ? '' : String(r.line)), what, + ...follow.map((k) => cell(r, k))); + rowEls.set(r.step, tr); + add(tbody, tr); + } + if (to < n) add(tbody, jump(`… ${n - to} later steps: show them`, to + WINDOW / 2)); + if (!rows.length) add(tbody, el('tr', {}, el('td', { colspan: 3 + follow.length, class: 'muted' }, 'No step changes anything.'))); + add(scroll, el('table', { class: 'tbl run-tbl' }, thead, tbody)); + if (trace.error) add(scroll, el('p', { class: 'small err run-error' }, `The run stopped: ${trace.error.message}`)); + renderNow(trace, follow, cols); + mark(); + } + + /** Where the stepper is: the step that just ran, and the one that runs next. */ + function mark() { + if (!built) return; + const at = t(); + const trace = built.trace; + if (trace.count > ALL_UP_TO && (at < windowAt - WINDOW / 2 || at > windowAt + WINDOW / 2)) { windowAt = at; build(true); return; } + for (const r of scroll.querySelectorAll('.row-last, .row-next')) r.classList.remove('row-last', 'row-next'); + rowEls.get(at - 1)?.classList.add('row-last'); + const nextRow = rowEls.get(at); + nextRow?.classList.add('row-next'); + const target = nextRow ?? rowEls.get(at - 1); + if (target) { + // keep the row in view inside this panel only (never scroll the page) + const top = target.offsetTop - scroll.clientHeight / 3; + if (target.offsetTop < scroll.scrollTop + 40 || target.offsetTop > scroll.scrollTop + scroll.clientHeight - 40) scroll.scrollTop = Math.max(0, top); + } + renderNow(trace, built.follow, built.cols); + } + + windowAt = t(); + build(true); + const offStep = session.onStep(() => mark()); + const offChange = session.onChange((what) => { if (what === 'source' || what === 'run') build(); }); + return () => { offStep(); offChange(); }; +} diff --git a/src/ui/views/tests.ts b/src/ui/views/tests.ts new file mode 100644 index 0000000..2229b26 --- /dev/null +++ b/src/ui/views/tests.ts @@ -0,0 +1,149 @@ +/** + * The Tests view: the fuzzer's report (core/fuzz.ts) for each routine, written out so a student can see exactly + * what was tried and what was checked, not just "we tested it": + * + * what each input must do, how the inputs were made (each parameter's generator, each strategy and how many + * inputs it made), every way of failing with the input that found it and each step of shrinking it, the lines + * the inputs reached and the ones none did, the answers given and how often, and every case run. + * + * The seed and the number of inputs are chosen here; the same seed always makes the same inputs. + */ +import { el, add, clear, button, copyText } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import type { LangId } from '../../core/types.js'; +import { BUDGETS, STRATEGY, type FuzzCase, type FuzzReport, type Strategy } from '../../core/fuzz.js'; + +export interface TestsHooks { + reveal(lang: LangId, line: number): void; + /** Run this call in the stepper (pseudo: the call box), and show the run. */ + stepThrough?(call: string): void; +} + +const KIND: Record = { + index: 'index out of range', bounds: 'index out of bounds', unset: 'value used before it is set', value: 'bad value', type: 'wrong type', divide: 'division by zero', + ensure: 'ENSURE broken', invariant: 'INVARIANT broken', decreases: 'DECREASES broken', assert: 'ASSERT broken', limit: 'does not finish', raise: 'uncaught raise', + depth: 'calls too deep', nondeterministic: 'a different answer the second time', +}; + +const OUTCOME_WORD: Record = { pass: 'passed', fail: 'failed', skip: 'skipped', raises: 'raised' }; + +export function testsView(session: Session, root: HTMLElement, hooks: TestsHooks): () => void { + let seed = 1; + let budget = 300; + const filters = new Map(); // per routine: 'all' | 'fail' | 'skip' | a strategy + const open = new Set(); + + function render() { + clear(root); + const mojo = session.state.lang === 'mojo'; + const pane: LangId = mojo ? 'mojo' : 'pseudo'; + const reports = session.fuzz({ seed, budget }); + const seedBox = el('input', { class: 'input mono fuzz-seed', type: 'number', min: 1, value: String(seed), title: 'The seed: the same seed always makes the same inputs' }) as HTMLInputElement; + seedBox.addEventListener('change', () => { seed = Math.max(1, Math.floor(Number(seedBox.value) || 1)); render(); }); + const budgetBox = el('select', { class: 'select', title: 'How many inputs to try for each routine', onChange: (e: Event) => { budget = Number((e.target as HTMLSelectElement).value); render(); } }, + ...BUDGETS.map((b) => el('option', { value: String(b), selected: b === budget }, `${b} inputs`))); + add(root, el('div', { class: 'fuzz-bar' }, + el('span', { class: 'small muted' }, mojo ? 'Each function other than main, in Programming+\'s interpreter.' : 'Each routine of the pseudo, with the speco woven in.'), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label' }, 'seed ', seedBox), button('new seed', () => { seed = 1 + Math.floor(Math.random() * 99999); render(); }, { class: 'btn btn-small', title: 'Different inputs from the same strategies' }), + budgetBox)); + if (!reports.length) { add(root, el('p', { class: 'muted' }, mojo ? 'Generated-input testing needs a function other than main, in a Mojo program with no problems.' : 'Generated-input testing needs a FUNCTION or PROCEDURE that parses.')); return; } + reports.forEach((r, i) => add(root, routine(r, pane, i === 0 || r.failures.length > 0))); + } + + function routine(r: FuzzReport, pane: LangId, first: boolean): HTMLElement { + const covered = r.coverage.filter((c) => c.inputs > 0).length; + const isOpen = open.has(r.name) || (!open.size && first); + const sec = el('details', { class: 'fuzz-unit', open: isOpen }); + sec.addEventListener('toggle', () => { if (sec.open) open.add(r.name); else open.delete(r.name); }); + const tried = r.cases.filter((c) => c.strategy !== 'shrink' && c.strategy !== 'repeat').length; + add(sec, el('summary', {}, + el('code', { class: 'fuzz-sig' }, r.signature), + r.problem && !r.cases.length ? el('span', { class: 'badge badge-open' }, 'not tested') : el('span', { class: `badge ${r.failures.length ? 'badge-broken' : 'badge-proved'}` }, r.failures.length ? `${r.failures.length} way${r.failures.length === 1 ? '' : 's'} of failing` : 'no failures'), + r.cases.length ? el('span', { class: 'small muted' }, ` ${tried} inputs · ${r.counts.fail} failed · ${r.counts.skip} skipped${r.counts.raises ? ` · ${r.counts.raises} raised` : ''}${r.coverage.length ? ` · ${covered}/${r.coverage.length} lines reached` : ''}`) : null)); + if (r.problem) add(sec, el('p', { class: r.cases.length ? 'hint' : 'muted' }, r.problem)); + if (!r.cases.length) return sec; + + // what each input must do + add(sec, el('h5', {}, 'What each input must do'), el('ul', { class: 'fuzz-checks' }, ...r.checks.map((c) => el('li', {}, c)))); + + // how the inputs were made + const gens = el('table', { class: 'tbl fuzz-gens' }, el('tr', {}, el('th', {}, 'parameter'), el('th', {}, 'type'), el('th', {}, 'values tried'))); + for (const p of r.params) add(gens, el('tr', {}, el('td', { class: 'mono' }, p.name), el('td', { class: 'mono muted' }, p.type), el('td', {}, p.how))); + const strat = el('ul', { class: 'fuzz-strats' }, ...r.strategies.map((s) => el('li', {}, el('b', {}, `${s.count} ${s.label}`), ': ', s.how))); + add(sec, el('h5', {}, `How the inputs were made (seed ${r.seed})`), r.params.length ? gens : el('p', { class: 'small muted' }, 'It takes no parameters, so it runs once.'), strat); + + // the failures, each with the input that found it and every step of shrinking it + if (r.failures.length) { + add(sec, el('h5', {}, 'Failures')); + for (const f of r.failures) { + const card = el('div', { class: 'fuzz-fail' }, + el('div', { class: 'fuzz-fail-head' }, el('span', { class: 'badge badge-broken' }, KIND[f.kind] ?? f.kind), ' ', el('code', {}, f.call), + f.line ? button(`line ${f.line}`, () => hooks.reveal(pane, f.line!), { class: 'btn btn-small btn-quiet mono' }) : null, el('span', { class: 'spacer' }), + hooks.stepThrough && r.lang === 'pseudo' ? button('Step through this input', () => hooks.stepThrough!(f.call), { class: 'btn btn-small', title: 'Put this call in the call box and show the run' }) : button('Copy the call', async (e) => { await copyText(f.call); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' })), + el('p', { class: 'fuzz-msg' }, f.message)); + if (f.shrink.length > 1) add(card, el('div', { class: 'small muted' }, `Found by case #${f.n} and shrunk in ${f.shrink.length - 1} step${f.shrink.length === 2 ? '' : 's'} to the smallest input that still fails this way:`), + el('ol', { class: 'fuzz-shrink' }, ...f.shrink.map((c, i) => el('li', { class: i === f.shrink.length - 1 ? 'fuzz-shrink-last' : '' }, el('code', {}, c))))); + else add(card, el('div', { class: 'small muted' }, `Found by case #${f.n}; no smaller input fails the same way.`)); + add(sec, card); + } + } + + // coverage: the lines the inputs reached, and the ones none did + if (r.coverage.length) { + const src = session.source(pane).split('\n'); + const most = Math.max(1, ...r.coverage.map((c) => c.inputs)); + const never = r.coverage.filter((c) => !c.inputs); + const list = el('div', { class: 'fuzz-cov' }); + for (const c of r.coverage) { + add(list, el('button', { type: 'button', class: 'fuzz-cov-row' + (c.inputs ? '' : ' never'), title: c.inputs ? `${c.inputs} of the inputs reached line ${c.line}, ${c.hits} time${c.hits === 1 ? '' : 's'} in all` : `No input reached line ${c.line}`, onClick: () => hooks.reveal(pane, c.line) }, + el('span', { class: 'fuzz-cov-line mono' }, String(c.line)), + el('span', { class: 'fuzz-cov-bar' }, el('span', { style: { width: `${(100 * c.inputs) / most}%` } })), + el('span', { class: 'fuzz-cov-n mono' }, c.inputs ? String(c.inputs) : 'never'), + el('code', { class: 'fuzz-cov-src' }, (src[c.line - 1] ?? '').trim()))); + } + add(sec, el('h5', {}, `Lines reached: ${r.coverage.length - never.length} of ${r.coverage.length}`), + never.length ? el('p', { class: 'hint' }, `No input reached ${never.length === 1 ? `line ${never[0].line}` : `lines ${never.map((c) => c.line).join(', ')}`}. Either no input of these kinds can get there, or the generators need a case they do not make; a line no input reaches is a line no test has checked.`) : null, + list); + } + + // the answers it gave + if (r.results.length) { + const total = r.results.reduce((a, x) => a + x.count, 0); + const top = r.results.slice(0, 10); + add(sec, el('h5', {}, `Answers: ${r.results.length} different${r.results.length > 10 ? ', the 10 most common' : ''}`), + el('div', { class: 'fuzz-results' }, ...top.map((x) => el('div', { class: 'fuzz-result' }, el('code', {}, x.value.length > 40 ? `${x.value.slice(0, 39)}…` : x.value), el('span', { class: 'fuzz-cov-bar' }, el('span', { style: { width: `${(100 * x.count) / total}%` } })), el('span', { class: 'small muted mono' }, String(x.count)))))); + } + + // every case run + const filter = filters.get(r.name) ?? (r.counts.fail ? 'fail' : 'all'); + const choose = (f: string) => { filters.set(r.name, f); open.add(r.name); render(); }; + const strategiesUsed = [...new Set(r.cases.map((c) => c.strategy))] as Strategy[]; + const chips = el('div', { class: 'fuzz-filter' }, + ...[['all', `all ${r.cases.length}`], ['fail', `failed ${r.counts.fail}`], ['skip', `skipped ${r.counts.skip}`], ...(r.counts.raises ? [['raises', `raised ${r.counts.raises}`]] : []), ...strategiesUsed.map((s) => [s, `${STRATEGY[s].label} ${r.cases.filter((c) => c.strategy === s).length}`])] + .map(([id, label]) => el('button', { type: 'button', class: 'run-chip' + (filter === id ? ' on' : ''), onClick: () => choose(id) }, label))); + const shown = r.cases.filter((c) => filter === 'all' || c.outcome === filter || c.strategy === filter); + const MAX = 300; + const table = el('table', { class: 'tbl fuzz-cases' }, el('thead', {}, el('tr', {}, el('th', {}, '#'), el('th', {}, 'how'), el('th', {}, 'input'), el('th', {}, 'outcome'), el('th', {}, 'answer, or what went wrong'), el('th', { title: 'steps the run took' }, 'steps')))); + const body = el('tbody'); + for (const c of shown.slice(0, MAX)) add(body, caseRow(c, pane)); + add(table, body); + add(sec, el('h5', {}, 'Every case run'), chips, el('div', { class: 'fuzz-cases-wrap' }, table), shown.length > MAX ? el('p', { class: 'small muted' }, `The first ${MAX} of ${shown.length} are shown.`) : null); + return sec; + } + + function caseRow(c: FuzzCase, pane: LangId): HTMLElement { + return el('tr', { class: `fuzz-case fuzz-${c.outcome}` }, + el('td', { class: 'muted mono' }, String(c.n)), + el('td', { class: 'small' }, STRATEGY[c.strategy].label), + el('td', { class: 'mono', title: c.call }, c.args.join(', ') || '()'), + el('td', {}, el('span', { class: `fuzz-out fuzz-out-${c.outcome}` }, OUTCOME_WORD[c.outcome])), + el('td', { class: 'mono small' }, c.outcome === 'pass' ? (c.result ?? '') : c.message ?? '', c.line ? el('button', { type: 'button', class: 'linkish', onClick: () => hooks.reveal(pane, c.line!) }, ` line ${c.line}`) : null, + c.newLines?.length ? el('span', { class: 'fuzz-new', title: 'This input reached lines no earlier input had; the fuzzer mutates it to explore further' }, ` new: line${c.newLines.length === 1 ? '' : 's'} ${c.newLines.join(', ')}`) : null), + el('td', { class: 'mono muted' }, String(c.steps))); + } + + const off = session.onChange((what) => { if (what === 'source' || what === 'run') render(); }); + render(); + return off; +} diff --git a/src/ui/views/trace.ts b/src/ui/views/trace.ts new file mode 100644 index 0000000..19cbdc2 --- /dev/null +++ b/src/ui/views/trace.ts @@ -0,0 +1,536 @@ +/** + * The step-through view. One controller (back, step, play, slider, + * keyboard, breakpoints, loop-pass jumps, predict mode) over either trace + * shape; the body switches on the language: pseudocode shows what runs next, + * the trace table, and the variables with rulers and history; assembly shows + * registers, flags, memory, and what the instruction did. + */ +import { el, clear, add, button } from '../dom.js'; +import { frameAt, type Trace } from '../../core/types.js'; +import { formatValue, UNSET } from '../../engines/pseudo/lang.js'; +import { varIn } from '../../core/runview.js'; +import { formatHex, FLAG_NAMES } from '../../engines/asm86/interp.js'; +import type { Session } from '../../core/session.js'; +import { familyOf, FAMILY_LABEL } from '../stepkinds.js'; + +export interface StepperApi { goto(t: number): void; t: number; destroy(): void; toggleBreakpoint(line: number): void; breakpoints: Set } + +/** + * Where the stepper's parts go. With no hosts, everything stacks inside `root` + * (the embeds). The shell gives each part its own persistent panel: the + * controls stay in one place, the variables in another, and the trace table + * and the output in panels of their own. + */ +export interface TraceHosts { + controls: HTMLElement; + /** The "what runs next" box and the predict box. */ + next: HTMLElement; + /** The variables and the trace table, for a host that shows them itself; the workspace's Run view does instead (views/run.ts). */ + vars?: HTMLElement; + table?: HTMLElement; + output: HTMLElement; + /** One line: the loops in flight, or the machine's counts. */ + status: HTMLElement; +} + +export interface TraceOptions { + onStep?: (line: number | null, last: number | null, hits: Map) => void; + onBreakpoints?: (lines: Set) => void; + compact?: boolean; + hosts?: TraceHosts; + /** Called with the number of output lines so far and whether the run ended with an error (the dock's summary). */ + onOutput?: (lines: string[], error: string | null) => void; +} + +export function traceView(session: Session, root: HTMLElement, opts: TraceOptions = {}): StepperApi { + let t = session.state.t ?? 0; + let timer: number | null = null; + let trace: Trace | null = null; + let speed = 350; + let predictOn = false; + let onlyWrites = false; + const score = { right: 0, asked: 0 }; + const breakpoints = new Set(); + + const controls = el('div', { class: 'stepper' }); + const row2 = el('div', { class: 'stepper-row2' }); + const nextBox = el('div', { class: 'trace-next' }); + const predictBox = el('div', { class: 'predict', style: { display: 'none' } }); + const status = el('div', { class: 'trace-status' }); + const body = el('div', { class: 'trace-body' }); + const output = el('pre', { class: 'trace-output' }); + const H = opts.hosts; + // in the shell the variables and the table have panels of their own; in an embed they share `body` + const varsHost = H?.vars ?? el('div', { class: 'trace-col' }); + const tableHost = H?.table ?? el('div', { class: 'trace-col' }); + /** Whether this stepper draws the variables and the trace table at all (not when the Run view does). */ + const drawsBody = !H || !!(H.vars && H.table); + if (H) { add(H.controls, controls, row2); add(H.next, nextBox, predictBox); add(H.status, status); add(H.output, output); } + else add(root, controls, row2, nextBox, predictBox, status, body, output); + + const slider = el('input', { type: 'range', min: 0, max: 0, value: 0, class: 'stepper-slider', 'aria-label': 'step', onInput: () => goto(Number(slider.value)) }); + const counter = el('span', { class: 'stepper-count' }); + const playBtn = button('Play', () => (timer ? pause() : play()), { title: 'Space' }); + add(controls, + button('⏮', () => goto(0), { title: 'First step (Home)' }), + button('◀', () => goto(t - 1), { title: 'Back one step (←)' }), + button('▶', () => stepForward(), { title: 'One step (→)' }), + button('⏭', () => goto(trace?.count ?? 0), { title: 'Last step (End)' }), + playBtn, slider, counter, + ); + const passBack = button('↶ pass', () => jumpPass(-1), { class: 'btn-small', title: 'Previous pass of the loop you are in (Shift+←)' }); + const passFwd = button('pass ↷', () => jumpPass(1), { class: 'btn-small', title: 'Next pass of the loop you are in (Shift+→)' }); + const toBreak = button('to breakpoint', () => runToBreakpoint(), { class: 'btn-small', title: 'Run until a breakpointed line is next (click a line number to set one)' }); + const predictBtn = button('Predict mode', () => { predictOn = !predictOn; predictBtn.classList.toggle('on', predictOn); renderPredict(); }, { class: 'btn-small', title: 'Say what the next step will write before you take it (P)' }); + const writesBtn = button('Only writes', () => { onlyWrites = !onlyWrites; writesBtn.classList.toggle('on', onlyWrites); goto(t); }, { class: 'btn-small', title: 'Hide steps that change nothing' }); + const speedCtl = el('input', { type: 'range', min: 60, max: 1200, step: 10, value: 1200 - speed + 60, class: 'speed', title: 'Play speed', onInput: () => { speed = 1200 - Number(speedCtl.value) + 60; if (timer) { pause(); play(); } } }); + const csvBtn = button('CSV', () => exportCsv(), { class: 'btn-small btn-quiet', title: 'Download the trace table' }); + add(row2, passBack, passFwd, toBreak, predictBtn, drawsBody ? writesBtn : null, el('span', { class: 'spacer' }), el('span', {}, 'speed'), speedCtl, csvBtn); + + function pause() { if (timer) { clearInterval(timer); timer = null; playBtn.textContent = 'Play'; } } + function play() { + if (!trace || t >= trace.count) t = 0; + playBtn.textContent = 'Pause'; + timer = window.setInterval(() => { + if (!trace || t >= trace.count) return pause(); + const nextLine = lineOfStep(t); + if (breakpoints.size && nextLine != null && breakpoints.has(nextLine) && t !== 0) { pause(); return; } + goto(t + 1); + }, speed); + } + + function stepForward() { + if (!trace) return; + if (predictOn && t < trace.count && pendingPrediction()) { predictBox.querySelector('input')?.focus(); return; } + goto(t + 1); + } + + function lineOfStep(i: number): number | null { + if (!trace || i >= trace.count) return null; + const s: any = trace.steps[i]; + return trace.lang === 'asm' ? s.instr.lineNo + 1 : s.line ?? null; + } + + function runToBreakpoint() { + if (!trace) return; + if (!breakpoints.size) { status.textContent = 'No breakpoints yet: click a line number in the editor to set one.'; return; } + for (let i = t + 1; i < trace.count; i++) { const ln = lineOfStep(i); if (ln != null && breakpoints.has(ln)) { goto(i); return; } } + goto(trace.count); + } + + /** The loop the current step is inside, from the state's loop stack (pseudocode only). */ + function jumpPass(dir: 1 | -1) { + if (!trace || trace.lang === 'asm') { jumpBranch(dir); return; } + const st: any = trace.states[t]; + const loop = st?.loops?.[st.loops.length - 1]; + if (!loop) { status.textContent = 'Not inside a loop at this step.'; return; } + const passAt = (i: number) => { const s: any = trace!.states[i]; const l = s?.loops?.find((x: any) => x.line === loop.line); return l ? l.pass : null; }; + const cur = loop.pass; + if (dir > 0) { for (let i = t + 1; i <= trace.count; i++) { const p = passAt(i); if (p == null) { goto(i); return; } if (p === cur + 1) { goto(i); return; } } goto(trace.count); } + else { let i = t - 1; while (i > 0 && passAt(i) === cur) i--; const target = passAt(i); if (target == null) { goto(Math.max(0, i)); return; } while (i > 0 && passAt(i - 1) === target) i--; goto(i); } + } + + /** Assembly: the next (or previous) taken backward branch is the next pass. */ + function jumpBranch(dir: 1 | -1) { + if (!trace) return; + const isBack = (i: number) => { const s: any = trace!.steps[i]; return s?.branch && s.branch.taken && s.pcAfter < s.pcBefore; }; + if (dir > 0) { for (let i = t; i < trace.count; i++) if (isBack(i)) { goto(i + 1); return; } goto(trace.count); } + else { for (let i = t - 2; i >= 0; i--) if (isBack(i)) { goto(i + 1); return; } goto(0); } + } + + function goto(n: number) { + if (!trace) return; + t = Math.max(0, Math.min(n, trace.count)); + session.state.t = t; + slider.value = String(t); + counter.textContent = `step ${t} of ${trace.count}`; + const fr = frameAt(trace, t); + const nextLine = (fr.next as any)?.line ?? asmLine(trace, (fr.state as any)?.pc) ?? null; + const lastLine = (fr.last as any)?.line ?? asmLine(trace, (fr.last as any)?.pcBefore) ?? null; + opts.onStep?.(nextLine, lastLine, hitsUpTo(trace, t)); + renderNext(fr); + renderPredict(); + renderBody(fr); + session.notifyStep(t); + } + + function asmLine(tr: Trace, pc: number | undefined): number | null { + if (tr.lang !== 'asm' || pc == null) return null; + const instr = (tr.raw as any).trace.program.instrs[pc]; + return instr ? instr.lineNo + 1 : null; + } + + function hitsUpTo(tr: Trace, upto: number): Map { + const m = new Map(); + for (let i = 0; i < upto; i++) { const ln = lineOfStep(i); if (ln != null) m.set(ln, (m.get(ln) || 0) + 1); } + return m; + } + + /* ---------- what runs next ---------- */ + + function renderNext(fr: ReturnType) { + clear(nextBox); + if (!trace) return; + nextBox.className = 'trace-next'; + nextBox.title = ''; + // The box keeps one height whatever the step (two lines, in CSS): the step's line, and under it what it reads + // and writes. Each line is cut with an ellipsis rather than wrapped, and the whole text is in the tooltip. + const line = el('div', { class: 'trace-next-line' }); + add(nextBox, line); + if (!fr.next) { + nextBox.classList.add(trace.error ? 'k-error' : 'k-done'); + add(line, 'The run has finished.', trace.error ? ` It stopped with: ${trace.error.message}` : ''); + nextBox.title = line.textContent ?? ''; + return; + } + const s: any = fr.next; + if (trace.lang !== 'asm') { const fam = familyOf(s, trace.lang); nextBox.classList.add(`k-${fam}`); } + let sub = ''; + if (trace.lang === 'asm') { + const ins = s.instr; + add(line, 'Next: ', el('span', { class: 'mono' }, `${ins.op} ${ins.operands.map((o: any) => o.source ?? '').join(', ')}`), el('span', { class: 'muted' }, ` on line ${ins.lineNo + 1}`)); + } else { + const srcLine = sourceLine(s.line); + add(line, 'Next: line ', String(s.line ?? '?'), srcLine ? el('span', { class: 'mono' }, ` ${srcLine.trim()}`) : null); + const reads = (s.reads || []).map((r: any) => r.path ? `${r.name}[${r.path.join(', ')}]` : r.name); + const writes = (s.writes || []).map((w: any) => w.path ? `${w.name}[${w.path.join(', ')}]` : w.name); + sub = [reads.length ? `reads ${[...new Set(reads)].join(', ')}` : '', writes.length ? `writes ${[...new Set(writes)].join(', ')}` : ''].filter(Boolean).join(' · '); + } + // the second line is always there, empty or not, so a step that reads nothing does not shrink the box + add(nextBox, el('div', { class: 'trace-next-sub small muted' }, sub || '\u00a0')); + const fam = trace.lang !== 'asm' ? FAMILY_LABEL[familyOf(s, trace.lang)] : ''; + nextBox.title = [fam, line.textContent?.trim(), sub].filter(Boolean).join('\n'); + } + + function sourceLine(line: number | null): string | null { + if (line == null || !trace) return null; + const src = trace.lang === 'lingo' ? session.source('lingo') : trace.lang === 'matho' ? session.source('matho') : trace.lang === 'mojo' ? session.source('mojo') : session.source('pseudo'); + return src.split('\n')[line - 1] ?? null; + } + + /* ---------- predict mode ---------- */ + + /** The variable the next step writes, if exactly one scalar it is worth predicting. */ + function pendingPrediction(): { name: string; frame: number } | null { + if (!trace || trace.lang === 'asm') return null; + const s: any = trace.steps[t]; + const writes = (s?.writes || []).filter((w: any) => !w.path); + if (writes.length !== 1) return null; + return { name: writes[0].name, frame: writes[0].frame }; + } + + function valueAfter(name: string, frameId: number, at: number): { text: string } | null { + if (!trace) return null; + const st: any = trace.states[at]; + const f = (st?.frames || []).find((x: any) => x.id === frameId) || (st?.frames || []).slice(-1)[0]; + const v = varIn(f?.vars, name); + if (v && typeof v.text === 'string') return { text: v.text }; // a Mojo value carries its own display + if (!v || v.value === UNSET || typeof v.value === 'symbol') return null; + return { text: formatValue(v.value, v.type) }; + } + + function renderPredict() { + clear(predictBox); + if (!predictOn || !trace || trace.lang === 'asm') { predictBox.style.display = 'none'; return; } + predictBox.style.display = ''; + const p = pendingPrediction(); + const scoreEl = el('span', { class: 'predict-score' }, score.asked ? `${score.right} of ${score.asked} right` : 'no predictions yet'); + if (!p) { add(predictBox, el('div', { class: 'predict-row' }, el('span', { class: 'muted' }, t >= trace.count ? 'The run has finished.' : 'The next step writes nothing to predict; step on.'), scoreEl)); return; } + const input = el('input', { class: 'input mono', placeholder: `value of ${p.name} after this step`, style: { minWidth: '200px' } }); + const result = el('span'); + const check = () => { + const want = valueAfter(p.name, p.frame, t + 1); + const got = input.value.trim(); + if (!got) return; + score.asked++; + const norm = (x: string) => x.replace(/\s+/g, '').replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1').toUpperCase(); + const ok = !!want && norm(want.text) === norm(got); + if (ok) score.right++; + clear(result); + add(result, el('span', { class: ok ? 'predict-right' : 'predict-wrong' }, ok ? 'Right.' : `It will be ${want?.text ?? 'unset'}.`)); + scoreEl.textContent = `${score.right} of ${score.asked} right`; + input.disabled = true; + setTimeout(() => goto(t + 1), ok ? 500 : 1400); + }; + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); check(); } e.stopPropagation(); }); + add(predictBox, `Before you step: what will `, el('b', { class: 'mono' }, p.name), ' hold after this line?', + el('div', { class: 'predict-row' }, input, button('Check', check, { class: 'btn-small btn-primary' }), button('Skip', () => goto(t + 1), { class: 'btn-small btn-quiet' }), result, scoreEl)); + } + + /* ---------- pseudocode ---------- */ + + function renderBody(fr: ReturnType) { + clear(body); clear(varsHost); clear(tableHost); + if (!trace) return; + if (trace.lang === 'asm') renderAsm(fr); else renderPseudo(fr); + } + + /** The last step before `at` that wrote `name` in frame `frameId`. */ + function lastWrite(name: string, frameId: number, at: number): number | null { + if (!trace) return null; + for (let i = at - 1; i >= 0; i--) { const s: any = trace.steps[i]; if ((s.writes || []).some((w: any) => w.name === name && (w.frame == null || w.frame === frameId))) return i; } + return null; + } + + function ruler(value: any, type: any, reads: number[], writes: number[]): HTMLElement | null { + let cells: string[] | null = null; + if (typeof value === 'string') cells = value.length > 1 ? [...value] : null; + else if (Array.isArray(value) && value.length <= 64 && value.every((x) => typeof x !== 'object')) cells = value.map((x) => formatValue(x, type?.of, { bareChar: true })); + if (!cells || !cells.length || cells.length > 80) return null; + const r = el('div', { class: 'ruler' }); + cells.forEach((c, i) => add(r, el('span', { class: 'ruler-cell' + (reads.includes(i) ? ' read' : '') + (writes.includes(i) ? ' wrote' : '') }, el('b', {}, c === ' ' ? '␣' : c), el('i', {}, String(i))))); + return r; + } + + /** Every value a name took over the whole run, with the step that set it: the variable's timeline. */ + const histCache = new Map>(); + function history(name: string, frameId: number): Array<{ step: number; text: string }> { + const key = `${frameId}:${name}`; + const hit = histCache.get(key); + if (hit) return hit; + const out: Array<{ step: number; text: string }> = []; + if (trace) for (let i = 0; i < trace.count; i++) { + const s: any = trace.steps[i]; + if (!(s.writes || []).some((w: any) => w.name === name && (w.frame == null || w.frame === frameId))) continue; + const v = valueAfter(name, frameId, i + 1); + if (!v) continue; + if (out.length && out[out.length - 1].text === v.text) continue; + out.push({ step: i, text: v.text }); + } + histCache.set(key, out); + return out; + } + + /** The timeline as a row of chips: past values solid, the current one marked, values still to come faded. Click one to go there. */ + function track(name: string, frameId: number): HTMLElement | null { + const h = history(name, frameId); + if (h.length < 2) return null; + const cur = [...h].reverse().find((x) => x.step < t); + const row = el('div', { class: 'var-track', title: `${name}: every value it takes in this run, in order. Click one to step to where it was set.` }); + const MAX = 14; + let shown = h; + if (h.length > MAX) { + const ci = cur ? h.indexOf(cur) : 0; + const from = Math.max(0, Math.min(ci - 6, h.length - MAX)); + shown = h.slice(from, from + MAX); + if (from > 0) add(row, el('span', { class: 'var-chip var-chip-more' }, `…${from}`)); + } + for (const x of shown) { + const cls = 'var-chip' + (x === cur ? ' var-chip-now' : x.step < t ? ' var-chip-past' : ' var-chip-next'); + add(row, el('button', { type: 'button', class: cls, title: `step ${x.step + 1}`, onClick: (e: MouseEvent) => { e.stopPropagation(); goto(x.step + 1); } }, x.text.length > 18 ? x.text.slice(0, 17) + '…' : x.text)); + } + if (shown[shown.length - 1] !== h[h.length - 1]) add(row, el('span', { class: 'var-chip var-chip-more' }, `…${h.length - h.indexOf(shown[shown.length - 1]) - 1}`)); + return row; + } + + function renderPseudo(fr: ReturnType) { + const tr = trace!; + const state: any = fr.state; + if (!drawsBody) { renderStatus(state); renderOutput(tr, t >= tr.count ? tr.output.length : (state?.outputLength ?? tr.output.length)); return; } + const vars = el('div', { class: 'vars' }); + const lastWrites = ((fr.last as any)?.writes || []) as any[]; + const nextReads = ((fr.next as any)?.reads || []) as any[]; + const wroteKeys = new Set(lastWrites.map((w: any) => `${w.frame}:${w.name}`)); + const readKeys = new Set(nextReads.map((w: any) => `${w.frame}:${w.name}`)); + for (const f of (state?.frames || []).slice().reverse()) { + const table = el('table', { class: 'tbl vars-tbl' }, el('caption', {}, f.name === 'main' || !f.name ? 'main program' : `${f.name}`)); + const entries = Object.values(f.vars) as any[]; + if (!entries.length) add(table, el('tr', {}, el('td', { class: 'muted', colspan: 3 }, 'no names yet'))); + for (const v of entries) { + const key = `${f.id}:${v.name}`; + const own = typeof v.text === 'string'; // Mojo: the interpreter's display, "(moved out)" included + const unset = !own && (v.value === undefined || v.value === UNSET || typeof v.value === 'symbol'); + const shown = own ? v.text : unset ? '' : formatValue(v.value, v.type); + const prevIdx = lastWrite(v.name, f.id, t); + const prevVal = prevIdx != null ? valueAfter(v.name, f.id, prevIdx) : null; + const tl = H ? track(v.name, f.id) : null; + const hist = tl ?? (prevIdx != null ? el('div', { class: 'var-hist' }, prevVal && prevVal.text !== shown ? `was ${prevVal.text}; ` : '', el('button', { type: 'button', class: 'linkish', onClick: () => goto(prevIdx + 1) }, `changed at step ${prevIdx + 1}`)) : null); + add(table, el('tr', { class: (wroteKeys.has(key) ? 'just-wrote ' : '') + (readKeys.has(key) ? 'about-to-read' : '') }, + el('td', { class: 'mono' }, v.name), el('td', { class: 'muted' }, typeOf(v.type)), + el('td', { class: 'mono' }, unset ? el('span', { class: 'muted' }, 'no value yet') : shown, hist))); + if (!unset && !own) { + const reads = nextReads.filter((r: any) => r.name === v.name && r.frame === f.id && r.path).map((r: any) => Number(r.path[0])); + const writes = lastWrites.filter((w: any) => w.name === v.name && w.frame === f.id && w.path).map((w: any) => Number(w.path[0])); + const rl = ruler(v.value, v.type, reads, writes); + if (rl) add(table, el('tr', {}, el('td', { colspan: 3, class: 'var-ruler' }, rl))); + } + } + add(vars, table); + } + const rows = el('tbody'); + const idx: number[] = []; + for (let i = 0; i < tr.count; i++) if (!onlyWrites || ((tr.steps[i] as any).writes || []).length || i === t || i === t - 1) idx.push(i); + const pos = Math.max(0, idx.findIndex((i) => i >= t) === -1 ? idx.length - 1 : idx.findIndex((i) => i >= t)); + const win = opts.compact ? 4 : 9; + for (const i of idx.slice(Math.max(0, pos - win), pos + win)) { + const s: any = tr.steps[i]; + const w = (s.writes || []).map((x: any) => x.name).join(', '); + const fam = familyOf(s, tr.lang); + add(rows, el('tr', { class: `k-${fam} ` + (i === t - 1 ? 'row-last' : i === t ? 'row-next' : ''), onClick: () => goto(i + 1) }, + el('td', { class: 'muted step-no' }, el('span', { class: `k-dot k-${fam}`, title: FAMILY_LABEL[fam] }), String(i + 1)), el('td', { class: 'mono' }, String(s.line ?? '')), el('td', { class: 'mono' }, s.text || s.kind), el('td', { class: 'mono muted' }, w))); + } + const table = el('table', { class: 'tbl trace-tbl' }, el('thead', {}, el('tr', {}, el('th', {}, '#'), el('th', {}, 'line'), el('th', {}, 'what ran'), el('th', {}, 'wrote'))), rows); + if (H) { add(tableHost, table); add(varsHost, vars); (rows.querySelector('.row-next') ?? rows.querySelector('.row-last'))?.scrollIntoView({ block: 'nearest' }); } + else add(body, el('div', { class: 'trace-cols' }, el('div', { class: 'trace-col' }, el('h4', {}, 'Trace table'), table), el('div', { class: 'trace-col' }, el('h4', {}, 'Variables'), vars))); + renderStatus(state); + // at the end everything is shown, including the 'returned' line the run appends after its last step + renderOutput(tr, t >= tr.count ? tr.output.length : (state?.outputLength ?? tr.output.length)); + } + + /** The loops in flight, one line under the controls. */ + function renderStatus(state: any) { + const loops = state?.loops || []; + const lingo = trace?.lang === 'lingo'; + const say = (l: any) => { + // a lingo run is the pseudo's run underneath, so its loops name pseudo lines: name the English line instead + const line = lingo ? lingoLine(l.line) ?? l.line : l.line; + const what = lingo ? 'The loop' : l.kind === 'For' ? 'FOR' : l.kind === 'ForEach' ? 'FOR EACH' : String(l.kind).toUpperCase(); + // pass 0 is the moment before the first pass, when the trace's next row already reads "pass 1" + return `${what} on line ${line}: ${l.pass > 0 ? `pass ${l.pass}` : 'about to start its first pass'}`; + }; + status.textContent = loops.map(say).join(' · '); + status.title = status.textContent; + } + + /** The lingo line a pseudo line came from, read off the lingo run's own steps. */ + let lingoLines: { trace: any; map: Map } | null = null; + function lingoLine(pseudoLine: number): number | undefined { + if (lingoLines?.trace !== trace) { + const map = new Map(); + for (const s of (trace?.steps ?? []) as any[]) if (s.pseudoLine != null && s.line != null && !map.has(s.pseudoLine)) map.set(s.pseudoLine, s.line); + lingoLines = { trace, map }; + } + return lingoLines.map.get(pseudoLine); + } + + function typeOf(t: any): string { + if (!t) return ''; + if (typeof t === 'string') return t; + if (t.k === 'LIST') return `LIST OF ${typeOf(t.of)}`; + if (t.k === 'ARRAY') return 'ARRAY'; + if (t.k === 'HASHMAP') return 'HASHMAP'; + if (t.k === 'SET') return `SET OF ${typeOf(t.of)}`; + return t.k || t.name || ''; + } + + /* ---------- assembly ---------- */ + + const WATCH = ['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15']; + + function renderAsm(fr: ReturnType) { + const tr = trace!; + const st: any = fr.state; + const last: any = fr.last; + const changed = new Set((last?.diff?.regs || []).map((r: any) => r.name)); + const flagsChanged = new Set((last?.diff?.flags || []).map((f: any) => f.name)); + const regs = el('table', { class: 'tbl regs-tbl' }, el('caption', {}, 'Registers')); + for (const r of WATCH) { + const v: bigint = st.regs[r]; + add(regs, el('tr', { class: changed.has(r) ? 'just-wrote' : '' }, el('td', { class: 'mono' }, r), el('td', { class: 'mono' }, formatHex(v)), el('td', { class: 'mono muted' }, BigInt.asIntN(64, v).toString()))); + } + const flags = el('div', { class: 'flags' }, ...FLAG_NAMES.map((f: string) => el('span', { class: 'flag' + (st.flags[f] ? ' on' : '') + (flagsChanged.has(f) ? ' just-wrote' : '') }, f))); + const mem = el('div', { class: 'mem' }); + const touched = new Set((last?.accesses || []).flatMap((a: any) => Array.from({ length: a.size || 1 }, (_, k) => Number(a.addr) + k))); + for (const region of st.mem) { + if (region.hidden && ![...touched].some((a) => a >= region.addr && a < region.addr + region.bytes.length)) continue; + const row = el('div', { class: 'mem-region' }, el('div', { class: 'mem-label' }, `${region.label} at ${formatHex(BigInt(region.addr), 4)}`)); + const cells = el('div', { class: 'mem-cells' }); + const max = Math.min(region.bytes.length, 64); + for (let i = 0; i < max; i++) { + const b = region.bytes[i]; + const ch = b >= 32 && b < 127 ? String.fromCharCode(b) : '·'; + add(cells, el('span', { class: 'mem-cell' + (touched.has(region.addr + i) ? ' touched' : ''), title: `${formatHex(BigInt(region.addr + i), 4)} = ${b}` }, el('b', {}, ch), el('i', {}, b.toString(16).padStart(2, '0')))); + } + if (region.bytes.length > max) add(cells, el('span', { class: 'muted' }, ` … ${region.bytes.length - max} more`)); + add(row, cells); add(mem, row); + } + const explain = el('div', { class: 'explain' }); + if (last) { + const ins = last.instr; + const parts: string[] = [`${ins.op} ${ins.operands.map((o: any) => o.source ?? '').join(', ')}`]; + if (last.alu) parts.push(`${last.alu.kind}: ${formatHex(last.alu.a, last.alu.width)}${last.alu.b != null ? ' , ' + formatHex(last.alu.b, last.alu.width) : ''} → ${formatHex(last.alu.result, last.alu.width)}`); + if (last.branch) parts.push(last.branch.taken ? `branch taken${last.prediction ? (last.prediction.correct ? ', predicted' : ', mispredicted') : ''}` : `not taken${last.prediction ? (last.prediction.correct ? ', predicted' : ', mispredicted') : ''}`); + for (const r of last.diff.regs || []) parts.push(`${r.name}: ${formatHex(r.before)} → ${formatHex(r.after)}`); + for (const m of last.diff.mem || []) parts.push(`[${formatHex(BigInt(m.addr), 4)}]: ${m.before} → ${m.after}`); + if (last.diff.out) parts.push(`wrote "${last.diff.out}"`); + add(explain, el('h4', {}, 'What that instruction did'), el('ul', {}, ...parts.map((p) => el('li', { class: 'mono' }, p)))); + } else add(explain, el('p', { class: 'muted' }, 'Nothing has run yet. Step once.')); + if (H) { add(varsHost, regs, el('h4', {}, 'Flags'), flags); add(tableHost, el('h4', {}, 'Memory'), mem, explain); } + else add(body, el('div', { class: 'trace-cols' }, el('div', { class: 'trace-col' }, regs, el('h4', {}, 'Flags'), flags), el('div', { class: 'trace-col' }, el('h4', {}, 'Memory'), mem, explain))); + const stats = (tr.raw as any).trace.stats; + status.textContent = `${stats.instructions} instructions, ${stats.branches} branches (${stats.mispredicts} mispredicted), ${stats.reads} loads, ${stats.writes} stores` + (st.halted ? ', halted' : ''); + renderOutput(tr, t >= tr.count ? tr.output.length : (tr.output.length > 0 && tr.output[0] && !tr.output[0].startsWith('rax =') ? 1 : 0)); + } + + function renderOutput(tr: Trace, upto: number) { + const lines = tr.output.slice(0, upto); + const err = tr.error && t >= tr.count ? tr.error.message : null; + output.textContent = lines.join('\n') + (err ? `\n\n⚠ ${err}` : '') + (tr.truncated && t >= tr.count ? '\n(the run was cut off at the step limit)' : ''); + output.style.display = output.textContent.trim() ? '' : 'none'; + opts.onOutput?.(lines, err); + } + + function exportCsv() { + if (!trace) return; + const esc = (s: any) => `"${String(s ?? '').replace(/"/g, '""')}"`; + const rows = trace.lang === 'asm' + ? [['step', 'line', 'instruction', 'changed'], ...trace.steps.map((s: any, i: number) => [i + 1, s.instr.lineNo + 1, `${s.instr.op} ${s.instr.operands.map((o: any) => o.source ?? '').join(', ')}`, (s.diff.regs || []).map((r: any) => `${r.name}=${formatHex(r.after)}`).join(' ')])] + : [['step', 'line', 'what ran', 'wrote'], ...trace.steps.map((s: any, i: number) => [i + 1, s.line ?? '', s.text || s.kind, (s.writes || []).map((w: any) => w.name).join(' ')])]; + const blob = new Blob([rows.map((r) => r.map(esc).join(',')).join('\n')], { type: 'text/csv' }); + const url = URL.createObjectURL(blob); + const a = el('a', { href: url, download: `${(session.state.title || 'procedure').toLowerCase().replace(/[^a-z0-9]+/g, '-')}-trace.csv` }); + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + + function refresh() { + trace = session.trace(); + histCache.clear(); + clear(body); + if (!trace) { + const why = session.runError || firstError(session) || 'Nothing to run yet.'; + status.textContent = ''; + clear(nextBox); nextBox.className = 'trace-next k-empty'; add(nextBox, el('div', { class: 'trace-next-line' }, why)); nextBox.title = String(why); predictBox.style.display = 'none'; + output.style.display = 'none'; opts.onOutput?.([], null); + clear(varsHost); clear(tableHost); + if (!H) add(body, el('p', { class: 'muted trace-empty' }, why)); + slider.max = '0'; counter.textContent = ''; + opts.onStep?.(null, null, new Map()); + return; + } + slider.max = String(trace.count); + goto(Math.min(t, trace.count)); + } + + function firstError(s: Session): string | null { + const lang = s.traceLang(); + const d = s.diagnostics(lang).find((x) => x.severity === 'error'); + return d ? `Line ${d.line}: ${d.message}` : null; + } + + const key = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + const tag = target?.tagName; + // anything that takes typing keeps its keys: form fields, and the editor (a contenteditable) + if (tag === 'TEXTAREA' || tag === 'INPUT' || tag === 'SELECT' || target?.isContentEditable || target?.closest?.('.cm-editor')) return; + if (e.key === 'ArrowRight') { e.shiftKey ? jumpPass(1) : stepForward(); e.preventDefault(); } + else if (e.key === 'ArrowLeft') { e.shiftKey ? jumpPass(-1) : goto(t - 1); e.preventDefault(); } + else if (e.key === 'Home') { goto(0); e.preventDefault(); } + else if (e.key === 'End') { goto(trace?.count ?? 0); e.preventDefault(); } + else if (e.key === ' ') { timer ? pause() : play(); e.preventDefault(); } + else if (e.key === 'p' || e.key === 'P') { predictBtn.click(); } + else if (e.key === 'b' || e.key === 'B') { runToBreakpoint(); } + }; + root.tabIndex = 0; + window.addEventListener('keydown', key); + + const off = session.onChange(() => refresh()); + refresh(); + return { + goto, + get t() { return t; }, + breakpoints, + toggleBreakpoint(line: number) { if (breakpoints.has(line)) breakpoints.delete(line); else breakpoints.add(line); opts.onBreakpoints?.(breakpoints); }, + destroy() { pause(); off(); window.removeEventListener('keydown', key); }, + }; +} diff --git a/src/ui/views/viz.ts b/src/ui/views/viz.ts new file mode 100644 index 0000000..d6dadcd --- /dev/null +++ b/src/ui/views/viz.ts @@ -0,0 +1,858 @@ +/** + * Three pictures of one procedure, drawn from the pseudo and the last run: + * + * flow a flowchart of the routine, laid out from its structure (so loops + * loop and branches branch), with every box shaded by how often its + * line ran and every edge labelled with how often it was taken; + * data the data-flow graph: which names feed which, from the parameters + * on the left to RETURN and OUTPUT on the right, one arrow per + * assignment, dashed when a condition decides rather than computes; + * table the table of values a student draws by hand: a column per step that + * changed something, a row per name, the new value in the cell. + * + * Everything is SVG or a plain table built from the Session; nothing here + * touches an engine. The routine drawn is the one the run call names. + */ +import { el, add, clear, button } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { mojoRoutine, mojoFunctions } from '../../mojo/flowir.js'; +import type { Trace } from '../../core/types.js'; +import { formatValue, typeName } from '../../engines/pseudo/lang.js'; +import { sourceOf } from '../../engines/pseudo/parse.js'; +import type { PanelHooks } from './panels.js'; + +/* ------------------------------------------------------------------ */ +/* Shared */ +/* ------------------------------------------------------------------ */ + +const NS = 'http://www.w3.org/2000/svg'; + +function svg(tag: K, attrs: Record = {}, ...children: Array): SVGElementTagNameMap[K] { + const n = document.createElementNS(NS, tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2).toLowerCase(), v); + else n.setAttribute(k, String(v)); + } + for (const c of children) { if (c == null) continue; n.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); } + return n; +} + +interface Routine { name: string; kind: 'Function' | 'Procedure' | 'main'; params: any[]; body: any[]; line: number; returns: any; symbols: any[] } + +/** The routine the run call names, else the main program, else the first subroutine. */ +/** The view's title; for Mojo, a choice of which function to draw. */ +function titleOf(session: Session, r: Routine, rerender: () => void): HTMLElement { + const p = session.state.lang === 'mojo' ? session.parsedMojo() : null; + const names = p?.program ? mojoFunctions(p.program.module) : []; + if (names.length < 2) return el('span', { class: 'viz-title' }, r.kind === 'main' ? 'the main program' : `${r.name}`); + const sel = el('select', { class: 'select', title: 'Which function to draw', onChange: () => { setMojoFocus(sel.value); rerender(); } }, + ...names.map((n) => el('option', { value: n, selected: n === r.name }, n))); + return el('label', { class: 'viz-title' }, sel); +} + +/** For Mojo: the function chosen in the view, else the one the run spent most steps in, else main. */ +export let mojoFocus: string | null = null; +export function setMojoFocus(name: string | null): void { mojoFocus = name; } + +function mojoRoutineOf(session: Session): Routine | null { + const p = session.parsedMojo(); + if (!p || !p.program || p.program.module.unread) return null; + const names = mojoFunctions(p.program.module); + let name = mojoFocus && names.includes(mojoFocus) ? mojoFocus : null; + if (!name) { + const trace = session.trace(); + if (trace?.lang === 'mojo') { + const count = new Map(); + for (const st of trace.steps as any[]) if (st.sub) count.set(st.sub, (count.get(st.sub) ?? 0) + 1); + name = [...count].filter(([n]) => names.includes(n)).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null; + } + } + return mojoRoutine(p.program.module, name ?? undefined) as Routine | null; +} + +export function routineOf(session: Session): Routine | null { + if (session.state.lang === 'mojo') return mojoRoutineOf(session); + const p = session.parsedPseudo(); + if (!p || !p.ok || !p.program) return null; + const prog = p.program.program; + const call = session.callText(); + const m = call ? /^\s*([A-Za-z_]\w*)/.exec(call) : null; + const pick = (sub: any): Routine => ({ name: sub.name, kind: sub.node.kind, params: sub.params?.length ? sub.params : sub.node.params || [], body: sub.node.body || [], line: sub.node.line, returns: sub.returns ?? sub.node.returns, symbols: sub.symbols || [] }); + if (m) { const sub = prog.subs.get(m[1].toUpperCase()); if (sub && sub.node) return pick(sub); } + if (prog.main?.body?.length) return { name: 'main', kind: 'main', params: [], body: prog.main.body, line: prog.main.body[0]?.line ?? 1, returns: null, symbols: prog.main.symbols || [] }; + const first = [...prog.subs.values()].find((s: any) => s.node); + return first ? pick(first) : null; +} + +/** How often each pseudo line ran in the trace up to step `upto` (lingo and matho traces carry the pseudo line on each step). */ +function pseudoHits(trace: Trace | null, upto = Infinity): Map { + const hits = new Map(); + if (!trace || trace.lang === 'asm') return hits; + (trace.steps as any[]).slice(0, upto).forEach((s) => { const ln = s.pseudoLine ?? s.line; if (ln != null) hits.set(ln, (hits.get(ln) || 0) + 1); }); + return hits; +} + +/** The pseudo line a step is on. */ +function stepLine(s: any): number | null { return s ? (s.pseudoLine ?? s.line ?? null) : null; } + +/** A node's classes for where the stepper is. */ +function cursorClass(ctx: FlowCtx, line: number | null): string { + if (line == null) return ''; + return (ctx.current === line ? ' flow-current' : '') + (ctx.last === line ? ' flow-last' : ''); +} + +function sourceLines(session: Session): string[] { + // Mojo: drop a trailing # comment (outside quotes) as pseudo's // comments are dropped + if (session.state.lang === 'mojo') return session.source('mojo').split('\n').map((l) => { let q: string | null = null; for (let i = 0; i < l.length; i++) { const c = l[i]; if (q) { if (c === '\\') i++; else if (c === q) q = null; } else if (c === '"' || c === "'") q = c; else if (c === '#') return l.slice(0, i).trimEnd(); } return l; }); + return session.source('pseudo').split('\n'); +} +function lineText(lines: string[], line: number): string { return (lines[line - 1] ?? '').replace(/\s*\/\/.*$/, '').trim(); } +function truncate(s: string, n: number): string { return s.length > n ? s.slice(0, n - 1) + '…' : s; } + +/** Every Name an expression (or statement fragment) mentions, in order, without duplicates. */ +function namesIn(e: any, out: string[] = []): string[] { + if (!e || typeof e !== 'object') return out; + if (Array.isArray(e)) { for (const x of e) namesIn(x, out); return out; } + if (e.kind === 'Name') { if (!out.includes(e.name)) out.push(e.name); return out; } + if (e.kind === 'CallExpr') { namesIn(e.args, out); return out; } + for (const [k, v] of Object.entries(e)) { if (k === 'type' || k === 'line' || k === 'col' || typeof v !== 'object') continue; namesIn(v, out); } + return out; +} + +function rootName(target: any): string | null { + let t = target; + while (t && (t.kind === 'Index' || t.kind === 'Field')) t = t.target; + return t && t.kind === 'Name' ? t.name : null; +} + +/** Scroll `box` (and only `box`) so that `target` is in view; scrollIntoView would also move the page. */ +function revealIn(box: HTMLElement | null, target: Element | null): void { + if (!box || !target) return; + const b = box.getBoundingClientRect(), t = target.getBoundingClientRect(); + if (t.left < b.left) box.scrollLeft += t.left - b.left - 24; + else if (t.right > b.right) box.scrollLeft += t.right - b.right + 24; + if (t.top < b.top) box.scrollTop += t.top - b.top - 24; + else if (t.bottom > b.bottom) box.scrollTop += t.bottom - b.bottom + 24; +} + +function emptyNote(root: HTMLElement, session: Session, what: string): void { + const p = session.parsedPseudo(); + add(root, el('p', { class: 'muted' }, !p ? `Write some pseudo (or lingo, or an equation) and the ${what} appears here.` : !p.ok ? `The pseudo has errors; fix them in the problems view and the ${what} appears here.` : `Nothing to draw yet.`)); +} + +/* ------------------------------------------------------------------ */ +/* Flowchart */ +/* ------------------------------------------------------------------ */ + +const FH = 30; // box height +const GAP = 22; // vertical gap between boxes +const HGAP = 34; // horizontal gap between branches +const CH = 7.3; // approximate width of one monospace character at 12px +const MAXCH = 40; // longest text in a box + +interface Block { + w: number; h: number; + /** x of the entry/exit spine inside the block */ + cx: number; + /** false when control never falls out of the bottom (RETURN, BREAK) */ + exits: boolean; + /** the line whose hits count how often the block was entered */ + entryLine: number | null; + draw(g: SVGGElement, x: number, y: number): void; +} + +interface FlowCtx { + /** The line about to run and the line that just ran, when the chart follows the stepper. */ + current: number | null; + last: number | null; + lines: string[]; + /** the pseudo line of every step, in order */ + stepLines: number[]; + hits: Map; + maxHits: number; + hasTrace: boolean; + onLine: ((line: number) => void) | null; + /** the set of lines of the loop headers, so the trace's loop steps are counted right */ + loopLines: Set; +} + +/** How often a loop went round again and how often it finished: from the step that follows each visit to its test line. */ +function loopCounts(ctx: FlowCtx, testLine: number, bodyFrom: number, bodyTo: number): { again: number; done: number } | null { + if (!ctx.hasTrace) return null; + let again = 0, done = 0; + for (let i = 0; i < ctx.stepLines.length; i++) { + if (ctx.stepLines[i] !== testLine) continue; + const next = ctx.stepLines[i + 1]; + if (next == null) { done++; continue; } + if (next >= bodyFrom && next <= bodyTo) again++; else if (next !== testLine) done++; + } + return { again, done }; +} + +function textWidth(s: string): number { return Math.max(96, Math.min(CH * MAXCH + 28, s.length * CH + 28)); } + +function shadeFor(ctx: FlowCtx, line: number | null): { fill: string; cls: string; count: number | null } { + if (!ctx.hasTrace || line == null) return { fill: 'var(--paper-2)', cls: '', count: null }; + const n = ctx.hits.get(line) || 0; + if (!n) return { fill: 'var(--paper-3)', cls: 'flow-never', count: 0 }; + const a = 0.1 + 0.55 * Math.sqrt(n / Math.max(1, ctx.maxHits)); + return { fill: `color-mix(in srgb, var(--accent) ${Math.round(a * 100)}%, var(--paper-2))`, cls: '', count: n }; +} + +function label(g: SVGGElement, x: number, y: number, text: string, cls = 'flow-text', anchor = 'middle'): void { + g.appendChild(svg('text', { x, y, class: cls, 'text-anchor': anchor, 'dominant-baseline': 'central' }, text)); +} + +function badge(g: SVGGElement, x: number, y: number, count: number | null): void { + if (count == null) return; + const t = count === 0 ? 'never ran' : `×${count.toLocaleString('en-US')}`; + const w = t.length * 6 + 10; + g.appendChild(svg('rect', { x: x - w + 4, y: y - 9, width: w, height: 16, rx: 8, class: 'flow-badge' + (count === 0 ? ' flow-badge-never' : '') })); + g.appendChild(svg('text', { x: x - w / 2 + 4, y, class: 'flow-badge-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, t)); +} + +function line(g: SVGGElement, pts: Array<[number, number]>, opts: { arrow?: boolean; cls?: string } = {}): void { + const d = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0]} ${p[1]}`).join(' '); + g.appendChild(svg('path', { d, class: 'flow-edge ' + (opts.cls || ''), 'marker-end': opts.arrow === false ? null : 'url(#flow-arrow)' })); +} + +function edgeLabel(g: SVGGElement, x: number, y: number, text: string): void { + const w = text.length * 6.2 + 8; + g.appendChild(svg('rect', { x: x - w / 2, y: y - 8, width: w, height: 16, rx: 3, class: 'flow-edge-label-bg' })); + g.appendChild(svg('text', { x, y, class: 'flow-edge-label', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, text)); +} + +function clickable(ctx: FlowCtx, node: SVGElement, line: number | null, full: string): void { + node.appendChild(svg('title', {}, line != null ? `line ${line}: ${full}` : full)); + if (ctx.onLine && line != null) { node.classList.add('flow-clickable'); node.addEventListener('click', () => ctx.onLine!(line)); } +} + +/** A plain statement box; `shape` picks the flowchart glyph. */ +function box(ctx: FlowCtx, lineNo: number, text: string, shape: 'rect' | 'pill' | 'para' | 'term' = 'rect'): Block { + const t = truncate(text, MAXCH); + const w = textWidth(t); + return { + w, h: FH, cx: w / 2, exits: shape !== 'term', entryLine: lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + if (shape === 'rect') grp.appendChild(svg('rect', { x, y, width: w, height: FH, rx: 5, fill: s.fill, class: 'flow-shape' })); + else if (shape === 'pill' || shape === 'term') grp.appendChild(svg('rect', { x, y, width: w, height: FH, rx: FH / 2, fill: s.fill, class: 'flow-shape' + (shape === 'term' ? ' flow-term' : '') })); + else grp.appendChild(svg('path', { d: `M${x + 10} ${y} H${x + w} L${x + w - 10} ${y + FH} H${x} Z`, fill: s.fill, class: 'flow-shape' })); + label(grp, x + w / 2, y + FH / 2, t); + badge(grp, x + w, y, s.count); + clickable(ctx, grp, lineNo, text); + g.appendChild(grp); + }, + }; +} + +function passthrough(): Block { return { w: 24, h: 0, cx: 12, exits: true, entryLine: null, draw() { /* nothing */ } }; } + +/** Blocks stacked, spines aligned, arrows between them. */ +function sequence(blocks: Block[]): Block { + if (!blocks.length) return passthrough(); + if (blocks.length === 1) return blocks[0]; + const left = Math.max(...blocks.map((b) => b.cx)); + const right = Math.max(...blocks.map((b) => b.w - b.cx)); + const h = blocks.reduce((a, b) => a + b.h, 0) + GAP * (blocks.length - 1); + const lastExits = blocks[blocks.length - 1].exits; + return { + w: left + right, h, cx: left, exits: lastExits, entryLine: blocks[0].entryLine, + draw(g, x, y) { + let yy = y; + blocks.forEach((b, i) => { + b.draw(g, x + left - b.cx, yy); + if (i < blocks.length - 1 && b.exits) line(g, [[x + left, yy + b.h], [x + left, yy + b.h + GAP]]); + yy += b.h + GAP; + }); + }, + }; +} + +/** A diamond on top, arms fanned out underneath, a merge bus below. Used for IF, ELSEIF chains and CASE. */ +function branching(ctx: FlowCtx, lineNo: number, condText: string, arms: Array<{ label: string; block: Block; countLine: number | null }>, fallthroughLabel: string | null): Block { + const t = truncate(condText, MAXCH); + const dw = Math.max(130, t.length * CH * 1.45 + 50); + const dh = 48; + const armsW = arms.reduce((a, b) => a + b.block.w, 0) + HGAP * (arms.length - 1); + const w = Math.max(armsW, dw + 24); + const off = (w - armsW) / 2; + const bodyH = Math.max(...arms.map((a) => a.block.h), 0); + const busY = dh + 20; // the fan-out bus + const topY = busY + 18; // where arms begin + const mergeY = topY + bodyH + GAP; // the merge bus + const h = mergeY + 12; + const anyExit = arms.some((a) => a.block.exits); + // the diamond is centered over the arms + const cx = w / 2; + return { + w, h, cx, exits: anyExit, entryLine: lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + const dx = x + cx; + grp.appendChild(svg('path', { d: `M${dx} ${y} L${dx + dw / 2} ${y + dh / 2} L${dx} ${y + dh} L${dx - dw / 2} ${y + dh / 2} Z`, fill: s.fill, class: 'flow-shape flow-diamond' })); + label(grp, dx, y + dh / 2, t); + badge(grp, dx + dw / 2 + 6, y + 6, s.count); + clickable(ctx, grp, lineNo, condText); + g.appendChild(grp); + // fan out + let ax = x + off; + const armX: number[] = []; + for (const a of arms) { armX.push(ax + a.block.cx); ax += a.block.w + HGAP; } + const minX = Math.min(dx, ...armX), maxX = Math.max(dx, ...armX); + line(g, [[dx, y + dh], [dx, y + busY]], { arrow: false }); + if (arms.length > 1 || armX[0] !== dx) line(g, [[minX, y + busY], [maxX, y + busY]], { arrow: false }); + ax = x + off; + arms.forEach((a, i) => { + const b = a.block; + const sx = armX[i]; + line(g, [[sx, y + busY], [sx, y + topY]], { arrow: b.h > 0 }); + let n = ctx.hasTrace && a.countLine != null ? ctx.hits.get(a.countLine) || 0 : null; + if (ctx.hasTrace && n == null && arms.length === 2 && i === 1 && arms[0].countLine != null) n = Math.max(0, (ctx.hits.get(lineNo) || 0) - (ctx.hits.get(arms[0].countLine) || 0)); + const lbl = a.label + (n != null ? ` ×${n}` : ''); + if (lbl.trim()) edgeLabel(g, arms.length === 1 ? sx + 22 : i === 0 ? sx - 22 : i === arms.length - 1 ? sx + 22 : sx, y + busY + 9, lbl); + b.draw(g, ax, y + topY); + if (b.exits) line(g, [[sx, y + topY + b.h], [sx, y + mergeY]], { arrow: false }); + ax += b.w + HGAP; + }); + // merge bus + const exiting = arms.map((a, i) => (a.block.exits ? armX[i] : null)).filter((v): v is number => v != null); + if (exiting.length) { + const lo = Math.min(dx, ...exiting), hi = Math.max(dx, ...exiting); + if (lo !== hi) line(g, [[lo, y + mergeY], [hi, y + mergeY]], { arrow: false }); + line(g, [[dx, y + mergeY], [dx, y + h]], { arrow: false }); + } + void fallthroughLabel; + }, + }; +} + +/** A loop: the test on top, the body below, a back edge up the left, the exit down the right. */ +function loop(ctx: FlowCtx, lineNo: number, headText: string, body: Block, kind: 'pre' | 'post', bodyRange: [number, number] | null): Block { + const t = truncate(headText, MAXCH); + const dw = Math.max(140, t.length * CH * 1.45 + 50); + const counts = bodyRange ? loopCounts(ctx, lineNo, bodyRange[0], bodyRange[1]) : null; + const dh = 44; + const inner = Math.max(dw + 24, body.w); + const sideL = 26, sideR = 30; + const w = sideL + inner + sideR; + const cx = sideL + inner / 2; + const h = kind === 'pre' ? dh + GAP + body.h + GAP + 14 : body.h + GAP + dh + GAP + 6; + return { + w, h, cx, exits: true, entryLine: kind === 'pre' ? lineNo : body.entryLine ?? lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const dx = x + cx; + const drawDiamond = (dy: number) => { + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + grp.appendChild(svg('path', { d: `M${dx} ${dy} L${dx + dw / 2} ${dy + dh / 2} L${dx} ${dy + dh} L${dx - dw / 2} ${dy + dh / 2} Z`, fill: s.fill, class: 'flow-shape flow-diamond' })); + label(grp, dx, dy + dh / 2, t); + if (counts) { const tt = `${counts.again} pass${counts.again === 1 ? '' : 'es'}`; const bw = tt.length * 6 + 10; grp.appendChild(svg('rect', { x: dx + dw / 2 - bw + 10, y: dy - 8, width: bw, height: 16, rx: 8, class: 'flow-badge' + (counts.again === 0 ? ' flow-badge-never' : '') })); grp.appendChild(svg('text', { x: dx + dw / 2 - bw / 2 + 10, y: dy, class: 'flow-badge-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, tt)); } + else badge(grp, dx + dw / 2 + 6, dy + 6, s.count); + clickable(ctx, grp, lineNo, headText); + g.appendChild(grp); + }; + const passes = counts ? counts.again : null; + if (kind === 'pre') { + drawDiamond(y); + const bodyY = y + dh + GAP; + line(g, [[dx, y + dh], [dx, bodyY]], { arrow: body.h > 0 }); + edgeLabel(g, dx + 26, y + dh + 10, 'again' + (passes != null ? ` ×${passes}` : '')); + body.draw(g, dx - body.cx, bodyY); + // back edge + const bottom = bodyY + body.h + GAP / 2; + if (body.exits) line(g, [[dx, bodyY + body.h], [dx, bottom], [x + 8, bottom], [x + 8, y + dh / 2], [dx - dw / 2, y + dh / 2]], { cls: 'flow-back' }); + // exit edge + line(g, [[dx + dw / 2, y + dh / 2], [x + w - 8, y + dh / 2], [x + w - 8, y + h], [dx, y + h]], { arrow: false }); + edgeLabel(g, x + w - 8, y + dh / 2 + 14, 'done' + (counts ? ` ×${counts.done}` : '')); + } else { + body.draw(g, dx - body.cx, y); + const dy = y + body.h + GAP; + if (body.exits) line(g, [[dx, y + body.h], [dx, dy]]); + drawDiamond(dy); + // back edge: not yet → body top + line(g, [[dx - dw / 2, dy + dh / 2], [x + 8, dy + dh / 2], [x + 8, y - 10], [dx, y - 10], [dx, y]], { cls: 'flow-back' }); + edgeLabel(g, x + 8 + 30, dy + dh / 2 - 12, 'not yet' + (counts ? ` ×${counts.again}` : '')); + line(g, [[dx, dy + dh], [dx, y + h]], { arrow: false }); + edgeLabel(g, dx + 30, dy + dh + 6, 'done' + (counts ? ` ×${counts.done}` : '')); + } + }, + }; +} + +function flowOf(ctx: FlowCtx, s: any): Block | null { + const text = (ln: number) => lineText(ctx.lines, ln); + switch (s.kind) { + case 'Declare': case 'Constant': case 'Define': case 'TypeDef': case 'SetTypeDef': case 'BlankStmt': return null; + case 'Assign': case 'Call': case 'BuiltinCall': case 'ExprStmt': return box(ctx, s.line, text(s.line)); + case 'Input': return box(ctx, s.line, text(s.line), 'para'); + case 'Output': return box(ctx, s.line, text(s.line), 'para'); + case 'Return': return box(ctx, s.line, text(s.line), 'term'); + case 'Break': case 'Continue': return box(ctx, s.line, text(s.line), 'term'); + case 'Assert': case 'Require': case 'Ensure': case 'Invariant': case 'Decreases': return box(ctx, s.line, text(s.line), 'pill'); + case 'If': { + // an ELSEIF chain is drawn as one diamond per test, nested in the "no" arm + const build = (i: number): Block => { + const br = s.branches[i]; + const then = blockOf(ctx, br.body); + const rest: Block = i + 1 < s.branches.length ? build(i + 1) : blockOf(ctx, s.elseBody || []); + const noLine = i + 1 < s.branches.length ? s.branches[i + 1].line : firstLine(s.elseBody || []); + return branching(ctx, br.line, text(br.line).replace(/^(ELSE\s*IF|ELSEIF|ELIF|IF)\s+/i, '').replace(/\s+THEN$/i, '').replace(/:$/, ''), [ + { label: 'yes', block: then, countLine: firstLine(br.body) }, + { label: 'no', block: rest, countLine: noLine }, + ], null); + }; + return build(0); + } + case 'Case': { + const arms = s.arms.map((a: any) => ({ label: truncate(a.labels.map((l: any) => sourceOf(l)).join(', '), 14), block: blockOf(ctx, a.body), countLine: firstLine(a.body) })); + if (s.otherwise) arms.push({ label: 'otherwise', block: blockOf(ctx, s.otherwise), countLine: firstLine(s.otherwise) }); + return branching(ctx, s.line, text(s.line), arms, null); + } + case 'For': case 'ForEach': case 'While': { + const body = blockOf(ctx, s.body); + return loop(ctx, s.line, text(s.line), body, 'pre', s.body.length ? [s.line + 1, Math.max(lastLine(s.body), s.line + 1)] : null); + } + case 'Repeat': { + const body = blockOf(ctx, s.body); + const untilLine = s.endLine ?? lastLine(s.body) + 1; + return loop(ctx, untilLine, text(untilLine) || `UNTIL ${s.cond ? sourceOf(s.cond) : '…'}`, body, 'post', s.body.length ? [s.line + 1, untilLine - 1] : null); + } + default: return box(ctx, s.line, text(s.line) || s.kind); + } +} + +function firstLine(body: any[]): number | null { for (const s of body) if (s.kind !== 'Declare' && s.kind !== 'BlankStmt') return s.line; return body[0]?.line ?? null; } +function lastLine(body: any[]): number { + let m = 0; + const w = (s: any) => { + if (!s) return; + if (s.line > m) m = s.line; + if (s.endLine > m) m = s.endLine; + if (Array.isArray(s.body)) s.body.forEach(w); + if (Array.isArray(s.branches)) for (const b of s.branches) b.body?.forEach(w); + if (Array.isArray(s.elseBody)) s.elseBody.forEach(w); + if (Array.isArray(s.arms)) for (const a of s.arms) a.body?.forEach(w); + if (Array.isArray(s.otherwise)) s.otherwise.forEach(w); + }; + body.forEach(w); + return m; +} +function blockOf(ctx: FlowCtx, body: any[]): Block { return sequence(body.map((s) => flowOf(ctx, s)).filter((b): b is Block => !!b)); } + +export function flowView(session: Session, root: HTMLElement, hooks?: PanelHooks): () => void { + let follow = true; // shade by the run so far, and mark where the stepper is + let scroll: HTMLElement | null = null; + const render = () => { + const keep = scroll ? { x: scroll.scrollLeft, y: scroll.scrollTop } : null; + clear(root); + const r = routineOf(session); + if (!r) { emptyNote(root, session, 'flowchart'); return; } + const trace = session.trace(); + const t = follow ? Math.min(session.state.t ?? (trace?.count ?? 0), trace?.count ?? 0) : (trace?.count ?? 0); + const hits = pseudoHits(trace, t); + const lines = sourceLines(session); + const steps = trace && trace.lang !== 'asm' ? (trace.steps as any[]) : []; + const stepLines = steps.slice(0, t).map((s) => stepLine(s) ?? -1); + const pane = session.state.lang === 'mojo' ? 'mojo' : 'pseudo'; + const ctx: FlowCtx = { + current: follow && trace && t < trace.count ? stepLine(steps[t]) : null, last: follow && trace && t > 0 ? stepLine(steps[t - 1]) : null, + lines, stepLines, hits, maxHits: Math.max(1, ...pseudoHits(trace).values()), hasTrace: !!trace, onLine: hooks ? (ln) => hooks.reveal(pane, ln) : null, loopLines: new Set(), + }; + const start = box(ctx, r.line, r.kind === 'main' ? 'start' : lineText(lines, r.line).replace(/\s+RETURNS\s+.*$/, ''), 'pill'); + start.entryLine = r.line; + const body = blockOf(ctx, r.body); + const end: Block = { ...box(ctx, -1, r.kind === 'Function' ? 'end' : 'end', 'pill'), entryLine: null }; + const parts = [start, body]; + if (body.exits) parts.push(end); + const all = sequence(parts); + const pad = 16; + const el_ = svg('svg', { class: 'flow-svg', width: all.w + pad * 2, height: all.h + pad * 2, viewBox: `0 0 ${all.w + pad * 2} ${all.h + pad * 2}`, role: 'img', 'aria-label': `Flowchart of ${r.name}` }); + const defs = svg('defs', {}, svg('marker', { id: 'flow-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, svg('path', { d: 'M0 0 L10 5 L0 10 Z', class: 'flow-arrowhead' }))); + el_.appendChild(defs); + const g = svg('g', {}); + all.draw(g, pad, pad); + el_.appendChild(g); + const where = trace ? (follow && t < trace.count ? `the path so far: shaded by how often each line has run up to step ${t} of ${trace.count}; the box with the marker runs next` : `shaded by how often each line ran for ${session.state.lang === 'mojo' ? 'this run' : session.callText() || 'this run'}; ×n on an arrow is how many times it was taken`) : 'Run the program and the boxes shade by how often each line ran.'; + const head = el('div', { class: 'viz-head' }, + titleOf(session, r, render), + el('span', { class: 'small muted' }, where), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label tool-check small', title: 'Shade the chart by the run up to the step you are on, and mark the box that runs next' }, el('input', { type: 'checkbox', checked: follow, onChange: (e: Event) => { follow = (e.target as HTMLInputElement).checked; render(); } }), ' follow the stepper'), + button('Download SVG', () => downloadSvg(el_, `${r.name.toLowerCase()}-flow.svg`), { class: 'btn btn-small btn-quiet' })); + scroll = el('div', { class: 'viz-scroll' }, el_); + add(root, head, scroll); + if (keep) { scroll.scrollLeft = keep.x; scroll.scrollTop = keep.y; } + else if (follow) revealIn(scroll, el_.querySelector('.flow-current')); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(() => { if (follow) render(); }); + return () => { off(); offStep(); }; +} + +function downloadSvg(node: SVGSVGElement, name: string): void { + // inline the colours so the file stands alone + const clone = node.cloneNode(true) as SVGSVGElement; + const style = document.createElementNS(NS, 'style'); + style.textContent = `text{font:12px ui-monospace,Menlo,Consolas,monospace;fill:#16191f}.flow-shape{stroke:#5c6370;stroke-width:1.2}.flow-edge{fill:none;stroke:#5c6370;stroke-width:1.4}.flow-back{stroke-dasharray:4 3}.flow-arrowhead{fill:#5c6370}.flow-badge{fill:#eef0f4;stroke:#dde1e8}.flow-badge-text,.flow-edge-label{font-size:10.5px;fill:#5c6370}.flow-edge-label-bg{fill:#fff}.flow-never .flow-shape{stroke-dasharray:3 3}.flow-never text{fill:#8a919c}.df-node{stroke:#5c6370;stroke-width:1.2;fill:#fff}.df-node-in{fill:#eaf1ff}.df-node-out{fill:#e8f6ee}.df-edge{fill:none;stroke:#5c6370;stroke-width:1.4}.df-edge-ctrl{stroke-dasharray:4 3;stroke:#8a919c}.df-type{font-size:10px;fill:#8a919c}.df-label{font-size:10px;fill:#5c6370}.df-label-bg{fill:#fff}`; + clone.insertBefore(style, clone.firstChild); + for (const e of clone.querySelectorAll('[fill^="color-mix"]')) e.setAttribute('fill', '#dbe4ff'); + for (const e of clone.querySelectorAll('[fill^="var("]')) e.setAttribute('fill', '#ffffff'); + const blob = new Blob([new XMLSerializer().serializeToString(clone)], { type: 'image/svg+xml' }); + const url = URL.createObjectURL(blob); + const a = el('a', { href: url, download: name }); + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/* ------------------------------------------------------------------ */ +/* Data flow */ +/* ------------------------------------------------------------------ */ + +interface DNode { id: string; label: string; type: string; kind: 'in' | 'var' | 'out' | 'loop'; rank: number; x: number; y: number; w: number; lines: Set } +interface DEdge { from: string; to: string; lines: Set; ctrl: boolean; texts: string[] } + +export function dataFlowOf(session: Session, r: Routine): { nodes: DNode[]; edges: DEdge[] } { + const lines = sourceLines(session); + const nodes = new Map(); + const edges = new Map(); + const typeOf = (p: any) => (p?.type ? typeNameOf(p.type) : ''); + const node = (id: string, kind: DNode['kind'], type = ''): DNode => { + let n = nodes.get(id); + if (!n) { n = { id, label: id, type, kind, rank: 0, x: 0, y: 0, w: 0, lines: new Set() }; nodes.set(id, n); } + else if (type && !n.type) n.type = type; + return n; + }; + const edge = (from: string, to: string, ln: number, ctrl: boolean) => { + if (from === to && ctrl) return; + const key = `${from}→${to}:${ctrl ? 'c' : 'd'}`; + let e = edges.get(key); + if (!e) { e = { from, to, lines: new Set(), ctrl, texts: [] }; edges.set(key, e); } + e.lines.add(ln); + const t = lineText(lines, ln); if (t && !e.texts.includes(t)) e.texts.push(t); + }; + for (const p of r.params) node(p.name, 'in', typeOf(p)); + const declared = new Map(); + for (const sym of r.symbols) if (sym?.name && sym.type) declared.set(sym.name, typeNameOf(sym.type)); + const ensure = (name: string): DNode => nodes.get(name) ?? node(name, 'var', declared.get(name) || ''); + const walk = (body: any[], ctrl: string[]) => { + for (const s of body) { + switch (s.kind) { + case 'Assign': { + const t = rootName(s.target); if (!t) break; + const tn = ensure(t); tn.lines.add(s.line); + const srcs = [...namesIn(s.value), ...(s.target.kind === 'Index' ? namesIn(s.target.indices) : [])]; + for (const n of srcs) { ensure(n); edge(n, t, s.line, false); } + for (const c of ctrl) if (!srcs.includes(c)) edge(c, t, s.line, true); + break; + } + case 'Input': { const t = rootName(s.target); if (t) { node('INPUT', 'in', 'keyboard'); ensure(t).lines.add(s.line); edge('INPUT', t, s.line, false); } break; } + case 'Output': { node('OUTPUT', 'out', 'screen'); for (const n of namesIn(s.values)) { ensure(n); edge(n, 'OUTPUT', s.line, false); } break; } + case 'Return': { if (s.value) { node('RETURN', 'out', r.returns ? typeNameOf(r.returns) : ''); for (const n of namesIn(s.value)) { ensure(n); edge(n, 'RETURN', s.line, false); } for (const c of ctrl) edge(c, 'RETURN', s.line, true); } break; } + case 'BuiltinCall': { + // APPEND(L, V), INSERT(L, I, V), ADD(S, V), SORT(L), …: the first argument is what changes + const t = s.args[0] ? rootName(s.args[0]) : null; + if (t) { ensure(t).lines.add(s.line); for (const n of namesIn(s.args.slice(1))) { ensure(n); edge(n, t, s.line, false); } if (!s.args.slice(1).length) edge(t, t, s.line, false); for (const c of ctrl) edge(c, t, s.line, true); } + break; + } + case 'MojoCall': { + // the arguments passed to mut parameters change; everything the call reads flows into them + const outs = (s.outs as any[]).map((o) => rootName(o)).filter((x): x is string => !!x); + const ins = namesIn(s.args); + for (const t of outs) { ensure(t).lines.add(s.line); for (const n of ins) if (n !== t) { ensure(n); edge(n, t, s.line, false); } for (const c of ctrl) edge(c, t, s.line, true); } + break; + } + case 'Call': { + const sub = session.parsedPseudo()?.program?.program?.subs?.get(String(s.name).toUpperCase()); + const outs: string[] = []; + (sub?.node?.params || sub?.params || []).forEach((p: any, i: number) => { if (p.mode === 'BYREF' && s.args[i]) { const t = rootName(s.args[i]); if (t) outs.push(t); } }); + const ins = namesIn(s.args); + for (const t of outs) { ensure(t).lines.add(s.line); for (const n of ins) if (n !== t) { ensure(n); edge(n, t, s.line, false); } } + break; + } + case 'For': { + const v = ensure(s.var); v.kind = v.kind === 'in' ? 'in' : 'loop'; v.type = v.type || 'INTEGER'; v.lines.add(s.line); + for (const n of namesIn([s.start, s.stop, s.step])) { ensure(n); edge(n, s.var, s.line, false); } + walk(s.body, ctrl); break; + } + case 'ForEach': { + const v = ensure(s.var); v.kind = 'loop'; v.lines.add(s.line); + for (const n of namesIn(s.iterable)) { ensure(n); edge(n, s.var, s.line, false); } + walk(s.body, ctrl); break; + } + case 'While': walk(s.body, [...ctrl, ...namesIn(s.cond)]); break; + case 'Repeat': walk(s.body, [...ctrl, ...namesIn(s.cond)]); break; + case 'If': for (const b of s.branches) walk(b.body, [...ctrl, ...namesIn(b.cond)]); if (s.elseBody) walk(s.elseBody, [...ctrl, ...s.branches.flatMap((b: any) => namesIn(b.cond))]); break; + case 'Case': { const c = [...ctrl, ...namesIn(s.subject)]; for (const a of s.arms) walk(a.body, c); if (s.otherwise) walk(s.otherwise, c); break; } + default: break; + } + } + }; + walk(r.body, []); + // ranks: longest path from the inputs over forward edges; a DFS decides which edges are forward + const ns = [...nodes.values()]; + const out = new Map(); + for (const e of edges.values()) { if (!out.has(e.from)) out.set(e.from, []); out.get(e.from)!.push(e); } + const state = new Map(); + const forward = new Set(); + const dfs = (id: string) => { + state.set(id, 'on'); + for (const e of out.get(id) || []) { + if (e.from === e.to) continue; + const st = state.get(e.to); + if (st === 'on') continue; // a back edge: a loop + forward.add(e); + if (!st) dfs(e.to); + } + state.set(id, 'done'); + }; + for (const n of ns) if (n.kind === 'in') dfs(n.id); + for (const n of ns) if (!state.has(n.id)) dfs(n.id); + const indeg = new Map(ns.map((n) => [n.id, 0])); + for (const e of forward) indeg.set(e.to, (indeg.get(e.to) || 0) + 1); + const queue = ns.filter((n) => !indeg.get(n.id)).map((n) => n.id); + const rank = new Map(ns.map((n) => [n.id, n.kind === 'in' ? 0 : 1])); + while (queue.length) { + const id = queue.shift()!; + for (const e of forward) if (e.from === id) { rank.set(e.to, Math.max(rank.get(e.to)!, rank.get(id)! + 1)); indeg.set(e.to, indeg.get(e.to)! - 1); if (!indeg.get(e.to)) queue.push(e.to); } + } + const maxRank = Math.max(1, ...[...rank.entries()].filter(([id]) => nodes.get(id)!.kind !== 'out').map(([, v]) => v)); + for (const n of ns) n.rank = n.kind === 'out' ? maxRank + 1 : n.kind === 'in' ? 0 : Math.max(1, rank.get(n.id)!); + return { nodes: ns, edges: [...edges.values()] }; +} + +function typeNameOf(t: any): string { + if (!t) return ''; + if (typeof t === 'string') return t; + if (t.k) { try { return typeName(t); } catch { return t.k; } } + if (t.tk === 'scalar' || t.tk === 'named') return t.name; + if (t.tk === 'list' || t.tk === 'set') return `${t.tk.toUpperCase()} OF ${typeNameOf(t.of)}`; + return ''; +} + +export function dataFlowView(session: Session, root: HTMLElement, hooks?: PanelHooks): () => void { + let live: SVGSVGElement | null = null; + /** Light up what the stepper is doing: the names the next step reads, the name the last step wrote, and the edge of the line that just ran. */ + const mark = (t: number) => { + const trace = session.trace(); + if (!live || !trace || trace.lang === 'asm') return; + const steps = trace.steps as any[]; + const next = t < trace.count ? steps[t] : null, last = t > 0 ? steps[t - 1] : null; + const reads = new Set((next?.reads || []).map((r: any) => r.name)); + const writes = new Set((last?.writes || []).map((w: any) => w.name)); + for (const g of live.querySelectorAll('.df-nodeg')) { const n = g.dataset.name || ''; g.classList.toggle('df-reads', reads.has(n)); g.classList.toggle('df-wrote', writes.has(n)); } + const ln = stepLine(last); + for (const e of live.querySelectorAll('.df-edge')) e.classList.toggle('df-edge-active', ln != null && (e.dataset.lines || '').split(' ').includes(String(ln))); + }; + const render = () => { + clear(root); + const r = routineOf(session); + if (!r) { emptyNote(root, session, 'data-flow graph'); return; } + const { nodes, edges } = dataFlowOf(session, r); + if (!nodes.length) { add(root, el('p', { class: 'muted' }, 'This routine moves no values between names yet.')); return; } + const COLW = 190, ROWH = 62, NH = 38; + const cols = new Map(); + for (const n of nodes) { if (!cols.has(n.rank)) cols.set(n.rank, []); cols.get(n.rank)!.push(n); } + const ranks = [...cols.keys()].sort((a, b) => a - b); + const tallest = Math.max(...[...cols.values()].map((c) => c.length)); + const H = tallest * ROWH + 40, W = ranks.length * COLW + 40; + ranks.forEach((rk, ci) => { + const col = cols.get(rk)!; + col.sort((a, b) => (a.kind === 'in' && b.kind !== 'in' ? -1 : 0) || Math.min(...a.lines, 1e9) - Math.min(...b.lines, 1e9)); + const top = (H - col.length * ROWH) / 2; + col.forEach((n, i) => { n.w = Math.max(72, Math.max(n.label.length, Math.min(n.type.length, 18)) * 7.3 + 24); n.x = 20 + ci * COLW + (COLW - n.w) / 2; n.y = top + i * ROWH + (ROWH - NH) / 2; }); + }); + const el_ = svg('svg', { class: 'flow-svg df-svg', width: W, height: H, viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': `Data flow of ${r.name}` }); + el_.appendChild(svg('defs', {}, svg('marker', { id: 'df-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, svg('path', { d: 'M0 0 L10 5 L0 10 Z', class: 'flow-arrowhead' })))); + const byId = new Map(nodes.map((n) => [n.id, n])); + const gE = svg('g', {}), gN = svg('g', {}); + const bez = (p0: number[], p1: number[], p2: number[], p3: number[], t: number): [number, number] => { const u = 1 - t; return [u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]]; }; + const intoCount = new Map(); + for (const e of edges) { + const a = byId.get(e.from)!, b = byId.get(e.to)!; + const lbl = [...e.lines].sort((x, y) => x - y).map((l) => `L${l}`).join(' '); + // labels on the edges into one node are spread along their curves so they do not pile up + const k = intoCount.get(b.id) || 0; intoCount.set(b.id, k + 1); + const tt = [0.5, 0.3, 0.7, 0.4, 0.6, 0.2, 0.8][k % 7]; + let d: string; let lx: number; let ly: number; + if (a === b) { + const x = a.x + a.w / 2, y = a.y; + d = `M${x - 14} ${y} C ${x - 24} ${y - 34}, ${x + 24} ${y - 34}, ${x + 14} ${y}`; + lx = x; ly = y - 30; + } else if (b.rank > a.rank) { + const p0 = [a.x + a.w, a.y + NH / 2], p3 = [b.x, b.y + NH / 2]; + const m = (p0[0] + p3[0]) / 2; + const p1 = [m, p0[1]], p2 = [m, p3[1]]; + d = `M${p0[0]} ${p0[1]} C ${p1[0]} ${p1[1]}, ${p2[0]} ${p2[1]}, ${p3[0]} ${p3[1]}`; + [lx, ly] = bez(p0, p1, p2, p3, tt); + ly += (k % 2 ? 7 : -7); + } else { + // a back edge: leave from the bottom, come in at the bottom + const p0 = [a.x + a.w / 2, a.y + NH], p3 = [b.x + b.w / 2, b.y + NH]; + const dip = Math.max(p0[1], p3[1]) + 26 + Math.abs(a.rank - b.rank) * 6; + const p1 = [p0[0], dip], p2 = [p3[0], dip]; + d = `M${p0[0]} ${p0[1]} C ${p1[0]} ${p1[1]}, ${p2[0]} ${p2[1]}, ${p3[0]} ${p3[1]}`; + [lx, ly] = bez(p0, p1, p2, p3, 0.5); + } + const path = svg('path', { d, class: 'df-edge' + (e.ctrl ? ' df-edge-ctrl' : ''), 'marker-end': 'url(#df-arrow)', 'data-lines': [...e.lines].join(' ') }); + path.appendChild(svg('title', {}, (e.ctrl ? 'decides: ' : '') + e.texts.join('\n'))); + gE.appendChild(path); + const w = lbl.length * 6.2 + 8; + gE.appendChild(svg('rect', { x: lx - w / 2, y: ly - 8, width: w, height: 15, rx: 3, class: 'df-label-bg' })); + gE.appendChild(svg('text', { x: lx, y: ly, class: 'df-label', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, lbl)); + } + for (const n of nodes) { + const g = svg('g', { class: `df-nodeg df-kind-${n.kind}` + (hooks && n.lines.size ? ' flow-clickable' : ''), 'data-name': n.label }); + g.appendChild(svg('rect', { x: n.x, y: n.y, width: n.w, height: NH, rx: n.kind === 'in' || n.kind === 'out' ? NH / 2 : 6, class: `df-node df-node-${n.kind}` })); + g.appendChild(svg('text', { x: n.x + n.w / 2, y: n.y + (n.type ? 13 : NH / 2), class: 'flow-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, n.label)); + if (n.type) g.appendChild(svg('text', { x: n.x + n.w / 2, y: n.y + 27, class: 'df-type', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, truncate(n.type, 18))); + g.appendChild(svg('title', {}, n.kind === 'in' ? `${n.label}: an input` : n.kind === 'out' ? `${n.label}: what leaves the routine` : `${n.label}: set on line${n.lines.size === 1 ? '' : 's'} ${[...n.lines].sort((a, b) => a - b).join(', ')}`)); + if (hooks && n.lines.size) g.addEventListener('click', () => hooks.reveal(session.state.lang === 'mojo' ? 'mojo' : 'pseudo', Math.min(...n.lines))); + gN.appendChild(g); + } + el_.appendChild(gE); el_.appendChild(gN); + live = el_; + const head = el('div', { class: 'viz-head' }, + titleOf(session, r, render), + el('span', { class: 'small muted' }, 'inputs on the left, what leaves on the right; an arrow is an assignment that reads the one and writes the other, dashed when a condition only decides whether it happens.', el('span', { class: 'viz-step-note' }, ' As you step, the names the next line reads and the name the last line wrote light up.')), + el('span', { class: 'spacer' }), + button('Download SVG', () => downloadSvg(el_, `${r.name.toLowerCase()}-dataflow.svg`), { class: 'btn btn-small btn-quiet' })); + add(root, head, el('div', { class: 'viz-scroll' }, el_)); + mark(Math.min(session.state.t ?? 0, session.trace()?.count ?? 0)); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(mark); + return () => { off(); offStep(); }; +} + +/* ------------------------------------------------------------------ */ +/* Trace table */ +/* ------------------------------------------------------------------ */ + +const MAX_COLS = 120; + +export function traceTableView(session: Session, root: HTMLElement, opts: { goto?: (t: number) => void } = {}): () => void { + let showAll = false; + /** The column of the step that just ran gets the marker; the table scrolls to keep it in view. */ + const mark = (t: number) => { + for (const c of root.querySelectorAll('.vals-now')) c.classList.remove('vals-now'); + if (t <= 0) return; + // the column of the last step that changed something at or before t + let best = 0; + for (const th of root.querySelectorAll('th.vals-step')) { const n = Number(th.dataset.step); if (n <= t && n > best) best = n; } + if (!best) return; + const cells = root.querySelectorAll(`[data-step="${best}"]`); + cells.forEach((c) => c.classList.add('vals-now')); + revealIn(root.querySelector('.vals-scroll'), cells[0] ?? null); + }; + const render = () => { + clear(root); + const trace = session.trace(); + if (!trace) { emptyNote(root, session, 'table of values'); if (session.runError) add(root, el('p', { class: 'small err' }, session.runError)); return; } + if (trace.lang === 'asm') { add(root, el('p', { class: 'muted' }, 'The table of values is for pseudo, lingo, matho and Mojo runs; the machine view shows the registers.')); return; } + const steps = trace.steps as any[]; + const states = trace.states as any[]; + // the columns: steps that wrote something (or printed) + const cols: number[] = []; + for (let i = 0; i < trace.count; i++) { + const s = steps[i]; + const printed = (states[i + 1]?.outputLength ?? 0) > (states[i]?.outputLength ?? 0); + if ((s.writes && s.writes.length) || printed || s.kind === 'return' || s.kind === 'error') cols.push(i); + } + const shown = cols.slice(0, MAX_COLS); + // the rows: every variable, by frame, in order of first appearance across the shown steps + type Row = { key: string; frame: string; name: string; label: string; type: any }; + const rows: Row[] = []; + const seen = new Set(); + const frameNames = new Set(); + for (const st of states) for (const f of st?.frames || []) frameNames.add(f.name || 'main'); + const valueAt = (i: number, row: Row): { text: string; unset: boolean } | null => { + const st = states[i]; + if (!st) return null; + const frames = (st.frames || []).filter((f: any) => (f.name || 'main') === row.frame); + const f = frames[frames.length - 1]; + if (!f || !(row.name in f.vars)) return null; + const v = f.vars[row.name]; + const text = typeof v.text === 'string' ? v.text : formatValue(v.value, v.type, { max: 48, unset: '' }); + return { text, unset: text === '' }; + }; + for (const i of shown) { + const st = states[i + 1]; + for (const f of st?.frames || []) { + for (const [name, v] of Object.entries(f.vars)) { + const key = `${f.name || 'main'}.${name}`; + if (seen.has(key)) continue; + seen.add(key); rows.push({ key, frame: f.name || 'main', name, label: v.name || name, type: v.type }); + } + } + } + const rowFrames = new Set(rows.map((r) => r.frame)); + const prefix = rowFrames.size > 1; + const lines = sourceLines(session); + const srcFor = (s: any) => { const ln = s.pseudoLine ?? s.line; return ln != null ? lineText(lines, ln) : ''; }; + const table = el('table', { class: 'tbl vals-tbl' }); + const thead = el('thead'); + const hr1 = el('tr', {}, el('th', { class: 'vals-corner' }, 'step')); + const hr2 = el('tr', {}, el('th', { class: 'vals-corner' }, 'line')); + for (const i of shown) { + const s = steps[i]; + const th = el('th', { class: 'vals-step' + (opts.goto ? ' linkish' : ''), 'data-step': String(i + 1), title: `step ${i + 1}: ${srcFor(s)}`, onClick: opts.goto ? () => opts.goto!(i + 1) : undefined }, String(i + 1)); + add(hr1, th); + add(hr2, el('th', { class: 'vals-line', 'data-step': String(i + 1), title: srcFor(s) }, s.pseudoLine ?? s.line ?? '')); + } + add(thead, hr1, hr2); + const tbody = el('tbody'); + for (const row of rows) { + const tr = el('tr', {}, el('th', { class: 'vals-var', title: row.type ? typeNameOf(row.type) : '' }, prefix ? el('span', { class: 'muted small' }, `${row.frame}.`) : null, row.label)); + let prev: string | null = null; + for (const i of shown) { + const after = valueAt(i + 1, row); + const wrote = (steps[i].writes || []).some((w: any) => w.name === row.name); + const changed = after && after.text !== prev; + let cell: HTMLElement; + if (!after) cell = el('td', { class: 'vals-cell vals-absent' }); + else if (changed || wrote) cell = el('td', { class: 'vals-cell vals-changed' + (after.unset ? ' vals-unset' : '') }, after.unset ? '—' : after.text); + else cell = el('td', { class: 'vals-cell vals-same' + (showAll ? '' : ' vals-blank') }, showAll ? after.text : ''); + cell.dataset.step = String(i + 1); + add(tr, cell); + if (after) prev = after.text; + } + add(tbody, tr); + } + // the output row + if (trace.output.length) { + const tr = el('tr', { class: 'vals-output-row' }, el('th', { class: 'vals-var' }, 'output')); + shown.forEach((i, k) => { + const before = states[i]?.outputLength ?? 0; + let after = states[i + 1]?.outputLength ?? before; + if (k === shown.length - 1 && shown.length === cols.length) after = trace.output.length; // what the last step printed or returned + add(tr, el('td', { class: 'vals-cell' + (after > before ? ' vals-changed vals-out' : '') }, after > before ? trace.output.slice(before, after).join(' ⏎ ') : '')); + }); + add(tbody, tr); + } + add(table, thead, tbody); + const head = el('div', { class: 'viz-head' }, + el('span', { class: 'viz-title' }, 'table of values'), + el('span', { class: 'small muted' }, `${shown.length} of ${trace.count} steps changed something${cols.length > MAX_COLS ? `; the first ${MAX_COLS} are shown` : ''}. A filled cell is a new value; a blank cell means "unchanged".`), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label tool-check small' }, el('input', { type: 'checkbox', checked: showAll, onChange: (e: Event) => { showAll = (e.target as HTMLInputElement).checked; render(); } }), ' show unchanged values too'), + button('Copy as text', async (e) => { await copyTable(table); (e.target as HTMLButtonElement).textContent = 'Copied'; setTimeout(() => ((e.target as HTMLButtonElement).textContent = 'Copy as text'), 1200); }, { class: 'btn btn-small btn-quiet' })); + add(root, head, el('div', { class: 'viz-scroll vals-scroll' }, table)); + if (trace.error) add(root, el('p', { class: 'small err' }, `The run stopped: ${trace.error.message}`)); + mark(Math.min(session.state.t ?? 0, trace.count)); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(mark); + return () => { off(); offStep(); }; +} + +async function copyTable(table: HTMLTableElement): Promise { + const rows = [...table.querySelectorAll('tr')].map((tr) => [...tr.children].map((c) => (c.textContent || '').trim()).join('\t')); + try { await navigator.clipboard.writeText(rows.join('\n')); } catch { /* ignore */ } +} diff --git a/src/vendor/CODEMIRROR-LICENSE b/src/vendor/CODEMIRROR-LICENSE new file mode 100644 index 0000000..9a91f48 --- /dev/null +++ b/src/vendor/CODEMIRROR-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/vendor/cm-types/commands/src/commands.d.ts b/src/vendor/cm-types/commands/src/commands.d.ts new file mode 100644 index 0000000..80c593c --- /dev/null +++ b/src/vendor/cm-types/commands/src/commands.d.ts @@ -0,0 +1,98 @@ +import { StateCommand } from "../../state/src/index.js"; +import { Command, KeyBinding } from "../../view/src/index.js"; +export { CommentTokens, toggleComment, toggleLineComment, lineComment, lineUncomment, toggleBlockComment, blockComment, blockUncomment, toggleBlockCommentByLine } from "./comment"; +export { history, historyKeymap, historyField, undo, redo, undoSelection, redoSelection, undoDepth, redoDepth, isolateHistory, invertedEffects } from "./history"; +export declare const cursorCharLeft: Command; +export declare const cursorCharRight: Command; +export declare const cursorCharForward: Command; +export declare const cursorCharBackward: Command; +export declare const cursorCharForwardLogical: StateCommand; +export declare const cursorCharBackwardLogical: StateCommand; +export declare const cursorGroupLeft: Command; +export declare const cursorGroupRight: Command; +export declare const cursorGroupForward: Command; +export declare const cursorGroupBackward: Command; +export declare const cursorGroupForwardWin: Command; +export declare const cursorSubwordForward: Command; +export declare const cursorSubwordBackward: Command; +export declare const cursorSyntaxLeft: Command; +export declare const cursorSyntaxRight: Command; +export declare const cursorLineUp: Command; +export declare const cursorLineDown: Command; +export declare const cursorPageUp: Command; +export declare const cursorPageDown: Command; +export declare const cursorLineBoundaryForward: Command; +export declare const cursorLineBoundaryBackward: Command; +export declare const cursorLineBoundaryLeft: Command; +export declare const cursorLineBoundaryRight: Command; +export declare const cursorLineStart: Command; +export declare const cursorLineEnd: Command; +export declare const cursorMatchingBracket: StateCommand; +export declare const selectMatchingBracket: StateCommand; +export declare const selectCharLeft: Command; +export declare const selectCharRight: Command; +export declare const selectCharForward: Command; +export declare const selectCharBackward: Command; +export declare const selectCharForwardLogical: StateCommand; +export declare const selectCharBackwardLogical: StateCommand; +export declare const selectGroupLeft: Command; +export declare const selectGroupRight: Command; +export declare const selectGroupForward: Command; +export declare const selectGroupBackward: Command; +export declare const selectGroupForwardWin: Command; +export declare const selectSubwordForward: Command; +export declare const selectSubwordBackward: Command; +export declare const selectSyntaxLeft: Command; +export declare const selectSyntaxRight: Command; +export declare const selectLineUp: Command; +export declare const selectLineDown: Command; +export declare const selectPageUp: Command; +export declare const selectPageDown: Command; +export declare const selectLineBoundaryForward: Command; +export declare const selectLineBoundaryBackward: Command; +export declare const selectLineBoundaryLeft: Command; +export declare const selectLineBoundaryRight: Command; +export declare const selectLineStart: Command; +export declare const selectLineEnd: Command; +export declare const cursorDocStart: StateCommand; +export declare const cursorDocEnd: StateCommand; +export declare const selectDocStart: StateCommand; +export declare const selectDocEnd: StateCommand; +export declare const selectAll: StateCommand; +export declare const selectLine: StateCommand; +export declare const selectParentSyntax: StateCommand; +export declare const addCursorAbove: Command; +export declare const addCursorBelow: Command; +export declare const simplifySelection: StateCommand; +export declare const deleteCharBackward: Command; +export declare const deleteCharBackwardStrict: Command; +export declare const deleteCharForward: Command; +export declare const deleteGroupBackward: StateCommand; +export declare const deleteGroupForward: StateCommand; +export declare const deleteGroupForwardWin: Command; +export declare const deleteToLineEnd: Command; +export declare const deleteToLineStart: Command; +export declare const deleteLineBoundaryBackward: Command; +export declare const deleteLineBoundaryForward: Command; +export declare const deleteTrailingWhitespace: StateCommand; +export declare const splitLine: StateCommand; +export declare const transposeChars: StateCommand; +export declare const moveLineUp: StateCommand; +export declare const moveLineDown: StateCommand; +export declare const copyLineUp: StateCommand; +export declare const copyLineDown: StateCommand; +export declare const deleteLine: Command; +export declare const insertNewline: StateCommand; +export declare const insertNewlineKeepIndent: StateCommand; +export declare const insertNewlineAndIndent: StateCommand; +export declare const insertBlankLine: StateCommand; +export declare const indentSelection: StateCommand; +export declare const indentMore: StateCommand; +export declare const indentLess: StateCommand; +export declare const toggleTabFocusMode: Command; +export declare const temporarilySetTabFocusMode: Command; +export declare const insertTab: StateCommand; +export declare const emacsStyleKeymap: readonly KeyBinding[]; +export declare const standardKeymap: readonly KeyBinding[]; +export declare const defaultKeymap: readonly KeyBinding[]; +export declare const indentWithTab: KeyBinding; diff --git a/src/vendor/cm-types/commands/src/comment.d.ts b/src/vendor/cm-types/commands/src/comment.d.ts new file mode 100644 index 0000000..3b450c9 --- /dev/null +++ b/src/vendor/cm-types/commands/src/comment.d.ts @@ -0,0 +1,16 @@ +import { StateCommand } from "../../state/src/index.js"; +export interface CommentTokens { + block?: { + open: string; + close: string; + }; + line?: string; +} +export declare const toggleComment: StateCommand; +export declare const toggleLineComment: StateCommand; +export declare const lineComment: StateCommand; +export declare const lineUncomment: StateCommand; +export declare const toggleBlockComment: StateCommand; +export declare const blockComment: StateCommand; +export declare const blockUncomment: StateCommand; +export declare const toggleBlockCommentByLine: StateCommand; diff --git a/src/vendor/cm-types/commands/src/history.d.ts b/src/vendor/cm-types/commands/src/history.d.ts new file mode 100644 index 0000000..ba5cdef --- /dev/null +++ b/src/vendor/cm-types/commands/src/history.d.ts @@ -0,0 +1,19 @@ +import { EditorState, Transaction, StateField, StateCommand, StateEffect, Facet, Extension } from "../../state/src/index.js"; +import { KeyBinding } from "../../view/src/index.js"; +export declare const isolateHistory: import("entry").AnnotationType<"before" | "after" | "full">; +export declare const invertedEffects: Facet<(tr: Transaction) => readonly StateEffect[], readonly ((tr: Transaction) => readonly StateEffect[])[]>; +interface HistoryConfig { + minDepth?: number; + newGroupDelay?: number; + joinToEvent?: (tr: Transaction, isAdjacent: boolean) => boolean; +} +export declare function history(config?: HistoryConfig): Extension; +export declare const historyField: StateField; +export declare const undo: StateCommand; +export declare const redo: StateCommand; +export declare const undoSelection: StateCommand; +export declare const redoSelection: StateCommand; +export declare const undoDepth: (state: EditorState) => number; +export declare const redoDepth: (state: EditorState) => number; +export declare const historyKeymap: readonly KeyBinding[]; +export {}; diff --git a/src/vendor/cm-types/commands/src/index.d.ts b/src/vendor/cm-types/commands/src/index.d.ts new file mode 100644 index 0000000..9a62daa --- /dev/null +++ b/src/vendor/cm-types/commands/src/index.d.ts @@ -0,0 +1,3 @@ +export * from "./commands"; +export * from "./history"; +export * from "./comment"; diff --git a/src/vendor/cm-types/common/src/index.d.ts b/src/vendor/cm-types/common/src/index.d.ts new file mode 100644 index 0000000..b687834 --- /dev/null +++ b/src/vendor/cm-types/common/src/index.d.ts @@ -0,0 +1,3 @@ +export { DefaultBufferLength, NodeProp, MountedTree, NodePropSource, NodeType, NodeSet, Tree, TreeBuffer, SyntaxNode, SyntaxNodeRef, TreeCursor, BufferCursor, NodeWeakMap, IterMode, NodeIterator } from "./tree"; +export { ChangedRange, TreeFragment, PartialParse, Parser, Input, ParseWrapper } from "./parse"; +export { NestedParse, parseMixed } from "./mix"; diff --git a/src/vendor/cm-types/common/src/mix.d.ts b/src/vendor/cm-types/common/src/mix.d.ts new file mode 100644 index 0000000..42c7ca5 --- /dev/null +++ b/src/vendor/cm-types/common/src/mix.d.ts @@ -0,0 +1,14 @@ +import { SyntaxNodeRef } from "./tree"; +import { Input, Parser, ParseWrapper } from "./parse"; +export interface NestedParse { + parser: Parser; + overlay?: readonly { + from: number; + to: number; + }[] | ((node: SyntaxNodeRef) => { + from: number; + to: number; + } | boolean); + bracketed?: boolean; +} +export declare function parseMixed(nest: (node: SyntaxNodeRef, input: Input) => NestedParse | null): ParseWrapper; diff --git a/src/vendor/cm-types/common/src/parse.d.ts b/src/vendor/cm-types/common/src/parse.d.ts new file mode 100644 index 0000000..4386426 --- /dev/null +++ b/src/vendor/cm-types/common/src/parse.d.ts @@ -0,0 +1,48 @@ +import { Tree } from "./tree"; +export interface ChangedRange { + fromA: number; + toA: number; + fromB: number; + toB: number; +} +export declare class TreeFragment { + readonly from: number; + readonly to: number; + readonly tree: Tree; + readonly offset: number; + constructor(from: number, to: number, tree: Tree, offset: number, openStart?: boolean, openEnd?: boolean); + get openStart(): boolean; + get openEnd(): boolean; + static addTree(tree: Tree, fragments?: readonly TreeFragment[], partial?: boolean): readonly TreeFragment[]; + static applyChanges(fragments: readonly TreeFragment[], changes: readonly ChangedRange[], minGap?: number): readonly TreeFragment[]; +} +export interface PartialParse { + advance(): Tree | null; + readonly parsedPos: number; + stopAt(pos: number): void; + readonly stoppedAt: number | null; +} +export declare abstract class Parser { + abstract createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]): PartialParse; + startParse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly { + from: number; + to: number; + }[]): PartialParse; + parse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly { + from: number; + to: number; + }[]): Tree; +} +export interface Input { + readonly length: number; + chunk(from: number): string; + readonly lineChunks: boolean; + read(from: number, to: number): string; +} +export type ParseWrapper = (inner: PartialParse, input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; +}[]) => PartialParse; diff --git a/src/vendor/cm-types/common/src/tree.d.ts b/src/vendor/cm-types/common/src/tree.d.ts new file mode 100644 index 0000000..c19e6ad --- /dev/null +++ b/src/vendor/cm-types/common/src/tree.d.ts @@ -0,0 +1,282 @@ +import { Parser } from "./parse"; +export declare const DefaultBufferLength = 1024; +export declare class Range { + readonly from: number; + readonly to: number; + constructor(from: number, to: number); +} +export declare class NodeProp { + perNode: boolean; + deserialize: (str: string) => T; + constructor(config?: { + deserialize?: (str: string) => T; + combine?: (a: T, b: T) => T; + perNode?: boolean; + }); + add(match: { + [selector: string]: T; + } | ((type: NodeType) => T | undefined)): NodePropSource; + static closedBy: NodeProp; + static openedBy: NodeProp; + static group: NodeProp; + static isolate: NodeProp<"rtl" | "auto" | "ltr">; + static contextHash: NodeProp; + static lookAhead: NodeProp; + static mounted: NodeProp; +} +export declare class MountedTree { + readonly tree: Tree; + readonly overlay: readonly { + from: number; + to: number; + }[] | null; + readonly parser: Parser; + readonly bracketed: boolean; + constructor(tree: Tree, overlay: readonly { + from: number; + to: number; + }[] | null, parser: Parser, bracketed?: boolean); +} +export type NodePropSource = (type: NodeType) => null | [NodeProp, any]; +export declare class NodeType { + readonly name: string; + readonly id: number; + static define(spec: { + id: number; + name?: string; + props?: readonly ([NodeProp, any] | NodePropSource)[]; + top?: boolean; + error?: boolean; + skipped?: boolean; + }): NodeType; + prop(prop: NodeProp): T | undefined; + get isTop(): boolean; + get isSkipped(): boolean; + get isError(): boolean; + get isAnonymous(): boolean; + is(name: string | number): boolean; + static none: NodeType; + static match(map: { + [selector: string]: T; + }): (node: NodeType) => T | undefined; +} +export declare class NodeSet { + readonly types: readonly NodeType[]; + constructor(types: readonly NodeType[]); + extend(...props: NodePropSource[]): NodeSet; +} +export declare enum IterMode { + ExcludeBuffers = 1, + IncludeAnonymous = 2, + IgnoreMounts = 4, + IgnoreOverlays = 8, + EnterBracketed = 16 +} +export declare class Tree { + readonly type: NodeType; + readonly children: readonly (Tree | TreeBuffer)[]; + readonly positions: readonly number[]; + readonly length: number; + constructor(type: NodeType, children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number, props?: readonly [NodeProp | number, any][]); + static empty: Tree; + cursor(mode?: IterMode): TreeCursor; + cursorAt(pos: number, side?: -1 | 0 | 1, mode?: IterMode): TreeCursor; + get topNode(): SyntaxNode; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveStack(pos: number, side?: -1 | 0 | 1): NodeIterator; + iterate(spec: { + enter(node: SyntaxNodeRef): boolean | void; + leave?(node: SyntaxNodeRef): void; + from?: number; + to?: number; + mode?: IterMode; + }): void; + prop(prop: NodeProp): T | undefined; + get propValues(): readonly [NodeProp | number, any][]; + balance(config?: { + makeTree?: (children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number) => Tree; + }): Tree; + static build(data: BuildData): Tree; +} +export type NodeIterator = { + node: SyntaxNode; + next: NodeIterator | null; +}; +type BuildData = { + buffer: BufferCursor | readonly number[]; + nodeSet: NodeSet; + topID: number; + start?: number; + bufferStart?: number; + length?: number; + maxBufferLength?: number; + reused?: readonly Tree[]; + minRepeatType?: number; +}; +export interface BufferCursor { + pos: number; + id: number; + start: number; + end: number; + size: number; + next(): void; + fork(): BufferCursor; +} +export declare class TreeBuffer { + readonly buffer: Uint16Array; + readonly length: number; + readonly set: NodeSet; + constructor(buffer: Uint16Array, length: number, set: NodeSet); +} +export interface SyntaxNodeRef { + readonly from: number; + readonly to: number; + readonly type: NodeType; + readonly name: string; + readonly tree: Tree | null; + readonly node: SyntaxNode; + matchContext(context: readonly string[]): boolean; +} +export interface SyntaxNode extends SyntaxNodeRef { + parent: SyntaxNode | null; + firstChild: SyntaxNode | null; + lastChild: SyntaxNode | null; + childAfter(pos: number): SyntaxNode | null; + childBefore(pos: number): SyntaxNode | null; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null; + nextSibling: SyntaxNode | null; + prevSibling: SyntaxNode | null; + prop(prop: NodeProp): T | undefined; + cursor(mode?: IterMode): TreeCursor; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + enterUnfinishedNodesBefore(pos: number): SyntaxNode; + toTree(): Tree; + getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode | null; + getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[]; +} +declare const enum Side { + Before = -2, + AtOrBefore = -1, + Around = 0, + AtOrAfter = 1, + After = 2, + DontCare = 4 +} +declare abstract class BaseNode implements SyntaxNode { + abstract from: number; + abstract to: number; + abstract type: NodeType; + abstract name: string; + abstract tree: Tree | null; + abstract parent: SyntaxNode | null; + abstract firstChild: SyntaxNode | null; + abstract lastChild: SyntaxNode | null; + abstract childAfter(pos: number): SyntaxNode | null; + abstract childBefore(pos: number): SyntaxNode | null; + abstract enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null; + abstract nextSibling: SyntaxNode | null; + abstract prevSibling: SyntaxNode | null; + abstract toTree(): Tree; + abstract prop(prop: NodeProp): T | undefined; + cursor(mode?: IterMode): TreeCursor; + getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode; + getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[]; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + matchContext(context: readonly string[]): boolean; + enterUnfinishedNodesBefore(pos: number): SyntaxNode; + get node(): this; + get next(): SyntaxNode; +} +export declare class TreeNode extends BaseNode implements SyntaxNode { + readonly _tree: Tree; + readonly from: number; + readonly index: number; + readonly _parent: TreeNode | null; + constructor(_tree: Tree, from: number, index: number, _parent: TreeNode | null); + get type(): NodeType; + get name(): string; + get to(): number; + nextChild(i: number, dir: 1 | -1, pos: number, side: Side, mode?: IterMode): TreeNode | BufferNode | null; + get firstChild(): TreeNode | BufferNode; + get lastChild(): TreeNode | BufferNode; + childAfter(pos: number): TreeNode | BufferNode; + childBefore(pos: number): TreeNode | BufferNode; + prop(prop: NodeProp): T | undefined; + enter(pos: number, side: -1 | 0 | 1, mode?: number): TreeNode | BufferNode; + nextSignificantParent(): TreeNode; + get parent(): TreeNode | null; + get nextSibling(): SyntaxNode | null; + get prevSibling(): SyntaxNode | null; + get tree(): Tree; + toTree(): Tree; +} +declare class BufferContext { + readonly parent: TreeNode; + readonly buffer: TreeBuffer; + readonly index: number; + readonly start: number; + constructor(parent: TreeNode, buffer: TreeBuffer, index: number, start: number); +} +export declare class BufferNode extends BaseNode { + readonly context: BufferContext; + readonly _parent: BufferNode | null; + readonly index: number; + type: NodeType; + get name(): string; + get from(): number; + get to(): number; + constructor(context: BufferContext, _parent: BufferNode | null, index: number); + child(dir: 1 | -1, pos: number, side: Side): BufferNode | null; + get firstChild(): BufferNode; + get lastChild(): BufferNode; + childAfter(pos: number): BufferNode; + childBefore(pos: number): BufferNode; + prop(prop: NodeProp): T | undefined; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): BufferNode; + get parent(): SyntaxNode | null; + externalSibling(dir: 1 | -1): TreeNode | BufferNode; + get nextSibling(): SyntaxNode | null; + get prevSibling(): SyntaxNode | null; + get tree(): any; + toTree(): Tree; +} +export declare class TreeCursor implements SyntaxNodeRef { + type: NodeType; + get name(): string; + from: number; + to: number; + private stack; + private bufferNode; + private yieldNode; + private yieldBuf; + firstChild(): boolean; + lastChild(): boolean; + childAfter(pos: number): boolean; + childBefore(pos: number): boolean; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): boolean; + parent(): boolean; + nextSibling(): boolean; + prevSibling(): boolean; + private atLastNode; + private move; + next(enter?: boolean): boolean; + prev(enter?: boolean): boolean; + moveTo(pos: number, side?: -1 | 0 | 1): this; + get node(): SyntaxNode; + get tree(): Tree | null; + iterate(enter: (node: SyntaxNodeRef) => boolean | void, leave?: (node: SyntaxNodeRef) => void): void; + matchContext(context: readonly string[]): boolean; +} +export declare class NodeWeakMap { + private map; + private setBuffer; + private getBuffer; + set(node: SyntaxNode, value: T): void; + get(node: SyntaxNode): T | undefined; + cursorSet(cursor: TreeCursor, value: T): void; + cursorGet(cursor: TreeCursor): T | undefined; +} +export {}; diff --git a/src/vendor/cm-types/crelt/index.d.ts b/src/vendor/cm-types/crelt/index.d.ts new file mode 100644 index 0000000..6d9aa89 --- /dev/null +++ b/src/vendor/cm-types/crelt/index.d.ts @@ -0,0 +1,4 @@ +type Child = string | Node | null | undefined | readonly Child[] + +export default function crelt(elt: string | HTMLElement, attrs: {[attr: string]: any}, ...children: Child[]): HTMLElement +export default function crelt(elt: string | HTMLElement, ...children: Child[]): HTMLElement diff --git a/src/vendor/cm-types/find-cluster-break/src/index.d.ts b/src/vendor/cm-types/find-cluster-break/src/index.d.ts new file mode 100644 index 0000000..b96d8b7 --- /dev/null +++ b/src/vendor/cm-types/find-cluster-break/src/index.d.ts @@ -0,0 +1,15 @@ +/** + Query whether the given character has a `Grapheme_Cluster_Break` + value of `Extend` in Unicode. +*/ +export declare function isExtendingChar(code: number): boolean + +/** + Returns a next grapheme cluster break _after_ (not equal to) `pos`, + if `forward` is true, or before otherwise. Returns `pos` itself if no + further cluster break is available in the string. Moves across + surrogate pairs, extending characters (when `includeExtending` is + true, which is the default), characters joined with zero-width joiners, + and flag emoji. +*/ +export declare function findClusterBreak(str: string, pos: number, forward?: boolean, includeExtending?: boolean): number diff --git a/src/vendor/cm-types/highlight/src/highlight.d.ts b/src/vendor/cm-types/highlight/src/highlight.d.ts new file mode 100644 index 0000000..8cd19a2 --- /dev/null +++ b/src/vendor/cm-types/highlight/src/highlight.d.ts @@ -0,0 +1,116 @@ +import { Tree, NodeType, SyntaxNodeRef } from "../../common/src/index.js"; +export declare class Tag { + readonly set: Tag[]; + toString(): string; + static define(name?: string, parent?: Tag): Tag; + static define(parent?: Tag): Tag; + static defineModifier(name?: string): (tag: Tag) => Tag; +} +export declare function styleTags(spec: { + [selector: string]: Tag | readonly Tag[]; +}): import("@lezer/common").NodePropSource; +export interface Highlighter { + style(tags: readonly Tag[]): string | null; + scope?(node: NodeType): boolean; +} +export declare function tagHighlighter(tags: readonly { + tag: Tag | readonly Tag[]; + class: string; +}[], options?: { + scope?: (node: NodeType) => boolean; + all?: string; +}): Highlighter; +export declare function highlightTree(tree: Tree, highlighter: Highlighter | readonly Highlighter[], putStyle: (from: number, to: number, classes: string) => void, from?: number, to?: number): void; +export declare function highlightCode(code: string, tree: Tree, highlighter: Highlighter | readonly Highlighter[], putText: (code: string, classes: string) => void, putBreak: () => void, from?: number, to?: number): void; +export declare function getStyleTags(node: SyntaxNodeRef): { + tags: readonly Tag[]; + opaque: boolean; + inherit: boolean; +} | null; +export declare const tags: { + comment: Tag; + lineComment: Tag; + blockComment: Tag; + docComment: Tag; + name: Tag; + variableName: Tag; + typeName: Tag; + tagName: Tag; + propertyName: Tag; + attributeName: Tag; + className: Tag; + labelName: Tag; + namespace: Tag; + macroName: Tag; + literal: Tag; + string: Tag; + docString: Tag; + character: Tag; + attributeValue: Tag; + number: Tag; + integer: Tag; + float: Tag; + bool: Tag; + regexp: Tag; + escape: Tag; + color: Tag; + url: Tag; + keyword: Tag; + self: Tag; + null: Tag; + atom: Tag; + unit: Tag; + modifier: Tag; + operatorKeyword: Tag; + controlKeyword: Tag; + definitionKeyword: Tag; + moduleKeyword: Tag; + operator: Tag; + derefOperator: Tag; + arithmeticOperator: Tag; + logicOperator: Tag; + bitwiseOperator: Tag; + compareOperator: Tag; + updateOperator: Tag; + definitionOperator: Tag; + typeOperator: Tag; + controlOperator: Tag; + punctuation: Tag; + separator: Tag; + bracket: Tag; + angleBracket: Tag; + squareBracket: Tag; + paren: Tag; + brace: Tag; + content: Tag; + heading: Tag; + heading1: Tag; + heading2: Tag; + heading3: Tag; + heading4: Tag; + heading5: Tag; + heading6: Tag; + contentSeparator: Tag; + list: Tag; + quote: Tag; + emphasis: Tag; + strong: Tag; + link: Tag; + monospace: Tag; + strikethrough: Tag; + inserted: Tag; + deleted: Tag; + changed: Tag; + invalid: Tag; + meta: Tag; + documentMeta: Tag; + annotation: Tag; + processingInstruction: Tag; + definition: (tag: Tag) => Tag; + constant: (tag: Tag) => Tag; + function: (tag: Tag) => Tag; + standard: (tag: Tag) => Tag; + local: (tag: Tag) => Tag; + special: (tag: Tag) => Tag; +}; +export declare const classHighlighter: Highlighter; diff --git a/src/vendor/cm-types/language/src/fold.d.ts b/src/vendor/cm-types/language/src/fold.d.ts new file mode 100644 index 0000000..2b8e559 --- /dev/null +++ b/src/vendor/cm-types/language/src/fold.d.ts @@ -0,0 +1,57 @@ +import { NodeProp, SyntaxNode } from "../../common/src/index.js"; +import { EditorState, Facet, StateField, Extension } from "../../state/src/index.js"; +import { EditorView, BlockInfo, Command, DecorationSet, KeyBinding, ViewUpdate } from "../../view/src/index.js"; +export declare const foldService: Facet<(state: EditorState, lineStart: number, lineEnd: number) => ({ + from: number; + to: number; +} | null), readonly ((state: EditorState, lineStart: number, lineEnd: number) => ({ + from: number; + to: number; +} | null))[]>; +export declare const foldNodeProp: NodeProp<(node: SyntaxNode, state: EditorState) => ({ + from: number; + to: number; +} | null)>; +export declare function foldInside(node: SyntaxNode): { + from: number; + to: number; +} | null; +export declare function foldable(state: EditorState, lineStart: number, lineEnd: number): { + from: number; + to: number; +}; +type DocRange = { + from: number; + to: number; +}; +export declare const foldEffect: import("entry").StateEffectType; +export declare const unfoldEffect: import("entry").StateEffectType; +export declare const foldState: StateField; +export declare function foldedRanges(state: EditorState): DecorationSet; +export declare const foldCode: Command; +export declare const unfoldCode: Command; +export declare const foldAll: Command; +export declare const unfoldAll: Command; +export declare const toggleFold: Command; +export declare const foldKeymap: readonly KeyBinding[]; +interface FoldConfig { + placeholderDOM?: ((view: EditorView, onclick: (event: Event) => void, prepared: any) => HTMLElement) | null; + placeholderText?: string; + preparePlaceholder?: (state: EditorState, range: { + from: number; + to: number; + }) => any; +} +export declare function codeFolding(config?: FoldConfig): Extension; +type Handlers = { + [event: string]: (view: EditorView, line: BlockInfo, event: Event) => boolean; +}; +interface FoldGutterConfig { + markerDOM?: ((open: boolean) => HTMLElement) | null; + openText?: string; + closedText?: string; + domEventHandlers?: Handlers; + foldingChanged?: (update: ViewUpdate) => boolean; +} +export declare function foldGutter(config?: FoldGutterConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/language/src/highlight.d.ts b/src/vendor/cm-types/language/src/highlight.d.ts new file mode 100644 index 0000000..4d25efd --- /dev/null +++ b/src/vendor/cm-types/language/src/highlight.d.ts @@ -0,0 +1,27 @@ +import { NodeType } from "../../common/src/index.js"; +import { Tag, Highlighter } from "../../highlight/src/highlight.js"; +import { StyleSpec, StyleModule } from "../../style-mod/src/style-mod.js"; +import { EditorState, Extension } from "../../state/src/index.js"; +import { Language } from "./language"; +export declare class HighlightStyle implements Highlighter { + readonly specs: readonly TagStyle[]; + readonly module: StyleModule | null; + readonly style: (tags: readonly Tag[]) => string | null; + readonly scope?: (type: NodeType) => boolean; + private constructor(); + static define(specs: readonly TagStyle[], options?: { + scope?: Language | NodeType; + all?: string | StyleSpec; + themeType?: "dark" | "light"; + }): HighlightStyle; +} +export declare function syntaxHighlighting(highlighter: Highlighter, options?: { + fallback: boolean; +}): Extension; +export declare function highlightingFor(state: EditorState, tags: readonly Tag[], scope?: NodeType): string | null; +export interface TagStyle { + tag: Tag | readonly Tag[]; + class?: string; + [styleProperty: string]: any; +} +export declare const defaultHighlightStyle: HighlightStyle; diff --git a/src/vendor/cm-types/language/src/indent.d.ts b/src/vendor/cm-types/language/src/indent.d.ts new file mode 100644 index 0000000..653bd8e --- /dev/null +++ b/src/vendor/cm-types/language/src/indent.d.ts @@ -0,0 +1,48 @@ +import { NodeProp, SyntaxNode } from "../../common/src/index.js"; +import { EditorState, Extension, Facet } from "../../state/src/index.js"; +export declare const indentService: Facet<(context: IndentContext, pos: number) => number | null | undefined, readonly ((context: IndentContext, pos: number) => number | null | undefined)[]>; +export declare const indentUnit: Facet; +export declare function getIndentUnit(state: EditorState): number; +export declare function indentString(state: EditorState, cols: number): string; +export declare function getIndentation(context: IndentContext | EditorState, pos: number): number | null; +export declare function indentRange(state: EditorState, from: number, to: number): import("entry").ChangeSet; +export declare class IndentContext { + readonly state: EditorState; + unit: number; + constructor(state: EditorState, options?: { + overrideIndentation?: (pos: number) => number; + simulateBreak?: number; + simulateDoubleBreak?: boolean; + }); + lineAt(pos: number, bias?: -1 | 1): { + text: string; + from: number; + }; + textAfterPos(pos: number, bias?: -1 | 1): string; + column(pos: number, bias?: -1 | 1): number; + countColumn(line: string, pos?: number): number; + lineIndent(pos: number, bias?: -1 | 1): number; + get simulatedBreak(): number | null; +} +export declare const indentNodeProp: NodeProp<(context: TreeIndentContext) => number | null>; +export declare class TreeIndentContext extends IndentContext { + private base; + readonly pos: number; + private constructor(); + get node(): SyntaxNode; + get textAfter(): string; + get baseIndent(): number; + baseIndentFor(node: SyntaxNode): number; + continue(): number; +} +export declare function delimitedIndent({ closing, align, units }: { + closing: string; + align?: boolean; + units?: number; +}): (context: TreeIndentContext) => number; +export declare const flatIndent: (context: TreeIndentContext) => number; +export declare function continuedIndent({ except, units }?: { + except?: RegExp; + units?: number; +}): (context: TreeIndentContext) => number; +export declare function indentOnInput(): Extension; diff --git a/src/vendor/cm-types/language/src/index.d.ts b/src/vendor/cm-types/language/src/index.d.ts new file mode 100644 index 0000000..9752681 --- /dev/null +++ b/src/vendor/cm-types/language/src/index.d.ts @@ -0,0 +1,8 @@ +export { language, Language, LRLanguage, Sublanguage, sublanguageProp, defineLanguageFacet, syntaxTree, ensureSyntaxTree, languageDataProp, ParseContext, LanguageSupport, LanguageDescription, syntaxTreeAvailable, syntaxParserRunning, forceParsing, DocInput } from "./language"; +export { IndentContext, getIndentUnit, indentString, indentOnInput, indentService, getIndentation, indentRange, indentUnit, TreeIndentContext, indentNodeProp, delimitedIndent, continuedIndent, flatIndent } from "./indent"; +export { foldService, foldNodeProp, foldInside, foldable, foldCode, unfoldCode, toggleFold, foldAll, unfoldAll, foldKeymap, codeFolding, foldGutter, foldedRanges, foldEffect, unfoldEffect, foldState } from "./fold"; +export { HighlightStyle, syntaxHighlighting, highlightingFor, TagStyle, defaultHighlightStyle } from "./highlight"; +export { bracketMatching, Config, matchBrackets, MatchResult, bracketMatchingHandle } from "./matchbrackets"; +export { StreamLanguage, StreamParser } from "./stream-parser"; +export { StringStream } from "./stringstream"; +export { bidiIsolates } from "./isolate"; diff --git a/src/vendor/cm-types/language/src/isolate.d.ts b/src/vendor/cm-types/language/src/isolate.d.ts new file mode 100644 index 0000000..ea0b5c4 --- /dev/null +++ b/src/vendor/cm-types/language/src/isolate.d.ts @@ -0,0 +1,4 @@ +import { Extension } from "../../state/src/index.js"; +export declare function bidiIsolates(options?: { + alwaysIsolate?: boolean; +}): Extension; diff --git a/src/vendor/cm-types/language/src/language.d.ts b/src/vendor/cm-types/language/src/language.d.ts new file mode 100644 index 0000000..ffa824d --- /dev/null +++ b/src/vendor/cm-types/language/src/language.d.ts @@ -0,0 +1,116 @@ +import { Tree, SyntaxNode, TreeFragment, NodeProp, Input, Parser } from "../../common/src/index.js"; +import type { LRParser, ParserConfig } from "../../lr/src/index.js"; +import { EditorState, Extension, Facet, Text } from "../../state/src/index.js"; +import { EditorView } from "../../view/src/index.js"; +export declare const languageDataProp: NodeProp>; +export declare function defineLanguageFacet(baseData?: { + [name: string]: any; +}): Facet<{ + [name: string]: any; +}, readonly { + [name: string]: any; +}[]>; +export interface Sublanguage { + type?: "replace" | "extend"; + test: (node: SyntaxNode, state: EditorState) => boolean; + facet: Facet<{ + [name: string]: any; + }>; +} +export declare const sublanguageProp: NodeProp; +export declare class Language { + readonly data: Facet<{ + [name: string]: any; + }>; + readonly name: string; + readonly extension: Extension; + parser: Parser; + constructor(data: Facet<{ + [name: string]: any; + }>, parser: Parser, extraExtensions?: Extension[], name?: string); + isActiveAt(state: EditorState, pos: number, side?: -1 | 0 | 1): boolean; + findRegions(state: EditorState): { + from: number; + to: number; + }[]; + get allowsNesting(): boolean; +} +export declare class LRLanguage extends Language { + readonly parser: LRParser; + private constructor(); + static define(spec: { + name?: string; + parser: LRParser; + languageData?: { + [name: string]: any; + }; + }): LRLanguage; + configure(options: ParserConfig, name?: string): LRLanguage; + get allowsNesting(): boolean; +} +export declare function syntaxTree(state: EditorState): Tree; +export declare function ensureSyntaxTree(state: EditorState, upto: number, timeout?: number): Tree | null; +export declare function syntaxTreeAvailable(state: EditorState, upto?: number): boolean; +export declare function forceParsing(view: EditorView, upto?: number, timeout?: number): boolean; +export declare function syntaxParserRunning(view: EditorView): boolean; +export declare class DocInput implements Input { + readonly doc: Text; + private cursor; + private cursorPos; + private string; + constructor(doc: Text); + get length(): number; + private syncTo; + chunk(pos: number): string; + get lineChunks(): boolean; + read(from: number, to: number): string; +} +export declare class ParseContext { + private parser; + readonly state: EditorState; + fragments: readonly TreeFragment[]; + viewport: { + from: number; + to: number; + }; + private parse; + private constructor(); + private startParse; + private withContext; + private withoutTempSkipped; + skipUntilInView(from: number, to: number): void; + static getSkippingParser(until?: Promise): Parser; + static get(): ParseContext; +} +export declare const language: Facet; +export declare class LanguageSupport { + readonly language: Language; + readonly support: Extension; + extension: Extension; + constructor(language: Language, support?: Extension); +} +export declare class LanguageDescription { + readonly name: string; + readonly alias: readonly string[]; + readonly extensions: readonly string[]; + readonly filename: RegExp | undefined; + private loadFunc; + support: LanguageSupport | undefined; + private loading; + private constructor(); + load(): Promise; + static of(spec: { + name: string; + alias?: readonly string[]; + extensions?: readonly string[]; + filename?: RegExp; + load?: () => Promise; + support?: LanguageSupport; + }): LanguageDescription; + static matchFilename(descs: readonly LanguageDescription[], filename: string): LanguageDescription; + static matchLanguageName(descs: readonly LanguageDescription[], name: string, fuzzy?: boolean): LanguageDescription; +} diff --git a/src/vendor/cm-types/language/src/matchbrackets.d.ts b/src/vendor/cm-types/language/src/matchbrackets.d.ts new file mode 100644 index 0000000..860f25e --- /dev/null +++ b/src/vendor/cm-types/language/src/matchbrackets.d.ts @@ -0,0 +1,23 @@ +import { EditorState, Extension, Range } from "../../state/src/index.js"; +import { Decoration } from "../../view/src/index.js"; +import { SyntaxNode, NodeProp } from "../../common/src/index.js"; +export interface Config { + afterCursor?: boolean; + brackets?: string; + maxScanDistance?: number; + renderMatch?: (match: MatchResult, state: EditorState) => readonly Range[]; +} +export declare function bracketMatching(config?: Config): Extension; +export declare const bracketMatchingHandle: NodeProp<(node: SyntaxNode) => SyntaxNode | null>; +export interface MatchResult { + start: { + from: number; + to: number; + }; + end?: { + from: number; + to: number; + }; + matched: boolean; +} +export declare function matchBrackets(state: EditorState, pos: number, dir: -1 | 1, config?: Config): MatchResult | null; diff --git a/src/vendor/cm-types/language/src/stream-parser.d.ts b/src/vendor/cm-types/language/src/stream-parser.d.ts new file mode 100644 index 0000000..80f6573 --- /dev/null +++ b/src/vendor/cm-types/language/src/stream-parser.d.ts @@ -0,0 +1,25 @@ +import { Tag } from "../../highlight/src/highlight.js"; +import { Language } from "./language"; +import { IndentContext } from "./indent"; +import { StringStream } from "./stringstream"; +export { StringStream }; +export interface StreamParser { + name?: string; + startState?(indentUnit: number): State; + token(stream: StringStream, state: State): string | null; + blankLine?(state: State, indentUnit: number): void; + copyState?(state: State): State; + indent?(state: State, textAfter: string, context: IndentContext): number | null; + languageData?: { + [name: string]: any; + }; + tokenTable?: { + [name: string]: Tag | readonly Tag[]; + }; + mergeTokens?: boolean; +} +export declare class StreamLanguage extends Language { + private constructor(); + static define(spec: StreamParser): StreamLanguage; + get allowsNesting(): boolean; +} diff --git a/src/vendor/cm-types/language/src/stringstream.d.ts b/src/vendor/cm-types/language/src/stringstream.d.ts new file mode 100644 index 0000000..91cae01 --- /dev/null +++ b/src/vendor/cm-types/language/src/stringstream.d.ts @@ -0,0 +1,25 @@ +export declare class StringStream { + string: string; + private tabSize; + indentUnit: number; + private overrideIndent?; + pos: number; + start: number; + private lastColumnPos; + private lastColumnValue; + constructor(string: string, tabSize: number, indentUnit: number, overrideIndent?: number); + eol(): boolean; + sol(): boolean; + peek(): string; + next(): string | void; + eat(match: string | RegExp | ((ch: string) => boolean)): string | void; + eatWhile(match: string | RegExp | ((ch: string) => boolean)): boolean; + eatSpace(): boolean; + skipToEnd(): void; + skipTo(ch: string): boolean | void; + backUp(n: number): void; + column(): number; + indentation(): number; + match(pattern: string | RegExp, consume?: boolean, caseInsensitive?: boolean): boolean | RegExpMatchArray | null; + current(): string; +} diff --git a/src/vendor/cm-types/lr/src/constants.d.ts b/src/vendor/cm-types/lr/src/constants.d.ts new file mode 100644 index 0000000..1657d56 --- /dev/null +++ b/src/vendor/cm-types/lr/src/constants.d.ts @@ -0,0 +1,45 @@ +export declare const enum Action { + ReduceFlag = 65536, + ValueMask = 65535, + ReduceDepthShift = 19, + RepeatFlag = 131072, + GotoFlag = 131072, + StayFlag = 262144 +} +export declare const enum StateFlag { + Skipped = 1, + Accepting = 2 +} +export declare const enum Specialize { + Specialize = 0, + Extend = 1 +} +export declare const enum Term { + Err = 0 +} +export declare const enum Seq { + End = 65535, + Done = 0, + Next = 1, + Other = 2 +} +export declare const enum ParseState { + Flags = 0, + Actions = 1, + Skip = 2, + TokenizerMask = 3, + DefaultReduce = 4, + ForcedReduce = 5, + Size = 6 +} +export declare const enum Encode { + BigValCode = 126, + BigVal = 65535, + Start = 32, + Gap1 = 34,// '"' + Gap2 = 92,// '\\; + Base = 46 +} +export declare const enum File { + Version = 14 +} diff --git a/src/vendor/cm-types/lr/src/decode.d.ts b/src/vendor/cm-types/lr/src/decode.d.ts new file mode 100644 index 0000000..5e34536 --- /dev/null +++ b/src/vendor/cm-types/lr/src/decode.d.ts @@ -0,0 +1,5 @@ +export declare function decodeArray(input: string | T, Type?: { + new (n: number): T; +}): T; diff --git a/src/vendor/cm-types/lr/src/index.d.ts b/src/vendor/cm-types/lr/src/index.d.ts new file mode 100644 index 0000000..5763a26 --- /dev/null +++ b/src/vendor/cm-types/lr/src/index.d.ts @@ -0,0 +1,3 @@ +export { LRParser, ParserConfig, ContextTracker } from "./parse"; +export { InputStream, ExternalTokenizer, LocalTokenGroup } from "./token"; +export { Stack } from "./stack"; diff --git a/src/vendor/cm-types/lr/src/parse.d.ts b/src/vendor/cm-types/lr/src/parse.d.ts new file mode 100644 index 0000000..8a3990c --- /dev/null +++ b/src/vendor/cm-types/lr/src/parse.d.ts @@ -0,0 +1,110 @@ +import { Tree, TreeFragment, NodeSet, NodeType, NodePropSource, Input, PartialParse, Parser, ParseWrapper } from "../../common/src/index.js"; +import { Stack } from "./stack"; +import { Tokenizer, ExternalTokenizer, CachedToken, InputStream } from "./token"; +declare class FragmentCursor { + readonly fragments: readonly TreeFragment[]; + readonly nodeSet: NodeSet; + i: number; + fragment: TreeFragment | null; + safeFrom: number; + safeTo: number; + trees: Tree[]; + start: number[]; + index: number[]; + nextStart: number; + constructor(fragments: readonly TreeFragment[], nodeSet: NodeSet); + nextFragment(): void; + nodeAt(pos: number): Tree | null; +} +declare class TokenCache { + readonly stream: InputStream; + tokens: CachedToken[]; + mainToken: CachedToken | null; + actions: number[]; + constructor(parser: LRParser, stream: InputStream); + getActions(stack: Stack): number[]; + getMainToken(stack: Stack): CachedToken; + updateCachedToken(token: CachedToken, tokenizer: Tokenizer, stack: Stack): void; + putAction(action: number, token: number, end: number, index: number): number; + addActions(stack: Stack, token: number, end: number, index: number): number; +} +export declare class Parse implements PartialParse { + readonly parser: LRParser; + readonly input: Input; + readonly ranges: readonly { + from: number; + to: number; + }[]; + stacks: Stack[]; + recovering: number; + fragments: FragmentCursor | null; + nextStackID: number; + minStackPos: number; + reused: Tree[]; + stream: InputStream; + tokens: TokenCache; + topTerm: number; + stoppedAt: null | number; + lastBigReductionStart: number; + lastBigReductionSize: number; + bigReductionCount: number; + constructor(parser: LRParser, input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]); + get parsedPos(): number; + advance(): Tree; + stopAt(pos: number): void; + private advanceStack; + private advanceFully; + private runRecovery; + stackToTree(stack: Stack): Tree; + private stackID; +} +export declare class Dialect { + readonly source: string | undefined; + readonly flags: readonly boolean[]; + readonly disabled: null | Uint8Array; + constructor(source: string | undefined, flags: readonly boolean[], disabled: null | Uint8Array); + allows(term: number): boolean; +} +export declare class ContextTracker { + constructor(spec: { + start: T; + shift?(context: T, term: number, stack: Stack, input: InputStream): T; + reduce?(context: T, term: number, stack: Stack, input: InputStream): T; + reuse?(context: T, node: Tree, stack: Stack, input: InputStream): T; + hash?(context: T): number; + strict?: boolean; + }); +} +export interface ParserConfig { + props?: readonly NodePropSource[]; + top?: string; + dialect?: string; + tokenizers?: { + from: ExternalTokenizer; + to: ExternalTokenizer; + }[]; + specializers?: { + from: (value: string, stack: Stack) => number; + to: (value: string, stack: Stack) => number; + }[]; + contextTracker?: ContextTracker; + strict?: boolean; + wrap?: ParseWrapper; + bufferLength?: number; +} +export declare class LRParser extends Parser { + readonly nodeSet: NodeSet; + createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]): PartialParse; + configure(config: ParserConfig): LRParser; + hasWrappers(): boolean; + getName(term: number): string; + get topNode(): NodeType; + static deserialize(spec: any): LRParser; +} +export {}; diff --git a/src/vendor/cm-types/lr/src/stack.d.ts b/src/vendor/cm-types/lr/src/stack.d.ts new file mode 100644 index 0000000..8fe3dfc --- /dev/null +++ b/src/vendor/cm-types/lr/src/stack.d.ts @@ -0,0 +1,38 @@ +import { BufferCursor } from "../../common/src/index.js"; +export declare const enum Lookahead { + Margin = 25 +} +export declare class Stack { + pos: number; + get context(): any; + canShift(term: number): boolean; + get parser(): import("./parse").LRParser; + dialectEnabled(dialectID: number): boolean; + private shiftContext; + private reduceContext; + private updateContext; +} +export declare const enum Recover { + Insert = 200, + Delete = 190, + Reduce = 100, + MaxNext = 4, + MaxInsertStackDepth = 300, + DampenInsertStackDepth = 120, + MinBigReduction = 2000 +} +export declare class StackBufferCursor implements BufferCursor { + stack: Stack; + pos: number; + index: number; + buffer: number[]; + constructor(stack: Stack, pos: number, index: number); + static create(stack: Stack, pos?: number): StackBufferCursor; + maybeNext(): void; + get id(): number; + get start(): number; + get end(): number; + get size(): number; + next(): void; + fork(): StackBufferCursor; +} diff --git a/src/vendor/cm-types/lr/src/token.d.ts b/src/vendor/cm-types/lr/src/token.d.ts new file mode 100644 index 0000000..7d77824 --- /dev/null +++ b/src/vendor/cm-types/lr/src/token.d.ts @@ -0,0 +1,46 @@ +import { Stack } from "./stack"; +export declare class CachedToken { + start: number; + value: number; + end: number; + extended: number; + lookAhead: number; + mask: number; + context: number; +} +export declare class InputStream { + private chunk2; + private chunk2Pos; + next: number; + pos: number; + private rangeIndex; + private range; + peek(offset: number): any; + acceptToken(token: number, endOffset?: number): void; + acceptTokenTo(token: number, endPos: number): void; + private getChunk; + private readNext; + advance(n?: number): number; + private setDone; +} +export interface Tokenizer { +} +export declare class LocalTokenGroup implements Tokenizer { + readonly precTable: number; + readonly elseToken?: number; + contextual: boolean; + fallback: boolean; + extend: boolean; + readonly data: Readonly; + constructor(data: Readonly | string, precTable: number, elseToken?: number); + token(input: InputStream, stack: Stack): void; +} +interface ExternalOptions { + contextual?: boolean; + fallback?: boolean; + extend?: boolean; +} +export declare class ExternalTokenizer { + constructor(token: (input: InputStream, stack: Stack) => void, options?: ExternalOptions); +} +export {}; diff --git a/src/vendor/cm-types/search/src/cursor.d.ts b/src/vendor/cm-types/search/src/cursor.d.ts new file mode 100644 index 0000000..5f1bd64 --- /dev/null +++ b/src/vendor/cm-types/search/src/cursor.d.ts @@ -0,0 +1,28 @@ +import { Text } from "../../state/src/index.js"; +export declare class SearchCursor implements Iterator<{ + from: number; + to: number; +}> { + private test?; + private iter; + value: { + from: number; + to: number; + }; + done: boolean; + private matches; + private buffer; + private bufferPos; + private bufferStart; + private normalize; + private query; + constructor(text: Text, query: string, from?: number, to?: number, normalize?: (string: string) => string, test?: (from: number, to: number, buffer: string, bufferPos: number) => boolean); + private peek; + next(): this; + nextOverlapping(): this; + private match; + [Symbol.iterator]: () => Iterator<{ + from: number; + to: number; + }>; +} diff --git a/src/vendor/cm-types/search/src/goto-line.d.ts b/src/vendor/cm-types/search/src/goto-line.d.ts new file mode 100644 index 0000000..2a525d3 --- /dev/null +++ b/src/vendor/cm-types/search/src/goto-line.d.ts @@ -0,0 +1,2 @@ +import { Command } from "../../view/src/index.js"; +export declare const gotoLine: Command; diff --git a/src/vendor/cm-types/search/src/index.d.ts b/src/vendor/cm-types/search/src/index.d.ts new file mode 100644 index 0000000..24d3fb5 --- /dev/null +++ b/src/vendor/cm-types/search/src/index.d.ts @@ -0,0 +1,5 @@ +export * from "./search"; +export * from "./cursor"; +export * from "./regexp"; +export * from "./goto-line"; +export * from "./selection-match"; diff --git a/src/vendor/cm-types/search/src/regexp.d.ts b/src/vendor/cm-types/search/src/regexp.d.ts new file mode 100644 index 0000000..d05c08c --- /dev/null +++ b/src/vendor/cm-types/search/src/regexp.d.ts @@ -0,0 +1,35 @@ +import { Text } from "../../state/src/index.js"; +export interface RegExpCursorOptions { + ignoreCase?: boolean; + test?: (from: number, to: number, match: RegExpExecArray) => boolean; +} +export declare class RegExpCursor implements Iterator<{ + from: number; + to: number; + match: RegExpExecArray; +}> { + private text; + private to; + private iter; + private re; + private test?; + private curLine; + private curLineStart; + private matchPos; + done: boolean; + value: { + from: number; + to: number; + match: RegExpExecArray; + }; + constructor(text: Text, query: string, options?: RegExpCursorOptions, from?: number, to?: number); + private getLine; + private nextLine; + next(): this; + [Symbol.iterator]: () => Iterator<{ + from: number; + to: number; + match: RegExpExecArray; + }>; +} +export declare function validRegExp(source: string): boolean; diff --git a/src/vendor/cm-types/search/src/search.d.ts b/src/vendor/cm-types/search/src/search.d.ts new file mode 100644 index 0000000..4ebc6ab --- /dev/null +++ b/src/vendor/cm-types/search/src/search.d.ts @@ -0,0 +1,54 @@ +import { EditorView, Command, KeyBinding, Panel } from "../../view/src/index.js"; +import { EditorState, StateEffect, SelectionRange, StateCommand, Extension, Text } from "../../state/src/index.js"; +import { SearchCursor } from "./cursor"; +import { RegExpCursor } from "./regexp"; +import { gotoLine } from "./goto-line"; +import { selectNextOccurrence } from "./selection-match"; +export { highlightSelectionMatches } from "./selection-match"; +export { SearchCursor, RegExpCursor, gotoLine, selectNextOccurrence }; +interface SearchConfig { + top?: boolean; + caseSensitive?: boolean; + literal?: boolean; + wholeWord?: boolean; + regexp?: boolean; + createPanel?: (view: EditorView) => Panel; + scrollToMatch?: (range: SelectionRange, view: EditorView) => StateEffect; +} +export declare function search(config?: SearchConfig): Extension; +export declare class SearchQuery { + readonly search: string; + readonly caseSensitive: boolean; + readonly literal: boolean; + readonly regexp: boolean; + readonly replace: string; + readonly valid: boolean; + readonly wholeWord: boolean; + readonly test: ((match: string, state: EditorState, from: number, to: number) => boolean) | undefined; + constructor(config: { + search: string; + caseSensitive?: boolean; + literal?: boolean; + regexp?: boolean; + replace?: string; + wholeWord?: boolean; + test?: (match: string, state: EditorState, from: number, to: number) => boolean; + }); + eq(other: SearchQuery): boolean; + getCursor(state: EditorState | Text, from?: number, to?: number): Iterator<{ + from: number; + to: number; + }>; +} +export declare const setSearchQuery: import("entry").StateEffectType; +export declare function getSearchQuery(state: EditorState): SearchQuery; +export declare function searchPanelOpen(state: EditorState): boolean; +export declare const findNext: Command; +export declare const findPrevious: Command; +export declare const selectMatches: Command; +export declare const selectSelectionMatches: StateCommand; +export declare const replaceNext: Command; +export declare const replaceAll: Command; +export declare const openSearchPanel: Command; +export declare const closeSearchPanel: Command; +export declare const searchKeymap: readonly KeyBinding[]; diff --git a/src/vendor/cm-types/search/src/selection-match.d.ts b/src/vendor/cm-types/search/src/selection-match.d.ts new file mode 100644 index 0000000..ff0c76e --- /dev/null +++ b/src/vendor/cm-types/search/src/selection-match.d.ts @@ -0,0 +1,10 @@ +import { Extension, StateCommand } from "../../state/src/index.js"; +type HighlightOptions = { + highlightWordAroundCursor?: boolean; + minSelectionLength?: number; + maxMatches?: number; + wholeWords?: boolean; +}; +export declare function highlightSelectionMatches(options?: HighlightOptions): Extension; +export declare const selectNextOccurrence: StateCommand; +export {}; diff --git a/src/vendor/cm-types/state/src/change.d.ts b/src/vendor/cm-types/state/src/change.d.ts new file mode 100644 index 0000000..abebc97 --- /dev/null +++ b/src/vendor/cm-types/state/src/change.d.ts @@ -0,0 +1,42 @@ +import { Text } from "./text"; +export declare const DefaultSplit: RegExp; +export declare enum MapMode { + Simple = 0, + TrackDel = 1, + TrackBefore = 2, + TrackAfter = 3 +} +export declare class ChangeDesc { + get length(): number; + get newLength(): number; + get empty(): boolean; + iterGaps(f: (posA: number, posB: number, length: number) => void): void; + iterChangedRanges(f: (fromA: number, toA: number, fromB: number, toB: number) => void, individual?: boolean): void; + get invertedDesc(): ChangeDesc; + composeDesc(other: ChangeDesc): ChangeDesc; + mapDesc(other: ChangeDesc, before?: boolean): ChangeDesc; + mapPos(pos: number, assoc?: number): number; + mapPos(pos: number, assoc: number, mode: MapMode): number | null; + touchesRange(from: number, to?: number): boolean | "cover"; + toJSON(): readonly number[]; + static fromJSON(json: any): ChangeDesc; +} +export type ChangeSpec = { + from: number; + to?: number; + insert?: string | Text; +} | ChangeSet | readonly ChangeSpec[]; +export declare class ChangeSet extends ChangeDesc { + private constructor(); + apply(doc: Text): Text; + mapDesc(other: ChangeDesc, before?: boolean): ChangeDesc; + invert(doc: Text): ChangeSet; + compose(other: ChangeSet): ChangeSet; + map(other: ChangeDesc, before?: boolean): ChangeSet; + iterChanges(f: (fromA: number, toA: number, fromB: number, toB: number, inserted: Text) => void, individual?: boolean): void; + get desc(): ChangeDesc; + toJSON(): any; + static of(changes: ChangeSpec, length: number, lineSep?: string): ChangeSet; + static empty(length: number): ChangeSet; + static fromJSON(json: any): ChangeSet; +} diff --git a/src/vendor/cm-types/state/src/char.d.ts b/src/vendor/cm-types/state/src/char.d.ts new file mode 100644 index 0000000..c01ee83 --- /dev/null +++ b/src/vendor/cm-types/state/src/char.d.ts @@ -0,0 +1,4 @@ +export declare function findClusterBreak(str: string, pos: number, forward?: boolean, includeExtending?: boolean): number; +export declare function codePointAt(str: string, pos: number): number; +export declare function fromCodePoint(code: number): string; +export declare function codePointSize(code: number): 1 | 2; diff --git a/src/vendor/cm-types/state/src/charcategory.d.ts b/src/vendor/cm-types/state/src/charcategory.d.ts new file mode 100644 index 0000000..4339cda --- /dev/null +++ b/src/vendor/cm-types/state/src/charcategory.d.ts @@ -0,0 +1,6 @@ +export declare enum CharCategory { + Word = 0, + Space = 1, + Other = 2 +} +export declare function makeCategorizer(wordChars: string): (char: string) => CharCategory; diff --git a/src/vendor/cm-types/state/src/column.d.ts b/src/vendor/cm-types/state/src/column.d.ts new file mode 100644 index 0000000..76eff07 --- /dev/null +++ b/src/vendor/cm-types/state/src/column.d.ts @@ -0,0 +1,2 @@ +export declare function countColumn(string: string, tabSize: number, to?: number): number; +export declare function findColumn(string: string, col: number, tabSize: number, strict?: boolean): number; diff --git a/src/vendor/cm-types/state/src/config.d.ts b/src/vendor/cm-types/state/src/config.d.ts new file mode 100644 index 0000000..a0d0216 --- /dev/null +++ b/src/vendor/cm-types/state/src/config.d.ts @@ -0,0 +1,4 @@ +export declare function combineConfig(configs: readonly Partial[], defaults: Partial, // Should hold only the optional properties of Config, but I haven't managed to express that +combine?: { + [P in keyof Config]?: (first: Config[P], second: Config[P]) => Config[P]; +}): Config; diff --git a/src/vendor/cm-types/state/src/extension.d.ts b/src/vendor/cm-types/state/src/extension.d.ts new file mode 100644 index 0000000..8713b4c --- /dev/null +++ b/src/vendor/cm-types/state/src/extension.d.ts @@ -0,0 +1,18 @@ +import { EditorState } from "./state"; +import { Transaction, TransactionSpec } from "./transaction"; +import { Facet } from "./facet"; +export declare const languageData: Facet<(state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; +}[], readonly ((state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; +}[])[]>; +export type StateCommand = (target: { + state: EditorState; + dispatch: (transaction: Transaction) => void; +}) => boolean; +export declare const allowMultipleSelections: Facet; +export declare const lineSeparator: Facet; +export declare const changeFilter: Facet<(tr: Transaction) => boolean | readonly number[], readonly ((tr: Transaction) => boolean | readonly number[])[]>; +export declare const transactionFilter: Facet<(tr: Transaction) => TransactionSpec | readonly TransactionSpec[], readonly ((tr: Transaction) => TransactionSpec | readonly TransactionSpec[])[]>; +export declare const transactionExtender: Facet<(tr: Transaction) => Pick | null, readonly ((tr: Transaction) => Pick | null)[]>; +export declare const readOnly: Facet; diff --git a/src/vendor/cm-types/state/src/facet.d.ts b/src/vendor/cm-types/state/src/facet.d.ts new file mode 100644 index 0000000..ea72179 --- /dev/null +++ b/src/vendor/cm-types/state/src/facet.d.ts @@ -0,0 +1,115 @@ +import { Transaction, StateEffect } from "./transaction"; +import { EditorState } from "./state"; +type FacetConfig = { + combine?: (value: readonly Input[]) => Output; + compare?: (a: Output, b: Output) => boolean; + compareInput?: (a: Input, b: Input) => boolean; + static?: boolean; + enables?: Extension | ((self: Facet) => Extension); +}; +export declare class Facet implements FacetReader { + private isStatic; + private constructor(); + get reader(): FacetReader; + static define(config?: FacetConfig): Facet; + of(value: Input): Extension; + compute(deps: readonly Slot[], get: (state: EditorState) => Input): Extension; + computeN(deps: readonly Slot[], get: (state: EditorState) => readonly Input[]): Extension; + from(field: StateField): Extension; + from(field: StateField, get: (value: T) => Input): Extension; + tag: Output; +} +export type FacetReader = { + tag: Output; +}; +type Slot = FacetReader | StateField | "doc" | "selection"; +declare const enum Provider { + Static = 0, + Single = 1, + Multi = 2 +} +declare class FacetProvider { + readonly dependencies: readonly Slot[]; + readonly facet: Facet; + readonly type: Provider; + readonly value: ((state: EditorState) => Input) | ((state: EditorState) => readonly Input[]) | Input; + readonly id: number; + extension: Extension; + constructor(dependencies: readonly Slot[], facet: Facet, type: Provider, value: ((state: EditorState) => Input) | ((state: EditorState) => readonly Input[]) | Input); + dynamicSlot(addresses: { + [id: number]: number; + }): DynamicSlot; +} +type StateFieldSpec = { + create: (state: EditorState) => Value; + update: (value: Value, transaction: Transaction) => Value; + compare?: (a: Value, b: Value) => boolean; + provide?: (field: StateField) => Extension; + toJSON?: (value: Value, state: EditorState) => any; + fromJSON?: (json: any, state: EditorState) => Value; +}; +export declare class StateField { + private createF; + private updateF; + private compareF; + private constructor(); + static define(config: StateFieldSpec): StateField; + private create; + init(create: (state: EditorState) => Value): Extension; + get extension(): Extension; +} +export type Extension = { + extension: Extension; +} | readonly Extension[]; +export declare const Prec: { + highest: (ext: Extension) => Extension; + high: (ext: Extension) => Extension; + default: (ext: Extension) => Extension; + low: (ext: Extension) => Extension; + lowest: (ext: Extension) => Extension; +}; +export declare class Compartment { + of(ext: Extension): Extension; + reconfigure(content: Extension): StateEffect; + get(state: EditorState): Extension | undefined; +} +export declare class CompartmentInstance { + readonly compartment: Compartment; + readonly inner: Extension; + constructor(compartment: Compartment, inner: Extension); + extension: Extension; +} +export interface DynamicSlot { + create(state: EditorState): SlotStatus; + update(state: EditorState, tr: Transaction): SlotStatus; + reconfigure(state: EditorState, oldState: EditorState): SlotStatus; +} +export declare class Configuration { + readonly base: Extension; + readonly compartments: Map; + readonly dynamicSlots: DynamicSlot[]; + readonly address: { + [id: number]: number; + }; + readonly staticValues: readonly any[]; + readonly facets: { + [id: number]: readonly FacetProvider[]; + }; + readonly statusTemplate: SlotStatus[]; + constructor(base: Extension, compartments: Map, dynamicSlots: DynamicSlot[], address: { + [id: number]: number; + }, staticValues: readonly any[], facets: { + [id: number]: readonly FacetProvider[]; + }); + staticFacet(facet: Facet): any; + static resolve(base: Extension, compartments: Map, oldState?: EditorState): Configuration; +} +export declare const enum SlotStatus { + Unresolved = 0, + Changed = 1, + Computed = 2, + Computing = 4 +} +export declare function ensureAddr(state: EditorState, addr: number): number; +export declare function getAddr(state: EditorState, addr: number): any; +export {}; diff --git a/src/vendor/cm-types/state/src/index.d.ts b/src/vendor/cm-types/state/src/index.d.ts new file mode 100644 index 0000000..d7ca635 --- /dev/null +++ b/src/vendor/cm-types/state/src/index.d.ts @@ -0,0 +1,12 @@ +export { EditorStateConfig, EditorState } from "./state"; +export { StateCommand } from "./extension"; +export { Facet, FacetReader, StateField, Extension, Prec, Compartment } from "./facet"; +export { EditorSelection, SelectionRange } from "./selection"; +export { Transaction, TransactionSpec, Annotation, AnnotationType, StateEffect, StateEffectType } from "./transaction"; +export { combineConfig } from "./config"; +export { ChangeSpec, ChangeSet, ChangeDesc, MapMode } from "./change"; +export { CharCategory } from "./charcategory"; +export { RangeValue, Range, RangeSet, RangeCursor, RangeSetBuilder, RangeComparator, SpanIterator } from "./rangeset"; +export { findClusterBreak, codePointAt, fromCodePoint, codePointSize } from "./char"; +export { countColumn, findColumn } from "./column"; +export { Line, TextIterator, Text } from "./text"; diff --git a/src/vendor/cm-types/state/src/rangeset.d.ts b/src/vendor/cm-types/state/src/rangeset.d.ts new file mode 100644 index 0000000..b8bcc64 --- /dev/null +++ b/src/vendor/cm-types/state/src/rangeset.d.ts @@ -0,0 +1,73 @@ +import { ChangeDesc, MapMode } from "./change"; +export declare abstract class RangeValue { + eq(other: RangeValue): boolean; + startSide: number; + endSide: number; + mapMode: MapMode; + point: boolean; + range(from: number, to?: number): Range; +} +export declare class Range { + readonly from: number; + readonly to: number; + readonly value: T; + private constructor(); +} +export interface RangeComparator { + compareRange(from: number, to: number, activeA: T[], activeB: T[]): void; + comparePoint(from: number, to: number, pointA: T | null, pointB: T | null): void; + boundChange?(pos: number): void; +} +export interface SpanIterator { + span(from: number, to: number, active: readonly T[], openStart: number): void; + point(from: number, to: number, value: T, active: readonly T[], openStart: number, index: number): void; +} +export interface RangeCursor { + next(): void; + goto(pos: number): void; + value: T | null; + from: number; + to: number; + rank: number; +} +type RangeSetUpdate = { + add?: readonly Range[]; + sort?: boolean; + filter?: (from: number, to: number, value: T) => boolean; + filterFrom?: number; + filterTo?: number; +}; +export declare class RangeSet { + private constructor(); + get size(): number; + update(updateSpec: RangeSetUpdate): RangeSet; + map(changes: ChangeDesc): RangeSet; + between(from: number, to: number, f: (from: number, to: number, value: T) => void | false): void; + iter(from?: number): RangeCursor; + static iter(sets: readonly RangeSet[], from?: number): RangeCursor; + static compare(oldSets: readonly RangeSet[], newSets: readonly RangeSet[], textDiff: ChangeDesc, comparator: RangeComparator, minPointSize?: number): void; + static eq(oldSets: readonly RangeSet[], newSets: readonly RangeSet[], from?: number, to?: number): boolean; + static spans(sets: readonly RangeSet[], from: number, to: number, iterator: SpanIterator, minPointSize?: number): number; + static of(ranges: readonly Range[] | Range, sort?: boolean): RangeSet; + static join(sets: readonly RangeSet[]): RangeSet; + static empty: RangeSet; +} +export declare class RangeSetBuilder { + private chunks; + private chunkPos; + private chunkStart; + private last; + private lastFrom; + private lastTo; + private from; + private to; + private value; + private maxPoint; + private setMaxPoint; + private nextLayer; + private finishChunk; + constructor(); + add(from: number, to: number, value: T): void; + finish(): RangeSet; +} +export {}; diff --git a/src/vendor/cm-types/state/src/selection.d.ts b/src/vendor/cm-types/state/src/selection.d.ts new file mode 100644 index 0000000..9841b56 --- /dev/null +++ b/src/vendor/cm-types/state/src/selection.d.ts @@ -0,0 +1,36 @@ +import { ChangeDesc } from "./change"; +export declare class SelectionRange { + readonly from: number; + readonly to: number; + private flags; + private constructor(); + get anchor(): number; + get head(): number; + get empty(): boolean; + get assoc(): -1 | 0 | 1; + get bidiLevel(): number | null; + get goalColumn(): number; + map(change: ChangeDesc, assoc?: number): SelectionRange; + extend(from: number, to?: number, assoc?: number): SelectionRange; + eq(other: SelectionRange, includeAssoc?: boolean): boolean; + toJSON(): any; + static fromJSON(json: any): SelectionRange; +} +export declare class EditorSelection { + readonly ranges: readonly SelectionRange[]; + readonly mainIndex: number; + private constructor(); + map(change: ChangeDesc, assoc?: number): EditorSelection; + eq(other: EditorSelection, includeAssoc?: boolean): boolean; + get main(): SelectionRange; + asSingle(): EditorSelection; + addRange(range: SelectionRange, main?: boolean): EditorSelection; + replaceRange(range: SelectionRange, which?: number): EditorSelection; + toJSON(): any; + static fromJSON(json: any): EditorSelection; + static single(anchor: number, head?: number): EditorSelection; + static create(ranges: readonly SelectionRange[], mainIndex?: number): EditorSelection; + static cursor(pos: number, assoc?: number, bidiLevel?: number, goalColumn?: number): SelectionRange; + static range(anchor: number, head: number, goalColumn?: number, bidiLevel?: number, assoc?: number): SelectionRange; +} +export declare function checkSelection(selection: EditorSelection, docLength: number): void; diff --git a/src/vendor/cm-types/state/src/state.d.ts b/src/vendor/cm-types/state/src/state.d.ts new file mode 100644 index 0000000..9e1d31b --- /dev/null +++ b/src/vendor/cm-types/state/src/state.d.ts @@ -0,0 +1,67 @@ +import { Text } from "./text"; +import { ChangeSet, ChangeSpec } from "./change"; +import { EditorSelection, SelectionRange } from "./selection"; +import { Transaction, TransactionSpec, StateEffect } from "./transaction"; +import { Facet, FacetReader, Extension, StateField } from "./facet"; +import { CharCategory } from "./charcategory"; +export interface EditorStateConfig { + doc?: string | Text; + selection?: EditorSelection | { + anchor: number; + head?: number; + }; + extensions?: Extension; +} +export declare class EditorState { + readonly doc: Text; + readonly selection: EditorSelection; + private constructor(); + field(field: StateField): T; + field(field: StateField, require: false): T | undefined; + update(...specs: readonly TransactionSpec[]): Transaction; + replaceSelection(text: string | Text): TransactionSpec; + changeByRange(f: (range: SelectionRange) => { + range: SelectionRange; + changes?: ChangeSpec; + effects?: StateEffect | readonly StateEffect[]; + }): { + changes: ChangeSet; + selection: EditorSelection; + effects: readonly StateEffect[]; + }; + changes(spec?: ChangeSpec): ChangeSet; + toText(string: string): Text; + sliceDoc(from?: number, to?: number): string; + facet(facet: FacetReader): Output; + toJSON(fields?: { + [prop: string]: StateField; + }): any; + static fromJSON(json: any, config?: EditorStateConfig, fields?: { + [prop: string]: StateField; + }): EditorState; + static create(config?: EditorStateConfig): EditorState; + static allowMultipleSelections: Facet; + static tabSize: Facet; + get tabSize(): number; + static lineSeparator: Facet; + get lineBreak(): string; + static readOnly: Facet; + get readOnly(): boolean; + static phrases: Facet<{ + [key: string]: string; + }, readonly { + [key: string]: string; + }[]>; + phrase(phrase: string, ...insert: any[]): string; + static languageData: Facet<(state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; + }[], readonly ((state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; + }[])[]>; + languageDataAt(name: string, pos: number, side?: -1 | 0 | 1): readonly T[]; + charCategorizer(at: number): (char: string) => CharCategory; + wordAt(pos: number): SelectionRange | null; + static changeFilter: Facet<(tr: Transaction) => boolean | readonly number[], readonly ((tr: Transaction) => boolean | readonly number[])[]>; + static transactionFilter: Facet<(tr: Transaction) => TransactionSpec | readonly TransactionSpec[], readonly ((tr: Transaction) => TransactionSpec | readonly TransactionSpec[])[]>; + static transactionExtender: Facet<(tr: Transaction) => Pick | null, readonly ((tr: Transaction) => Pick | null)[]>; +} diff --git a/src/vendor/cm-types/state/src/text.d.ts b/src/vendor/cm-types/state/src/text.d.ts new file mode 100644 index 0000000..059f1bd --- /dev/null +++ b/src/vendor/cm-types/state/src/text.d.ts @@ -0,0 +1,33 @@ +export interface TextIterator extends Iterator, Iterable { + next(skip?: number): this; + value: string; + done: boolean; + lineBreak: boolean; +} +export declare abstract class Text implements Iterable { + abstract readonly length: number; + abstract readonly lines: number; + lineAt(pos: number): Line; + line(n: number): Line; + replace(from: number, to: number, text: Text): Text; + append(other: Text): Text; + slice(from: number, to?: number): Text; + abstract sliceString(from: number, to?: number, lineSep?: string): string; + eq(other: Text): boolean; + iter(dir?: 1 | -1): TextIterator; + iterRange(from: number, to?: number): TextIterator; + iterLines(from?: number, to?: number): TextIterator; + toString(): string; + toJSON(): string[]; + abstract readonly children: readonly Text[] | null; + [Symbol.iterator]: () => Iterator; + static of(text: readonly string[]): Text; + static empty: Text; +} +export declare class Line { + readonly from: number; + readonly to: number; + readonly number: number; + readonly text: string; + get length(): number; +} diff --git a/src/vendor/cm-types/state/src/transaction.d.ts b/src/vendor/cm-types/state/src/transaction.d.ts new file mode 100644 index 0000000..3af0e44 --- /dev/null +++ b/src/vendor/cm-types/state/src/transaction.d.ts @@ -0,0 +1,65 @@ +import { ChangeSet, ChangeDesc, ChangeSpec } from "./change"; +import { EditorState } from "./state"; +import { EditorSelection } from "./selection"; +import { Extension } from "./facet"; +import { Text } from "./text"; +export declare class Annotation { + readonly type: AnnotationType; + readonly value: T; + static define(): AnnotationType; + private _isAnnotation; +} +export declare class AnnotationType { + of(value: T): Annotation; +} +interface StateEffectSpec { + map?: (value: Value, mapping: ChangeDesc) => Value | undefined; +} +export declare class StateEffectType { + readonly map: (value: any, mapping: ChangeDesc) => any | undefined; + of(value: Value): StateEffect; +} +export declare class StateEffect { + readonly value: Value; + map(mapping: ChangeDesc): StateEffect | undefined; + is(type: StateEffectType): this is StateEffect; + static define(spec?: StateEffectSpec): StateEffectType; + static mapEffects(effects: readonly StateEffect[], mapping: ChangeDesc): any[] | readonly StateEffect[]; + static reconfigure: StateEffectType; + static appendConfig: StateEffectType; +} +export interface TransactionSpec { + changes?: ChangeSpec; + selection?: EditorSelection | { + anchor: number; + head?: number; + } | undefined; + effects?: StateEffect | readonly StateEffect[]; + annotations?: Annotation | readonly Annotation[]; + userEvent?: string; + scrollIntoView?: boolean; + filter?: boolean; + sequential?: boolean; +} +export declare class Transaction { + readonly startState: EditorState; + readonly changes: ChangeSet; + readonly selection: EditorSelection | undefined; + readonly effects: readonly StateEffect[]; + readonly scrollIntoView: boolean; + private constructor(); + get newDoc(): Text; + get newSelection(): EditorSelection; + get state(): EditorState; + annotation(type: AnnotationType): T | undefined; + get docChanged(): boolean; + get reconfigured(): boolean; + isUserEvent(event: string): boolean; + static time: AnnotationType; + static userEvent: AnnotationType; + static addToHistory: AnnotationType; + static remote: AnnotationType; +} +export declare function resolveTransaction(state: EditorState, specs: readonly TransactionSpec[], filter: boolean): Transaction; +export declare function asArray(value: undefined | T | readonly T[]): readonly T[]; +export {}; diff --git a/src/vendor/cm-types/style-mod/src/style-mod.d.ts b/src/vendor/cm-types/style-mod/src/style-mod.d.ts new file mode 100644 index 0000000..081f0f2 --- /dev/null +++ b/src/vendor/cm-types/style-mod/src/style-mod.d.ts @@ -0,0 +1,16 @@ +export class StyleModule { + constructor(spec: {[selector: string]: StyleSpec}, options?: { + finish?(sel: string): string + }) + getRules(): string + static mount( + root: Document | ShadowRoot | DocumentOrShadowRoot, + module: StyleModule | ReadonlyArray, + options?: {nonce?: string} + ): void + static newName(): string +} + +export type StyleSpec = { + [propOrSelector: string]: string | number | StyleSpec | null +} diff --git a/src/vendor/cm-types/view/src/active-line.d.ts b/src/vendor/cm-types/view/src/active-line.d.ts new file mode 100644 index 0000000..0513c79 --- /dev/null +++ b/src/vendor/cm-types/view/src/active-line.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function highlightActiveLine(): Extension; diff --git a/src/vendor/cm-types/view/src/attributes.d.ts b/src/vendor/cm-types/view/src/attributes.d.ts new file mode 100644 index 0000000..e362da8 --- /dev/null +++ b/src/vendor/cm-types/view/src/attributes.d.ts @@ -0,0 +1,9 @@ +export type Attrs = { + [name: string]: string; +}; +export declare function combineAttrs(source: Attrs, target: Attrs): Attrs; +export declare const noAttrs: any; +export declare function attrsEq(a: Attrs | null, b: Attrs | null, ignore?: string): boolean; +export declare function setAttrs(dom: HTMLElement, attrs: Attrs): void; +export declare function updateAttrs(dom: HTMLElement, prev: Attrs | null, attrs: Attrs | null): boolean; +export declare function getAttrs(dom: HTMLElement): any; diff --git a/src/vendor/cm-types/view/src/bidi.d.ts b/src/vendor/cm-types/view/src/bidi.d.ts new file mode 100644 index 0000000..61279b2 --- /dev/null +++ b/src/vendor/cm-types/view/src/bidi.d.ts @@ -0,0 +1,23 @@ +import { SelectionRange, Line } from "../../state/src/index.js"; +export declare enum Direction { + LTR = 0, + RTL = 1 +} +export declare class BidiSpan { + readonly from: number; + readonly to: number; + readonly level: number; + get dir(): Direction; +} +export type Isolate = { + from: number; + to: number; + direction: Direction; + inner: readonly Isolate[]; +}; +export declare function isolatesEq(a: readonly Isolate[], b: readonly Isolate[]): boolean; +export declare function computeOrder(line: string, direction: Direction, isolates: readonly Isolate[]): BidiSpan[]; +export declare function trivialOrder(length: number): BidiSpan[]; +export declare let movedOver: string; +export declare function moveVisually(line: Line, order: readonly BidiSpan[], dir: Direction, start: SelectionRange, forward: boolean): SelectionRange; +export declare function autoDirection(text: string, from: number, to: number): Direction; diff --git a/src/vendor/cm-types/view/src/browser.d.ts b/src/vendor/cm-types/view/src/browser.d.ts new file mode 100644 index 0000000..ecb6929 --- /dev/null +++ b/src/vendor/cm-types/view/src/browser.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + mac: boolean; + windows: boolean; + linux: boolean; + ie: boolean; + ie_version: any; + gecko: boolean; + gecko_version: number; + chrome: boolean; + chrome_version: number; + ios: boolean; + android: boolean; + webkit: boolean; + webkit_version: number; + safari: boolean; + safari_version: number; + tabSize: string; +}; +export default _default; diff --git a/src/vendor/cm-types/view/src/buildtile.d.ts b/src/vendor/cm-types/view/src/buildtile.d.ts new file mode 100644 index 0000000..faa474e --- /dev/null +++ b/src/vendor/cm-types/view/src/buildtile.d.ts @@ -0,0 +1,95 @@ +import { Tile, CompositeTile, DocTile, LineTile, MarkTile, WidgetTile, WidgetBufferTile, TextTile, TileFlag, TilePointer, TileWalker } from "./tile"; +import { ChangedRange } from "./extension"; +import { Attrs } from "./attributes"; +import { DecorationSet, MarkDecoration, WidgetType, BlockWrapper } from "./decoration"; +import { RangeSet, TextIterator, Text as DocText, RangeCursor } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { Composition } from "./docview"; +export declare const enum Reused { + Full = 1, + DOM = 2 +} +declare class OpenWrapper { + readonly from: number; + readonly to: number; + readonly wrapper: BlockWrapper; + readonly rank: number; + constructor(from: number, to: number, wrapper: BlockWrapper, rank: number); +} +declare class TileBuilder { + readonly cache: TileCache; + readonly root: DocTile; + readonly blockWrappers: RangeCursor; + curLine: LineTile | null; + lastBlock: LineTile | WidgetTile | null; + afterWidget: WidgetTile | null; + pos: number; + wrappers: OpenWrapper[]; + wrapperPos: number; + constructor(cache: TileCache, root: DocTile, blockWrappers: RangeCursor); + addText(text: string, marks: MarkDecoration[], openStart: number, tile?: TextTile): void; + addComposition(composition: Composition, context: { + marks: MarkTile[]; + line: LineTile; + }): void; + addInlineWidget(widget: WidgetTile, marks: MarkDecoration[], openStart: number): void; + addMark(tile: MarkTile, marks: MarkDecoration[], openStart: number): void; + addBlockWidget(widget: WidgetTile): void; + continueWidget(length: number): void; + addLineStart(attrs: Attrs | null, dom?: HTMLElement): void; + addLine(tile: LineTile): void; + addBreak(): void; + addLineStartIfNotCovered(attrs: Attrs | null): void; + ensureLine(attrs: Attrs | null): void; + ensureMarks(marks: MarkDecoration[], openStart: number): CompositeTile; + endLine(): void; + updateBlockWrappers(): void; + getBlockPos(): CompositeTile; + blockPosCovered(): boolean; + getBuffer(side: -1 | 1): WidgetBufferTile; + flushBuffer(): void; +} +declare class TextStream { + cursor: TextIterator; + skipCount: number; + text: string; + textOff: number; + constructor(doc: DocText); + skip(len: number): void; + next(maxLen: number): null | string; +} +declare class TileCache { + readonly view: EditorView; + buckets: Tile[][]; + index: number[]; + reused: Map; + constructor(view: EditorView); + add(tile: Tile): void; + find(cls: new (...args: any) => Cls, test?: (a: Cls) => boolean, type?: Reused): Cls | null; + findWidget(widget: WidgetType, length: number, flags: TileFlag): WidgetTile; + reuse(tile: T): T; + maybeReuse(tile: T, type?: Reused): T["dom"] | undefined; + clear(): void; +} +export declare class TileUpdate { + readonly view: EditorView; + readonly decorations: readonly DecorationSet[]; + readonly disallowBlockEffectsFor: boolean[]; + text: TextStream; + builder: TileBuilder; + old: TilePointer; + openWidget: boolean; + openMarks: number; + cache: TileCache; + reuseWalker: TileWalker; + constructor(view: EditorView, old: DocTile, blockWrappers: readonly RangeSet[], decorations: readonly DecorationSet[], disallowBlockEffectsFor: boolean[]); + run(changes: readonly ChangedRange[], composition: Composition | null): DocTile; + preserve(length: number, incStart: boolean, incEnd: boolean): void; + emit(from: number, to: number): void; + forward(from: number, to: number, side?: -1 | 1): void; + getCompositionContext(text: Text): { + line: LineTile; + marks: MarkTile[]; + }; +} +export {}; diff --git a/src/vendor/cm-types/view/src/cursor.d.ts b/src/vendor/cm-types/view/src/cursor.d.ts new file mode 100644 index 0000000..c22ece4 --- /dev/null +++ b/src/vendor/cm-types/view/src/cursor.d.ts @@ -0,0 +1,26 @@ +import { EditorState, EditorSelection, SelectionRange, RangeSet } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { BlockInfo } from "./heightmap"; +declare global { + interface Selection { + modify(action: string, direction: string, granularity: string): void; + } +} +export declare function groupAt(state: EditorState, pos: number, bias?: 1 | -1): SelectionRange; +export declare function blockAt(view: EditorView, pos: number, side: -1 | 1): BlockInfo; +export declare function moveToLineBoundary(view: EditorView, start: SelectionRange, forward: boolean, includeWrap: boolean): SelectionRange; +export declare function moveByChar(view: EditorView, start: SelectionRange, forward: boolean, by?: (initial: string) => (next: string) => boolean): SelectionRange; +export declare function byGroup(view: EditorView, pos: number, start: string): (next: string) => boolean; +export declare function moveVertically(view: EditorView, start: SelectionRange, forward: boolean, distance?: number): SelectionRange; +export declare function skipAtomicRanges(atoms: readonly RangeSet[], pos: number, bias: -1 | 0 | 1): number; +export declare function skipAtomsForSelection(atoms: readonly RangeSet[], sel: EditorSelection): EditorSelection; +export declare function skipAtoms(view: EditorView, oldPos: SelectionRange, pos: SelectionRange): SelectionRange; +export declare class PosAssoc { + readonly pos: number; + readonly assoc: -1 | 1; + constructor(pos: number, assoc: -1 | 1); +} +export declare function posAtCoords(view: EditorView, coords: { + x: number; + y: number; +}, precise: boolean, scanY?: 1 | -1): PosAssoc | null; diff --git a/src/vendor/cm-types/view/src/decoration.d.ts b/src/vendor/cm-types/view/src/decoration.d.ts new file mode 100644 index 0000000..900966c --- /dev/null +++ b/src/vendor/cm-types/view/src/decoration.d.ts @@ -0,0 +1,104 @@ +import { RangeValue, Range, RangeSet } from "../../state/src/index.js"; +import { Direction } from "./bidi"; +import { Attrs } from "./attributes"; +import { EditorView } from "./editorview"; +import { Rect } from "./dom"; +interface MarkDecorationSpec { + inclusive?: boolean; + inclusiveStart?: boolean; + inclusiveEnd?: boolean; + attributes?: { + [key: string]: string; + }; + class?: string; + tagName?: string; + bidiIsolate?: Direction | null; + [other: string]: any; +} +interface WidgetDecorationSpec { + widget: WidgetType; + side?: number; + inlineOrder?: boolean; + block?: boolean; + [other: string]: any; +} +interface ReplaceDecorationSpec { + widget?: WidgetType; + inclusive?: boolean; + inclusiveStart?: boolean; + inclusiveEnd?: boolean; + block?: boolean; + [other: string]: any; +} +interface LineDecorationSpec { + attributes?: { + [key: string]: string; + }; + class?: string; + [other: string]: any; +} +export declare abstract class WidgetType { + abstract toDOM(view: EditorView): HTMLElement; + eq(widget: WidgetType): boolean; + updateDOM(dom: HTMLElement, view: EditorView, from: this): boolean; + get estimatedHeight(): number; + get lineBreaks(): number; + ignoreEvent(event: Event): boolean; + coordsAt(dom: HTMLElement, pos: number, side: number): Rect | null; + destroy(dom: HTMLElement): void; +} +export type DecorationSet = RangeSet; +export declare enum BlockType { + Text = 0, + WidgetBefore = 1, + WidgetAfter = 2, + WidgetRange = 3 +} +export declare abstract class Decoration extends RangeValue { + readonly spec: any; + protected constructor(startSide: number, endSide: number, widget: WidgetType | null, spec: any); + abstract eq(other: Decoration): boolean; + static mark(spec: MarkDecorationSpec): Decoration; + static widget(spec: WidgetDecorationSpec): Decoration; + static replace(spec: ReplaceDecorationSpec): Decoration; + static line(spec: LineDecorationSpec): Decoration; + static set(of: Range | readonly Range[], sort?: boolean): DecorationSet; + static none: DecorationSet; +} +export declare class MarkDecoration extends Decoration { + tagName: string; + attrs: Attrs; + constructor(spec: MarkDecorationSpec); + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare class LineDecoration extends Decoration { + constructor(spec: LineDecorationSpec); + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare class PointDecoration extends Decoration { + block: boolean; + readonly isReplace: boolean; + constructor(spec: any, startSide: number, endSide: number, block: boolean, widget: WidgetType | null, isReplace: boolean); + get type(): BlockType.WidgetBefore | BlockType.WidgetAfter | BlockType.WidgetRange; + get heightRelevant(): boolean; + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare function addRange(from: number, to: number, ranges: number[], margin?: number): void; +interface BlockWrapperSpec { + tagName: string; + attributes?: { + [key: string]: string; + }; +} +export declare class BlockWrapper extends RangeValue { + readonly tagName: string; + readonly attributes: Attrs; + private constructor(); + eq(other: RangeValue): boolean; + static create(spec: BlockWrapperSpec): BlockWrapper; + static set(of: Range | readonly Range[], sort?: boolean): RangeSet; +} +export {}; diff --git a/src/vendor/cm-types/view/src/dialog.d.ts b/src/vendor/cm-types/view/src/dialog.d.ts new file mode 100644 index 0000000..d52ea40 --- /dev/null +++ b/src/vendor/cm-types/view/src/dialog.d.ts @@ -0,0 +1,20 @@ +import { StateEffect } from "../../state/src/index.js"; +import { Panel } from "./panel"; +import { EditorView } from "./editorview"; +type DialogConfig = { + content?: (view: EditorView, close: () => void) => HTMLElement; + label?: string; + input?: { + [attr: string]: string; + }; + submitLabel?: string; + class?: string; + focus?: string | boolean; + top?: boolean; +}; +export declare function showDialog(view: EditorView, config: DialogConfig): { + close: StateEffect; + result: Promise; +}; +export declare function getDialog(view: EditorView, className: string): Panel; +export {}; diff --git a/src/vendor/cm-types/view/src/docview.d.ts b/src/vendor/cm-types/view/src/docview.d.ts new file mode 100644 index 0000000..cf387f2 --- /dev/null +++ b/src/vendor/cm-types/view/src/docview.d.ts @@ -0,0 +1,67 @@ +import { RangeSet, SelectionRange } from "../../state/src/index.js"; +import { DecorationSet, BlockWrapper } from "./decoration"; +import { Rect, DOMSelectionState, DOMPos } from "./dom"; +import { ViewUpdate, ChangedRange, ScrollTarget } from "./extension"; +import { EditorView } from "./editorview"; +import { Direction } from "./bidi"; +import { LineTile, DocTile } from "./tile"; +export type Composition = { + range: ChangedRange; + text: Text; +}; +export declare class DocView { + readonly view: EditorView; + tile: DocTile; + decorations: readonly DecorationSet[]; + blockWrappers: readonly RangeSet[]; + dynamicDecorationMap: boolean[]; + domChanged: { + newSel: SelectionRange | null; + } | null; + hasComposition: { + from: number; + to: number; + } | null; + editContextFormatting: DecorationSet; + lastCompositionAfterCursor: boolean; + minWidth: number; + minWidthFrom: number; + minWidthTo: number; + impreciseAnchor: DOMPos | null; + impreciseHead: DOMPos | null; + forceSelection: boolean; + lastUpdate: number; + constructor(view: EditorView); + update(update: ViewUpdate): boolean; + private updateInner; + private updateEditContextFormatting; + updateSelection(mustRead?: boolean, fromPointer?: boolean): void; + suppressWidgetCursorChange(sel: DOMSelectionState, cursor: SelectionRange): boolean; + enforceCursorAssoc(): void; + posFromDOM(node: Node, offset: number): number; + domAtPos(pos: number, side: number): DOMPos; + inlineDOMNearPos(pos: number, side: number): DOMPos; + coordsAt(pos: number, side: number): Rect | null; + lineAt(pos: number, side: number): LineTile; + coordsForChar(pos: number): DOMRect; + measureVisibleLineHeights(viewport: { + from: number; + to: number; + }): number[]; + textDirectionAt(pos: number): Direction; + measureTextSize(): { + lineHeight: number; + charWidth: number; + textHeight: number; + }; + computeBlockGapDeco(): DecorationSet; + updateDeco(): void; + scrollIntoView(target: ScrollTarget): boolean; + lineHasWidget(pos: number): boolean; + destroy(): void; +} +export declare function findCompositionNode(view: EditorView, headPos: number): { + from: number; + to: number; + node: Text; +} | null; diff --git a/src/vendor/cm-types/view/src/dom.d.ts b/src/vendor/cm-types/view/src/dom.d.ts new file mode 100644 index 0000000..fce002e --- /dev/null +++ b/src/vendor/cm-types/view/src/dom.d.ts @@ -0,0 +1,68 @@ +export declare function getSelection(root: DocumentOrShadowRoot): Selection | null; +export declare function contains(dom: Node, node: Node | null): boolean; +export declare function hasSelection(dom: HTMLElement, selection: SelectionRange): boolean; +export declare function clientRectsFor(dom: Node): DOMRectList; +export declare function isEquivalentPosition(node: Node, off: number, targetNode: Node | null, targetOff: number): boolean; +export declare function domIndex(node: Node): number; +export declare function isBlockElement(node: Node): boolean; +export declare function maxOffset(node: Node): number; +export interface Rect { + readonly left: number; + readonly right: number; + readonly top: number; + readonly bottom: number; +} +export declare function flattenRect(rect: Rect, left: boolean): { + left: number; + right: number; + top: number; + bottom: number; +}; +export type ScrollStrategy = "nearest" | "start" | "end" | "center"; +export declare function getScale(elt: HTMLElement, rect: DOMRect): { + scaleX: number; + scaleY: number; +}; +export declare function scrollRectIntoView(dom: HTMLElement, rect: Rect, side: -1 | 1, x: ScrollStrategy, y: ScrollStrategy, xMargin: number, yMargin: number, ltr: boolean): void; +export declare function scrollableParents(dom: HTMLElement, getX?: boolean): { + x: HTMLElement; + y: HTMLElement; +}; +export interface SelectionRange { + focusNode: Node | null; + focusOffset: number; + anchorNode: Node | null; + anchorOffset: number; +} +export declare class DOMSelectionState implements SelectionRange { + anchorNode: Node | null; + anchorOffset: number; + focusNode: Node | null; + focusOffset: number; + eq(domSel: SelectionRange): boolean; + setRange(range: SelectionRange): void; + set(anchorNode: Node | null, anchorOffset: number, focusNode: Node | null, focusOffset: number): void; +} +export declare function focusPreventScroll(dom: HTMLElement): any; +export declare function textRange(node: Text, from: number, to?: number): Range; +export declare function dispatchKey(elt: HTMLElement, name: string, code: number, mods?: KeyboardEvent): boolean; +export declare function getRoot(node: Node | null | undefined): DocumentOrShadowRoot | null; +export declare function clearAttributes(node: HTMLElement): void; +export declare function atElementStart(doc: HTMLElement, selection: SelectionRange): boolean; +export declare function isScrolledToBottom(elt: HTMLElement | Window): boolean; +export declare function textNodeBefore(startNode: Node, startOffset: number): { + node: Text; + offset: number; +} | null; +export declare function textNodeAfter(startNode: Node, startOffset: number): { + node: Text; + offset: number; +} | null; +export declare class DOMPos { + readonly node: Node; + readonly offset: number; + readonly precise: boolean; + constructor(node: Node, offset: number, precise?: boolean); + static before(dom: Node, precise?: boolean): DOMPos; + static after(dom: Node, precise?: boolean): DOMPos; +} diff --git a/src/vendor/cm-types/view/src/domchange.d.ts b/src/vendor/cm-types/view/src/domchange.d.ts new file mode 100644 index 0000000..387862d --- /dev/null +++ b/src/vendor/cm-types/view/src/domchange.d.ts @@ -0,0 +1,27 @@ +import { EditorView } from "./editorview"; +import { EditorSelection, SelectionRange, Text } from "../../state/src/index.js"; +export declare class DOMChange { + readonly typeOver: boolean; + bounds: { + startDOM: Node | null; + endDOM: Node | null; + from: number; + to: number; + } | null; + text: string; + newSel: EditorSelection | null; + domChanged: boolean; + constructor(view: EditorView, start: number, end: number, typeOver: boolean); +} +export declare function applyDOMChange(view: EditorView, domChange: DOMChange): boolean; +export declare function applyDOMChangeInner(view: EditorView, change: { + from: number; + to: number; + insert: Text; +}, newSel: EditorSelection | null, lastKey?: number): boolean; +export declare function findDiff(a: string, b: string, preferredPos: number, preferredSide: string | null): { + from: number; + toA: number; + toB: number; +} | null; +export declare function sameSelPos(selection: EditorSelection, range: SelectionRange): boolean; diff --git a/src/vendor/cm-types/view/src/domobserver.d.ts b/src/vendor/cm-types/view/src/domobserver.d.ts new file mode 100644 index 0000000..29bffc1 --- /dev/null +++ b/src/vendor/cm-types/view/src/domobserver.d.ts @@ -0,0 +1,109 @@ +import { EditorView } from "./editorview"; +import { ViewUpdate, MeasureRequest } from "./extension"; +import { DOMSelectionState } from "./dom"; +import { DOMChange } from "./domchange"; +import type { EditContext } from "./editcontext"; +import { Text, EditorState } from "../../state/src/index.js"; +export declare class DOMObserver { + private view; + dom: HTMLElement; + win: Window; + observer: MutationObserver; + active: boolean; + editContext: EditContextManager | null; + selectionRange: DOMSelectionState; + selectionChanged: boolean; + delayedFlush: number; + resizeTimeout: number; + queue: MutationRecord[]; + delayedAndroidKey: { + key: string; + keyCode: number; + force: boolean; + } | null; + flushingAndroidKey: number; + lastChange: number; + onCharData: any; + scrollTargets: HTMLElement[]; + intersection: IntersectionObserver | null; + resizeScroll: ResizeObserver | null; + intersecting: boolean; + gapIntersection: IntersectionObserver | null; + gaps: readonly HTMLElement[]; + printQuery: MediaQueryList | null; + parentCheck: number; + constructor(view: EditorView); + onScrollChanged(e: Event): void; + onScroll(e: Event): void; + onResize(): void; + onPrint(event: Event): void; + updateGaps(gaps: readonly HTMLElement[]): void; + onSelectionChange(event: Event): void; + readSelectionRange(): boolean; + setSelectionRange(anchor: { + node: Node; + offset: number; + }, head: { + node: Node; + offset: number; + }): void; + clearSelectionRange(): void; + listenForScroll(): void; + ignore(f: () => T): T; + start(): void; + stop(): void; + clear(): void; + delayAndroidKey(key: string, keyCode: number): void; + clearDelayedAndroidKey(): void; + flushSoon(): void; + forceFlush(): void; + pendingRecords(): MutationRecord[]; + processRecords(): { + from: number; + to: number; + typeOver: boolean; + }; + readChange(): DOMChange; + flush(readSelection?: boolean): boolean; + readMutation(rec: MutationRecord): { + from: number; + to: number; + typeOver: boolean; + } | null; + setWindow(win: Window): void; + addWindowListeners(win: Window): void; + removeWindowListeners(win: Window): void; + update(update: ViewUpdate): void; + destroy(): void; +} +declare class EditContextManager { + editContext: EditContext; + measureReq: MeasureRequest; + from: number; + to: number; + pendingContextChange: { + from: number; + to: number; + insert: Text; + } | null; + handlers: { + [name: string]: (e: any) => void; + }; + composing: { + contextBase: number; + editorBase: number; + drifted: boolean; + } | null; + constructor(view: EditorView); + applyEdits(update: ViewUpdate): boolean; + update(update: ViewUpdate): void; + resetRange(state: EditorState): void; + reset(state: EditorState): void; + revertPending(state: EditorState): void; + setSelection(state: EditorState): void; + rangeIsValid(state: EditorState): boolean; + toEditorPos(contextPos: number, clipLen?: number): number; + toContextPos(editorPos: number): number; + destroy(): void; +} +export {}; diff --git a/src/vendor/cm-types/view/src/domreader.d.ts b/src/vendor/cm-types/view/src/domreader.d.ts new file mode 100644 index 0000000..662056b --- /dev/null +++ b/src/vendor/cm-types/view/src/domreader.d.ts @@ -0,0 +1,22 @@ +import { EditorView } from "./editorview"; +export declare const LineBreakPlaceholder = "\uFFFF"; +export declare class DOMReader { + private points; + private view; + text: string; + lineSeparator: string | undefined; + constructor(points: DOMPoint[], view: EditorView); + append(text: string): void; + lineBreak(): void; + readRange(start: Node | null, end: Node | null): this; + readTextNode(node: Text): void; + readNode(node: Node): void; + findPointBefore(node: Node, next: Node | null): void; + findPointInside(node: Node, length: number): void; +} +export declare class DOMPoint { + readonly node: Node; + readonly offset: number; + pos: number; + constructor(node: Node, offset: number); +} diff --git a/src/vendor/cm-types/view/src/draw-selection.d.ts b/src/vendor/cm-types/view/src/draw-selection.d.ts new file mode 100644 index 0000000..65c816a --- /dev/null +++ b/src/vendor/cm-types/view/src/draw-selection.d.ts @@ -0,0 +1,9 @@ +import { Extension, EditorState } from "../../state/src/index.js"; +type SelectionConfig = { + cursorBlinkRate?: number; + drawRangeCursor?: boolean; + iosSelectionHandles?: boolean; +}; +export declare function drawSelection(config?: SelectionConfig): Extension; +export declare function getDrawSelectionConfig(state: EditorState): SelectionConfig; +export {}; diff --git a/src/vendor/cm-types/view/src/dropcursor.d.ts b/src/vendor/cm-types/view/src/dropcursor.d.ts new file mode 100644 index 0000000..761ff5f --- /dev/null +++ b/src/vendor/cm-types/view/src/dropcursor.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function dropCursor(): Extension; diff --git a/src/vendor/cm-types/view/src/editorview.d.ts b/src/vendor/cm-types/view/src/editorview.d.ts new file mode 100644 index 0000000..41bb33e --- /dev/null +++ b/src/vendor/cm-types/view/src/editorview.d.ts @@ -0,0 +1,185 @@ +import { EditorState, Transaction, TransactionSpec, Extension, SelectionRange, StateEffect, Facet, Line, EditorStateConfig } from "../../state/src/index.js"; +import { StyleModule, StyleSpec } from "../../style-mod/src/style-mod.js"; +import { Rect, ScrollStrategy } from "./dom"; +import { BlockInfo } from "./heightmap"; +import { ViewUpdate, AttrSource, ViewPlugin, PluginValue, MeasureRequest, ScrollTarget } from "./extension"; +import { BidiSpan, Direction } from "./bidi"; +export interface EditorViewConfig extends EditorStateConfig { + state?: EditorState; + parent?: Element | DocumentFragment; + root?: Document | ShadowRoot; + scrollTo?: StateEffect; + dispatchTransactions?: (trs: readonly Transaction[], view: EditorView) => void; + dispatch?: (tr: Transaction, view: EditorView) => void; +} +export declare const enum UpdateState { + Idle = 0,// Not updating + Measuring = 1,// In the layout-reading phase of a layout check + Updating = 2 +} +export declare class EditorView { + get state(): EditorState; + get viewport(): { + from: number; + to: number; + }; + get visibleRanges(): readonly { + from: number; + to: number; + }[]; + get inView(): boolean; + get composing(): boolean; + get compositionStarted(): boolean; + private dispatchTransactions; + private _root; + get root(): DocumentOrShadowRoot; + readonly dom: HTMLElement; + readonly scrollDOM: HTMLElement; + readonly contentDOM: HTMLElement; + private announceDOM; + private plugins; + private pluginMap; + private editorAttrs; + private contentAttrs; + private styleModules; + private bidiCache; + private destroyed; + constructor(config?: EditorViewConfig); + dispatch(tr: Transaction): void; + dispatch(trs: readonly Transaction[]): void; + dispatch(...specs: TransactionSpec[]): void; + update(transactions: readonly Transaction[]): void; + setState(newState: EditorState): void; + private updatePlugins; + private docViewUpdate; + get themeClasses(): string; + private updateAttrs; + private showAnnouncements; + private mountStyles; + private readMeasured; + requestMeasure(request?: MeasureRequest): void; + plugin(plugin: ViewPlugin): T | null; + get documentTop(): number; + get documentPadding(): { + top: number; + bottom: number; + }; + get scaleX(): number; + get scaleY(): number; + elementAtHeight(height: number): BlockInfo; + lineBlockAtHeight(height: number): BlockInfo; + get viewportLineBlocks(): BlockInfo[]; + lineBlockAt(pos: number): BlockInfo; + get contentHeight(): number; + moveByChar(start: SelectionRange, forward: boolean, by?: (initial: string) => (next: string) => boolean): SelectionRange; + moveByGroup(start: SelectionRange, forward: boolean): SelectionRange; + visualLineSide(line: Line, end: boolean): SelectionRange; + moveToLineBoundary(start: SelectionRange, forward: boolean, includeWrap?: boolean): SelectionRange; + moveVertically(start: SelectionRange, forward: boolean, distance?: number): SelectionRange; + domAtPos(pos: number, side?: -1 | 1): { + node: Node; + offset: number; + }; + posAtDOM(node: Node, offset?: number): number; + posAtCoords(coords: { + x: number; + y: number; + }, precise: false): number; + posAtCoords(coords: { + x: number; + y: number; + }): number | null; + posAndSideAtCoords(coords: { + x: number; + y: number; + }, precise: false): { + pos: number; + assoc: -1 | 1; + }; + posAndSideAtCoords(coords: { + x: number; + y: number; + }): { + pos: number; + assoc: -1 | 1; + } | null; + coordsAtPos(pos: number, side?: -1 | 1): Rect | null; + coordsForChar(pos: number): Rect | null; + get defaultCharacterWidth(): number; + get defaultLineHeight(): number; + get textDirection(): Direction; + textDirectionAt(pos: number): Direction; + get lineWrapping(): boolean; + bidiSpans(line: Line): readonly BidiSpan[]; + get hasFocus(): boolean; + focus(): void; + setRoot(root: Document | ShadowRoot): void; + destroy(): void; + static scrollIntoView(pos: number | SelectionRange, options?: { + y?: ScrollStrategy; + x?: ScrollStrategy; + yMargin?: number; + xMargin?: number; + }): StateEffect; + scrollSnapshot(): StateEffect; + setTabFocusMode(to?: boolean | number): void; + static styleModule: Facet; + static domEventHandlers(handlers: DOMEventHandlers): Extension; + static domEventObservers(observers: DOMEventHandlers): Extension; + static inputHandler: Facet<(view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean, readonly ((view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean)[]>; + static clipboardInputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; + static clipboardOutputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; + static scrollHandler: Facet<(view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; + }) => boolean, readonly ((view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; + }) => boolean)[]>; + static focusChangeEffect: Facet<(state: EditorState, focusing: boolean) => StateEffect | null, readonly ((state: EditorState, focusing: boolean) => StateEffect | null)[]>; + static perLineTextDirection: Facet; + static exceptionSink: Facet<(exception: any) => void, readonly ((exception: any) => void)[]>; + static updateListener: Facet<(update: ViewUpdate) => void, readonly ((update: ViewUpdate) => void)[]>; + static editable: Facet; + static mouseSelectionStyle: Facet; + static dragMovesSelection: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; + static clickAddsSelectionRange: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; + static decorations: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static blockWrappers: Facet | ((view: EditorView) => import("entry").RangeSet), readonly (import("entry").RangeSet | ((view: EditorView) => import("entry").RangeSet))[]>; + static outerDecorations: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static atomicRanges: Facet<(view: EditorView) => import("entry").RangeSet, readonly ((view: EditorView) => import("entry").RangeSet)[]>; + static bidiIsolatedRanges: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static cursorScrollMargin: Facet; + static scrollMargins: Facet<(view: EditorView) => Partial | null, readonly ((view: EditorView) => Partial | null)[]>; + static theme(spec: { + [selector: string]: StyleSpec; + }, options?: { + dark?: boolean; + }): Extension; + static darkTheme: Facet; + static baseTheme(spec: { + [selector: string]: StyleSpec; + }): Extension; + static cspNonce: Facet; + static contentAttributes: Facet; + static editorAttributes: Facet; + static lineWrapping: Extension; + static announce: import("entry").StateEffectType; + static findFromDOM(dom: HTMLElement): EditorView | null; +} +export interface DOMEventMap extends HTMLElementEventMap { + [other: string]: any; +} +export type DOMEventHandlers = { + [event in keyof DOMEventMap]?: (this: This, event: DOMEventMap[event], view: EditorView) => boolean | void; +}; diff --git a/src/vendor/cm-types/view/src/extension.d.ts b/src/vendor/cm-types/view/src/extension.d.ts new file mode 100644 index 0000000..06ab954 --- /dev/null +++ b/src/vendor/cm-types/view/src/extension.d.ts @@ -0,0 +1,137 @@ +import { EditorState, Transaction, ChangeSet, ChangeDesc, Facet, Line, StateEffect, Extension, SelectionRange, RangeSet } from "../../state/src/index.js"; +import { StyleModule } from "../../style-mod/src/style-mod.js"; +import { DecorationSet, BlockWrapper } from "./decoration"; +import { EditorView, DOMEventHandlers } from "./editorview"; +import { Attrs } from "./attributes"; +import { Isolate } from "./bidi"; +import { Rect, ScrollStrategy } from "./dom"; +import { MakeSelectionStyle } from "./input"; +export type Command = (target: EditorView) => boolean; +export declare const clickAddsSelectionRange: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; +export declare const dragMovesSelection: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; +export declare const mouseSelectionStyle: Facet; +export declare const exceptionSink: Facet<(exception: any) => void, readonly ((exception: any) => void)[]>; +export declare const updateListener: Facet<(update: ViewUpdate) => void, readonly ((update: ViewUpdate) => void)[]>; +export declare const inputHandler: Facet<(view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean, readonly ((view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean)[]>; +export declare const focusChangeEffect: Facet<(state: EditorState, focusing: boolean) => StateEffect | null, readonly ((state: EditorState, focusing: boolean) => StateEffect | null)[]>; +export declare const clipboardInputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; +export declare const clipboardOutputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; +export declare const perLineTextDirection: Facet; +export declare const nativeSelectionHidden: Facet; +export declare const scrollHandler: Facet<(view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; +}) => boolean, readonly ((view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; +}) => boolean)[]>; +export declare class ScrollTarget { + readonly range: SelectionRange; + readonly y: ScrollStrategy; + readonly x: ScrollStrategy; + readonly yMargin: number; + readonly xMargin: number; + readonly isSnapshot: boolean; + constructor(range: SelectionRange, y: ScrollStrategy, x: ScrollStrategy, yMargin: number, xMargin: number, isSnapshot?: boolean); + map(changes: ChangeDesc): ScrollTarget; + clip(state: EditorState): ScrollTarget; +} +export declare const scrollIntoView: import("entry").StateEffectType; +export declare const setEditContextFormatting: import("entry").StateEffectType; +export declare function logException(state: EditorState, exception: any, context?: string): void; +export declare const editable: Facet; +export interface PluginValue extends Object { + update?(update: ViewUpdate): void; + docViewUpdate?(view: EditorView): void; + destroy?(): void; +} +type PluginSource = { + plugin: ViewPlugin; + arg: Arg; +}; +export declare const viewPlugin: Facet, readonly PluginSource[]>; +export interface PluginSpec { + eventHandlers?: DOMEventHandlers; + eventObservers?: DOMEventHandlers; + provide?: (plugin: ViewPlugin) => Extension; + decorations?: (value: V) => DecorationSet; +} +export declare class ViewPlugin { + extension: Arg extends undefined ? Extension : null; + private baseExtensions; + private constructor(); + of(arg: Arg): Extension; + static define(create: (view: EditorView, arg: Arg) => V, spec?: PluginSpec): ViewPlugin; + static fromClass(cls: { + new (view: EditorView, arg: Arg): V; + }, spec?: PluginSpec): ViewPlugin; +} +export declare class PluginInstance { + spec: PluginSource | null; + mustUpdate: ViewUpdate | null; + value: PluginValue | null; + constructor(spec: PluginSource | null); + get plugin(): ViewPlugin; + update(view: EditorView): this; + destroy(view: EditorView): void; + deactivate(): void; +} +export interface MeasureRequest { + read(view: EditorView): T; + write?(measure: T, view: EditorView): void; + key?: any; +} +export type AttrSource = Attrs | ((view: EditorView) => Attrs | null); +export declare const editorAttributes: Facet; +export declare const contentAttributes: Facet; +export declare const decorations: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare const blockWrappers: Facet | ((view: EditorView) => RangeSet), readonly (RangeSet | ((view: EditorView) => RangeSet))[]>; +export declare const outerDecorations: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare const atomicRanges: Facet<(view: EditorView) => RangeSet, readonly ((view: EditorView) => RangeSet)[]>; +export declare const bidiIsolatedRanges: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare function getIsolatedRanges(view: EditorView, line: Line): readonly Isolate[]; +export declare const scrollMargins: Facet<(view: EditorView) => Partial | null, readonly ((view: EditorView) => Partial | null)[]>; +export declare function getScrollMargins(view: EditorView): { + left: number; + right: number; + top: number; + bottom: number; +}; +export declare const styleModule: Facet; +export declare const enum UpdateFlag { + Focus = 1, + Height = 2, + Viewport = 4, + ViewportMoved = 8, + Geometry = 16 +} +export declare class ChangedRange { + readonly fromA: number; + readonly toA: number; + readonly fromB: number; + readonly toB: number; + constructor(fromA: number, toA: number, fromB: number, toB: number); + join(other: ChangedRange): ChangedRange; + addToSet(set: ChangedRange[]): ChangedRange[]; + static extendWithRanges(diff: readonly ChangedRange[], ranges: number[]): readonly ChangedRange[]; +} +export declare class ViewUpdate { + readonly view: EditorView; + readonly state: EditorState; + readonly transactions: readonly Transaction[]; + readonly changes: ChangeSet; + readonly startState: EditorState; + private constructor(); + get viewportChanged(): boolean; + get viewportMoved(): boolean; + get heightChanged(): boolean; + get geometryChanged(): boolean; + get focusChanged(): boolean; + get docChanged(): boolean; + get selectionSet(): boolean; +} +export {}; diff --git a/src/vendor/cm-types/view/src/gutter.d.ts b/src/vendor/cm-types/view/src/gutter.d.ts new file mode 100644 index 0000000..1abd377 --- /dev/null +++ b/src/vendor/cm-types/view/src/gutter.d.ts @@ -0,0 +1,41 @@ +import { Facet, Extension, EditorState, RangeValue, RangeSet } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { WidgetType } from "./decoration"; +import { BlockInfo } from "./heightmap"; +export declare abstract class GutterMarker extends RangeValue { + eq(other: GutterMarker): boolean; + toDOM?(view: EditorView): Node; + elementClass: string; + destroy(dom: Node): void; +} +export declare const gutterLineClass: Facet, readonly RangeSet[]>; +export declare const gutterWidgetClass: Facet<(view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null, readonly ((view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null)[]>; +type Handlers = { + [event: string]: (view: EditorView, line: BlockInfo, event: Event) => boolean; +}; +interface GutterConfig { + class?: string; + renderEmptyElements?: boolean; + markers?: (view: EditorView) => (RangeSet | readonly RangeSet[]); + lineMarker?: (view: EditorView, line: BlockInfo, otherMarkers: readonly GutterMarker[]) => GutterMarker | null; + widgetMarker?: (view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null; + lineMarkerChange?: null | ((update: ViewUpdate) => boolean); + initialSpacer?: null | ((view: EditorView) => GutterMarker); + updateSpacer?: null | ((spacer: GutterMarker, update: ViewUpdate) => GutterMarker); + domEventHandlers?: Handlers; + side?: "before" | "after"; +} +export declare function gutter(config: GutterConfig): Extension; +export declare function gutters(config?: { + fixed?: boolean; +}): Extension; +interface LineNumberConfig { + formatNumber?: (lineNo: number, state: EditorState) => string; + domEventHandlers?: Handlers; +} +export declare const lineNumberMarkers: Facet, readonly RangeSet[]>; +export declare const lineNumberWidgetMarker: Facet<(view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null, readonly ((view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null)[]>; +export declare function lineNumbers(config?: LineNumberConfig): Extension; +export declare function highlightActiveLineGutter(): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/heightmap.d.ts b/src/vendor/cm-types/view/src/heightmap.d.ts new file mode 100644 index 0000000..f445910 --- /dev/null +++ b/src/vendor/cm-types/view/src/heightmap.d.ts @@ -0,0 +1,71 @@ +import { Text, ChangeSet } from "../../state/src/index.js"; +import { DecorationSet, PointDecoration, BlockType, WidgetType } from "./decoration"; +import { ChangedRange } from "./extension"; +export declare let heightChangeFlag: boolean; +export declare function clearHeightChangeFlag(): void; +export declare class HeightOracle { + lineWrapping: boolean; + doc: Text; + heightSamples: { + [key: number]: boolean; + }; + lineHeight: number; + charWidth: number; + textHeight: number; + lineLength: number; + constructor(lineWrapping: boolean); + heightForGap(from: number, to: number): number; + heightForLine(length: number): number; + setDoc(doc: Text): this; + mustRefreshForWrapping(whiteSpace: string): boolean; + mustRefreshForHeights(lineHeights: number[]): boolean; + refresh(whiteSpace: string, lineHeight: number, charWidth: number, textHeight: number, lineLength: number, knownHeights: number[]): boolean; +} +export declare class MeasuredHeights { + readonly from: number; + readonly heights: number[]; + index: number; + constructor(from: number, heights: number[]); + get more(): boolean; +} +export declare class BlockInfo { + readonly from: number; + readonly length: number; + readonly top: number; + readonly height: number; + readonly _content: readonly BlockInfo[] | PointDecoration | number; + get type(): BlockType | readonly BlockInfo[]; + get to(): number; + get bottom(): number; + get widget(): WidgetType | null; + get widgetLineBreaks(): number; +} +export declare enum QueryType { + ByPos = 0, + ByHeight = 1, + ByPosNoHeight = 2 +} +export declare abstract class HeightMap { + length: number; + height: number; + flags: number; + constructor(length: number, // The number of characters covered + height: number, // Height of this part of the document + flags?: number); + size: number; + get outdated(): boolean; + set outdated(value: boolean); + abstract blockAt(height: number, oracle: HeightOracle, top: number, offset: number): BlockInfo; + abstract lineAt(value: number, type: QueryType, oracle: HeightOracle, top: number, offset: number): BlockInfo; + abstract forEachLine(from: number, to: number, oracle: HeightOracle, top: number, offset: number, f: (line: BlockInfo) => void): void; + abstract updateHeight(oracle: HeightOracle, offset?: number, force?: boolean, measured?: MeasuredHeights): HeightMap; + abstract toString(): void; + setHeight(height: number): void; + replace(_from: number, _to: number, nodes: (HeightMap | null)[]): HeightMap; + decomposeLeft(_to: number, result: (HeightMap | null)[]): void; + decomposeRight(_from: number, result: (HeightMap | null)[]): void; + applyChanges(decorations: readonly DecorationSet[], oldDoc: Text, oracle: HeightOracle, changes: readonly ChangedRange[]): HeightMap; + static empty(): HeightMap; + static of(nodes: (HeightMap | null)[]): HeightMap; +} +export declare function heightRelevantDecoChanges(a: readonly DecorationSet[], b: readonly DecorationSet[], diff: ChangeSet): number[]; diff --git a/src/vendor/cm-types/view/src/highlight-space.d.ts b/src/vendor/cm-types/view/src/highlight-space.d.ts new file mode 100644 index 0000000..ef71faa --- /dev/null +++ b/src/vendor/cm-types/view/src/highlight-space.d.ts @@ -0,0 +1,3 @@ +import { Extension } from "../../state/src/index.js"; +export declare function highlightWhitespace(): Extension; +export declare function highlightTrailingWhitespace(): Extension; diff --git a/src/vendor/cm-types/view/src/index.d.ts b/src/vendor/cm-types/view/src/index.d.ts new file mode 100644 index 0000000..3de254d --- /dev/null +++ b/src/vendor/cm-types/view/src/index.d.ts @@ -0,0 +1,22 @@ +export { EditorView, EditorViewConfig, DOMEventMap, DOMEventHandlers } from "./editorview"; +export { Command, ViewPlugin, PluginValue, PluginSpec, ViewUpdate, logException } from "./extension"; +export { Decoration, DecorationSet, WidgetType, BlockType, BlockWrapper } from "./decoration"; +export { BlockInfo } from "./heightmap"; +export { MouseSelectionStyle } from "./input"; +export { BidiSpan, Direction } from "./bidi"; +export { KeyBinding, keymap, runScopeHandlers } from "./keymap"; +export { drawSelection, getDrawSelectionConfig } from "./draw-selection"; +export { dropCursor } from "./dropcursor"; +export { highlightSpecialChars } from "./special-chars"; +export { scrollPastEnd } from "./scrollpastend"; +export { highlightActiveLine } from "./active-line"; +export { placeholder } from "./placeholder"; +export { Rect } from "./dom"; +export { layer, LayerMarker, RectangleMarker } from "./layer"; +export { MatchDecorator } from "./matchdecorator"; +export { rectangularSelection, crosshairCursor } from "./rectangular-selection"; +export { showTooltip, Tooltip, TooltipView, tooltips, getTooltip, hoverTooltip, HoverTooltipSource, hasHoverTooltips, closeHoverTooltips, repositionTooltips } from "./tooltip"; +export { showPanel, PanelConstructor, Panel, getPanel, panels } from "./panel"; +export { showDialog, getDialog } from "./dialog"; +export { lineNumbers, highlightActiveLineGutter, gutter, gutters, GutterMarker, gutterLineClass, gutterWidgetClass, lineNumberMarkers, lineNumberWidgetMarker } from "./gutter"; +export { highlightWhitespace, highlightTrailingWhitespace } from "./highlight-space"; diff --git a/src/vendor/cm-types/view/src/input.d.ts b/src/vendor/cm-types/view/src/input.d.ts new file mode 100644 index 0000000..5fc127f --- /dev/null +++ b/src/vendor/cm-types/view/src/input.d.ts @@ -0,0 +1,94 @@ +import { EditorSelection, EditorState, SelectionRange, RangeSet, Text } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate, PluginInstance } from "./extension"; +export declare class InputState { + readonly view: EditorView; + lastKeyCode: number; + lastKeyTime: number; + lastTouchTime: number; + lastTouchX: number; + lastTouchY: number; + lastFocusTime: number; + lastScrollTop: number; + lastScrollLeft: number; + lastWheelEvent: number; + pendingIOSKey: undefined | { + key: string; + keyCode: number; + } | KeyboardEvent; + tabFocusMode: number; + lastSelectionOrigin: string | null; + lastSelectionTime: number; + lastContextMenu: number; + scrollHandlers: ((event: Event) => boolean | void)[]; + handlers: { + [event: string]: { + observers: readonly HandlerFunction[]; + handlers: readonly HandlerFunction[]; + }; + }; + composing: number; + compositionFirstChange: boolean | null; + compositionEndedAt: number; + compositionPendingKey: boolean; + compositionPendingChange: boolean; + insertingText: string; + insertingTextAt: number; + mouseSelection: MouseSelection | null; + draggedContent: SelectionRange | null; + notifiedFocused: boolean; + setSelectionOrigin(origin: string): void; + constructor(view: EditorView); + handleEvent(event: Event): void; + runHandlers(type: string, event: Event): void; + ensureHandlers(plugins: readonly PluginInstance[]): void; + keydown(event: KeyboardEvent): boolean; + flushIOSKey(change?: { + from: number; + to: number; + insert: Text; + }): boolean; + ignoreDuringComposition(event: Event): boolean; + startMouseSelection(mouseSelection: MouseSelection): void; + update(update: ViewUpdate): void; + destroy(): void; +} +type HandlerFunction = (view: EditorView, event: Event) => boolean | void; +export declare const modifierCodes: number[]; +export interface MouseSelectionStyle { + get: (curEvent: MouseEvent, extend: boolean, multiple: boolean) => EditorSelection; + update: (update: ViewUpdate) => boolean | void; +} +export type MakeSelectionStyle = (view: EditorView, event: MouseEvent) => MouseSelectionStyle | null; +declare class MouseSelection { + private view; + private startEvent; + private style; + private mustSelect; + dragging: null | boolean; + extend: boolean; + multiple: boolean; + lastEvent: MouseEvent; + scrollParents: { + x: HTMLElement | null; + y: HTMLElement | null; + }; + scrollSpeed: { + x: number; + y: number; + }; + scrolling: number; + atoms: readonly RangeSet[]; + constructor(view: EditorView, startEvent: MouseEvent, style: MouseSelectionStyle, mustSelect: boolean); + start(event: MouseEvent): void; + move(event: MouseEvent): void; + up(event: MouseEvent): void; + destroy(): void; + setScrollSpeed(sx: number, sy: number): void; + scroll(): void; + select(event: MouseEvent): void; + update(update: ViewUpdate): void; +} +export declare const isFocusChange: import("entry").AnnotationType; +export declare function focusChangeTransaction(state: EditorState, focus: boolean): import("entry").Transaction; +export {}; diff --git a/src/vendor/cm-types/view/src/keymap.d.ts b/src/vendor/cm-types/view/src/keymap.d.ts new file mode 100644 index 0000000..b18ee9a --- /dev/null +++ b/src/vendor/cm-types/view/src/keymap.d.ts @@ -0,0 +1,17 @@ +import { EditorView } from "./editorview"; +import { Command } from "./extension"; +import { Facet } from "../../state/src/index.js"; +export interface KeyBinding { + key?: string; + mac?: string; + win?: string; + linux?: string; + run?: Command; + shift?: Command; + any?: (view: EditorView, event: KeyboardEvent) => boolean; + scope?: string; + preventDefault?: boolean; + stopPropagation?: boolean; +} +export declare const keymap: Facet; +export declare function runScopeHandlers(view: EditorView, event: KeyboardEvent, scope: string): boolean; diff --git a/src/vendor/cm-types/view/src/layer.d.ts b/src/vendor/cm-types/view/src/layer.d.ts new file mode 100644 index 0000000..12187ad --- /dev/null +++ b/src/vendor/cm-types/view/src/layer.d.ts @@ -0,0 +1,32 @@ +import { Extension, SelectionRange } from "../../state/src/index.js"; +import { ViewUpdate } from "./extension"; +import { EditorView } from "./editorview"; +export interface LayerMarker { + eq(other: LayerMarker): boolean; + draw(): HTMLElement; + update?(dom: HTMLElement, oldMarker: LayerMarker): boolean; +} +export declare class RectangleMarker implements LayerMarker { + private className; + readonly left: number; + readonly top: number; + readonly width: number | null; + readonly height: number; + constructor(className: string, left: number, top: number, width: number | null, height: number); + draw(): HTMLDivElement; + update(elt: HTMLElement, prev: RectangleMarker): boolean; + private adjust; + eq(p: RectangleMarker): boolean; + static forRange(view: EditorView, className: string, range: SelectionRange): readonly RectangleMarker[]; +} +interface LayerConfig { + above: boolean; + class?: string; + update(update: ViewUpdate, layer: HTMLElement): boolean; + updateOnDocViewUpdate?: boolean; + markers(view: EditorView): readonly LayerMarker[]; + mount?(layer: HTMLElement, view: EditorView): void; + destroy?(layer: HTMLElement, view: EditorView): void; +} +export declare function layer(config: LayerConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/matchdecorator.d.ts b/src/vendor/cm-types/view/src/matchdecorator.d.ts new file mode 100644 index 0000000..99f2682 --- /dev/null +++ b/src/vendor/cm-types/view/src/matchdecorator.d.ts @@ -0,0 +1,19 @@ +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { Decoration, DecorationSet } from "./decoration"; +export declare class MatchDecorator { + private regexp; + private addMatch; + private boundary; + private maxLength; + constructor(config: { + regexp: RegExp; + decoration?: Decoration | ((match: RegExpExecArray, view: EditorView, pos: number) => Decoration | null); + decorate?: (add: (from: number, to: number, decoration: Decoration) => void, from: number, to: number, match: RegExpExecArray, view: EditorView) => void; + boundary?: RegExp; + maxLength?: number; + }); + createDeco(view: EditorView): import("entry").RangeSet; + updateDeco(update: ViewUpdate, deco: DecorationSet): DecorationSet; + private updateRange; +} diff --git a/src/vendor/cm-types/view/src/panel.d.ts b/src/vendor/cm-types/view/src/panel.d.ts new file mode 100644 index 0000000..114bc68 --- /dev/null +++ b/src/vendor/cm-types/view/src/panel.d.ts @@ -0,0 +1,19 @@ +import { Facet, Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +type PanelConfig = { + topContainer?: HTMLElement; + bottomContainer?: HTMLElement; +}; +export declare function panels(config?: PanelConfig): Extension; +export interface Panel { + dom: HTMLElement; + mount?(): void; + update?(update: ViewUpdate): void; + destroy?(): void; + top?: boolean; +} +export declare function getPanel(view: EditorView, panel: PanelConstructor): Panel; +export type PanelConstructor = (view: EditorView) => Panel; +export declare const showPanel: Facet; +export {}; diff --git a/src/vendor/cm-types/view/src/placeholder.d.ts b/src/vendor/cm-types/view/src/placeholder.d.ts new file mode 100644 index 0000000..4d13cda --- /dev/null +++ b/src/vendor/cm-types/view/src/placeholder.d.ts @@ -0,0 +1,3 @@ +import { Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +export declare function placeholder(content: string | HTMLElement | ((view: EditorView) => HTMLElement)): Extension; diff --git a/src/vendor/cm-types/view/src/rectangular-selection.d.ts b/src/vendor/cm-types/view/src/rectangular-selection.d.ts new file mode 100644 index 0000000..41e2ae8 --- /dev/null +++ b/src/vendor/cm-types/view/src/rectangular-selection.d.ts @@ -0,0 +1,7 @@ +import { Extension } from "../../state/src/index.js"; +export declare function rectangularSelection(options?: { + eventFilter?: (event: MouseEvent) => boolean; +}): Extension; +export declare function crosshairCursor(options?: { + key?: "Alt" | "Control" | "Shift" | "Meta"; +}): Extension; diff --git a/src/vendor/cm-types/view/src/scrollpastend.d.ts b/src/vendor/cm-types/view/src/scrollpastend.d.ts new file mode 100644 index 0000000..bf7ca55 --- /dev/null +++ b/src/vendor/cm-types/view/src/scrollpastend.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function scrollPastEnd(): Extension; diff --git a/src/vendor/cm-types/view/src/special-chars.d.ts b/src/vendor/cm-types/view/src/special-chars.d.ts new file mode 100644 index 0000000..9060d84 --- /dev/null +++ b/src/vendor/cm-types/view/src/special-chars.d.ts @@ -0,0 +1,8 @@ +import { Extension } from "../../state/src/index.js"; +interface SpecialCharConfig { + render?: ((code: number, description: string | null, placeholder: string) => HTMLElement) | null; + specialChars?: RegExp; + addSpecialChars?: RegExp | null; +} +export declare function highlightSpecialChars(config?: SpecialCharConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/theme.d.ts b/src/vendor/cm-types/view/src/theme.d.ts new file mode 100644 index 0000000..a353939 --- /dev/null +++ b/src/vendor/cm-types/view/src/theme.d.ts @@ -0,0 +1,15 @@ +import { Facet } from "../../state/src/index.js"; +import { StyleModule, StyleSpec } from "../../style-mod/src/style-mod.js"; +export declare const theme: Facet; +export declare const darkTheme: Facet; +export declare const baseThemeID: string, baseLightID: string, baseDarkID: string; +export declare const lightDarkIDs: { + "&light": string; + "&dark": string; +}; +export declare function buildTheme(main: string, spec: { + [name: string]: StyleSpec; +}, scopes?: { + [name: string]: string; +}): StyleModule; +export declare const baseTheme: StyleModule; diff --git a/src/vendor/cm-types/view/src/tile.d.ts b/src/vendor/cm-types/view/src/tile.d.ts new file mode 100644 index 0000000..e6c3502 --- /dev/null +++ b/src/vendor/cm-types/view/src/tile.d.ts @@ -0,0 +1,161 @@ +import { Text as DocText } from "../../state/src/index.js"; +import { WidgetType, BlockWrapper, MarkDecoration } from "./decoration"; +import { Attrs } from "./attributes"; +import { type EditorView } from "./editorview"; +import { Rect, DOMPos } from "./dom"; +export declare const enum TileFlag { + BreakAfter = 1, + Synced = 2, + AttrsDirty = 4, + Composition = 8, + Before = 16,// Single-point widget before cursor position + After = 32,// Single-point widget after cursor position + PointWidget = 48, + IncStart = 64,// For replace widgets, IncStart/IncEnd encode inclusivity + IncEnd = 128, + Block = 256,// Distinguishes block widgets from non-block widgets + Widget = 496 +} +export declare abstract class Tile { + dom: HTMLElement | Text; + length: number; + flags: TileFlag; + parent: CompositeTile | null; + constructor(dom: HTMLElement | Text, length: number, flags?: TileFlag); + get breakAfter(): 0 | 1; + get children(): readonly Tile[]; + isWidget(): this is WidgetTile; + get isHidden(): boolean; + isComposite(): this is CompositeTile; + isLine(): this is LineTile; + isText(): this is TextTile; + isBlock(): boolean; + get domAttrs(): Attrs | null; + sync(track?: { + node: Node; + written: boolean; + }): void; + toString(): string; + destroy(): void; + setDOM(dom: this["dom"]): void; + get posAtStart(): number; + get posAtEnd(): number; + posBefore(tile: Tile, start?: number): number; + posAfter(tile: Tile): number; + covers(side: -1 | 1): boolean; + coordsIn(pos: number, side: number): Rect | null; + domPosFor(off: number, side: number): DOMPos; + markDirty(attrs: boolean): void; + get overrideDOMText(): DocText | null; + get root(): DocTile | null; + static get(dom: Node): Tile | undefined; +} +export declare abstract class CompositeTile extends Tile { + dom: HTMLElement; + _children: Tile[]; + constructor(dom: HTMLElement); + isComposite(): this is CompositeTile; + get children(): Tile[]; + get lastChild(): Tile; + append(child: Tile): void; + sync(track?: { + node: Node; + written: boolean; + }): void; +} +export declare class DocTile extends CompositeTile { + readonly view: EditorView; + constructor(view: EditorView, dom: HTMLElement); + owns(tile: Tile | null): boolean; + isBlock(): boolean; + nearest(dom: Node | null): Tile | null; + blockTiles(f: (tile: WidgetTile | LineTile, pos: number) => T | undefined): T; + resolveBlock(pos: number, side: number): { + tile: LineTile | WidgetTile; + offset: number; + }; +} +export declare class BlockWrapperTile extends CompositeTile { + readonly wrapper: BlockWrapper; + dom: HTMLElement; + constructor(dom: HTMLElement, wrapper: BlockWrapper); + isBlock(): boolean; + covers(side: -1 | 1): boolean; + get domAttrs(): Attrs; + static of(wrapper: BlockWrapper, dom?: HTMLElement): BlockWrapperTile; +} +export declare class LineTile extends CompositeTile { + attrs: Attrs; + constructor(dom: HTMLElement, attrs: Attrs); + isLine(): this is LineTile; + static start(attrs: Attrs, dom?: HTMLElement, keepAttrs?: boolean): LineTile; + get domAttrs(): Attrs; + resolveInline(pos: number, side: number, forCoords?: boolean): { + tile: TextTile | WidgetTile | WidgetBufferTile; + offset: number; + } | null; + coordsIn(pos: number, side: number): Rect | null; + domIn(pos: number, side: number): DOMPos; +} +export declare class MarkTile extends CompositeTile { + readonly mark: MarkDecoration; + constructor(dom: HTMLElement, mark: MarkDecoration); + get domAttrs(): Attrs; + static of(mark: MarkDecoration, dom?: HTMLElement): MarkTile; +} +export declare class TextTile extends Tile { + readonly text: string; + dom: Text; + constructor(dom: Text, text: string); + sync(track?: { + node: Node; + written: boolean; + }): void; + isText(): this is TextTile; + toString(): string; + coordsIn(pos: number, side: number): { + left: number; + right: number; + top: number; + bottom: number; + } | DOMRect; + static of(text: string, dom?: Text): TextTile; +} +export declare class WidgetTile extends Tile { + readonly widget: WidgetType; + dom: HTMLElement; + constructor(dom: HTMLElement, length: number, widget: WidgetType, flags: TileFlag); + isWidget(): this is WidgetTile; + get isHidden(): boolean; + covers(side: -1 | 1): boolean; + coordsIn(pos: number, side: number): Rect; + coordsInWidget(pos: number, side: number, block: boolean): Rect; + get overrideDOMText(): DocText; + destroy(): void; + static of(widget: WidgetType, view: EditorView, length: number, flags: TileFlag, dom?: HTMLElement | null): WidgetTile; +} +export declare class WidgetBufferTile extends Tile { + dom: HTMLElement; + constructor(flags: TileFlag); + get isHidden(): boolean; + get overrideDOMText(): DocText; + coordsIn(pos: number): Rect | null; +} +export declare class TilePointer { + tile: Tile; + index: number; + beforeBreak: boolean; + readonly parents: { + tile: CompositeTile; + index: number; + }[]; + constructor(top: DocTile); + advance(dist: number, side: -1 | 1, walker?: TileWalker): this; + get root(): DocTile; +} +export interface TileWalker { + enter(tile: CompositeTile): void; + leave(tile: CompositeTile): void; + skip(tile: Tile, from: number, to: number): boolean | void; + break(): void; +} diff --git a/src/vendor/cm-types/view/src/tooltip.d.ts b/src/vendor/cm-types/view/src/tooltip.d.ts new file mode 100644 index 0000000..f896e27 --- /dev/null +++ b/src/vendor/cm-types/view/src/tooltip.d.ts @@ -0,0 +1,45 @@ +import { EditorState, Transaction, StateEffect, Facet, StateField, Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { Rect } from "./dom"; +export declare function tooltips(config?: { + position?: "fixed" | "absolute"; + parent?: HTMLElement; + tooltipSpace?: (view: EditorView) => Rect; +}): Extension; +export interface Tooltip { + pos: number; + end?: number; + create(view: EditorView): TooltipView; + above?: boolean; + strictSide?: boolean; + arrow?: boolean; + clip?: boolean; +} +export interface TooltipView { + dom: HTMLElement; + offset?: { + x: number; + y: number; + }; + getCoords?: (pos: number) => Rect; + overlap?: boolean; + mount?(view: EditorView): void; + update?(update: ViewUpdate): void; + destroy?(): void; + positioned?(space: Rect): void; + resize?: boolean; +} +export declare const showTooltip: Facet; +export type HoverTooltipSource = (view: EditorView, pos: number, side: -1 | 1) => Tooltip | readonly Tooltip[] | null | Promise; +export declare function hoverTooltip(source: HoverTooltipSource, options?: { + hideOn?: (tr: Transaction, tooltip: Tooltip) => boolean; + hideOnChange?: boolean | "touch"; + hoverTime?: number; +}): Extension & { + active: StateField; +}; +export declare function getTooltip(view: EditorView, tooltip: Tooltip): TooltipView | null; +export declare function hasHoverTooltips(state: EditorState): boolean; +export declare const closeHoverTooltips: StateEffect; +export declare function repositionTooltips(view: EditorView): void; diff --git a/src/vendor/cm-types/view/src/viewstate.d.ts b/src/vendor/cm-types/view/src/viewstate.d.ts new file mode 100644 index 0000000..8525412 --- /dev/null +++ b/src/vendor/cm-types/view/src/viewstate.d.ts @@ -0,0 +1,95 @@ +import { EditorState, ChangeSet, ChangeDesc } from "../../state/src/index.js"; +import { Rect } from "./dom"; +import { HeightMap, HeightOracle, BlockInfo } from "./heightmap"; +import { ViewUpdate, UpdateFlag, ScrollTarget } from "./extension"; +import { Decoration, DecorationSet } from "./decoration"; +import { EditorView } from "./editorview"; +import { Direction } from "./bidi"; +export declare class LineGap { + readonly from: number; + readonly to: number; + readonly size: number; + readonly displaySize: number; + constructor(from: number, to: number, size: number, displaySize: number); + static same(a: readonly LineGap[], b: readonly LineGap[]): boolean; + draw(viewState: ViewState, wrapping: boolean): import("entry").Range; +} +export declare class ViewState { + view: EditorView; + state: EditorState; + pixelViewport: Rect; + inView: boolean; + paddingTop: number; + paddingBottom: number; + contentDOMWidth: number; + contentDOMHeight: number; + editorHeight: number; + editorWidth: number; + scaleX: number; + scaleY: number; + scrollParent: HTMLElement | null; + scrollOffset: number; + scrolledToBottom: boolean; + scrollAnchorPos: number; + scrollAnchorHeight: number; + heightOracle: HeightOracle; + heightMap: HeightMap; + scaler: YScaler; + scrollTarget: ScrollTarget | null; + printing: boolean; + mustMeasureContent: boolean | "refresh"; + stateDeco: readonly DecorationSet[]; + viewportLines: BlockInfo[]; + defaultTextDirection: Direction; + viewport: Viewport; + viewports: readonly Viewport[]; + visibleRanges: readonly { + from: number; + to: number; + }[]; + lineGaps: readonly LineGap[]; + lineGapDeco: DecorationSet; + mustEnforceCursorAssoc: boolean; + constructor(view: EditorView, state: EditorState); + updateForViewport(): 0 | UpdateFlag.Height; + updateScaler(): 0 | UpdateFlag.Height; + updateViewportLines(): void; + update(update: ViewUpdate, scrollTarget?: ScrollTarget | null): void; + measure(): number; + get visibleTop(): number; + get visibleBottom(): number; + getViewport(bias: number, scrollTarget: ScrollTarget | null): Viewport; + mapViewport(viewport: Viewport, changes: ChangeDesc): Viewport; + viewportIsAppropriate({ from, to }: Viewport, bias?: number): boolean; + mapLineGaps(gaps: readonly LineGap[], changes: ChangeSet): any[] | readonly LineGap[]; + ensureLineGaps(current: readonly LineGap[], mayMeasure?: EditorView): LineGap[]; + gapSize(line: BlockInfo, from: number, to: number, structure: LineStructure): number; + updateLineGaps(gaps: readonly LineGap[]): void; + computeVisibleRanges(changes?: ChangeDesc): number; + lineBlockAt(pos: number): BlockInfo; + lineBlockAtHeight(height: number): BlockInfo; + getScrollOffset(): number; + scrollAnchorAt(scrollOffset: number): BlockInfo; + elementAtHeight(height: number): BlockInfo; + get docHeight(): number; + get contentHeight(): number; +} +export declare class Viewport { + readonly from: number; + readonly to: number; + constructor(from: number, to: number); +} +type LineStructure = { + total: number; + ranges: { + from: number; + to: number; + }[]; +}; +type YScaler = { + toDOM(n: number): number; + fromDOM(n: number): number; + scale: number; + eq(other: YScaler): boolean; +}; +export {}; diff --git a/src/vendor/cm-types/w3c-keyname/index.d.ts b/src/vendor/cm-types/w3c-keyname/index.d.ts new file mode 100644 index 0000000..1deebe7 --- /dev/null +++ b/src/vendor/cm-types/w3c-keyname/index.d.ts @@ -0,0 +1,5 @@ +export function keyName(event: Event): string; + +export const base: {[keyCode: number]: string}; + +export const shift: {[keyCode: number]: string}; diff --git a/src/vendor/codemirror.d.ts b/src/vendor/codemirror.d.ts new file mode 100644 index 0000000..e924a52 --- /dev/null +++ b/src/vendor/codemirror.d.ts @@ -0,0 +1,5 @@ +export * from "./cm-types/state/src/index.js"; +export * from "./cm-types/view/src/index.js"; +export { history, historyKeymap, undo, redo, defaultKeymap, indentWithTab, insertNewlineAndIndent, toggleComment, selectAll, indentMore, indentLess } from "./cm-types/commands/src/index.js"; +export { search, searchKeymap, highlightSelectionMatches, openSearchPanel, closeSearchPanel, gotoLine } from "./cm-types/search/src/index.js"; +export { indentUnit, bracketMatching, foldGutter, foldKeymap, codeFolding, foldService, indentService, StreamLanguage, LanguageSupport, syntaxHighlighting, HighlightStyle, defaultHighlightStyle } from "./cm-types/language/src/index.js"; diff --git a/src/vendor/codemirror.js b/src/vendor/codemirror.js new file mode 100644 index 0000000..d6569d6 --- /dev/null +++ b/src/vendor/codemirror.js @@ -0,0 +1,68 @@ +/* CodeMirror 6, bundled for Programming+ from the packages' sources (MIT; see CODEMIRROR-LICENSE next to this file). + * @codemirror/state@6.6.0 @codemirror/view@6.41.0 @codemirror/language@6.12.3 @codemirror/commands@6.10.3 @codemirror/search@6.6.0 @lezer/common@1.5.2 @lezer/highlight@1.2.3 @lezer/lr@1.4.8 style-mod@4.1.3 w3c-keyname@2.2.8 crelt@1.0.6 @marijn/find-cluster-break@1.0.2 + * Rebuild with scripts/vendor/codemirror.sh; do not edit by hand. */ +var Text = class _Text { lineAt(pos) { if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); return this.lineInner(pos, !1, 1, 0) } line(n) { if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); return this.lineInner(n, !0, 1, 0) } replace(from, to, text) { [from, to] = clip(this, from, to); let parts = []; return this.decompose(0, from, parts, 2), text.length && text.decompose(0, text.length, parts, 3), this.decompose(to, this.length, parts, 1), TextNode.from(parts, this.length - (to - from) + text.length) } append(other) { return this.replace(this.length, this.length, other) } slice(from, to = this.length) { [from, to] = clip(this, from, to); let parts = []; return this.decompose(from, to, parts, 0), TextNode.from(parts, to - from) } eq(other) { if (other == this) return !0; if (other.length != this.length || other.lines != this.lines) return !1; let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1), a = new RawTextCursor(this), b = new RawTextCursor(other); for (let skip = start, pos = start; ;) { if (a.next(skip), b.next(skip), skip = 0, a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return !1; if (pos += a.value.length, a.done || pos >= end) return !0 } } iter(dir = 1) { return new RawTextCursor(this, dir) } iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to) } iterLines(from, to) { let inner; if (from == null) inner = this.iter(); else { to == null && (to = this.lines + 1); let start = this.line(from).from; inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)) } return new LineCursor(inner) } toString() { return this.sliceString(0) } toJSON() { let lines = []; return this.flatten(lines), lines } constructor() { } static of(text) { if (text.length == 0) throw new RangeError("A document must have at least one line"); return text.length == 1 && !text[0] ? _Text.empty : text.length <= 32 ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])) } static empty }, TextLeaf = class _TextLeaf extends Text { + constructor(text, length = textLength(text)) { super(); this.text = text; this.length = length } text; length; get lines() { return this.text.length } get children() { return null } lineInner(target, isLine, line, offset) { for (let i2 = 0; ; i2++) { let string2 = this.text[i2], end = offset + string2.length; if ((isLine ? line : end) >= target) return new Line(offset, end, line, string2); offset = end + 1, line++ } } decompose(from, to, target, open) { let text = from <= 0 && to >= this.length ? this : new _TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); if (open & 1) { let prev = target.pop(), joined = appendText(text.text, prev.text.slice(), 0, text.length); if (joined.length <= 32) target.push(new _TextLeaf(joined, prev.length + text.length)); else { let mid = joined.length >> 1; target.push(new _TextLeaf(joined.slice(0, mid)), new _TextLeaf(joined.slice(mid))) } } else target.push(text) } replace(from, to, text) { if (!(text instanceof _TextLeaf)) return super.replace(from, to, text);[from, to] = clip(this, from, to); let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to), newLen = this.length + text.length - (to - from); return lines.length <= 32 ? new _TextLeaf(lines, newLen) : TextNode.from(_TextLeaf.split(lines, []), newLen) } sliceString(from, to = this.length, lineSep = ` +`) { [from, to] = clip(this, from, to); let result = ""; for (let pos = 0, i2 = 0; pos <= to && i2 < this.text.length; i2++) { let line = this.text[i2], end = pos + line.length; pos > from && i2 && (result += lineSep), from < end && to > pos && (result += line.slice(Math.max(0, from - pos), to - pos)), pos = end + 1 } return result } flatten(target) { for (let line of this.text) target.push(line) } scanIdentical() { return 0 } static split(text, target) { let part = [], len = -1; for (let line of text) part.push(line), len += line.length + 1, part.length == 32 && (target.push(new _TextLeaf(part, len)), part = [], len = -1); return len > -1 && target.push(new _TextLeaf(part, len)), target } +}, TextNode = class _TextNode extends Text { + constructor(children, length) { super(); this.children = children; this.length = length; for (let child of children) this.lines += child.lines } children; length; lines = 0; lineInner(target, isLine, line, offset) { for (let i2 = 0; ; i2++) { let child = this.children[i2], end = offset + child.length, endLine = line + child.lines - 1; if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset); offset = end + 1, line = endLine + 1 } } decompose(from, to, target, open) { for (let i2 = 0, pos = 0; pos <= to && i2 < this.children.length; i2++) { let child = this.children[i2], end = pos + child.length; if (from <= end && to >= pos) { let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0)); pos >= from && end <= to && !childOpen ? target.push(child) : child.decompose(from - pos, to - pos, target, childOpen) } pos = end + 1 } } replace(from, to, text) { if ([from, to] = clip(this, from, to), text.lines < this.lines) for (let i2 = 0, pos = 0; i2 < this.children.length; i2++) { let child = this.children[i2], end = pos + child.length; if (from >= pos && to <= end) { let updated = child.replace(from - pos, to - pos, text), totalLines = this.lines - child.lines + updated.lines; if (updated.lines < totalLines >> 4 && updated.lines > totalLines >> 6) { let copy = this.children.slice(); return copy[i2] = updated, new _TextNode(copy, this.length - (to - from) + text.length) } return super.replace(pos, end, updated) } pos = end + 1 } return super.replace(from, to, text) } sliceString(from, to = this.length, lineSep = ` +`) { [from, to] = clip(this, from, to); let result = ""; for (let i2 = 0, pos = 0; i2 < this.children.length && pos <= to; i2++) { let child = this.children[i2], end = pos + child.length; pos > from && i2 && (result += lineSep), from < end && to > pos && (result += child.sliceString(from - pos, to - pos, lineSep)), pos = end + 1 } return result } flatten(target) { for (let child of this.children) child.flatten(target) } scanIdentical(other, dir) { if (!(other instanceof _TextNode)) return 0; let length = 0, [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1]; for (; ; iA += dir, iB += dir) { if (iA == eA || iB == eB) return length; let chA = this.children[iA], chB = other.children[iB]; if (chA != chB) return length + chA.scanIdentical(chB, dir); length += chA.length + 1 } } static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { let lines = 0; for (let ch of children) lines += ch.lines; if (lines < 32) { let flat = []; for (let ch of children) ch.flatten(flat); return new TextLeaf(flat, length) } let chunk = Math.max(32, lines >> 5), maxChunk = chunk << 1, minChunk = chunk >> 1, chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; function add2(child) { let last; if (child.lines > maxChunk && child instanceof _TextNode) for (let node of child.children) add2(node); else child.lines > minChunk && (currentLines > minChunk || !currentLines) ? (flush(), chunked.push(child)) : child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32 ? (currentLines += child.lines, currentLen += child.length + 1, currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length)) : (currentLines + child.lines > chunk && flush(), currentLines += child.lines, currentLen += child.length + 1, currentChunk.push(child)) } function flush() { currentLines != 0 && (chunked.push(currentChunk.length == 1 ? currentChunk[0] : _TextNode.from(currentChunk, currentLen)), currentLen = -1, currentLines = currentChunk.length = 0) } for (let child of children) add2(child); return flush(), chunked.length == 1 ? chunked[0] : new _TextNode(chunked, length) } +}; Text.empty = new TextLeaf([""], 0); function textLength(text) { let length = -1; for (let line of text) length += line.length + 1; return length } function appendText(text, target, from = 0, to = 1e9) { for (let pos = 0, i2 = 0, first = !0; i2 < text.length && pos <= to; i2++) { let line = text[i2], end = pos + line.length; end >= from && (end > to && (line = line.slice(0, to - pos)), pos < from && (line = line.slice(from - pos)), first ? (target[target.length - 1] += line, first = !1) : target.push(line)), pos = end + 1 } return target } function sliceText(text, from, to) { return appendText(text, [""], from, to) } var RawTextCursor = class { + constructor(text, dir = 1) { this.dir = dir; this.nodes = [text], this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1] } dir; done = !1; lineBreak = !1; value = ""; nodes; offsets; nextInner(skip, dir) { + for (this.done = this.lineBreak = !1; ;) { + let last = this.nodes.length - 1, top2 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1, size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length; if (offset == (dir > 0 ? size : 0)) { if (last == 0) return this.done = !0, this.value = "", this; dir > 0 && this.offsets[last - 1]++, this.nodes.pop(), this.offsets.pop() } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + if (this.offsets[last] += dir, skip == 0) return this.lineBreak = !0, this.value = ` +`, this; skip-- + } else if (top2 instanceof TextLeaf) { let next = top2.text[offset + (dir < 0 ? -1 : 0)]; if (this.offsets[last] += dir, next.length > Math.max(0, skip)) return this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip), this; skip -= next.length } else { let next = top2.children[offset + (dir < 0 ? -1 : 0)]; skip > next.length ? (skip -= next.length, this.offsets[last] += dir) : (dir < 0 && this.offsets[last]--, this.nodes.push(next), this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1)) } + } + } next(skip = 0) { return skip < 0 && (this.nextInner(-skip, -this.dir), skip = this.value.length), this.nextInner(skip, this.dir) } +}, PartialTextCursor = class { cursor; value = ""; pos; from; to; done = !1; constructor(text, start, end) { this.cursor = new RawTextCursor(text, start > end ? -1 : 1), this.pos = start > end ? text.length : 0, this.from = Math.min(start, end), this.to = Math.max(start, end) } nextInner(skip, dir) { if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) return this.value = "", this.done = !0, this; skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; skip > limit && (skip = limit), limit -= skip; let { value } = this.cursor.next(skip); return this.pos += (value.length + skip) * dir, this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit), this.done = !this.value, this } next(skip = 0) { return skip < 0 ? skip = Math.max(skip, this.from - this.pos) : skip > 0 && (skip = Math.min(skip, this.to - this.pos)), this.nextInner(skip, this.cursor.dir) } get lineBreak() { return this.cursor.lineBreak && this.value != "" } }, LineCursor = class { constructor(inner) { this.inner = inner } inner; afterBreak = !0; value = ""; done = !1; next(skip = 0) { let { done, lineBreak, value } = this.inner.next(skip); return done && this.afterBreak ? (this.value = "", this.afterBreak = !1) : done ? (this.done = !0, this.value = "") : lineBreak ? this.afterBreak ? this.value = "" : (this.afterBreak = !0, this.next()) : (this.value = value, this.afterBreak = !1), this } get lineBreak() { return !1 } }; typeof Symbol < "u" && (Text.prototype[Symbol.iterator] = function () { return this.iter() }, RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function () { return this }); var Line = class { constructor(from, to, number2, text) { this.from = from; this.to = to; this.number = number2; this.text = text } from; to; number; text; get length() { return this.to - this.from } }; function clip(text, from, to) { return from = Math.max(0, Math.min(text.length, from)), [from, Math.max(from, Math.min(text.length, to))] } var rangeFrom = [], rangeTo = []; (() => { let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1); for (let i2 = 0, n = 0; i2 < numbers.length; i2++)(i2 % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i2]) })(); function isExtendingChar(code2) { if (code2 < 768) return !1; for (let from = 0, to = rangeFrom.length; ;) { let mid = from + to >> 1; if (code2 < rangeFrom[mid]) to = mid; else if (code2 >= rangeTo[mid]) from = mid + 1; else return !0; if (from == to) return !1 } } function isRegionalIndicator(code2) { return code2 >= 127462 && code2 <= 127487 } var ZWJ = 8205; function findClusterBreak(str, pos, forward = !0, includeExtending = !0) { return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending) } function nextClusterBreak(str, pos, includeExtending) { if (pos == str.length) return pos; pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)) && pos--; let prev = codePointAt(str, pos); for (pos += codePointSize(prev); pos < str.length;) { let next = codePointAt(str, pos); if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) pos += codePointSize(next), prev = next; else if (isRegionalIndicator(next)) { let countBefore = 0, i2 = pos - 2; for (; i2 >= 0 && isRegionalIndicator(codePointAt(str, i2));)countBefore++, i2 -= 2; if (countBefore % 2 == 0) break; pos += 2 } else break } return pos } function prevClusterBreak(str, pos, includeExtending) { for (; pos > 1;) { let found = nextClusterBreak(str, pos - 2, includeExtending); if (found < pos) return found; pos-- } return 0 } function codePointAt(str, pos) { let code0 = str.charCodeAt(pos); if (!surrogateHigh(code0) || pos + 1 == str.length) return code0; let code1 = str.charCodeAt(pos + 1); return surrogateLow(code1) ? (code0 - 55296 << 10) + (code1 - 56320) + 65536 : code0 } function surrogateLow(ch) { return ch >= 56320 && ch < 57344 } function surrogateHigh(ch) { return ch >= 55296 && ch < 56320 } function codePointSize(code2) { return code2 < 65536 ? 1 : 2 } function findClusterBreak2(str, pos, forward = !0, includeExtending = !0) { return findClusterBreak(str, pos, forward, includeExtending) } function surrogateLow2(ch) { return ch >= 56320 && ch < 57344 } function surrogateHigh2(ch) { return ch >= 55296 && ch < 56320 } function codePointAt2(str, pos) { let code0 = str.charCodeAt(pos); if (!surrogateHigh2(code0) || pos + 1 == str.length) return code0; let code1 = str.charCodeAt(pos + 1); return surrogateLow2(code1) ? (code0 - 55296 << 10) + (code1 - 56320) + 65536 : code0 } function fromCodePoint(code2) { return code2 <= 65535 ? String.fromCharCode(code2) : (code2 -= 65536, String.fromCharCode((code2 >> 10) + 55296, (code2 & 1023) + 56320)) } function codePointSize2(code2) { return code2 < 65536 ? 1 : 2 } var DefaultSplit = /\r\n?|\n/, MapMode = (MapMode2 => (MapMode2[MapMode2.Simple = 0] = "Simple", MapMode2[MapMode2.TrackDel = 1] = "TrackDel", MapMode2[MapMode2.TrackBefore = 2] = "TrackBefore", MapMode2[MapMode2.TrackAfter = 3] = "TrackAfter", MapMode2))(MapMode || {}), ChangeDesc = class _ChangeDesc { constructor(sections) { this.sections = sections } sections; get length() { let result = 0; for (let i2 = 0; i2 < this.sections.length; i2 += 2)result += this.sections[i2]; return result } get newLength() { let result = 0; for (let i2 = 0; i2 < this.sections.length; i2 += 2) { let ins = this.sections[i2 + 1]; result += ins < 0 ? this.sections[i2] : ins } return result } get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0 } iterGaps(f) { for (let i2 = 0, posA = 0, posB = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; ins < 0 ? (f(posA, posB, len), posB += len) : posB += ins, posA += len } } iterChangedRanges(f, individual = !1) { iterChanges(this, f, individual) } get invertedDesc() { let sections = []; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; ins < 0 ? sections.push(len, ins) : sections.push(ins, len) } return new _ChangeDesc(sections) } composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other) } mapDesc(other, before = !1) { return other.empty ? this : mapSet(this, other, before) } mapPos(pos, assoc = -1, mode = 0) { let posA = 0, posB = 0; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++], endA = posA + len; if (ins < 0) { if (endA > pos) return posB + (pos - posA); posB += len } else { if (mode != 0 && endA >= pos && (mode == 1 && posA < pos && endA > pos || mode == 2 && posA < pos || mode == 3 && endA > pos)) return null; if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins; posB += ins } posA = endA } if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); return posB } touchesRange(from, to = from) { for (let i2 = 0, pos = 0; i2 < this.sections.length && pos <= to;) { let len = this.sections[i2++], ins = this.sections[i2++], end = pos + len; if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : !0; pos = end } return !1 } toString() { let result = ""; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "") } return result } toJSON() { return this.sections } static fromJSON(json) { if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc"); return new _ChangeDesc(json) } static create(sections) { return new _ChangeDesc(sections) } }, ChangeSet = class _ChangeSet extends ChangeDesc { constructor(sections, inserted) { super(sections); this.inserted = inserted } inserted; apply(doc2) { if (this.length != doc2.length) throw new RangeError("Applying change set to a document with the wrong length"); return iterChanges(this, (fromA, toA, fromB, _toB, text) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text), !1), doc2 } mapDesc(other, before = !1) { return mapSet(this, other, before, !0) } invert(doc2) { let sections = this.sections.slice(), inserted = []; for (let i2 = 0, pos = 0; i2 < sections.length; i2 += 2) { let len = sections[i2], ins = sections[i2 + 1]; if (ins >= 0) { sections[i2] = ins, sections[i2 + 1] = len; let index = i2 >> 1; for (; inserted.length < index;)inserted.push(Text.empty); inserted.push(len ? doc2.slice(pos, pos + len) : Text.empty) } pos += len } return new _ChangeSet(sections, inserted) } compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, !0) } map(other, before = !1) { return other.empty ? this : mapSet(this, other, before, !0) } iterChanges(f, individual = !1) { iterChanges(this, f, individual) } get desc() { return ChangeDesc.create(this.sections) } filter(ranges) { let resultSections = [], resultInserted = [], filteredSections = [], iter = new SectionIter(this); done: for (let i2 = 0, pos = 0; ;) { let next = i2 == ranges.length ? 1e9 : ranges[i2++]; for (; pos < next || pos == next && iter.len == 0;) { if (iter.done) break done; let len = Math.min(iter.len, next - pos); addSection(filteredSections, len, -1); let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; addSection(resultSections, len, ins), ins > 0 && addInsert(resultInserted, resultSections, iter.text), iter.forward(len), pos += len } let end = ranges[i2++]; for (; pos < end;) { if (iter.done) break done; let len = Math.min(iter.len, end - pos); addSection(resultSections, len, -1), addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0), iter.forward(len), pos += len } } return { changes: new _ChangeSet(resultSections, resultInserted), filtered: ChangeDesc.create(filteredSections) } } toJSON() { let parts = []; for (let i2 = 0; i2 < this.sections.length; i2 += 2) { let len = this.sections[i2], ins = this.sections[i2 + 1]; ins < 0 ? parts.push(len) : ins == 0 ? parts.push([len]) : parts.push([len].concat(this.inserted[i2 >> 1].toJSON())) } return parts } static of(changes, length, lineSep) { let sections = [], inserted = [], pos = 0, total = null; function flush(force = !1) { if (!force && !sections.length) return; pos < length && addSection(sections, length - pos, -1); let set = new _ChangeSet(sections, inserted); total = total ? total.compose(set.map(total)) : set, sections = [], inserted = [], pos = 0 } function process(spec) { if (Array.isArray(spec)) for (let sub of spec) process(sub); else if (spec instanceof _ChangeSet) { if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); flush(), total = total ? total.compose(spec.map(total)) : spec } else { let { from, to = from, insert: insert2 } = spec; if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); let insText = insert2 ? typeof insert2 == "string" ? Text.of(insert2.split(lineSep || DefaultSplit)) : insert2 : Text.empty, insLen = insText.length; if (from == to && insLen == 0) return; from < pos && flush(), from > pos && addSection(sections, from - pos, -1), addSection(sections, to - from, insLen), addInsert(inserted, sections, insText), pos = to } } return process(changes), flush(!total), total } static empty(length) { return new _ChangeSet(length ? [length, -1] : [], []) } static fromJSON(json) { if (!Array.isArray(json)) throw new RangeError("Invalid JSON representation of ChangeSet"); let sections = [], inserted = []; for (let i2 = 0; i2 < json.length; i2++) { let part = json[i2]; if (typeof part == "number") sections.push(part, -1); else { if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i3) => i3 && typeof e != "string")) throw new RangeError("Invalid JSON representation of ChangeSet"); if (part.length == 1) sections.push(part[0], 0); else { for (; inserted.length < i2;)inserted.push(Text.empty); inserted[i2] = Text.of(part.slice(1)), sections.push(part[0], inserted[i2].length) } } } return new _ChangeSet(sections, inserted) } static createSet(sections, inserted) { return new _ChangeSet(sections, inserted) } }; function addSection(sections, len, ins, forceJoin = !1) { if (len == 0 && ins <= 0) return; let last = sections.length - 2; last >= 0 && ins <= 0 && ins == sections[last + 1] ? sections[last] += len : last >= 0 && len == 0 && sections[last] == 0 ? sections[last + 1] += ins : forceJoin ? (sections[last] += len, sections[last + 1] += ins) : sections.push(len, ins) } function addInsert(values, sections, value) { if (value.length == 0) return; let index = sections.length - 2 >> 1; if (index < values.length) values[values.length - 1] = values[values.length - 1].append(value); else { for (; values.length < index;)values.push(Text.empty); values.push(value) } } function iterChanges(desc, f, individual) { let inserted = desc.inserted; for (let posA = 0, posB = 0, i2 = 0; i2 < desc.sections.length;) { let len = desc.sections[i2++], ins = desc.sections[i2++]; if (ins < 0) posA += len, posB += len; else { let endA = posA, endB = posB, text = Text.empty; for (; endA += len, endB += ins, ins && inserted && (text = text.append(inserted[i2 - 2 >> 1])), !(individual || i2 == desc.sections.length || desc.sections[i2 + 1] < 0);)len = desc.sections[i2++], ins = desc.sections[i2++]; f(posA, endA, posB, endB, text), posA = endA, posB = endB } } } function mapSet(setA, setB, before, mkSet = !1) { let sections = [], insert2 = mkSet ? [] : null, a = new SectionIter(setA), b = new SectionIter(setB); for (let inserted = -1; ;) { if (a.done && b.len || b.done && a.len) throw new Error("Mismatched change set lengths"); if (a.ins == -1 && b.ins == -1) { let len = Math.min(a.len, b.len); addSection(sections, len, -1), a.forward(len), b.forward(len) } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { let len = b.len; for (addSection(sections, b.ins, -1); len;) { let piece = Math.min(a.len, len); a.ins >= 0 && inserted < a.i && a.len <= piece && (addSection(sections, 0, a.ins), insert2 && addInsert(insert2, sections, a.text), inserted = a.i), a.forward(piece), len -= piece } b.next() } else if (a.ins >= 0) { let len = 0, left = a.len; for (; left;)if (b.ins == -1) { let piece = Math.min(left, b.len); len += piece, left -= piece, b.forward(piece) } else if (b.ins == 0 && b.len < left) left -= b.len, b.next(); else break; addSection(sections, len, inserted < a.i ? a.ins : 0), insert2 && inserted < a.i && addInsert(insert2, sections, a.text), inserted = a.i, a.forward(a.len - left) } else { if (a.done && b.done) return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); throw new Error("Mismatched change set lengths") } } } function composeSets(setA, setB, mkSet = !1) { let sections = [], insert2 = mkSet ? [] : null, a = new SectionIter(setA), b = new SectionIter(setB); for (let open = !1; ;) { if (a.done && b.done) return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); if (a.ins == 0) addSection(sections, a.len, 0, open), a.next(); else if (b.len == 0 && !b.done) addSection(sections, 0, b.ins, open), insert2 && addInsert(insert2, sections, b.text), b.next(); else { if (a.done || b.done) throw new Error("Mismatched change set lengths"); { let len = Math.min(a.len2, b.len), sectionLen = sections.length; if (a.ins == -1) { let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; addSection(sections, len, insB, open), insert2 && insB && addInsert(insert2, sections, b.text) } else b.ins == -1 ? (addSection(sections, a.off ? 0 : a.len, len, open), insert2 && addInsert(insert2, sections, a.textBit(len))) : (addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open), insert2 && !b.off && addInsert(insert2, sections, b.text)); open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen), a.forward2(len), b.forward(len) } } } } var SectionIter = class { constructor(set) { this.set = set; this.next() } set; i = 0; next() { let { sections } = this.set; this.i < sections.length ? (this.len = sections[this.i++], this.ins = sections[this.i++]) : (this.len = 0, this.ins = -2), this.off = 0 } get done() { return this.ins == -2 } get len2() { return this.ins < 0 ? this.len : this.ins } get text() { let { inserted } = this.set, index = this.i - 2 >> 1; return index >= inserted.length ? Text.empty : inserted[index] } textBit(len) { let { inserted } = this.set, index = this.i - 2 >> 1; return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len) } forward(len) { len == this.len ? this.next() : (this.len -= len, this.off += len) } forward2(len) { this.ins == -1 ? this.forward(len) : len == this.ins ? this.next() : (this.ins -= len, this.off += len) } }; var SelectionRange = class _SelectionRange { constructor(from, to, flags) { this.from = from; this.to = to; this.flags = flags } from; to; flags; get anchor() { return this.flags & 32 ? this.to : this.from } get head() { return this.flags & 32 ? this.from : this.to } get empty() { return this.from == this.to } get assoc() { return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0 } get bidiLevel() { let level = this.flags & 7; return level == 7 ? null : level } get goalColumn() { let value = this.flags >> 6; return value == 16777215 ? void 0 : value } map(change, assoc = -1) { let from, to; return this.empty ? from = to = change.mapPos(this.from, assoc) : (from = change.mapPos(this.from, 1), to = change.mapPos(this.to, -1)), from == this.from && to == this.to ? this : new _SelectionRange(from, to, this.flags) } extend(from, to = from, assoc = 0) { if (from <= this.anchor && to >= this.anchor) return EditorSelection.range(from, to, void 0, void 0, assoc); let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; return EditorSelection.range(this.anchor, head, void 0, void 0, assoc) } eq(other, includeAssoc = !1) { return this.anchor == other.anchor && this.head == other.head && this.goalColumn == other.goalColumn && (!includeAssoc || !this.empty || this.assoc == other.assoc) } toJSON() { return { anchor: this.anchor, head: this.head } } static fromJSON(json) { if (!json || typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange"); return EditorSelection.range(json.anchor, json.head) } static create(from, to, flags) { return new _SelectionRange(from, to, flags) } }, EditorSelection = class _EditorSelection { constructor(ranges, mainIndex) { this.ranges = ranges; this.mainIndex = mainIndex } ranges; mainIndex; map(change, assoc = -1) { return change.empty ? this : _EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex) } eq(other, includeAssoc = !1) { if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return !1; for (let i2 = 0; i2 < this.ranges.length; i2++)if (!this.ranges[i2].eq(other.ranges[i2], includeAssoc)) return !1; return !0 } get main() { return this.ranges[this.mainIndex] } asSingle() { return this.ranges.length == 1 ? this : new _EditorSelection([this.main], 0) } addRange(range, main = !0) { return _EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1) } replaceRange(range, which = this.mainIndex) { let ranges = this.ranges.slice(); return ranges[which] = range, _EditorSelection.create(ranges, this.mainIndex) } toJSON() { return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex } } static fromJSON(json) { if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection"); return new _EditorSelection(json.ranges.map(r => SelectionRange.fromJSON(r)), json.main) } static single(anchor, head = anchor) { return new _EditorSelection([_EditorSelection.range(anchor, head)], 0) } static create(ranges, mainIndex = 0) { if (ranges.length == 0) throw new RangeError("A selection needs at least one range"); for (let pos = 0, i2 = 0; i2 < ranges.length; i2++) { let range = ranges[i2]; if (range.empty ? range.from <= pos : range.from < pos) return _EditorSelection.normalized(ranges.slice(), mainIndex); pos = range.to } return new _EditorSelection(ranges, mainIndex) } static cursor(pos, assoc = 0, bidiLevel, goalColumn) { return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn ?? 16777215) << 6) } static range(anchor, head, goalColumn, bidiLevel, assoc) { let flags = (goalColumn ?? 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)); return !assoc && anchor != head && (assoc = head < anchor ? 1 : -1), head < anchor ? SelectionRange.create(head, anchor, 48 | flags) : SelectionRange.create(anchor, head, (assoc ? assoc < 0 ? 8 : 16 : 0) | flags) } static normalized(ranges, mainIndex = 0) { let main = ranges[mainIndex]; ranges.sort((a, b) => a.from - b.from), mainIndex = ranges.indexOf(main); for (let i2 = 1; i2 < ranges.length; i2++) { let range = ranges[i2], prev = ranges[i2 - 1]; if (range.empty ? range.from <= prev.to : range.from < prev.to) { let from = prev.from, to = Math.max(range.to, prev.to); i2 <= mainIndex && mainIndex--, ranges.splice(--i2, 2, range.anchor > range.head ? _EditorSelection.range(to, from) : _EditorSelection.range(from, to)) } } return new _EditorSelection(ranges, mainIndex) } }; function checkSelection(selection, docLength) { for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document") } var nextID = 0, Facet = class _Facet { constructor(combine, compareInput, compare2, isStatic, enables) { this.combine = combine; this.compareInput = compareInput; this.compare = compare2; this.isStatic = isStatic; this.default = combine([]), this.extensions = typeof enables == "function" ? enables(this) : enables } combine; compareInput; compare; isStatic; id = nextID++; default; extensions; get reader() { return this } static define(config = {}) { return new _Facet(config.combine || (a => a), config.compareInput || ((a, b) => a === b), config.compare || (config.combine ? (a, b) => a === b : sameArray), !!config.static, config.enables) } of(value) { return new FacetProvider([], this, 0, value) } compute(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 1, get) } computeN(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 2, get) } from(field, get) { return get || (get = x => x), this.compute([field], state => get(state.field(field))) } }; function sameArray(a, b) { return a == b || a.length == b.length && a.every((e, i2) => e === b[i2]) } var FacetProvider = class { constructor(dependencies, facet, type, value) { this.dependencies = dependencies; this.facet = facet; this.type = type; this.value = value } dependencies; facet; type; value; id = nextID++; dynamicSlot(addresses) { let getter = this.value, compare2 = this.facet.compareInput, id = this.id, idx = addresses[id] >> 1, multi = this.type == 2, depDoc = !1, depSel = !1, depAddrs = []; for (let dep of this.dependencies) dep == "doc" ? depDoc = !0 : dep == "selection" ? depSel = !0 : ((addresses[dep.id] ?? 1) & 1) == 0 && depAddrs.push(addresses[dep.id]); return { create(state) { return state.values[idx] = getter(state), 1 }, update(state, tr) { if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) { let newVal = getter(state); if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) return state.values[idx] = newVal, 1 } return 0 }, reconfigure: (state, oldState) => { let newVal, oldAddr = oldState.config.address[id]; if (oldAddr != null) { let oldVal = getAddr(oldState, oldAddr); if (this.dependencies.every(dep => dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, !1) == state.field(dep, !1) : !0) || (multi ? compareArray(newVal = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) return state.values[idx] = oldVal, 0 } else newVal = getter(state); return state.values[idx] = newVal, 1 } } } }; function compareArray(a, b, compare2) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (!compare2(a[i2], b[i2])) return !1; return !0 } function ensureAll(state, addrs) { let changed = !1; for (let addr of addrs) ensureAddr(state, addr) & 1 && (changed = !0); return changed } function dynamicFacetSlot(addresses, facet, providers) { let providerAddrs = providers.map(p => addresses[p.id]), providerTypes = providers.map(p => p.type), dynamic = providerAddrs.filter(p => !(p & 1)), idx = addresses[facet.id] >> 1; function get(state) { let values = []; for (let i2 = 0; i2 < providerAddrs.length; i2++) { let value = getAddr(state, providerAddrs[i2]); if (providerTypes[i2] == 2) for (let val of value) values.push(val); else values.push(value) } return facet.combine(values) } return { create(state) { for (let addr of providerAddrs) ensureAddr(state, addr); return state.values[idx] = get(state), 1 }, update(state, tr) { if (!ensureAll(state, dynamic)) return 0; let value = get(state); return facet.compare(value, state.values[idx]) ? 0 : (state.values[idx] = value, 1) }, reconfigure(state, oldState) { let depChanged = ensureAll(state, providerAddrs), oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); if (oldProviders && !depChanged && sameArray(providers, oldProviders)) return state.values[idx] = oldValue, 0; let value = get(state); return facet.compare(value, oldValue) ? (state.values[idx] = oldValue, 0) : (state.values[idx] = value, 1) } } } var initField = Facet.define({ static: !0 }), StateField = class _StateField { constructor(id, createF, updateF, compareF, spec) { this.id = id; this.createF = createF; this.updateF = updateF; this.compareF = compareF; this.spec = spec } id; createF; updateF; compareF; spec; provides = void 0; static define(config) { let field = new _StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); return config.provide && (field.provides = config.provide(field)), field } create(state) { return (state.facet(initField).find(i2 => i2.field == this)?.create || this.createF)(state) } slot(addresses) { let idx = addresses[this.id] >> 1; return { create: state => (state.values[idx] = this.create(state), 1), update: (state, tr) => { let oldVal = state.values[idx], value = this.updateF(oldVal, tr); return this.compareF(oldVal, value) ? 0 : (state.values[idx] = value, 1) }, reconfigure: (state, oldState) => { let init = state.facet(initField), oldInit = oldState.facet(initField), reInit; return (reInit = init.find(i2 => i2.field == this)) && reInit != oldInit.find(i2 => i2.field == this) ? (state.values[idx] = reInit.create(state), 1) : oldState.config.address[this.id] != null ? (state.values[idx] = oldState.field(this), 0) : (state.values[idx] = this.create(state), 1) } } } init(create) { return [this, initField.of({ field: this, create })] } get extension() { return this } }, Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; function prec(value) { return ext => new PrecExtension(ext, value) } var Prec = { highest: prec(Prec_.highest), high: prec(Prec_.high), default: prec(Prec_.default), low: prec(Prec_.low), lowest: prec(Prec_.lowest) }, PrecExtension = class { constructor(inner, prec2) { this.inner = inner; this.prec = prec2 } inner; prec }, Compartment = class _Compartment { of(ext) { return new CompartmentInstance(this, ext) } reconfigure(content2) { return _Compartment.reconfigure.of({ compartment: this, extension: content2 }) } get(state) { return state.config.compartments.get(this) } static reconfigure }, CompartmentInstance = class { constructor(compartment, inner) { this.compartment = compartment; this.inner = inner } compartment; inner }, Configuration = class _Configuration { constructor(base2, compartments, dynamicSlots, address, staticValues, facets) { this.base = base2; this.compartments = compartments; this.dynamicSlots = dynamicSlots; this.address = address; this.staticValues = staticValues; this.facets = facets; for (; this.statusTemplate.length < dynamicSlots.length;)this.statusTemplate.push(0) } base; compartments; dynamicSlots; address; staticValues; facets; statusTemplate = []; staticFacet(facet) { let addr = this.address[facet.id]; return addr == null ? facet.default : this.staticValues[addr >> 1] } static resolve(base2, compartments, oldState) { let fields = [], facets = Object.create(null), newCompartments = new Map; for (let ext of flatten(base2, compartments, newCompartments)) ext instanceof StateField ? fields.push(ext) : (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); let address = Object.create(null), staticValues = [], dynamicSlots = []; for (let field of fields) address[field.id] = dynamicSlots.length << 1, dynamicSlots.push(a => field.slot(a)); let oldFacets = oldState?.config.facets; for (let id in facets) { let providers = facets[id], facet = providers[0].facet, oldProviders = oldFacets && oldFacets[id] || []; if (providers.every(p => p.type == 0)) if (address[facet.id] = staticValues.length << 1 | 1, sameArray(oldProviders, providers)) staticValues.push(oldState.facet(facet)); else { let value = facet.combine(providers.map(p => p.value)); staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value) } else { for (let p of providers) p.type == 0 ? (address[p.id] = staticValues.length << 1 | 1, staticValues.push(p.value)) : (address[p.id] = dynamicSlots.length << 1, dynamicSlots.push(a => p.dynamicSlot(a))); address[facet.id] = dynamicSlots.length << 1, dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)) } } let dynamic = dynamicSlots.map(f => f(address)); return new _Configuration(base2, newCompartments, dynamic, address, staticValues, facets) } }; function flatten(extension, compartments, newCompartments) { let result = [[], [], [], [], []], seen = new Map; function inner(ext, prec2) { let known = seen.get(ext); if (known != null) { if (known <= prec2) return; let found = result[known].indexOf(ext); found > -1 && result[known].splice(found, 1), ext instanceof CompartmentInstance && newCompartments.delete(ext.compartment) } if (seen.set(ext, prec2), Array.isArray(ext)) for (let e of ext) inner(e, prec2); else if (ext instanceof CompartmentInstance) { if (newCompartments.has(ext.compartment)) throw new RangeError("Duplicate use of compartment in extensions"); let content2 = compartments.get(ext.compartment) || ext.inner; newCompartments.set(ext.compartment, content2), inner(content2, prec2) } else if (ext instanceof PrecExtension) inner(ext.inner, ext.prec); else if (ext instanceof StateField) result[prec2].push(ext), ext.provides && inner(ext.provides, prec2); else if (ext instanceof FacetProvider) result[prec2].push(ext), ext.facet.extensions && inner(ext.facet.extensions, Prec_.default); else { let content2 = ext.extension; if (!content2) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); inner(content2, prec2) } } return inner(extension, Prec_.default), result.reduce((a, b) => a.concat(b)) } function ensureAddr(state, addr) { if (addr & 1) return 2; let idx = addr >> 1, status = state.status[idx]; if (status == 4) throw new Error("Cyclic dependency between fields and/or facets"); if (status & 2) return status; state.status[idx] = 4; let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); return state.status[idx] = 2 | changed } function getAddr(state, addr) { return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1] } var languageData = Facet.define(), allowMultipleSelections = Facet.define({ combine: values => values.some(v => v), static: !0 }), lineSeparator = Facet.define({ combine: values => values.length ? values[0] : void 0, static: !0 }), changeFilter = Facet.define(), transactionFilter = Facet.define(), transactionExtender = Facet.define(), readOnly = Facet.define({ combine: values => values.length ? values[0] : !1 }); var Annotation = class { constructor(type, value) { this.type = type; this.value = value } type; value; static define() { return new AnnotationType } }, AnnotationType = class { of(value) { return new Annotation(this, value) } }, StateEffectType = class { constructor(map) { this.map = map } map; of(value) { return new StateEffect(this, value) } }, StateEffect = class _StateEffect { constructor(type, value) { this.type = type; this.value = value } type; value; map(mapping) { let mapped = this.type.map(this.value, mapping); return mapped === void 0 ? void 0 : mapped == this.value ? this : new _StateEffect(this.type, mapped) } is(type) { return this.type == type } static define(spec = {}) { return new StateEffectType(spec.map || (v => v)) } static mapEffects(effects, mapping) { if (!effects.length) return effects; let result = []; for (let effect of effects) { let mapped = effect.map(mapping); mapped && result.push(mapped) } return result } static reconfigure = _StateEffect.define(); static appendConfig = _StateEffect.define() }, Transaction = class _Transaction { constructor(startState, changes, selection, effects, annotations, scrollIntoView2) { this.startState = startState; this.changes = changes; this.selection = selection; this.effects = effects; this.annotations = annotations; this.scrollIntoView = scrollIntoView2; selection && checkSelection(selection, changes.newLength), annotations.some(a => a.type == _Transaction.time) || (this.annotations = annotations.concat(_Transaction.time.of(Date.now()))) } startState; changes; selection; effects; annotations; scrollIntoView; _doc = null; _state = null; static create(startState, changes, selection, effects, annotations, scrollIntoView2) { return new _Transaction(startState, changes, selection, effects, annotations, scrollIntoView2) } get newDoc() { return this._doc || (this._doc = this.changes.apply(this.startState.doc)) } get newSelection() { return this.selection || this.startState.selection.map(this.changes) } get state() { return this._state || this.startState.applyTransaction(this), this._state } annotation(type) { for (let ann of this.annotations) if (ann.type == type) return ann.value } get docChanged() { return !this.changes.empty } get reconfigured() { return this.startState.config != this.state.config } isUserEvent(event) { let e = this.annotation(_Transaction.userEvent); return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")) } static time = Annotation.define(); static userEvent = Annotation.define(); static addToHistory = Annotation.define(); static remote = Annotation.define() }; function joinRanges(a, b) { let result = []; for (let iA = 0, iB = 0; ;) { let from, to; if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) from = a[iA++], to = a[iA++]; else if (iB < b.length) from = b[iB++], to = b[iB++]; else return result; !result.length || result[result.length - 1] < from ? result.push(from, to) : result[result.length - 1] < to && (result[result.length - 1] = to) } } function mergeTransaction(a, b, sequential) { let mapForA, mapForB, changes; return sequential ? (mapForA = b.changes, mapForB = ChangeSet.empty(b.changes.length), changes = a.changes.compose(b.changes)) : (mapForA = b.changes.map(a.changes), mapForB = a.changes.mapDesc(b.changes, !0), changes = a.changes.compose(mapForA)), { changes, selection: b.selection ? b.selection.map(mapForB) : a.selection?.map(mapForA), effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, scrollIntoView: a.scrollIntoView || b.scrollIntoView } } function resolveTransactionInner(state, spec, docSize) { let sel = spec.selection, annotations = asArray(spec.annotations); return spec.userEvent && (annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent))), { changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), effects: asArray(spec.effects), annotations, scrollIntoView: !!spec.scrollIntoView } } function resolveTransaction(state, specs, filter) { let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); specs.length && specs[0].filter === !1 && (filter = !1); for (let i2 = 1; i2 < specs.length; i2++) { specs[i2].filter === !1 && (filter = !1); let seq = !!specs[i2].sequential; s = mergeTransaction(s, resolveTransactionInner(state, specs[i2], seq ? s.changes.newLength : state.doc.length), seq) } let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); return extendTransaction(filter ? filterTransaction(tr) : tr) } function filterTransaction(tr) { let state = tr.startState, result = !0; for (let filter of state.facet(changeFilter)) { let value = filter(tr); if (value === !1) { result = !1; break } Array.isArray(value) && (result = result === !0 ? value : joinRanges(result, value)) } if (result !== !0) { let changes, back; if (result === !1) back = tr.changes.invertedDesc, changes = ChangeSet.empty(state.doc.length); else { let filtered = tr.changes.filter(result); changes = filtered.changes, back = filtered.filtered.mapDesc(filtered.changes).invertedDesc } tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView) } let filters = state.facet(transactionFilter); for (let i2 = filters.length - 1; i2 >= 0; i2--) { let filtered = filters[i2](tr); filtered instanceof Transaction ? tr = filtered : Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction ? tr = filtered[0] : tr = resolveTransaction(state, asArray(filtered), !1) } return tr } function extendTransaction(tr) { let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; for (let i2 = extenders.length - 1; i2 >= 0; i2--) { let extension = extenders[i2](tr); extension && Object.keys(extension).length && (spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), !0)) } return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView) } var none = []; function asArray(value) { return value == null ? none : Array.isArray(value) ? value : [value] } var CharCategory = (CharCategory2 => (CharCategory2[CharCategory2.Word = 0] = "Word", CharCategory2[CharCategory2.Space = 1] = "Space", CharCategory2[CharCategory2.Other = 2] = "Other", CharCategory2))(CharCategory || {}), nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/, wordChar; try { wordChar = new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u") } catch { } function hasWordChar(str) { if (wordChar) return wordChar.test(str); for (let i2 = 0; i2 < str.length; i2++) { let ch = str[i2]; if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) return !0 } return !1 } function makeCategorizer(wordChars) { return char => { if (!/\S/.test(char)) return 1; if (hasWordChar(char)) return 0; for (let i2 = 0; i2 < wordChars.length; i2++)if (char.indexOf(wordChars[i2]) > -1) return 0; return 2 } } var EditorState = class _EditorState { + constructor(config, doc2, selection, values, computeSlot, tr) { this.config = config; this.doc = doc2; this.selection = selection; this.values = values; this.status = config.statusTemplate.slice(), this.computeSlot = computeSlot, tr && (tr._state = this); for (let i2 = 0; i2 < this.config.dynamicSlots.length; i2++)ensureAddr(this, i2 << 1); this.computeSlot = null } config; doc; selection; values; status; computeSlot; field(field, require2 = !0) { let addr = this.config.address[field.id]; if (addr == null) { if (require2) throw new RangeError("Field is not present in this state"); return } return ensureAddr(this, addr), getAddr(this, addr) } update(...specs) { return resolveTransaction(this, specs, !0) } applyTransaction(tr) { let conf = this.config, { base: base2, compartments } = conf; for (let effect of tr.effects) effect.is(Compartment.reconfigure) ? (conf && (compartments = new Map, conf.compartments.forEach((val, key) => compartments.set(key, val)), conf = null), compartments.set(effect.value.compartment, effect.value.extension)) : effect.is(StateEffect.reconfigure) ? (conf = null, base2 = effect.value) : effect.is(StateEffect.appendConfig) && (conf = null, base2 = asArray(base2).concat(effect.value)); let startValues; conf ? startValues = tr.startState.values.slice() : (conf = Configuration.resolve(base2, compartments, this), startValues = new _EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null).values); let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle(); new _EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr) } replaceSelection(text) { return typeof text == "string" && (text = this.toText(text)), this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, range: EditorSelection.cursor(range.from + text.length) })) } changeByRange(f) { let sel = this.selection, result1 = f(sel.ranges[0]), changes = this.changes(result1.changes), ranges = [result1.range], effects = asArray(result1.effects); for (let i2 = 1; i2 < sel.ranges.length; i2++) { let result = f(sel.ranges[i2]), newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); for (let j = 0; j < i2; j++)ranges[j] = ranges[j].map(newMapped); let mapBy = changes.mapDesc(newChanges, !0); ranges.push(result.range.map(mapBy)), changes = changes.compose(newMapped), effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy)) } return { changes, selection: EditorSelection.create(ranges, sel.mainIndex), effects } } changes(spec = []) { return spec instanceof ChangeSet ? spec : ChangeSet.of(spec, this.doc.length, this.facet(_EditorState.lineSeparator)) } toText(string2) { return Text.of(string2.split(this.facet(_EditorState.lineSeparator) || DefaultSplit)) } sliceDoc(from = 0, to = this.doc.length) { return this.doc.sliceString(from, to, this.lineBreak) } facet(facet) { let addr = this.config.address[facet.id]; return addr == null ? facet.default : (ensureAddr(this, addr), getAddr(this, addr)) } toJSON(fields) { let result = { doc: this.sliceDoc(), selection: this.selection.toJSON() }; if (fields) for (let prop in fields) { let value = fields[prop]; value instanceof StateField && this.config.address[value.id] != null && (result[prop] = value.spec.toJSON(this.field(fields[prop]), this)) } return result } static fromJSON(json, config = {}, fields) { if (!json || typeof json.doc != "string") throw new RangeError("Invalid JSON representation for EditorState"); let fieldInit = []; if (fields) { for (let prop in fields) if (Object.prototype.hasOwnProperty.call(json, prop)) { let field = fields[prop], value = json[prop]; fieldInit.push(field.init(state => field.spec.fromJSON(value, state))) } } return _EditorState.create({ doc: json.doc, selection: EditorSelection.fromJSON(json.selection), extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit }) } static create(config = {}) { let configuration = Configuration.resolve(config.extensions || [], new Map), doc2 = config.doc instanceof Text ? config.doc : Text.of((config.doc || "").split(configuration.staticFacet(_EditorState.lineSeparator) || DefaultSplit)), selection = config.selection ? config.selection instanceof EditorSelection ? config.selection : EditorSelection.single(config.selection.anchor, config.selection.head) : EditorSelection.single(0); return checkSelection(selection, doc2.length), configuration.staticFacet(allowMultipleSelections) || (selection = selection.asSingle()), new _EditorState(configuration, doc2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null) } static allowMultipleSelections = allowMultipleSelections; static tabSize = Facet.define({ combine: values => values.length ? values[0] : 4 }); get tabSize() { return this.facet(_EditorState.tabSize) } static lineSeparator = lineSeparator; get lineBreak() { + return this.facet(_EditorState.lineSeparator) || ` +`} static readOnly = readOnly; get readOnly() { return this.facet(readOnly) } static phrases = Facet.define({ compare(a, b) { let kA = Object.keys(a), kB = Object.keys(b); return kA.length == kB.length && kA.every(k => a[k] == b[k]) } }); phrase(phrase2, ...insert2) { for (let map of this.facet(_EditorState.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase2)) { phrase2 = map[phrase2]; break } return insert2.length && (phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m, i2) => { if (i2 == "$") return "$"; let n = +(i2 || 1); return !n || n > insert2.length ? m : insert2[n - 1] })), phrase2 } static languageData = languageData; languageDataAt(name2, pos, side = -1) { let values = []; for (let provider of this.facet(languageData)) for (let result of provider(this, pos, side)) Object.prototype.hasOwnProperty.call(result, name2) && values.push(result[name2]); return values } charCategorizer(at) { let chars = this.languageDataAt("wordChars", at); return makeCategorizer(chars.length ? chars[0] : "") } wordAt(pos) { let { text, from, length } = this.doc.lineAt(pos), cat = this.charCategorizer(pos), start = pos - from, end = pos - from; for (; start > 0;) { let prev = findClusterBreak2(text, start, !1); if (cat(text.slice(prev, start)) != 0) break; start = prev } for (; end < length;) { let next = findClusterBreak2(text, end); if (cat(text.slice(end, next)) != 0) break; end = next } return start == end ? null : EditorSelection.range(start + from, end + from) } static changeFilter = changeFilter; static transactionFilter = transactionFilter; static transactionExtender = transactionExtender +}; Compartment.reconfigure = StateEffect.define(); function combineConfig(configs, defaults2, combine = {}) { let result = {}; for (let config of configs) for (let key of Object.keys(config)) { let value = config[key], current = result[key]; if (current === void 0) result[key] = value; else if (!(current === value || value === void 0)) if (Object.hasOwnProperty.call(combine, key)) result[key] = combine[key](current, value); else throw new Error("Config merge conflict for field " + key) } for (let key in defaults2) result[key] === void 0 && (result[key] = defaults2[key]); return result } var RangeValue = class { eq(other) { return this == other } range(from, to = from) { return Range.create(from, to, this) } }; RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; RangeValue.prototype.point = !1; RangeValue.prototype.mapMode = 1; function cmpVal(a, b) { return a == b || a.constructor == b.constructor && a.eq(b) } var Range = class _Range { constructor(from, to, value) { this.from = from; this.to = to; this.value = value } from; to; value; static create(from, to, value) { return new _Range(from, to, value) } }; function cmpRange(a, b) { return a.from - b.from || a.value.startSide - b.value.startSide } var Chunk = class _Chunk { constructor(from, to, value, maxPoint) { this.from = from; this.to = to; this.value = value; this.maxPoint = maxPoint } from; to; value; maxPoint; get length() { return this.to[this.to.length - 1] } findIndex(pos, side, end, startAt = 0) { let arr = end ? this.to : this.from; for (let lo = startAt, hi = arr.length; ;) { if (lo == hi) return lo; let mid = lo + hi >> 1, diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; if (mid == lo) return diff >= 0 ? lo : hi; diff >= 0 ? hi = mid : lo = mid + 1 } } between(offset, from, to, f) { for (let i2 = this.findIndex(from, -1e9, !0), e = this.findIndex(to, 1e9, !1, i2); i2 < e; i2++)if (f(this.from[i2] + offset, this.to[i2] + offset, this.value[i2]) === !1) return !1 } map(offset, changes) { let value = [], from = [], to = [], newPos = -1, maxPoint = -1; for (let i2 = 0; i2 < this.value.length; i2++) { let val = this.value[i2], curFrom = this.from[i2] + offset, curTo = this.to[i2] + offset, newFrom, newTo; if (curFrom == curTo) { let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); if (mapped == null || (newFrom = newTo = mapped, val.startSide != val.endSide && (newTo = changes.mapPos(curFrom, val.endSide), newTo < newFrom))) continue } else if (newFrom = changes.mapPos(curFrom, val.startSide), newTo = changes.mapPos(curTo, val.endSide), newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) continue; (newTo - newFrom || val.endSide - val.startSide) < 0 || (newPos < 0 && (newPos = newFrom), val.point && (maxPoint = Math.max(maxPoint, newTo - newFrom)), value.push(val), from.push(newFrom - newPos), to.push(newTo - newPos)) } return { mapped: value.length ? new _Chunk(from, to, value, maxPoint) : null, pos: newPos } } }, RangeSet = class _RangeSet { constructor(chunkPos, chunk, nextLayer, maxPoint) { this.chunkPos = chunkPos; this.chunk = chunk; this.nextLayer = nextLayer; this.maxPoint = maxPoint } chunkPos; chunk; nextLayer; maxPoint; static create(chunkPos, chunk, nextLayer, maxPoint) { return new _RangeSet(chunkPos, chunk, nextLayer, maxPoint) } get length() { let last = this.chunk.length - 1; return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length) } get size() { if (this.isEmpty) return 0; let size = this.nextLayer.size; for (let chunk of this.chunk) size += chunk.value.length; return size } chunkEnd(index) { return this.chunkPos[index] + this.chunk[index].length } update(updateSpec) { let { add: add2 = [], sort = !1, filterFrom = 0, filterTo = this.length } = updateSpec, filter = updateSpec.filter; if (add2.length == 0 && !filter) return this; if (sort && (add2 = add2.slice().sort(cmpRange)), this.isEmpty) return add2.length ? _RangeSet.of(add2) : this; let cur = new LayerCursor(this, null, -1).goto(0), i2 = 0, spill = [], builder = new RangeSetBuilder; for (; cur.value || i2 < add2.length;)if (i2 < add2.length && (cur.from - add2[i2].from || cur.startSide - add2[i2].value.startSide) >= 0) { let range = add2[i2++]; builder.addInner(range.from, range.to, range.value) || spill.push(range) } else cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && (i2 == add2.length || this.chunkEnd(cur.chunkIndex) < add2[i2].from) && (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex]) ? cur.nextChunk() : ((!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) && (builder.addInner(cur.from, cur.to, cur.value) || spill.push(Range.create(cur.from, cur.to, cur.value))), cur.next()); return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? _RangeSet.empty : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })) } map(changes) { if (changes.empty || this.isEmpty) return this; let chunks = [], chunkPos = [], maxPoint = -1; for (let i2 = 0; i2 < this.chunk.length; i2++) { let start = this.chunkPos[i2], chunk = this.chunk[i2], touch = changes.touchesRange(start, start + chunk.length); if (touch === !1) maxPoint = Math.max(maxPoint, chunk.maxPoint), chunks.push(chunk), chunkPos.push(changes.mapPos(start)); else if (touch === !0) { let { mapped, pos } = chunk.map(start, changes); mapped && (maxPoint = Math.max(maxPoint, mapped.maxPoint), chunks.push(mapped), chunkPos.push(pos)) } } let next = this.nextLayer.map(changes); return chunks.length == 0 ? next : new _RangeSet(chunkPos, chunks, next || _RangeSet.empty, maxPoint) } between(from, to, f) { if (!this.isEmpty) { for (let i2 = 0; i2 < this.chunk.length; i2++) { let start = this.chunkPos[i2], chunk = this.chunk[i2]; if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === !1) return } this.nextLayer.between(from, to, f) } } iter(from = 0) { return HeapCursor.from([this]).goto(from) } get isEmpty() { return this.nextLayer == this } static iter(sets, from = 0) { return HeapCursor.from(sets).goto(from) } static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) { let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize), b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize), sharedChunks = findSharedChunks(a, b, textDiff), sideA = new SpanCursor(a, sharedChunks, minPointSize), sideB = new SpanCursor(b, sharedChunks, minPointSize); textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)), textDiff.empty && textDiff.length == 0 && compare(sideA, 0, sideB, 0, 0, comparator) } static eq(oldSets, newSets, from = 0, to) { to == null && (to = 999999999); let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0), b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); if (a.length != b.length) return !1; if (!a.length) return !0; let sharedChunks = findSharedChunks(a, b), sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); for (; ;) { if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point))) return !1; if (sideA.to > to) return !0; sideA.next(), sideB.next() } } static spans(sets, from, to, iterator, minPointSize = -1) { let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from, openRanges = cursor.openStart; for (; ;) { let curTo = Math.min(cursor.to, to); if (cursor.point) { let active = cursor.activeForPoint(cursor.to), openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges); iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank), openRanges = Math.min(cursor.openEnd(curTo), active.length) } else curTo > pos && (iterator.span(pos, curTo, cursor.active, openRanges), openRanges = cursor.openEnd(curTo)); if (cursor.to > to) return openRanges + (cursor.point && cursor.to > to ? 1 : 0); pos = cursor.to, cursor.next() } } static of(ranges, sort = !1) { let build = new RangeSetBuilder; for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value); return build.finish() } static join(sets) { if (!sets.length) return _RangeSet.empty; let result = sets[sets.length - 1]; for (let i2 = sets.length - 2; i2 >= 0; i2--)for (let layer2 = sets[i2]; layer2 != _RangeSet.empty; layer2 = layer2.nextLayer)result = new _RangeSet(layer2.chunkPos, layer2.chunk, result, Math.max(layer2.maxPoint, result.maxPoint)); return result } static empty = new _RangeSet([], [], null, -1) }; function lazySort(ranges) { if (ranges.length > 1) for (let prev = ranges[0], i2 = 1; i2 < ranges.length; i2++) { let cur = ranges[i2]; if (cmpRange(prev, cur) > 0) return ranges.slice().sort(cmpRange); prev = cur } return ranges } RangeSet.empty.nextLayer = RangeSet.empty; var RangeSetBuilder = class _RangeSetBuilder { chunks = []; chunkPos = []; chunkStart = -1; last = null; lastFrom = -1e9; lastTo = -1e9; from = []; to = []; value = []; maxPoint = -1; setMaxPoint = -1; nextLayer = null; finishChunk(newArrays) { this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint)), this.chunkPos.push(this.chunkStart), this.chunkStart = -1, this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint), this.maxPoint = -1, newArrays && (this.from = [], this.to = [], this.value = []) } constructor() { } add(from, to, value) { this.addInner(from, to, value) || (this.nextLayer || (this.nextLayer = new _RangeSetBuilder)).add(from, to, value) } addInner(from, to, value) { let diff = from - this.lastTo || value.startSide - this.last.endSide; if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) throw new Error("Ranges must be added sorted by `from` position and `startSide`"); return diff < 0 ? !1 : (this.from.length == 250 && this.finishChunk(!0), this.chunkStart < 0 && (this.chunkStart = from), this.from.push(from - this.chunkStart), this.to.push(to - this.chunkStart), this.last = value, this.lastFrom = from, this.lastTo = to, this.value.push(value), value.point && (this.maxPoint = Math.max(this.maxPoint, to - from)), !0) } addChunk(from, chunk) { if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) return !1; this.from.length && this.finishChunk(!0), this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint), this.chunks.push(chunk), this.chunkPos.push(from); let last = chunk.value.length - 1; return this.last = chunk.value[last], this.lastFrom = chunk.from[last] + from, this.lastTo = chunk.to[last] + from, !0 } finish() { return this.finishInner(RangeSet.empty) } finishInner(next) { if (this.from.length && this.finishChunk(!1), this.chunks.length == 0) return next; let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); return this.from = null, result } }; function findSharedChunks(a, b, textDiff) { let inA = new Map; for (let set of a) for (let i2 = 0; i2 < set.chunk.length; i2++)set.chunk[i2].maxPoint <= 0 && inA.set(set.chunk[i2], set.chunkPos[i2]); let shared = new Set; for (let set of b) for (let i2 = 0; i2 < set.chunk.length; i2++) { let known = inA.get(set.chunk[i2]); known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i2] && !textDiff?.touchesRange(known, known + set.chunk[i2].length) && shared.add(set.chunk[i2]) } return shared } var LayerCursor = class { constructor(layer2, skip, minPoint, rank = 0) { this.layer = layer2; this.skip = skip; this.minPoint = minPoint; this.rank = rank } layer; skip; minPoint; rank; get startSide() { return this.value ? this.value.startSide : 0 } get endSide() { return this.value ? this.value.endSide : 0 } goto(pos, side = -1e9) { return this.chunkIndex = this.rangeIndex = 0, this.gotoInner(pos, side, !1), this } gotoInner(pos, side, forward) { for (; this.chunkIndex < this.layer.chunk.length;) { let next = this.layer.chunk[this.chunkIndex]; if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) break; this.chunkIndex++, forward = !1 } if (this.chunkIndex < this.layer.chunk.length) { let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, !0); (!forward || this.rangeIndex < rangeIndex) && this.setRangeIndex(rangeIndex) } this.next() } forward(pos, side) { (this.to - pos || this.endSide - side) < 0 && this.gotoInner(pos, side, !0) } next() { for (; ;)if (this.chunkIndex == this.layer.chunk.length) { this.from = this.to = 1e9, this.value = null; break } else { let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex], from = chunkPos + chunk.from[this.rangeIndex]; if (this.from = from, this.to = chunkPos + chunk.to[this.rangeIndex], this.value = chunk.value[this.rangeIndex], this.setRangeIndex(this.rangeIndex + 1), this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) break } } setRangeIndex(index) { if (index == this.layer.chunk[this.chunkIndex].value.length) { if (this.chunkIndex++, this.skip) for (; this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++; this.rangeIndex = 0 } else this.rangeIndex = index } nextChunk() { this.chunkIndex++, this.rangeIndex = 0, this.next() } compare(other) { return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide } }, HeapCursor = class _HeapCursor { constructor(heap) { this.heap = heap } heap; static from(sets, skip = null, minPoint = -1) { let heap = []; for (let i2 = 0; i2 < sets.length; i2++)for (let cur = sets[i2]; !cur.isEmpty; cur = cur.nextLayer)cur.maxPoint >= minPoint && heap.push(new LayerCursor(cur, skip, minPoint, i2)); return heap.length == 1 ? heap[0] : new _HeapCursor(heap) } get startSide() { return this.value ? this.value.startSide : 0 } goto(pos, side = -1e9) { for (let cur of this.heap) cur.goto(pos, side); for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)heapBubble(this.heap, i2); return this.next(), this } forward(pos, side) { for (let cur of this.heap) cur.forward(pos, side); for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)heapBubble(this.heap, i2); (this.to - pos || this.value.endSide - side) < 0 && this.next() } next() { if (this.heap.length == 0) this.from = this.to = 1e9, this.value = null, this.rank = -1; else { let top2 = this.heap[0]; this.from = top2.from, this.to = top2.to, this.value = top2.value, this.rank = top2.rank, top2.value && top2.next(), heapBubble(this.heap, 0) } } }; function heapBubble(heap, index) { for (let cur = heap[index]; ;) { let childIndex = (index << 1) + 1; if (childIndex >= heap.length) break; let child = heap[childIndex]; if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0 && (child = heap[childIndex + 1], childIndex++), cur.compare(child) < 0) break; heap[childIndex] = cur, heap[index] = child, index = childIndex } } var SpanCursor = class { constructor(sets, skip, minPoint) { this.minPoint = minPoint; this.cursor = HeapCursor.from(sets, skip, minPoint) } minPoint; cursor; active = []; activeTo = []; activeRank = []; minActive = -1; point = null; pointFrom = 0; pointRank = 0; to = -1e9; endSide = 0; openStart = -1; goto(pos, side = -1e9) { return this.cursor.goto(pos, side), this.active.length = this.activeTo.length = this.activeRank.length = 0, this.minActive = -1, this.to = pos, this.endSide = side, this.openStart = -1, this.next(), this } forward(pos, side) { for (; this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0;)this.removeActive(this.minActive); this.cursor.forward(pos, side) } removeActive(index) { remove(this.active, index), remove(this.activeTo, index), remove(this.activeRank, index), this.minActive = findMinIndex(this.active, this.activeTo) } addActive(trackOpen) { let i2 = 0, { value, to, rank } = this.cursor; for (; i2 < this.activeRank.length && (rank - this.activeRank[i2] || to - this.activeTo[i2]) > 0;)i2++; insert(this.active, i2, value), insert(this.activeTo, i2, to), insert(this.activeRank, i2, rank), trackOpen && insert(trackOpen, i2, this.cursor.from), this.minActive = findMinIndex(this.active, this.activeTo) } next() { let from = this.to, wasPoint = this.point; this.point = null; let trackOpen = this.openStart < 0 ? [] : null; for (; ;) { let a = this.minActive; if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { if (this.activeTo[a] > from) { this.to = this.activeTo[a], this.endSide = this.active[a].endSide; break } this.removeActive(a), trackOpen && remove(trackOpen, a) } else if (this.cursor.value) if (this.cursor.from > from) { this.to = this.cursor.from, this.endSide = this.cursor.startSide; break } else { let nextVal = this.cursor.value; if (!nextVal.point) this.addActive(trackOpen), this.cursor.next(); else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) this.cursor.next(); else { this.point = nextVal, this.pointFrom = this.cursor.from, this.pointRank = this.cursor.rank, this.to = this.cursor.to, this.endSide = nextVal.endSide, this.cursor.next(), this.forward(this.to, this.endSide); break } } else { this.to = this.endSide = 1e9; break } } if (trackOpen) { this.openStart = 0; for (let i2 = trackOpen.length - 1; i2 >= 0 && trackOpen[i2] < from; i2--)this.openStart++ } } activeForPoint(to) { if (!this.active.length) return this.active; let active = []; for (let i2 = this.active.length - 1; i2 >= 0 && !(this.activeRank[i2] < this.pointRank); i2--)(this.activeTo[i2] > to || this.activeTo[i2] == to && this.active[i2].endSide >= this.point.endSide) && active.push(this.active[i2]); return active.reverse() } openEnd(to) { let open = 0; for (let i2 = this.activeTo.length - 1; i2 >= 0 && this.activeTo[i2] > to; i2--)open++; return open } }; function compare(a, startA, b, startB, length, comparator) { a.goto(startA), b.goto(startB); let endB = startB + length, pos = startB, dPos = startB - startA, bounds = !!comparator.boundChange; for (let boundChange = !1; ;) { let dEnd = a.to + dPos - b.to, diff = dEnd || a.endSide - b.endSide, end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); if (a.point || b.point ? (a.point && b.point && cmpVal(a.point, b.point) && sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to)) || comparator.comparePoint(pos, clipEnd, a.point, b.point), boundChange = !1) : (boundChange && comparator.boundChange(pos), clipEnd > pos && !sameValues(a.active, b.active) && comparator.compareRange(pos, clipEnd, a.active, b.active), bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)) && (boundChange = !0)), end > endB) break; pos = end, diff <= 0 && a.next(), diff >= 0 && b.next() } } function sameValues(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (a[i2] != b[i2] && !cmpVal(a[i2], b[i2])) return !1; return !0 } function remove(array, index) { for (let i2 = index, e = array.length - 1; i2 < e; i2++)array[i2] = array[i2 + 1]; array.pop() } function insert(array, index, value) { for (let i2 = array.length - 1; i2 >= index; i2--)array[i2 + 1] = array[i2]; array[index] = value } function findMinIndex(value, array) { let found = -1, foundPos = 1e9; for (let i2 = 0; i2 < array.length; i2++)(array[i2] - foundPos || value[i2].endSide - value[found].endSide) < 0 && (found = i2, foundPos = array[i2]); return found } function countColumn(string2, tabSize, to = string2.length) { let n = 0; for (let i2 = 0; i2 < to && i2 < string2.length;)string2.charCodeAt(i2) == 9 ? (n += tabSize - n % tabSize, i2++) : (n++, i2 = findClusterBreak2(string2, i2)); return n } function findColumn(string2, col, tabSize, strict) { for (let i2 = 0, n = 0; ;) { if (n >= col) return i2; if (i2 == string2.length) break; n += string2.charCodeAt(i2) == 9 ? tabSize - n % tabSize : 1, i2 = findClusterBreak2(string2, i2) } return strict === !0 ? -1 : string2.length } var COUNT = typeof Symbol > "u" ? "__\u037C" : Symbol.for("\u037C"), SET = typeof Symbol > "u" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"), top = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : {}, StyleModule = class { + constructor(spec, options) { this.rules = []; let { finish } = options || {}; function splitSelector(selector) { return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) } function render(selectors, spec2, target, isKeyframes) { let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; if (isAt && spec2 == null) return target.push(selectors[0] + ";"); for (let prop in spec2) { let value = spec2[prop]; if (/&/.test(prop)) render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), value, target); else if (value && typeof value == "object") { if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value."); render(splitSelector(prop), value, local, keyframes) } else value != null && local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";") } (local.length || keyframes) && target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}") } for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules) } getRules() { + return this.rules.join(` +`) + } static newName() { let id = top[COUNT] || 1; return top[COUNT] = id + 1, "\u037C" + id.toString(36) } static mount(root, modules, options) { let set = root[SET], nonce = options && options.nonce; set ? nonce && set.setNonce(nonce) : set = new StyleSet(root, nonce), set.mount(Array.isArray(modules) ? modules : [modules], root) } +}, adoptedSet = new Map, StyleSet = class { + constructor(root, nonce) { let doc2 = root.ownerDocument || root, win = doc2.defaultView; if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) { let adopted = adoptedSet.get(doc2); if (adopted) return root[SET] = adopted; this.sheet = new win.CSSStyleSheet, adoptedSet.set(doc2, this) } else this.styleTag = doc2.createElement("style"), nonce && this.styleTag.setAttribute("nonce", nonce); this.modules = [], root[SET] = this } mount(modules, root) { + let sheet = this.sheet, pos = 0, j = 0; for (let i2 = 0; i2 < modules.length; i2++) { let mod = modules[i2], index = this.modules.indexOf(mod); if (index < j && index > -1 && (this.modules.splice(index, 1), j--, index = -1), index == -1) { if (this.modules.splice(j++, 0, mod), sheet) for (let k = 0; k < mod.rules.length; k++)sheet.insertRule(mod.rules[k], pos++) } else { for (; j < index;)pos += this.modules[j++].rules.length; pos += mod.rules.length, j++ } } if (sheet) root.adoptedStyleSheets.indexOf(this.sheet) < 0 && (root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets]); else { + let text = ""; for (let i2 = 0; i2 < this.modules.length; i2++)text += this.modules[i2].getRules() + ` +`; this.styleTag.textContent = text; let target = root.head || root; this.styleTag.parentNode != target && target.insertBefore(this.styleTag, target.firstChild) + } + } setNonce(nonce) { this.styleTag && this.styleTag.getAttribute("nonce") != nonce && this.styleTag.setAttribute("nonce", nonce) } +}; var nav = typeof navigator < "u" ? navigator : { userAgent: "", vendor: "", platform: "" }, doc = typeof document < "u" ? document : { documentElement: { style: {} } }, ie_edge = /Edge\/(\d+)/.exec(nav.userAgent), ie_upto10 = /MSIE \d/.test(nav.userAgent), ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent), ie = !!(ie_upto10 || ie_11up || ie_edge), gecko = !ie && /gecko\/(\d+)/i.test(nav.userAgent), chrome = !ie && /Chrome\/(\d+)/.exec(nav.userAgent), webkit = "webkitFontSmoothing" in doc.documentElement.style, safari = !ie && /Apple Computer/.test(nav.vendor), ios = safari && (/Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2), browser_default = { mac: ios || /Mac/.test(nav.platform), windows: /Win/.test(nav.platform), linux: /Linux|X11/.test(nav.platform), ie, ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, gecko, gecko_version: gecko ? +(/Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, chrome: !!chrome, chrome_version: chrome ? +chrome[1] : 0, ios, android: /Android\b/.test(nav.userAgent), webkit, webkit_version: webkit ? +(/\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, safari, safari_version: safari ? +(/\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0, tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" }; function combineAttrs(source, target) { for (let name2 in source) name2 == "class" && target.class ? target.class += " " + source.class : name2 == "style" && target.style ? target.style += ";" + source.style : target[name2] = source[name2]; return target } var noAttrs = Object.create(null); function attrsEq(a, b, ignore) { if (a == b) return !0; a || (a = noAttrs), b || (b = noAttrs); let keysA = Object.keys(a), keysB = Object.keys(b); if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0)) return !1; for (let key of keysA) if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key])) return !1; return !0 } function setAttrs(dom, attrs) { for (let i2 = dom.attributes.length - 1; i2 >= 0; i2--) { let name2 = dom.attributes[i2].name; attrs[name2] == null && dom.removeAttribute(name2) } for (let name2 in attrs) { let value = attrs[name2]; name2 == "style" ? dom.style.cssText = value : dom.getAttribute(name2) != value && dom.setAttribute(name2, value) } } function updateAttrs(dom, prev, attrs) { let changed = !1; if (prev) for (let name2 in prev) attrs && name2 in attrs || (changed = !0, name2 == "style" ? dom.style.cssText = "" : dom.removeAttribute(name2)); if (attrs) for (let name2 in attrs) prev && prev[name2] == attrs[name2] || (changed = !0, name2 == "style" ? dom.style.cssText = attrs[name2] : dom.setAttribute(name2, attrs[name2])); return changed } function getAttrs(dom) { let attrs = Object.create(null); for (let i2 = 0; i2 < dom.attributes.length; i2++) { let attr = dom.attributes[i2]; attrs[attr.name] = attr.value } return attrs } var WidgetType = class { eq(widget) { return !1 } updateDOM(dom, view, from) { return !1 } compare(other) { return this == other || this.constructor == other.constructor && this.eq(other) } get estimatedHeight() { return -1 } get lineBreaks() { return 0 } ignoreEvent(event) { return !0 } coordsAt(dom, pos, side) { return null } get isHidden() { return !1 } get editable() { return !1 } destroy(dom) { } }; var BlockType = (BlockType2 => (BlockType2[BlockType2.Text = 0] = "Text", BlockType2[BlockType2.WidgetBefore = 1] = "WidgetBefore", BlockType2[BlockType2.WidgetAfter = 2] = "WidgetAfter", BlockType2[BlockType2.WidgetRange = 3] = "WidgetRange", BlockType2))(BlockType || {}), Decoration = class extends RangeValue { constructor(startSide, endSide, widget, spec) { super(); this.startSide = startSide; this.endSide = endSide; this.widget = widget; this.spec = spec } startSide; endSide; widget; spec; get heightRelevant() { return !1 } static mark(spec) { return new MarkDecoration(spec) } static widget(spec) { let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)), block = !!spec.block; return side += block && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8, new PointDecoration(spec, side, side, block, spec.widget || null, !1) } static replace(spec) { let block = !!spec.block, startSide, endSide; if (spec.isBlockGap) startSide = -5e8, endSide = 4e8; else { let { start, end } = getInclusive(spec, block); startSide = (start ? block ? -3e8 : -1 : 5e8) - 1, endSide = (end ? block ? 2e8 : 1 : -6e8) + 1 } return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, !0) } static line(spec) { return new LineDecoration(spec) } static set(of, sort = !1) { return RangeSet.of(of, sort) } static none = RangeSet.empty; hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : !1 } }, MarkDecoration = class _MarkDecoration extends Decoration { tagName; attrs; constructor(spec) { let { start, end } = getInclusive(spec); super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec), this.tagName = spec.tagName || "span", this.attrs = spec.class && spec.attributes ? combineAttrs(spec.attributes, { class: spec.class }) : spec.class ? { class: spec.class } : spec.attributes || noAttrs } eq(other) { return this == other || other instanceof _MarkDecoration && this.tagName == other.tagName && attrsEq(this.attrs, other.attrs) } range(from, to = from) { if (from >= to) throw new RangeError("Mark decorations may not be empty"); return super.range(from, to) } }; MarkDecoration.prototype.point = !1; var LineDecoration = class _LineDecoration extends Decoration { constructor(spec) { super(-2e8, -2e8, null, spec) } eq(other) { return other instanceof _LineDecoration && this.spec.class == other.spec.class && attrsEq(this.spec.attributes, other.spec.attributes) } range(from, to = from) { if (to != from) throw new RangeError("Line decoration ranges must be zero-length"); return super.range(from, to) } }; LineDecoration.prototype.mapMode = 2; LineDecoration.prototype.point = !0; var PointDecoration = class _PointDecoration extends Decoration { constructor(spec, startSide, endSide, block, widget, isReplace) { super(startSide, endSide, widget, spec); this.block = block; this.isReplace = isReplace; this.mapMode = block ? startSide <= 0 ? 2 : 3 : 1 } block; isReplace; get type() { return this.startSide != this.endSide ? 3 : this.startSide <= 0 ? 1 : 2 } get heightRelevant() { return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0) } eq(other) { return other instanceof _PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide } range(from, to = from) { if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0)) throw new RangeError("Invalid range for replacement decoration"); if (!this.isReplace && to != from) throw new RangeError("Widget decorations can only have zero-length ranges"); return super.range(from, to) } }; PointDecoration.prototype.point = !0; function getInclusive(spec, block = !1) { let { inclusiveStart: start, inclusiveEnd: end } = spec; return start == null && (start = spec.inclusive), end == null && (end = spec.inclusive), { start: start ?? block, end: end ?? block } } function widgetsEq(a, b) { return a == b || !!(a && b && a.compare(b)) } function addRange(from, to, ranges, margin = 0) { let last = ranges.length - 1; last >= 0 && ranges[last] + margin >= from ? ranges[last] = Math.max(ranges[last], to) : ranges.push(from, to) } var BlockWrapper = class _BlockWrapper extends RangeValue { constructor(tagName, attributes) { super(); this.tagName = tagName; this.attributes = attributes } tagName; attributes; eq(other) { return other == this || other instanceof _BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes) } static create(spec) { return new _BlockWrapper(spec.tagName, spec.attributes || noAttrs) } static set(of, sort = !1) { return RangeSet.of(of, sort) } }; BlockWrapper.prototype.startSide = BlockWrapper.prototype.endSide = -1; function getSelection(root) { let target; return root.nodeType == 11 ? target = root.getSelection ? root : root.ownerDocument : target = root, target.getSelection() } function contains(dom, node) { return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : !1 } function hasSelection(dom, selection) { if (!selection.anchorNode) return !1; try { return contains(dom, selection.anchorNode) } catch { return !1 } } function clientRectsFor(dom) { return dom.nodeType == 3 ? textRange(dom, 0, dom.nodeValue.length).getClientRects() : dom.nodeType == 1 ? dom.getClientRects() : [] } function isEquivalentPosition(node, off, targetNode, targetOff) { return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : !1 } function domIndex(node) { for (var index = 0; ; index++)if (node = node.previousSibling, !node) return index } function isBlockElement(node) { return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName) } function scanFor(node, off, targetNode, targetOff, dir) { for (; ;) { if (node == targetNode && off == targetOff) return !0; if (off == (dir < 0 ? 0 : maxOffset(node))) { if (node.nodeName == "DIV") return !1; let parent = node.parentNode; if (!parent || parent.nodeType != 1) return !1; off = domIndex(node) + (dir < 0 ? 0 : 1), node = parent } else if (node.nodeType == 1) { if (node = node.childNodes[off + (dir < 0 ? -1 : 0)], node.nodeType == 1 && node.contentEditable == "false") return !1; off = dir < 0 ? maxOffset(node) : 0 } else return !1 } } function maxOffset(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length } function flattenRect(rect, left) { let x = left ? rect.left : rect.right; return { left: x, right: x, top: rect.top, bottom: rect.bottom } } function windowRect(win) { let vp = win.visualViewport; return vp ? { left: 0, right: vp.width, top: 0, bottom: vp.height } : { left: 0, right: win.innerWidth, top: 0, bottom: win.innerHeight } } function getScale(elt, rect) { let scaleX = rect.width / elt.offsetWidth, scaleY = rect.height / elt.offsetHeight; return (scaleX > .995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1) && (scaleX = 1), (scaleY > .995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1) && (scaleY = 1), { scaleX, scaleY } } function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { let doc2 = dom.ownerDocument, win = doc2.defaultView || window; for (let cur = dom, stop = !1; cur && !stop;)if (cur.nodeType == 1) { let bounding, top2 = cur == doc2.body, scaleX = 1, scaleY = 1; if (top2) bounding = windowRect(win); else { if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position) && (stop = !0), cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { cur = cur.assignedSlot || cur.parentNode; continue } let rect2 = cur.getBoundingClientRect(); ({ scaleX, scaleY } = getScale(cur, rect2)), bounding = { left: rect2.left, right: rect2.left + cur.clientWidth * scaleX, top: rect2.top, bottom: rect2.top + cur.clientHeight * scaleY } } let moveX = 0, moveY = 0; if (y == "nearest") rect.top < bounding.top + yMargin ? (moveY = rect.top - (bounding.top + yMargin), side > 0 && rect.bottom > bounding.bottom + moveY && (moveY = rect.bottom - bounding.bottom + yMargin)) : rect.bottom > bounding.bottom - yMargin && (moveY = rect.bottom - bounding.bottom + yMargin, side < 0 && rect.top - moveY < bounding.top && (moveY = rect.top - (bounding.top + yMargin))); else { let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; moveY = (y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin) - bounding.top } if (x == "nearest" ? rect.left < bounding.left + xMargin ? (moveX = rect.left - (bounding.left + xMargin), side > 0 && rect.right > bounding.right + moveX && (moveX = rect.right - bounding.right + xMargin)) : rect.right > bounding.right - xMargin && (moveX = rect.right - bounding.right + xMargin, side < 0 && rect.left < bounding.left + moveX && (moveX = rect.left - (bounding.left + xMargin))) : moveX = (x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin) - bounding.left, moveX || moveY) if (top2) win.scrollBy(moveX, moveY); else { let movedX = 0, movedY = 0; if (moveY) { let start = cur.scrollTop; cur.scrollTop += moveY / scaleY, movedY = (cur.scrollTop - start) * scaleY } if (moveX) { let start = cur.scrollLeft; cur.scrollLeft += moveX / scaleX, movedX = (cur.scrollLeft - start) * scaleX } rect = { left: rect.left - movedX, top: rect.top - movedY, right: rect.right - movedX, bottom: rect.bottom - movedY }, movedX && Math.abs(movedX - moveX) < 1 && (x = "nearest"), movedY && Math.abs(movedY - moveY) < 1 && (y = "nearest") } if (top2) break; (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right) && (rect = { left: Math.max(rect.left, bounding.left), right: Math.min(rect.right, bounding.right), top: Math.max(rect.top, bounding.top), bottom: Math.min(rect.bottom, bounding.bottom) }), cur = cur.assignedSlot || cur.parentNode } else if (cur.nodeType == 11) cur = cur.host; else break } function scrollableParents(dom, getX = !0) { let doc2 = dom.ownerDocument, x = null, y = null; for (let cur = dom.parentNode; cur && !(cur == doc2.body || (!getX || x) && y);)if (cur.nodeType == 1) !y && cur.scrollHeight > cur.clientHeight && (y = cur), getX && !x && cur.scrollWidth > cur.clientWidth && (x = cur), cur = cur.assignedSlot || cur.parentNode; else if (cur.nodeType == 11) cur = cur.host; else break; return { x, y } } var DOMSelectionState = class { anchorNode = null; anchorOffset = 0; focusNode = null; focusOffset = 0; eq(domSel) { return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset } setRange(range) { let { anchorNode, focusNode } = range; this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0)) } set(anchorNode, anchorOffset, focusNode, focusOffset) { this.anchorNode = anchorNode, this.anchorOffset = anchorOffset, this.focusNode = focusNode, this.focusOffset = focusOffset } }, preventScrollSupported = null; browser_default.safari && browser_default.safari_version >= 26 && (preventScrollSupported = !1); function focusPreventScroll(dom) { if (dom.setActive) return dom.setActive(); if (preventScrollSupported) return dom.focus(preventScrollSupported); let stack = []; for (let cur = dom; cur && (stack.push(cur, cur.scrollTop, cur.scrollLeft), cur != cur.ownerDocument); cur = cur.parentNode); if (dom.focus(preventScrollSupported == null ? { get preventScroll() { return preventScrollSupported = { preventScroll: !0 }, !0 } } : void 0), !preventScrollSupported) { preventScrollSupported = !1; for (let i2 = 0; i2 < stack.length;) { let elt = stack[i2++], top2 = stack[i2++], left = stack[i2++]; elt.scrollTop != top2 && (elt.scrollTop = top2), elt.scrollLeft != left && (elt.scrollLeft = left) } } } var scratchRange; function textRange(node, from, to = from) { let range = scratchRange || (scratchRange = document.createRange()); return range.setEnd(node, to), range.setStart(node, from), range } function dispatchKey(elt, name2, code2, mods) { let options = { key: name2, code: name2, keyCode: code2, which: code2, cancelable: !0 }; mods && ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods); let down = new KeyboardEvent("keydown", options); down.synthetic = !0, elt.dispatchEvent(down); let up = new KeyboardEvent("keyup", options); return up.synthetic = !0, elt.dispatchEvent(up), down.defaultPrevented || up.defaultPrevented } function getRoot(node) { for (; node;) { if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) return node; node = node.assignedSlot || node.parentNode } return null } function atElementStart(doc2, selection) { let node = selection.focusNode, offset = selection.focusOffset; if (!node || selection.anchorNode != node || selection.anchorOffset != offset) return !1; for (offset = Math.min(offset, maxOffset(node)); ;)if (offset) { if (node.nodeType != 1) return !1; let prev = node.childNodes[offset - 1]; prev.contentEditable == "false" ? offset-- : (node = prev, offset = maxOffset(node)) } else { if (node == doc2) return !0; offset = domIndex(node), node = node.parentNode } } function isScrolledToBottom(elt) { return elt instanceof Window ? elt.pageYOffset > Math.max(0, elt.document.documentElement.scrollHeight - elt.innerHeight - 4) : elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4) } function textNodeBefore(startNode, startOffset) { for (let node = startNode, offset = startOffset; ;) { if (node.nodeType == 3 && offset > 0) return { node, offset }; if (node.nodeType == 1 && offset > 0) { if (node.contentEditable == "false") return null; node = node.childNodes[offset - 1], offset = maxOffset(node) } else if (node.parentNode && !isBlockElement(node)) offset = domIndex(node), node = node.parentNode; else return null } } function textNodeAfter(startNode, startOffset) { for (let node = startNode, offset = startOffset; ;) { if (node.nodeType == 3 && offset < node.nodeValue.length) return { node, offset }; if (node.nodeType == 1 && offset < node.childNodes.length) { if (node.contentEditable == "false") return null; node = node.childNodes[offset], offset = 0 } else if (node.parentNode && !isBlockElement(node)) offset = domIndex(node) + 1, node = node.parentNode; else return null } } var DOMPos = class _DOMPos { constructor(node, offset, precise = !0) { this.node = node; this.offset = offset; this.precise = precise } node; offset; precise; static before(dom, precise) { return new _DOMPos(dom.parentNode, domIndex(dom), precise) } static after(dom, precise) { return new _DOMPos(dom.parentNode, domIndex(dom) + 1, precise) } }; var Direction = (Direction2 => (Direction2[Direction2.LTR = 0] = "LTR", Direction2[Direction2.RTL = 1] = "RTL", Direction2))(Direction || {}), LTR = 0, RTL = 1; function dec(str) { let result = []; for (let i2 = 0; i2 < str.length; i2++)result.push(1 << +str[i2]); return result } var LowTypes = dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"), ArabicTypes = dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"), Brackets = Object.create(null), BracketStack = []; for (let p of ["()", "[]", "{}"]) { let l = p.charCodeAt(0), r = p.charCodeAt(1); Brackets[l] = r, Brackets[r] = -l } function charType(ch) { return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1 } var BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/, BidiSpan = class { constructor(from, to, level) { this.from = from; this.to = to; this.level = level } from; to; level; get dir() { return this.level % 2 ? RTL : LTR } side(end, dir) { return this.dir == dir == end ? this.to : this.from } forward(forward, dir) { return forward == (this.dir == dir) } static find(order, index, level, assoc) { let maybe = -1; for (let i2 = 0; i2 < order.length; i2++) { let span = order[i2]; if (span.from <= index && span.to >= index) { if (span.level == level) return i2; (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index : span.to > index : order[maybe].level > span.level)) && (maybe = i2) } } if (maybe < 0) throw new RangeError("Index out of range"); return maybe } }; function isolatesEq(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++) { let iA = a[i2], iB = b[i2]; if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner)) return !1 } return !0 } var types = []; function computeCharTypes(line, rFrom, rTo, isolates, outerType) { for (let iI = 0; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo, prevType = iI ? 256 : outerType; for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to; i2++) { let type = charType(line.charCodeAt(i2)); type == 512 ? type = prev : type == 8 && prevStrong == 4 && (type = 16), types[i2] = type == 4 ? 2 : type, type & 7 && (prevStrong = type), prev = type } for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to; i2++) { let type = types[i2]; if (type == 128) i2 < to - 1 && prev == types[i2 + 1] && prev & 24 ? type = types[i2] = prev : types[i2] = 256; else if (type == 64) { let end = i2 + 1; for (; end < to && types[end] == 64;)end++; let replace2 = i2 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256; for (let j = i2; j < end; j++)types[j] = replace2; i2 = end - 1 } else type == 8 && prevStrong == 1 && (types[i2] = 1); prev = type, type & 7 && (prevStrong = type) } } } function processBracketPairs(line, rFrom, rTo, isolates, outerType) { let oppositeType = outerType == 1 ? 2 : 1; for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo; for (let i2 = from, ch, br, type; i2 < to; i2++)if (br = Brackets[ch = line.charCodeAt(i2)]) if (br < 0) { for (let sJ = sI - 3; sJ >= 0; sJ -= 3)if (BracketStack[sJ + 1] == -br) { let flags = BracketStack[sJ + 2], type2 = flags & 2 ? outerType : flags & 4 ? flags & 1 ? oppositeType : outerType : 0; type2 && (types[i2] = types[BracketStack[sJ]] = type2), sI = sJ; break } } else { if (BracketStack.length == 189) break; BracketStack[sI++] = i2, BracketStack[sI++] = ch, BracketStack[sI++] = context } else if ((type = types[i2]) == 2 || type == 1) { let embed = type == outerType; context = embed ? 0 : 1; for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { let cur = BracketStack[sJ + 2]; if (cur & 2) break; if (embed) BracketStack[sJ + 2] |= 2; else { if (cur & 4) break; BracketStack[sJ + 2] |= 4 } } } } } function processNeutrals(rFrom, rTo, isolates, outerType) { for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo; for (let i2 = from; i2 < to;) { let type = types[i2]; if (type == 256) { let end = i2 + 1; for (; ;)if (end == to) { if (iI == isolates.length) break; end = isolates[iI++].to, to = iI < isolates.length ? isolates[iI].from : rTo } else if (types[end] == 256) end++; else break; let beforeL = prev == 1, afterL = (end < rTo ? types[end] : outerType) == 1, replace2 = beforeL == afterL ? beforeL ? 1 : 2 : outerType; for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i2;)j == fromJ && (j = isolates[--jI].from, fromJ = jI ? isolates[jI - 1].to : rFrom), types[--j] = replace2; i2 = end } else prev = type, i2++ } } } function emitSpans(line, from, to, level, baseLevel, isolates, order) { let ourType = level % 2 ? 2 : 1; if (level % 2 == baseLevel % 2) for (let iCh = from, iI = 0; iCh < to;) { let sameDir = !0, isNum = !1; if (iI == isolates.length || iCh < isolates[iI].from) { let next = types[iCh]; next != ourType && (sameDir = !1, isNum = next == 16) } let recurse = !sameDir && ourType == 1 ? [] : null, localLevel = sameDir ? level : level + 1, iScan = iCh; run: for (; ;)if (iI < isolates.length && iScan == isolates[iI].from) { if (isNum) break run; let iso = isolates[iI]; if (!sameDir) for (let upto = iso.to, jI = iI + 1; ;) { if (upto == to) break run; if (jI < isolates.length && isolates[jI].from == upto) upto = isolates[jI++].to; else { if (types[upto] == ourType) break run; break } } if (iI++, recurse) recurse.push(iso); else { iso.from > iCh && order.push(new BidiSpan(iCh, iso.from, localLevel)); let dirSwap = iso.direction == LTR != !(localLevel % 2); computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order), iCh = iso.to } iScan = iso.to } else { if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) break; iScan++ } recurse ? emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order) : iCh < iScan && order.push(new BidiSpan(iCh, iScan, localLevel)), iCh = iScan } else for (let iCh = to, iI = isolates.length; iCh > from;) { let sameDir = !0, isNum = !1; if (!iI || iCh > isolates[iI - 1].to) { let next = types[iCh - 1]; next != ourType && (sameDir = !1, isNum = next == 16) } let recurse = !sameDir && ourType == 1 ? [] : null, localLevel = sameDir ? level : level + 1, iScan = iCh; run: for (; ;)if (iI && iScan == isolates[iI - 1].to) { if (isNum) break run; let iso = isolates[--iI]; if (!sameDir) for (let upto = iso.from, jI = iI; ;) { if (upto == from) break run; if (jI && isolates[jI - 1].to == upto) upto = isolates[--jI].from; else { if (types[upto - 1] == ourType) break run; break } } if (recurse) recurse.push(iso); else { iso.to < iCh && order.push(new BidiSpan(iso.to, iCh, localLevel)); let dirSwap = iso.direction == LTR != !(localLevel % 2); computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order), iCh = iso.from } iScan = iso.from } else { if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) break; iScan-- } recurse ? emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order) : iScan < iCh && order.push(new BidiSpan(iScan, iCh, localLevel)), iCh = iScan } } function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) { let outerType = level % 2 ? 2 : 1; computeCharTypes(line, from, to, isolates, outerType), processBracketPairs(line, from, to, isolates, outerType), processNeutrals(from, to, isolates, outerType), emitSpans(line, from, to, level, baseLevel, isolates, order) } function computeOrder(line, direction, isolates) { if (!line) return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)]; if (direction == LTR && !isolates.length && !BidiRE.test(line)) return trivialOrder(line.length); if (isolates.length) for (; line.length > types.length;)types[types.length] = 256; let order = [], level = direction == LTR ? 0 : 1; return computeSectionOrder(line, level, level, isolates, 0, line.length, order), order } function trivialOrder(length) { return [new BidiSpan(0, length, 0)] } var movedOver = ""; function moveVisually(line, order, dir, start, forward) { let startIndex = start.head - line.from, spanI = BidiSpan.find(order, startIndex, start.bidiLevel ?? -1, start.assoc), span = order[spanI], spanEnd = span.side(forward, dir); if (startIndex == spanEnd) { let nextI = spanI += forward ? 1 : -1; if (nextI < 0 || nextI >= order.length) return null; span = order[spanI = nextI], startIndex = span.side(!forward, dir), spanEnd = span.side(forward, dir) } let nextIndex = findClusterBreak2(line.text, startIndex, span.forward(forward, dir)); (nextIndex < span.from || nextIndex > span.to) && (nextIndex = spanEnd), movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; return nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level ? EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level) : EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level) } function autoDirection(text, from, to) { for (let i2 = from; i2 < to; i2++) { let type = charType(text.charCodeAt(i2)); if (type == 1) return LTR; if (type == 2 || type == 4) return RTL } return LTR } var clickAddsSelectionRange = Facet.define(), dragMovesSelection = Facet.define(), mouseSelectionStyle = Facet.define(), exceptionSink = Facet.define(), updateListener = Facet.define(), inputHandler = Facet.define(), focusChangeEffect = Facet.define(), clipboardInputFilter = Facet.define(), clipboardOutputFilter = Facet.define(), perLineTextDirection = Facet.define({ combine: values => values.some(x => x) }), nativeSelectionHidden = Facet.define({ combine: values => values.some(x => x) }), scrollHandler = Facet.define(), ScrollTarget = class _ScrollTarget { constructor(range, y, x, yMargin, xMargin, isSnapshot = !1) { this.range = range; this.y = y; this.x = x; this.yMargin = yMargin; this.xMargin = xMargin; this.isSnapshot = isSnapshot } range; y; x; yMargin; xMargin; isSnapshot; map(changes) { return changes.empty ? this : new _ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot) } clip(state) { return this.range.to <= state.doc.length ? this : new _ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot) } }, scrollIntoView = StateEffect.define({ map: (t2, ch) => t2.map(ch) }), setEditContextFormatting = StateEffect.define(); function logException(state, exception, context) { let handler = state.facet(exceptionSink); handler.length ? handler[0](exception) : window.onerror && window.onerror(String(exception), context, void 0, void 0, exception) || (context ? console.error(context + ":", exception) : console.error(exception)) } var editable = Facet.define({ combine: values => values.length ? values[0] : !0 }), nextPluginID = 0, viewPlugin = Facet.define({ combine(plugins) { return plugins.filter((p, i2) => { for (let j = 0; j < i2; j++)if (plugins[j].plugin == p.plugin) return !1; return !0 }) } }), ViewPlugin = class _ViewPlugin { constructor(id, create, domEventHandlers, domEventObservers, buildExtensions) { this.id = id; this.create = create; this.domEventHandlers = domEventHandlers; this.domEventObservers = domEventObservers; this.baseExtensions = buildExtensions(this), this.extension = this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg: void 0 })) } id; create; domEventHandlers; domEventObservers; extension; baseExtensions; of(arg) { return this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg })) } static define(create, spec) { let { eventHandlers, eventObservers, provide, decorations: deco } = spec || {}; return new _ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin2 => { let ext = []; return deco && ext.push(decorations.of(view => { let pluginInst = view.plugin(plugin2); return pluginInst ? deco(pluginInst) : Decoration.none })), provide && ext.push(provide(plugin2)), ext }) } static fromClass(cls, spec) { return _ViewPlugin.define((view, arg) => new cls(view, arg), spec) } }, PluginInstance = class { constructor(spec) { this.spec = spec } spec; mustUpdate = null; value = null; get plugin() { return this.spec && this.spec.plugin } update(view) { if (this.value) { if (this.mustUpdate) { let update = this.mustUpdate; if (this.mustUpdate = null, this.value.update) try { this.value.update(update) } catch (e) { if (logException(update.state, e, "CodeMirror plugin crashed"), this.value.destroy) try { this.value.destroy() } catch { } this.deactivate() } } } else if (this.spec) try { this.value = this.spec.plugin.create(view, this.spec.arg) } catch (e) { logException(view.state, e, "CodeMirror plugin crashed"), this.deactivate() } return this } destroy(view) { if (this.value?.destroy) try { this.value.destroy() } catch (e) { logException(view.state, e, "CodeMirror plugin crashed") } } deactivate() { this.spec = this.value = null } }, editorAttributes = Facet.define(), contentAttributes = Facet.define(), decorations = Facet.define(), blockWrappers = Facet.define(), outerDecorations = Facet.define(), atomicRanges = Facet.define(), bidiIsolatedRanges = Facet.define(); function getIsolatedRanges(view, line) { let isolates = view.state.facet(bidiIsolatedRanges); if (!isolates.length) return isolates; let sets = isolates.map(i2 => i2 instanceof Function ? i2(view) : i2), result = []; return RangeSet.spans(sets, line.from, line.to, { point() { }, span(fromDoc, toDoc, active, open) { let from = fromDoc - line.from, to = toDoc - line.from, level = result; for (let i2 = active.length - 1; i2 >= 0; i2--, open--) { let direction = active[i2].spec.bidiIsolate, update; if (direction == null && (direction = autoDirection(line.text, from, to)), open > 0 && level.length && (update = level[level.length - 1]).to == from && update.direction == direction) update.to = to, level = update.inner; else { let add2 = { from, to, direction, inner: [] }; level.push(add2), level = add2.inner } } } }), result } var scrollMargins = Facet.define(); function getScrollMargins(view) { let left = 0, right = 0, top2 = 0, bottom = 0; for (let source of view.state.facet(scrollMargins)) { let m = source(view); m && (m.left != null && (left = Math.max(left, m.left)), m.right != null && (right = Math.max(right, m.right)), m.top != null && (top2 = Math.max(top2, m.top)), m.bottom != null && (bottom = Math.max(bottom, m.bottom))) } return { left, right, top: top2, bottom } } var styleModule = Facet.define(); var ChangedRange = class _ChangedRange { constructor(fromA, toA, fromB, toB) { this.fromA = fromA; this.toA = toA; this.fromB = fromB; this.toB = toB } fromA; toA; fromB; toB; join(other) { return new _ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)) } addToSet(set) { let i2 = set.length, me = this; for (; i2 > 0; i2--) { let range = set[i2 - 1]; if (!(range.fromA > me.toA)) { if (range.toA < me.fromA) break; me = me.join(range), set.splice(i2 - 1, 1) } } return set.splice(i2, 0, me), set } static extendWithRanges(diff, ranges) { if (ranges.length == 0) return diff; let result = []; for (let dI = 0, rI = 0, off = 0; ;) { let nextD = dI < diff.length ? diff[dI].fromB : 1e9, nextR = rI < ranges.length ? ranges[rI] : 1e9, fromB = Math.min(nextD, nextR); if (fromB == 1e9) break; let fromA = fromB + off, toB = fromB, toA = fromA; for (; ;)if (rI < ranges.length && ranges[rI] <= toB) { let end = ranges[rI + 1]; rI += 2, toB = Math.max(toB, end); for (let i2 = dI; i2 < diff.length && diff[i2].fromB <= toB; i2++)off = diff[i2].toA - diff[i2].toB; toA = Math.max(toA, end + off) } else if (dI < diff.length && diff[dI].fromB <= toB) { let next = diff[dI++]; toB = Math.max(toB, next.toB), toA = Math.max(toA, next.toA), off = next.toA - next.toB } else break; result.push(new _ChangedRange(fromA, toA, fromB, toB)) } return result } }, ViewUpdate = class _ViewUpdate { constructor(view, state, transactions) { this.view = view; this.state = state; this.transactions = transactions; this.startState = view.state, this.changes = ChangeSet.empty(this.startState.doc.length); for (let tr of transactions) this.changes = this.changes.compose(tr.changes); let changedRanges = []; this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))), this.changedRanges = changedRanges } view; state; transactions; changes; startState; flags = 0; changedRanges; static create(view, state, transactions) { return new _ViewUpdate(view, state, transactions) } get viewportChanged() { return (this.flags & 4) > 0 } get viewportMoved() { return (this.flags & 8) > 0 } get heightChanged() { return (this.flags & 2) > 0 } get geometryChanged() { return this.docChanged || (this.flags & 18) > 0 } get focusChanged() { return (this.flags & 1) > 0 } get docChanged() { return !this.changes.empty } get selectionSet() { return this.transactions.some(tr => tr.selection) } get empty() { return this.flags == 0 && this.transactions.length == 0 } }; var noChildren = [], Tile = class { constructor(dom, length, flags = 0) { this.dom = dom; this.length = length; this.flags = flags; dom.cmTile = this } dom; length; flags; parent = null; get breakAfter() { return this.flags & 1 } get children() { return noChildren } isWidget() { return !1 } get isHidden() { return !1 } isComposite() { return !1 } isLine() { return !1 } isText() { return !1 } isBlock() { return !1 } get domAttrs() { return null } sync(track) { if (this.flags |= 2, this.flags & 4) { this.flags &= -5; let attrs = this.domAttrs; attrs && setAttrs(this.dom, attrs) } } toString() { return this.constructor.name + (this.children.length ? `(${this.children})` : "") + (this.breakAfter ? "#" : "") } destroy() { this.parent = null } setDOM(dom) { this.dom = dom, dom.cmTile = this } get posAtStart() { return this.parent ? this.parent.posBefore(this) : 0 } get posAtEnd() { return this.posAtStart + this.length } posBefore(tile, start = this.posAtStart) { let pos = start; for (let child of this.children) { if (child == tile) return pos; pos += child.length + child.breakAfter } throw new RangeError("Invalid child in posBefore") } posAfter(tile) { return this.posBefore(tile) + tile.length } covers(side) { return !0 } coordsIn(pos, side) { return null } domPosFor(off, side) { let index = domIndex(this.dom), after = this.length ? off > 0 : side > 0; return new DOMPos(this.parent.dom, index + (after ? 1 : 0), off == 0 || off == this.length) } markDirty(attrs) { this.flags &= -3, attrs && (this.flags |= 4), this.parent && this.parent.flags & 2 && this.parent.markDirty(!1) } get overrideDOMText() { return null } get root() { for (let t2 = this; t2; t2 = t2.parent)if (t2 instanceof DocTile) return t2; return null } static get(dom) { return dom.cmTile } }, CompositeTile = class extends Tile { _children = []; constructor(dom) { super(dom, 0) } isComposite() { return !0 } get children() { return this._children } get lastChild() { return this.children.length ? this.children[this.children.length - 1] : null } append(child) { this.children.push(child), child.parent = this } sync(track) { if (this.flags & 2) return; super.sync(track); let parent = this.dom, prev = null, next, tracking = track?.node == parent ? track : null, length = 0; for (let child of this.children) { if (child.sync(track), length += child.length + child.breakAfter, next = prev ? prev.nextSibling : parent.firstChild, tracking && next != child.dom && (tracking.written = !0), child.dom.parentNode == parent) for (; next && next != child.dom;)next = rm(next); else parent.insertBefore(child.dom, next); prev = child.dom } for (next = prev ? prev.nextSibling : parent.firstChild, tracking && next && (tracking.written = !0); next;)next = rm(next); this.length = length } }; function rm(dom) { let next = dom.nextSibling; return dom.parentNode.removeChild(dom), next } var DocTile = class extends CompositeTile { constructor(view, dom) { super(dom); this.view = view } view; owns(tile) { for (; tile; tile = tile.parent)if (tile == this) return !0; return !1 } isBlock() { return !0 } nearest(dom) { for (; ;) { if (!dom) return null; let tile = Tile.get(dom); if (tile && this.owns(tile)) return tile; dom = dom.parentNode } } blockTiles(f) { for (let stack = [], cur = this, i2 = 0, pos = 0; ;)if (i2 == cur.children.length) { if (!stack.length) return; cur = cur.parent, cur.breakAfter && pos++, i2 = stack.pop() } else { let next = cur.children[i2++]; if (next instanceof BlockWrapperTile) stack.push(i2), cur = next, i2 = 0; else { let end = pos + next.length, result = f(next, pos); if (result !== void 0) return result; pos = end + next.breakAfter } } } resolveBlock(pos, side) { let before, beforeOff = -1, after, afterOff = -1; if (this.blockTiles((tile, off) => { let end = off + tile.length; if (pos >= off && pos <= end) { if (tile.isWidget() && side >= -1 && side <= 1) { if (tile.flags & 32) return !0; tile.flags & 16 && (before = void 0) } (off < pos || pos == end && (side < -1 ? tile.length : tile.covers(1))) && (!before || !tile.isWidget() && before.isWidget()) && (before = tile, beforeOff = pos - off), (end > pos || pos == off && (side > 1 ? tile.length : tile.covers(-1))) && (!after || !tile.isWidget() && after.isWidget()) && (after = tile, afterOff = pos - off) } }), !before && !after) throw new Error("No tile at position " + pos); return before && side < 0 || !after ? { tile: before, offset: beforeOff } : { tile: after, offset: afterOff } } }, BlockWrapperTile = class _BlockWrapperTile extends CompositeTile { constructor(dom, wrapper) { super(dom); this.wrapper = wrapper } wrapper; isBlock() { return !0 } covers(side) { return this.children.length ? side < 0 ? this.children[0].covers(-1) : this.lastChild.covers(1) : !1 } get domAttrs() { return this.wrapper.attributes } static of(wrapper, dom) { let tile = new _BlockWrapperTile(dom || document.createElement(wrapper.tagName), wrapper); return dom || (tile.flags |= 4), tile } }, LineTile = class _LineTile extends CompositeTile { constructor(dom, attrs) { super(dom); this.attrs = attrs } attrs; isLine() { return !0 } static start(attrs, dom, keepAttrs) { let line = new _LineTile(dom || document.createElement("div"), attrs); return (!dom || !keepAttrs) && (line.flags |= 4), line } get domAttrs() { return this.attrs } resolveInline(pos, side, forCoords) { let before = null, beforeOff = -1, after = null, afterOff = -1; function scan(tile, pos2) { for (let i2 = 0, off = 0; i2 < tile.children.length && off <= pos2; i2++) { let child = tile.children[i2], end = off + child.length; end >= pos2 && (child.isComposite() ? scan(child, pos2 - off) : (!after || after.isHidden && (side > 0 || forCoords && onSameLine(after, child))) && (end > pos2 || child.flags & 32) ? (after = child, afterOff = pos2 - off) : (off < pos2 || child.flags & 16 && !child.isHidden) && (before = child, beforeOff = pos2 - off)), off = end } } scan(this, pos); let target = (side < 0 ? before : after) || before || after; return target ? { tile: target, offset: target == before ? beforeOff : afterOff } : null } coordsIn(pos, side) { let found = this.resolveInline(pos, side, !0); return found ? found.tile.coordsIn(Math.max(0, found.offset), side) : fallbackRect(this) } domIn(pos, side) { let found = this.resolveInline(pos, side); if (found) { let { tile, offset } = found; if (this.dom.contains(tile.dom)) return tile.isText() ? new DOMPos(tile.dom, Math.min(tile.dom.nodeValue.length, offset)) : tile.domPosFor(offset, tile.flags & 16 ? 1 : tile.flags & 32 ? -1 : side); let parent = found.tile.parent, saw = !1, last; for (let ch of parent.children) { if (saw) return new DOMPos(ch.dom, 0); if (ch == found.tile) { if (last) return new DOMPos(last.dom, maxOffset(last.dom)); saw = !0 } } } return new DOMPos(this.dom, 0) } }; function fallbackRect(tile) { let last = tile.dom.lastChild; if (!last) return tile.dom.getBoundingClientRect(); let rects = clientRectsFor(last); return rects[rects.length - 1] || null } function onSameLine(a, b) { let posA = a.coordsIn(0, 1), posB = b.coordsIn(0, 1); return posA && posB && posB.top < posA.bottom } var MarkTile = class _MarkTile extends CompositeTile { constructor(dom, mark) { super(dom); this.mark = mark } mark; get domAttrs() { return this.mark.attrs } static of(mark, dom) { let tile = new _MarkTile(dom || document.createElement(mark.tagName), mark); return dom || (tile.flags |= 4), tile } }, TextTile = class _TextTile extends Tile { constructor(dom, text) { super(dom, text.length); this.text = text } text; sync(track) { this.flags & 2 || (super.sync(track), this.dom.nodeValue != this.text && (track && track.node == this.dom && (track.written = !0), this.dom.nodeValue = this.text)) } isText() { return !0 } toString() { return JSON.stringify(this.text) } coordsIn(pos, side) { let length = this.dom.nodeValue.length; pos > length && (pos = length); let from = pos, to = pos, flatten2 = 0; pos == 0 && side < 0 || pos == length && side >= 0 ? browser_default.chrome || browser_default.gecko || (pos ? (from--, flatten2 = 1) : to < length && (to++, flatten2 = -1)) : side < 0 ? from-- : to < length && to++; let rects = textRange(this.dom, from, to).getClientRects(); if (!rects.length) return null; let rect = rects[(flatten2 ? flatten2 < 0 : side >= 0) ? 0 : rects.length - 1]; return browser_default.safari && !flatten2 && rect.width == 0 && (rect = Array.prototype.find.call(rects, r => r.width) || rect), flatten2 ? flattenRect(rect, flatten2 < 0) : rect || null } static of(text, dom) { let tile = new _TextTile(dom || document.createTextNode(text), text); return dom || (tile.flags |= 2), tile } }, WidgetTile = class _WidgetTile extends Tile { constructor(dom, length, widget, flags) { super(dom, length, flags); this.widget = widget } widget; isWidget() { return !0 } get isHidden() { return this.widget.isHidden } covers(side) { return this.flags & 48 ? !1 : (this.flags & (side < 0 ? 64 : 128)) > 0 } coordsIn(pos, side) { return this.coordsInWidget(pos, side, !1) } coordsInWidget(pos, side, block) { let custom = this.widget.coordsAt(this.dom, pos, side); if (custom) return custom; if (block) return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0); { let rects = this.dom.getClientRects(), rect = null; if (!rects.length) return null; let fromBack = this.flags & 16 ? !0 : this.flags & 32 ? !1 : pos > 0; for (let i2 = fromBack ? rects.length - 1 : 0; rect = rects[i2], !(pos > 0 ? i2 == 0 : i2 == rects.length - 1 || rect.top < rect.bottom); i2 += fromBack ? -1 : 1); return flattenRect(rect, !fromBack) } } get overrideDOMText() { if (!this.length) return Text.empty; let { root } = this; if (!root) return Text.empty; let start = this.posAtStart; return root.view.state.doc.slice(start, start + this.length) } destroy() { super.destroy(), this.widget.destroy(this.dom) } static of(widget, view, length, flags, dom) { return dom || (dom = widget.toDOM(view), widget.editable || (dom.contentEditable = "false")), new _WidgetTile(dom, length, widget, flags) } }, WidgetBufferTile = class extends Tile { constructor(flags) { let img = document.createElement("img"); img.className = "cm-widgetBuffer", img.setAttribute("aria-hidden", "true"), super(img, 0, flags) } get isHidden() { return !0 } get overrideDOMText() { return Text.empty } coordsIn(pos) { return this.dom.getBoundingClientRect() } }, TilePointer = class { tile; index = 0; beforeBreak = !1; parents = []; constructor(top2) { this.tile = top2 } advance(dist2, side, walker) { let { tile, index, beforeBreak, parents } = this; for (; dist2 || side > 0;)if (tile.isComposite()) if (beforeBreak) { if (!dist2) break; walker && walker.break(), dist2--, beforeBreak = !1 } else if (index == tile.children.length) { if (!dist2 && !parents.length) break; walker && walker.leave(tile), beforeBreak = !!tile.breakAfter, { tile, index } = parents.pop(), index++ } else { let next = tile.children[index], brk = next.breakAfter; (side > 0 ? next.length <= dist2 : next.length < dist2) && (!walker || walker.skip(next, 0, next.length) !== !1 || !next.isComposite) ? (beforeBreak = !!brk, index++, dist2 -= next.length) : (parents.push({ tile, index }), tile = next, index = 0, walker && next.isComposite() && walker.enter(next)) } else if (index == tile.length) beforeBreak = !!tile.breakAfter, { tile, index } = parents.pop(), index++; else if (dist2) { let take = Math.min(dist2, tile.length - index); walker && walker.skip(tile, index, index + take), dist2 -= take, index += take } else break; return this.tile = tile, this.index = index, this.beforeBreak = beforeBreak, this } get root() { return this.parents.length ? this.parents[0].tile : this.tile } }; var LOG_builder = !1; var OpenWrapper = class { constructor(from, to, wrapper, rank) { this.from = from; this.to = to; this.wrapper = wrapper; this.rank = rank } from; to; wrapper; rank }, TileBuilder = class { constructor(cache, root, blockWrappers2) { this.cache = cache; this.root = root; this.blockWrappers = blockWrappers2 } cache; root; blockWrappers; curLine = null; lastBlock = null; afterWidget = null; pos = 0; wrappers = []; wrapperPos = 0; addText(text, marks, openStart, tile) { this.flushBuffer(); let parent = this.ensureMarks(marks, openStart), prev = parent.lastChild; if (prev && prev.isText() && !(prev.flags & 8) && prev.length + text.length < 512) { this.cache.reused.set(prev, 2); let tile2 = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text); tile2.parent = parent } else parent.append(tile || TextTile.of(text, this.cache.find(TextTile)?.dom)); this.pos += text.length, this.afterWidget = null } addComposition(composition, context) { let line = this.curLine; line.dom != context.line.dom && (line.setDOM(this.cache.reused.has(context.line) ? freeNode(context.line.dom) : context.line.dom), this.cache.reused.set(context.line, 2)); let head = line; for (let i2 = context.marks.length - 1; i2 >= 0; i2--) { let mark = context.marks[i2], last = head.lastChild; if (last instanceof MarkTile && last.mark.eq(mark.mark)) last.dom != mark.dom && last.setDOM(freeNode(mark.dom)), head = last; else { if (this.cache.reused.get(mark)) { let tile = Tile.get(mark.dom); tile && tile.setDOM(freeNode(mark.dom)) } let nw = MarkTile.of(mark.mark, mark.dom); head.append(nw), head = nw } this.cache.reused.set(mark, 2) } let oldTile = Tile.get(composition.text); oldTile && this.cache.reused.set(oldTile, 2); let text = new TextTile(composition.text, composition.text.nodeValue); text.flags |= 8, head.append(text) } addInlineWidget(widget, marks, openStart) { let noSpace = this.afterWidget && widget.flags & 48 && (this.afterWidget.flags & 48) == (widget.flags & 48); noSpace || this.flushBuffer(); let parent = this.ensureMarks(marks, openStart); !noSpace && !(widget.flags & 16) && parent.append(this.getBuffer(1)), parent.append(widget), this.pos += widget.length, this.afterWidget = widget } addMark(tile, marks, openStart) { this.flushBuffer(), this.ensureMarks(marks, openStart).append(tile), this.pos += tile.length, this.afterWidget = null } addBlockWidget(widget) { this.getBlockPos().append(widget), this.pos += widget.length, this.lastBlock = widget, this.endLine() } continueWidget(length) { let widget = this.afterWidget || this.lastBlock; widget.length += length, this.pos += length } addLineStart(attrs, dom) { attrs || (attrs = lineBaseAttrs); let tile = LineTile.start(attrs, dom || this.cache.find(LineTile)?.dom, !!dom); this.getBlockPos().append(this.lastBlock = this.curLine = tile) } addLine(tile) { this.getBlockPos().append(tile), this.pos += tile.length, this.lastBlock = tile, this.endLine() } addBreak() { this.lastBlock.flags |= 1, this.endLine(), this.pos++ } addLineStartIfNotCovered(attrs) { this.blockPosCovered() || this.addLineStart(attrs) } ensureLine(attrs) { this.curLine || this.addLineStart(attrs) } ensureMarks(marks, openStart) { let parent = this.curLine; for (let i2 = marks.length - 1; i2 >= 0; i2--) { let mark = marks[i2], last; if (openStart > 0 && (last = parent.lastChild) && last instanceof MarkTile && last.mark.eq(mark)) parent = last, openStart--; else { let tile = MarkTile.of(mark, this.cache.find(MarkTile, m => m.mark.eq(mark))?.dom); parent.append(tile), parent = tile, openStart = 0 } } return parent } endLine() { if (this.curLine) { this.flushBuffer(); let last = this.curLine.lastChild; (!last || !hasContent(this.curLine, !1) || last.dom.nodeName != "BR" && last.isWidget() && !(browser_default.ios && hasContent(this.curLine, !0))) && this.curLine.append(this.cache.findWidget(BreakWidget, 0, 32) || new WidgetTile(BreakWidget.toDOM(), 0, BreakWidget, 32)), this.curLine = this.afterWidget = null } } updateBlockWrappers() { this.wrapperPos > this.pos + 1e4 && (this.blockWrappers.goto(this.pos), this.wrappers.length = 0); for (let i2 = this.wrappers.length - 1; i2 >= 0; i2--)this.wrappers[i2].to < this.pos && this.wrappers.splice(i2, 1); for (let cur = this.blockWrappers; cur.value && cur.from <= this.pos; cur.next())if (cur.to >= this.pos) { let wrap = new OpenWrapper(cur.from, cur.to, cur.value, cur.rank), i2 = this.wrappers.length; for (; i2 > 0 && (this.wrappers[i2 - 1].rank - wrap.rank || this.wrappers[i2 - 1].to - wrap.to) < 0;)i2--; this.wrappers.splice(i2, 0, wrap) } this.wrapperPos = this.pos } getBlockPos() { this.updateBlockWrappers(); let parent = this.root; for (let wrap of this.wrappers) { let last = parent.lastChild; if (wrap.from < this.pos && last instanceof BlockWrapperTile && last.wrapper.eq(wrap.wrapper)) parent = last; else { let tile = BlockWrapperTile.of(wrap.wrapper, this.cache.find(BlockWrapperTile, t2 => t2.wrapper.eq(wrap.wrapper))?.dom); parent.append(tile), parent = tile } } return parent } blockPosCovered() { let last = this.lastBlock; return last != null && !last.breakAfter && (!last.isWidget() || (last.flags & 160) > 0) } getBuffer(side) { let flags = 2 | (side < 0 ? 16 : 32), found = this.cache.find(WidgetBufferTile, void 0, 1); return found && (found.flags = flags), found || new WidgetBufferTile(flags) } flushBuffer() { this.afterWidget && !(this.afterWidget.flags & 32) && (this.afterWidget.parent.append(this.getBuffer(-1)), this.afterWidget = null) } }, TextStream = class { cursor; skipCount = 0; text = ""; textOff = 0; constructor(doc2) { this.cursor = doc2.iter() } skip(len) { this.textOff + len <= this.text.length ? this.textOff += len : (this.skipCount += len - (this.text.length - this.textOff), this.text = "", this.textOff = 0) } next(maxLen) { if (this.textOff == this.text.length) { let { value, lineBreak, done } = this.cursor.next(this.skipCount); if (this.skipCount = 0, done) throw new Error("Ran out of text content when drawing inline views"); this.text = value; let len = this.textOff = Math.min(maxLen, value.length); return lineBreak ? null : value.slice(0, len) } let end = Math.min(this.text.length, this.textOff + maxLen), chars = this.text.slice(this.textOff, end); return this.textOff = end, chars } }, buckets = [WidgetTile, LineTile, TextTile, MarkTile, WidgetBufferTile, BlockWrapperTile, DocTile]; for (let i2 = 0; i2 < buckets.length; i2++)buckets[i2].bucket = i2; var TileCache = class { constructor(view) { this.view = view } view; buckets = buckets.map(() => []); index = buckets.map(() => 0); reused = new Map; add(tile) { let i2 = tile.constructor.bucket, bucket = this.buckets[i2]; bucket.length < 6 ? bucket.push(tile) : bucket[this.index[i2] = (this.index[i2] + 1) % 6] = tile } find(cls, test, type = 2) { let i2 = cls.bucket, bucket = this.buckets[i2], off = this.index[i2]; for (let j = bucket.length - 1; j >= 0; j--) { let index = (j + off) % bucket.length, tile = bucket[index]; if ((!test || test(tile)) && !this.reused.has(tile)) return bucket.splice(index, 1), index < off && this.index[i2]--, this.reused.set(tile, type), tile } return null } findWidget(widget, length, flags) { let widgets = this.buckets[0]; if (widgets.length) for (let i2 = 0, pass = 0; ; i2++) { if (i2 == widgets.length) { if (pass) return null; pass = 1, i2 = 0 } let tile = widgets[i2]; if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view, tile.widget))) return widgets.splice(i2, 1), i2 < this.index[0] && this.index[0]--, tile.widget == widget && tile.length == length && (tile.flags & 497) == flags ? (this.reused.set(tile, 1), tile) : (this.reused.set(tile, 2), new WidgetTile(tile.dom, length, widget, tile.flags & -498 | flags)) } } reuse(tile) { return this.reused.set(tile, 1), tile } maybeReuse(tile, type = 2) { if (!this.reused.has(tile)) return this.reused.set(tile, type), tile.dom } clear() { for (let i2 = 0; i2 < this.buckets.length; i2++)this.buckets[i2].length = this.index[i2] = 0 } }, TileUpdate = class { constructor(view, old, blockWrappers2, decorations2, disallowBlockEffectsFor) { this.view = view; this.decorations = decorations2; this.disallowBlockEffectsFor = disallowBlockEffectsFor; this.cache = new TileCache(view), this.text = new TextStream(view.state.doc), this.builder = new TileBuilder(this.cache, new DocTile(view, view.contentDOM), RangeSet.iter(blockWrappers2)), this.cache.reused.set(old, 2), this.old = new TilePointer(old), this.reuseWalker = { skip: (tile, from, to) => { if (this.cache.add(tile), tile.isComposite()) return !1 }, enter: tile => this.cache.add(tile), leave: () => { }, break: () => { } } } view; decorations; disallowBlockEffectsFor; text; builder; old; openWidget = !1; openMarks = 0; cache; reuseWalker; run(changes, composition) { LOG_builder && console.log("Build with changes", JSON.stringify(changes)), LOG_builder && composition && console.log("Composition=", JSON.stringify(composition.range), composition.text.nodeValue), LOG_builder && console.log("<<< " + this.old.tile); let compositionContext = composition && this.getCompositionContext(composition.text); for (let posA = 0, posB = 0, i2 = 0; ;) { let next = i2 < changes.length ? changes[i2++] : null, skipA = next ? next.fromA : this.old.root.length; if (skipA > posA) { LOG_builder && console.log("Preserve", posA, "to", skipA); let len = skipA - posA; this.preserve(len, !i2, !next), posA = skipA, posB += len } if (!next) break; composition && next.fromA <= composition.range.fromA && next.toA >= composition.range.toA ? (LOG_builder && console.log("Emit composition", posB, "to", next.toB, "over", posA, "to", next.toA), this.forward(next.fromA, composition.range.fromA, composition.range.fromA < composition.range.toA ? 1 : -1), this.emit(posB, composition.range.fromB), this.cache.clear(), this.builder.addComposition(composition, compositionContext), this.text.skip(composition.range.toB - composition.range.fromB), this.forward(composition.range.fromA, next.toA), this.emit(composition.range.toB, next.toB)) : (LOG_builder && console.log("Emit", posB, "to", next.toB, "over", posA, "to", next.toA), this.forward(next.fromA, next.toA), this.emit(posB, next.toB)), posB = next.toB, posA = next.toA } return LOG_builder && console.log(">>> " + this.builder.root), this.builder.curLine && this.builder.endLine(), this.builder.root } preserve(length, incStart, incEnd) { let activeMarks = getMarks(this.old), openMarks = this.openMarks; this.old.advance(length, incEnd ? 1 : -1, { skip: (tile, from, to) => { if (tile.isWidget()) if (this.openWidget) this.builder.continueWidget(to - from); else { let widget = to > 0 || from < tile.length ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile); widget.flags & 256 ? (widget.flags &= -2, this.builder.addBlockWidget(widget)) : (this.builder.ensureLine(null), this.builder.addInlineWidget(widget, activeMarks, openMarks), openMarks = activeMarks.length) } else if (tile.isText()) this.builder.ensureLine(null), !from && to == tile.length && !this.cache.reused.has(tile) ? this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile)) : (this.cache.add(tile), this.builder.addText(tile.text.slice(from, to), activeMarks, openMarks)), openMarks = activeMarks.length; else if (tile.isLine()) tile.flags &= -2, this.cache.reused.set(tile, 1), this.builder.addLine(tile); else if (tile instanceof WidgetBufferTile) this.cache.add(tile); else if (tile instanceof MarkTile) this.builder.ensureLine(null), this.builder.addMark(tile, activeMarks, openMarks), this.cache.reused.set(tile, 1), openMarks = activeMarks.length; else return !1; this.openWidget = !1 }, enter: tile => { tile.isLine() ? this.builder.addLineStart(tile.attrs, this.cache.maybeReuse(tile)) : (this.cache.add(tile), tile instanceof MarkTile && activeMarks.unshift(tile.mark)), this.openWidget = !1 }, leave: tile => { tile.isLine() ? activeMarks.length && (activeMarks.length = openMarks = 0) : tile instanceof MarkTile && (activeMarks.shift(), openMarks = Math.min(openMarks, activeMarks.length)) }, break: () => { this.builder.addBreak(), this.openWidget = !1 } }), this.text.skip(length) } emit(from, to) { let pendingLineAttrs = null, b = this.builder, markCount = 0, openEnd = RangeSet.spans(this.decorations, from, to, { point: (from2, to2, deco, active, openStart, index) => { if (deco instanceof PointDecoration) { if (this.disallowBlockEffectsFor[index]) { if (deco.block) throw new RangeError("Block decorations may not be specified via plugins"); if (to2 > this.view.state.doc.lineAt(from2).to) throw new RangeError("Decorations that replace line breaks may not be specified via plugins") } if (markCount = active.length, openStart > active.length) b.continueWidget(to2 - from2); else { let widget = deco.widget || (deco.block ? NullWidget.block : NullWidget.inline), flags = widgetFlags(deco), tile = this.cache.findWidget(widget, to2 - from2, flags) || WidgetTile.of(widget, this.view, to2 - from2, flags); deco.block ? (deco.startSide > 0 && b.addLineStartIfNotCovered(pendingLineAttrs), b.addBlockWidget(tile)) : (b.ensureLine(pendingLineAttrs), b.addInlineWidget(tile, active, openStart)) } pendingLineAttrs = null } else pendingLineAttrs = addLineDeco(pendingLineAttrs, deco); to2 > from2 && this.text.skip(to2 - from2) }, span: (from2, to2, active, openStart) => { for (let pos = from2; pos < to2;) { let chars = this.text.next(Math.min(512, to2 - pos)); chars == null ? (b.addLineStartIfNotCovered(pendingLineAttrs), b.addBreak(), pos++) : (b.ensureLine(pendingLineAttrs), b.addText(chars, active, pos == from2 ? openStart : active.length), pos += chars.length), pendingLineAttrs = null } } }); b.addLineStartIfNotCovered(pendingLineAttrs), this.openWidget = openEnd > markCount, this.openMarks = openEnd } forward(from, to, side = 1) { to - from <= 10 ? this.old.advance(to - from, side, this.reuseWalker) : (this.old.advance(5, -1, this.reuseWalker), this.old.advance(to - from - 10, -1), this.old.advance(5, side, this.reuseWalker)) } getCompositionContext(text) { let marks = [], line = null; for (let parent = text.parentNode; ; parent = parent.parentNode) { let tile = Tile.get(parent); if (parent == this.view.contentDOM) break; tile instanceof MarkTile ? marks.push(tile) : tile?.isLine() ? line = tile : tile instanceof BlockWrapperTile || (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM ? line = new LineTile(parent, lineBaseAttrs) : line || marks.push(MarkTile.of(new MarkDecoration({ tagName: parent.nodeName.toLowerCase(), attributes: getAttrs(parent) }), parent))) } return { line, marks } } }; function hasContent(tile, requireText) { let scan = tile2 => { for (let ch of tile2.children) if ((requireText ? ch.isText() : ch.length) || scan(ch)) return !0; return !1 }; return scan(tile) } function widgetFlags(deco) { let flags = deco.isReplace ? (deco.startSide < 0 ? 64 : 0) | (deco.endSide > 0 ? 128 : 0) : deco.startSide > 0 ? 32 : 16; return deco.block && (flags |= 256), flags } var lineBaseAttrs = { class: "cm-line" }; function addLineDeco(value, deco) { let attrs = deco.spec.attributes, cls = deco.spec.class; return !attrs && !cls || (value || (value = { class: "cm-line" }), attrs && combineAttrs(attrs, value), cls && (value.class += " " + cls)), value } function getMarks(ptr) { let found = []; for (let i2 = ptr.parents.length; i2 > 1; i2--) { let tile = i2 == ptr.parents.length ? ptr.tile : ptr.parents[i2].tile; tile instanceof MarkTile && found.push(tile.mark) } return found } function freeNode(node) { let tile = Tile.get(node); return tile && tile.setDOM(node.cloneNode()), node } var NullWidget = class _NullWidget extends WidgetType { constructor(tag) { super(); this.tag = tag } tag; eq(other) { return other.tag == this.tag } toDOM() { return document.createElement(this.tag) } updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag } get isHidden() { return !0 } static inline = new _NullWidget("span"); static block = new _NullWidget("div") }, BreakWidget = new class extends WidgetType { toDOM() { return document.createElement("br") } get isHidden() { return !0 } get editable() { return !0 } }; var DocView = class { constructor(view) { this.view = view; this.updateDeco(), this.tile = new DocTile(view, view.contentDOM), this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], null) } view; tile; decorations = []; blockWrappers = []; dynamicDecorationMap = [!1]; domChanged = null; hasComposition = null; editContextFormatting = Decoration.none; lastCompositionAfterCursor = !1; minWidth = 0; minWidthFrom = 0; minWidthTo = 0; impreciseAnchor = null; impreciseHead = null; forceSelection = !1; lastUpdate = Date.now(); update(update) { let changedRanges = update.changedRanges; this.minWidth > 0 && changedRanges.length && (changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo) ? (this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1), this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1)) : this.minWidth = this.minWidthFrom = this.minWidthTo = 0), this.updateEditContextFormatting(update); let readCompositionAt = -1; this.view.inputState.composing >= 0 && !this.view.observer.editContext && (this.domChanged?.newSel ? readCompositionAt = this.domChanged.newSel.head : !touchesComposition(update.changes, this.hasComposition) && !update.selectionSet && (readCompositionAt = update.state.selection.main.head)); let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null; if (this.domChanged = null, this.hasComposition) { let { from, to } = this.hasComposition; changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1)).addToSet(changedRanges.slice()) } this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null, (browser_default.ie || browser_default.chrome) && !composition && update && update.state.doc.lines != update.startState.doc.lines && (this.forceSelection = !0); let prevDeco = this.decorations, prevWrappers = this.blockWrappers; this.updateDeco(); let decoDiff = findChangedDeco(prevDeco, this.decorations, update.changes); decoDiff.length && (changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff)); let blockDiff = findChangedWrappers(prevWrappers, this.blockWrappers, update.changes); return blockDiff.length && (changedRanges = ChangedRange.extendWithRanges(changedRanges, blockDiff)), composition && !changedRanges.some(r => r.fromA <= composition.range.fromA && r.toA >= composition.range.toA) && (changedRanges = composition.range.addToSet(changedRanges.slice())), this.tile.flags & 2 && changedRanges.length == 0 ? !1 : (this.updateInner(changedRanges, composition), update.transactions.length && (this.lastUpdate = Date.now()), !0) } updateInner(changes, composition) { this.view.viewState.mustMeasureContent = !0; let { observer } = this.view; observer.ignore(() => { if (composition || changes.length) { let oldTile = this.tile, builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap); composition && Tile.get(composition.text) && builder.cache.reused.set(Tile.get(composition.text), 2), this.tile = builder.run(changes, composition), destroyDropped(oldTile, builder.cache.reused) } this.tile.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px", this.tile.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : ""; let track = browser_default.chrome || browser_default.ios ? { node: observer.selectionRange.focusNode, written: !1 } : void 0; this.tile.sync(track), track && (track.written || observer.selectionRange.focusNode != track.node || !this.tile.dom.contains(track.node)) && (this.forceSelection = !0), this.tile.dom.style.height = "" }); let gaps = []; if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) for (let child of this.tile.children) child.isWidget() && child.widget instanceof BlockGapWidget && gaps.push(child.dom); observer.updateGaps(gaps) } updateEditContextFormatting(update) { this.editContextFormatting = this.editContextFormatting.map(update.changes); for (let tr of update.transactions) for (let effect of tr.effects) effect.is(setEditContextFormatting) && (this.editContextFormatting = effect.value) } updateSelection(mustRead = !1, fromPointer = !1) { (mustRead || !this.view.observer.selectionRange.focusNode) && this.view.observer.readSelectionRange(); let { dom } = this.tile, activeElt = this.view.root.activeElement, focused = activeElt == dom, selectionNotFocus = !focused && !(this.view.state.facet(editable) || dom.tabIndex > -1) && hasSelection(dom, this.view.observer.selectionRange) && !(activeElt && dom.contains(activeElt)); if (!(focused || fromPointer || selectionNotFocus)) return; let force = this.forceSelection; this.forceSelection = !1; let main = this.view.state.selection.main, anchor, head; if (main.empty ? head = anchor = this.inlineDOMNearPos(main.anchor, main.assoc || 1) : (head = this.inlineDOMNearPos(main.head, main.head == main.from ? 1 : -1), anchor = this.inlineDOMNearPos(main.anchor, main.anchor == main.from ? 1 : -1)), browser_default.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) { let dummy = document.createTextNode(""); this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)), anchor = head = new DOMPos(dummy, 0), force = !0 } let domSel = this.view.observer.selectionRange; (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) && (this.view.observer.ignore(() => { browser_default.android && browser_default.chrome && dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, dom) && (dom.blur(), dom.focus({ preventScroll: !0 })); let rawSel = getSelection(this.view.root); if (rawSel) if (main.empty) { if (browser_default.gecko) { let nextTo = nextToUneditable(anchor.node, anchor.offset); if (nextTo && nextTo != 3) { let text = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset); text && (anchor = new DOMPos(text.node, text.offset)) } } rawSel.collapse(anchor.node, anchor.offset), main.bidiLevel != null && rawSel.caretBidiLevel !== void 0 && (rawSel.caretBidiLevel = main.bidiLevel) } else if (rawSel.extend) { rawSel.collapse(anchor.node, anchor.offset); try { rawSel.extend(head.node, head.offset) } catch { } } else { let range = document.createRange(); main.anchor > main.head && ([anchor, head] = [head, anchor]), range.setEnd(head.node, head.offset), range.setStart(anchor.node, anchor.offset), rawSel.removeAllRanges(), rawSel.addRange(range) } selectionNotFocus && this.view.root.activeElement == dom && (dom.blur(), activeElt && activeElt.focus()) }), this.view.observer.setSelectionRange(anchor, head)), this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset), this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset) } suppressWidgetCursorChange(sel, cursor) { return this.hasComposition && cursor.empty && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head } enforceCursorAssoc() { if (this.hasComposition) return; let { view } = this, cursor = view.state.selection.main, sel = getSelection(view.root), { anchorNode, anchorOffset } = view.observer.selectionRange; if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) return; let line = this.lineAt(cursor.head, cursor.assoc); if (!line) return; let lineStart = line.posAtStart; if (cursor.head == lineStart || cursor.head == lineStart + line.length) return; let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); if (!before || !after || before.bottom > after.top) return; let dom = this.domAtPos(cursor.head + cursor.assoc, cursor.assoc); sel.collapse(dom.node, dom.offset), sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"), view.observer.readSelectionRange(); let newRange = view.observer.selectionRange; view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from && sel.collapse(anchorNode, anchorOffset) } posFromDOM(node, offset) { let tile = this.tile.nearest(node); if (!tile) return this.tile.dom.compareDocumentPosition(node) & 2 ? 0 : this.view.state.doc.length; let start = tile.posAtStart; if (tile.isComposite()) { let after; if (node == tile.dom) after = tile.dom.childNodes[offset]; else { let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; for (; ;) { let parent = node.parentNode; if (parent == tile.dom) break; bias == 0 && parent.firstChild != parent.lastChild && (node == parent.firstChild ? bias = -1 : bias = 1), node = parent } bias < 0 ? after = node : after = node.nextSibling } if (after == tile.dom.firstChild) return start; for (; after && !Tile.get(after);)after = after.nextSibling; if (!after) return start + tile.length; for (let i2 = 0, pos = start; ; i2++) { let child = tile.children[i2]; if (child.dom == after) return pos; pos += child.length + child.breakAfter } } else return tile.isText() ? node == tile.dom ? start + offset : start + (offset ? tile.length : 0) : start } domAtPos(pos, side) { let { tile, offset } = this.tile.resolveBlock(pos, side); return tile.isWidget() ? tile.domPosFor(pos, side) : tile.domIn(offset, side) } inlineDOMNearPos(pos, side) { let before, beforeOff = -1, beforeBad = !1, after, afterOff = -1, afterBad = !1; return this.tile.blockTiles((tile, off) => { if (tile.isWidget()) { if (tile.flags & 32 && off >= pos) return !0; tile.flags & 16 && (beforeBad = !0) } else { let end = off + tile.length; if (off <= pos && (before = tile, beforeOff = pos - off, beforeBad = end < pos), end >= pos && !after && (after = tile, afterOff = pos - off, afterBad = off > pos), off > pos && after) return !0 } }), !before && !after ? this.domAtPos(pos, side) : (beforeBad && after ? before = null : afterBad && before && (after = null), before && side < 0 || !after ? before.domIn(beforeOff, side) : after.domIn(afterOff, side)) } coordsAt(pos, side) { let { tile, offset } = this.tile.resolveBlock(pos, side); return tile.isWidget() ? tile.widget instanceof BlockGapWidget ? null : tile.coordsInWidget(offset, side, !0) : tile.coordsIn(offset, side) } lineAt(pos, side) { let { tile } = this.tile.resolveBlock(pos, side); return tile.isLine() ? tile : null } coordsForChar(pos) { let { tile, offset } = this.tile.resolveBlock(pos, 1); if (!tile.isLine()) return null; function scan(tile2, offset2) { if (tile2.isComposite()) for (let ch of tile2.children) { if (ch.length >= offset2) { let found = scan(ch, offset2); if (found) return found } if (offset2 -= ch.length, offset2 < 0) break } else if (tile2.isText() && offset2 < tile2.length) { let end = findClusterBreak2(tile2.text, offset2); if (end == offset2) return null; let rects = textRange(tile2.dom, offset2, end).getClientRects(); for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2]; if (i2 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right) return rect } } return null } return scan(tile, offset) } measureVisibleLineHeights(viewport) { let result = [], { from, to } = viewport, contentWidth = this.view.contentDOM.clientWidth, isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1, widest = -1, ltr = this.view.textDirection == 0, spaceAbove = 0, scan = (tile, pos, measureBounds) => { for (let i2 = 0; i2 < tile.children.length && !(pos > to); i2++) { let child = tile.children[i2], end = pos + child.length, childRect = child.dom.getBoundingClientRect(), { height } = childRect; if (measureBounds && !i2 && (spaceAbove += childRect.top - measureBounds.top), child instanceof BlockWrapperTile) end > from && scan(child, pos, childRect); else if (pos >= from && (spaceAbove > 0 && result.push(-spaceAbove), result.push(height + spaceAbove), spaceAbove = 0, isWider)) { let last = child.dom.lastChild, rects = last ? clientRectsFor(last) : []; if (rects.length) { let rect = rects[rects.length - 1], width = ltr ? rect.right - childRect.left : childRect.right - rect.left; width > widest && (widest = width, this.minWidth = contentWidth, this.minWidthFrom = pos, this.minWidthTo = end) } } measureBounds && i2 == tile.children.length - 1 && (spaceAbove += measureBounds.bottom - childRect.bottom), pos = end + child.breakAfter } }; return scan(this.tile, 0, null), result } textDirectionAt(pos) { let { tile } = this.tile.resolveBlock(pos, 1); return getComputedStyle(tile.dom).direction == "rtl" ? 1 : 0 } measureTextSize() { let lineMeasure = this.tile.blockTiles(tile => { if (tile.isLine() && tile.children.length && tile.length <= 20) { let totalWidth = 0, textHeight2; for (let child of tile.children) { if (!child.isText() || /[^ -~]/.test(child.text)) return; let rects = clientRectsFor(child.dom); if (rects.length != 1) return; totalWidth += rects[0].width, textHeight2 = rects[0].height } if (totalWidth) return { lineHeight: tile.dom.getBoundingClientRect().height, charWidth: totalWidth / tile.length, textHeight: textHeight2 } } }); if (lineMeasure) return lineMeasure; let dummy = document.createElement("div"), lineHeight, charWidth, textHeight; return dummy.className = "cm-line", dummy.style.width = "99999px", dummy.style.position = "absolute", dummy.textContent = "abc def ghi jkl mno pqr stu", this.view.observer.ignore(() => { this.tile.dom.appendChild(dummy); let rect = clientRectsFor(dummy.firstChild)[0]; lineHeight = dummy.getBoundingClientRect().height, charWidth = rect && rect.width ? rect.width / 27 : 7, textHeight = rect && rect.height ? rect.height : lineHeight, dummy.remove() }), { lineHeight, charWidth, textHeight } } computeBlockGapDeco() { let deco = [], vs = this.view.viewState; for (let pos = 0, i2 = 0; ; i2++) { let next = i2 == vs.viewports.length ? null : vs.viewports[i2], end = next ? next.from - 1 : this.view.state.doc.length; if (end > pos) { let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY; deco.push(Decoration.replace({ widget: new BlockGapWidget(height), block: !0, inclusive: !0, isBlockGap: !0 }).range(pos, end)) } if (!next) break; pos = next.to + 1 } return Decoration.set(deco) } updateDeco() { let i2 = 1, allDeco = this.view.state.facet(decorations).map(d => (this.dynamicDecorationMap[i2++] = typeof d == "function") ? d(this.view) : d), dynamicOuter = !1, outerDeco = this.view.state.facet(outerDecorations).map((d, i3) => { let dynamic = typeof d == "function"; return dynamic && (dynamicOuter = !0), dynamic ? d(this.view) : d }); for (outerDeco.length && (this.dynamicDecorationMap[i2++] = dynamicOuter, allDeco.push(RangeSet.join(outerDeco))), this.decorations = [this.editContextFormatting, ...allDeco, this.computeBlockGapDeco(), this.view.viewState.lineGapDeco]; i2 < this.decorations.length;)this.dynamicDecorationMap[i2++] = !1; this.blockWrappers = this.view.state.facet(blockWrappers).map(v => typeof v == "function" ? v(this.view) : v) } scrollIntoView(target) { if (target.isSnapshot) { let ref = this.view.viewState.lineBlockAt(target.range.head); this.view.scrollDOM.scrollTop = ref.top - target.yMargin, this.view.scrollDOM.scrollLeft = target.xMargin; return } for (let handler of this.view.state.facet(scrollHandler)) try { if (handler(this.view, target.range, target)) return !0 } catch (e) { logException(this.view.state, e, "scroll handler") } let { range } = target, rect = this.coordsAt(range.head, range.assoc ?? (range.empty ? 0 : range.head > range.anchor ? -1 : 1)), other; if (!rect) return; !range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)) && (rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }); let margins = getScrollMargins(this.view), targetRect = { left: rect.left - margins.left, top: rect.top - margins.top, right: rect.right + margins.right, bottom: rect.bottom + margins.bottom }, { offsetWidth, offsetHeight } = this.view.scrollDOM; if (scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == 0), window.visualViewport && window.innerHeight - window.visualViewport.height > 1 && (rect.top > window.pageYOffset + window.visualViewport.offsetTop + window.visualViewport.height || rect.bottom < window.pageYOffset + window.visualViewport.offsetTop)) { let line = this.view.docView.lineAt(range.head, 1); line && line.dom.scrollIntoView({ block: "nearest" }) } } lineHasWidget(pos) { let scan = child => child.isWidget() || child.children.some(scan); return scan(this.tile.resolveBlock(pos, 1).tile) } destroy() { destroyDropped(this.tile) } }; function destroyDropped(tile, reused) { let r = reused?.get(tile); if (r != 1) { r == null && tile.destroy(); for (let ch of tile.children) destroyDropped(ch, reused) } } function betweenUneditable(pos) { return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false") } function findCompositionNode(view, headPos) { let sel = view.observer.selectionRange; if (!sel.focusNode) return null; let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset), textAfter = textNodeAfter(sel.focusNode, sel.focusOffset), textNode = textBefore || textAfter; if (textAfter && textBefore && textAfter.node != textBefore.node) { let tileAfter = Tile.get(textAfter.node); if (!tileAfter || tileAfter.isText() && tileAfter.text != textAfter.node.nodeValue) textNode = textAfter; else if (view.docView.lastCompositionAfterCursor) { let tileBefore = Tile.get(textBefore.node); !tileBefore || tileBefore.isText() && tileBefore.text != textBefore.node.nodeValue || (textNode = textAfter) } } if (view.docView.lastCompositionAfterCursor = textNode != textBefore, !textNode) return null; let from = headPos - textNode.offset; return { from, to: from + textNode.node.nodeValue.length, node: textNode.node } } function findCompositionRange(view, changes, headPos) { let found = findCompositionNode(view, headPos); if (!found) return null; let { node: textNode, from, to } = found, text = textNode.nodeValue; if (/[\n\r]/.test(text) || view.state.doc.sliceString(found.from, found.to) != text) return null; let inv = changes.invertedDesc; return { range: new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to), text: textNode } } function nextToUneditable(node, offset) { return node.nodeType != 1 ? 0 : (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0) } var DecorationComparator = class { changes = []; compareRange(from, to) { addRange(from, to, this.changes) } comparePoint(from, to) { addRange(from, to, this.changes) } boundChange(pos) { addRange(pos, pos, this.changes) } }; function findChangedDeco(a, b, diff) { let comp = new DecorationComparator; return RangeSet.compare(a, b, diff, comp), comp.changes } var WrapperComparator = class { changes = []; compareRange(from, to) { addRange(from, to, this.changes) } comparePoint() { } boundChange(pos) { addRange(pos, pos, this.changes) } }; function findChangedWrappers(a, b, diff) { let comp = new WrapperComparator; return RangeSet.compare(a, b, diff, comp), comp.changes } function inUneditable(node, inside) { for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode)if (cur.nodeType == 1 && cur.contentEditable == "false") return !0; return !1 } function touchesComposition(changes, composition) { let touched = !1; return composition && changes.iterChangedRanges((from, to) => { from < composition.to && to > composition.from && (touched = !0) }), touched } var BlockGapWidget = class extends WidgetType { constructor(height) { super(); this.height = height } height; toDOM() { let elt = document.createElement("div"); return elt.className = "cm-gap", this.updateDOM(elt), elt } eq(other) { return other.height == this.height } updateDOM(elt) { return elt.style.height = this.height + "px", !0 } get editable() { return !0 } get estimatedHeight() { return this.height } ignoreEvent() { return !1 } }; function groupAt(state, pos, bias = 1) { let categorize = state.charCategorizer(pos), line = state.doc.lineAt(pos), linePos = pos - line.from; if (line.length == 0) return EditorSelection.cursor(pos); linePos == 0 ? bias = 1 : linePos == line.length && (bias = -1); let from = linePos, to = linePos; bias < 0 ? from = findClusterBreak2(line.text, linePos, !1) : to = findClusterBreak2(line.text, linePos); let cat = categorize(line.text.slice(from, to)); for (; from > 0;) { let prev = findClusterBreak2(line.text, from, !1); if (categorize(line.text.slice(prev, from)) != cat) break; from = prev } for (; to < line.length;) { let next = findClusterBreak2(line.text, to); if (categorize(line.text.slice(to, next)) != cat) break; to = next } return EditorSelection.range(from + line.from, to + line.from) } function posAtCoordsImprecise(view, contentRect, block, x, y) { let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { let textHeight = view.viewState.heightOracle.textHeight, line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * .5) / textHeight); into += line * view.viewState.heightOracle.lineLength } let content2 = view.state.sliceDoc(block.from, block.to); return block.from + findColumn(content2, into, view.state.tabSize) } function blockAt(view, pos, side) { let line = view.lineBlockAt(pos); if (Array.isArray(line.type)) { let best; for (let l of line.type) { if (l.from > pos) break; if (!(l.to < pos)) { if (l.from < pos && l.to > pos) return l; (!best || l.type == 0 && (best.type != l.type || (side < 0 ? l.from < pos : l.to > pos))) && (best = l) } } return best || line } return line } function moveToLineBoundary(view, start, forward, includeWrap) { let line = blockAt(view, start.head, start.assoc || -1), coords = !includeWrap || line.type != 0 || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); if (coords) { let editorRect = view.dom.getBoundingClientRect(), direction = view.textDirectionAt(line.from), pos = view.posAtCoords({ x: forward == (direction == 0) ? editorRect.right - 1 : editorRect.left + 1, y: (coords.top + coords.bottom) / 2 }); if (pos != null) return EditorSelection.cursor(pos, forward ? -1 : 1) } return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1) } function moveByChar(view, start, forward, by) { + let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line), direction = view.textDirectionAt(line.from); for (let cur = start, check = null; ;) { + let next = moveVisually(line, spans, direction, cur, forward), char = movedOver; if (!next) { + if (line.number == (forward ? view.state.doc.lines : 1)) return cur; char = ` +`, line = view.state.doc.line(line.number + (forward ? 1 : -1)), spans = view.bidiSpans(line), next = view.visualLineSide(line, !forward) + } if (check) { if (!check(char)) return cur } else { if (!by) return next; check = by(char) } cur = next + } +} function byGroup(view, pos, start) { let categorize = view.state.charCategorizer(pos), cat = categorize(start); return next => { let nextCat = categorize(next); return cat == 1 && (cat = nextCat), cat == nextCat } } function moveVertically(view, start, forward, distance) { let startPos = start.head, dir = forward ? 1 : -1; if (startPos == (forward ? view.state.doc.length : 0)) return EditorSelection.cursor(startPos, start.assoc); let goal = start.goalColumn, startY, rect = view.contentDOM.getBoundingClientRect(), startCoords = view.coordsAtPos(startPos, start.assoc || ((start.empty ? forward : start.head == start.from) ? 1 : -1)), docTop = view.documentTop; if (startCoords) goal == null && (goal = startCoords.left - rect.left), startY = dir < 0 ? startCoords.top : startCoords.bottom; else { let line = view.viewState.lineBlockAt(startPos); goal == null && (goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from))), startY = (dir < 0 ? line.top : line.bottom) + docTop } let resolvedGoal = rect.left + goal, halfText = view.viewState.heightOracle.textHeight >> 1, dist2 = distance ?? halfText; for (let scan = 0; ; scan += halfText) { let y = startY + (dist2 + scan) * dir, pos = posAtCoords(view, { x: resolvedGoal, y }, !1, dir); if (forward ? y > rect.bottom : y < rect.top) return EditorSelection.cursor(pos.pos, pos.assoc); let posCoords = view.coordsAtPos(pos.pos, pos.assoc), mid = posCoords ? (posCoords.top + posCoords.bottom) / 2 : 0; if (!posCoords || (forward ? mid > startY : mid < startY)) return EditorSelection.cursor(pos.pos, pos.assoc, void 0, goal) } } function skipAtomicRanges(atoms, pos, bias) { for (; ;) { let moved = 0; for (let set of atoms) set.between(pos - 1, pos + 1, (from, to, value) => { if (pos > from && pos < to) { let side = moved || bias || (pos - from < to - pos ? -1 : 1); pos = side < 0 ? from : to, moved = side } }); if (!moved) return pos } } function skipAtomsForSelection(atoms, sel) { let ranges = null; for (let i2 = 0; i2 < sel.ranges.length; i2++) { let range = sel.ranges[i2], updated = null; if (range.empty) { let pos = skipAtomicRanges(atoms, range.from, 0); pos != range.from && (updated = EditorSelection.cursor(pos, -1)) } else { let from = skipAtomicRanges(atoms, range.from, -1), to = skipAtomicRanges(atoms, range.to, 1); (from != range.from || to != range.to) && (updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to)) } updated && (ranges || (ranges = sel.ranges.slice()), ranges[i2] = updated) } return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel } function skipAtoms(view, oldPos, pos) { let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1); return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1) } var PosAssoc = class { constructor(pos, assoc) { this.pos = pos; this.assoc = assoc } pos; assoc }; function posAtCoords(view, coords, precise, scanY) { let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop, { x, y } = coords, yOffset = y - docTop, block; for (; ;) { if (yOffset < 0) return new PosAssoc(0, 1); if (yOffset > view.viewState.docHeight) return new PosAssoc(view.state.doc.length, -1); if (block = view.elementAtHeight(yOffset), scanY == null) break; if (block.type == 0) { if (scanY < 0 ? block.to < view.viewport.from : block.from > view.viewport.to) break; let rect = view.docView.coordsAt(scanY < 0 ? block.from : block.to, scanY > 0 ? -1 : 1); if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop)) break } let halfLine = view.viewState.heightOracle.textHeight / 2; yOffset = scanY > 0 ? block.bottom + halfLine : block.top - halfLine } if (view.viewport.from >= block.to || view.viewport.to <= block.from) { if (precise) return null; if (block.type == 0) { let pos = posAtCoordsImprecise(view, content2, block, x, y); return new PosAssoc(pos, pos == block.from ? 1 : -1) } } if (block.type != 0) return yOffset < (block.top + block.bottom) / 2 ? new PosAssoc(block.from, 1) : new PosAssoc(block.to, -1); let line = view.docView.lineAt(block.from, 2); return (!line || line.length != block.length) && (line = view.docView.lineAt(block.from, -2)), new InlineCoordsScan(view, x, y, view.textDirectionAt(block.from)).scanTile(line, block.from) } var InlineCoordsScan = class { constructor(view, x, y, baseDir) { this.view = view; this.x = x; this.y = y; this.baseDir = baseDir } view; x; y; baseDir; line = null; spans = null; bidiSpansAt(pos) { return (!this.line || this.line.from > pos || this.line.to < pos) && (this.line = this.view.state.doc.lineAt(pos), this.spans = this.view.bidiSpans(this.line)), this } baseDirAt(pos, side) { let { line, spans } = this.bidiSpansAt(pos); return spans[BidiSpan.find(spans, pos - line.from, -1, side)].level == this.baseDir } dirAt(pos, side) { let { line, spans } = this.bidiSpansAt(pos); return spans[BidiSpan.find(spans, pos - line.from, -1, side)].dir } bidiIn(from, to) { let { spans, line } = this.bidiSpansAt(from); return spans.length > 1 || spans.length && (spans[0].level != this.baseDir || spans[0].to + line.from < to) } scan(positions, getRects) { let lo = 0, hi = positions.length - 1, seen = new Set, bidi = this.bidiIn(positions[0], positions[hi]), above, below, closestI = -1, closestDx = 1e9, closestRect; search: for (; lo < hi;) { let dist2 = hi - lo, mid = lo + hi >> 1; adjust: if (seen.has(mid)) { let scan = lo + Math.floor(Math.random() * dist2); for (let i2 = 0; i2 < dist2; i2++) { if (!seen.has(scan)) { mid = scan; break adjust } scan++, scan == hi && (scan = lo) } break search } seen.add(mid); let rects = getRects(mid); if (rects) for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2], side = 0; if (!(rect.width == 0 && rects.length > 1)) { if (rect.bottom < this.y) (!above || above.bottom < rect.bottom) && (above = rect), side = 1; else if (rect.top > this.y) (!below || below.top > rect.top) && (below = rect), side = -1; else { let off = rect.left > this.x ? this.x - rect.left : rect.right < this.x ? this.x - rect.right : 0, dx = Math.abs(off); dx < closestDx && (closestI = mid, closestDx = dx, closestRect = rect), off && (side = off < 0 == (this.baseDir == 0) ? -1 : 1) } side == -1 && (!bidi || this.baseDirAt(positions[mid], 1)) ? hi = mid : side == 1 && (!bidi || this.baseDirAt(positions[mid + 1], -1)) && (lo = mid + 1) } } } if (!closestRect) { let side = above && (!below || this.y - above.bottom < below.top - this.y) ? above : below; return this.y = (side.top + side.bottom) / 2, this.scan(positions, getRects) } if (closestDx) { if (above && above.bottom > closestRect.top) return this.y = above.bottom - 1, this.scan(positions, getRects); if (below && below.top < closestRect.bottom) return this.y = below.top + 1, this.scan(positions, getRects) } let ltr = (bidi ? this.dirAt(positions[closestI], 1) : this.baseDir) == 0; return { i: closestI, after: this.x > (closestRect.left + closestRect.right) / 2 == ltr } } scanText(tile, offset) { let positions = []; for (let i2 = 0; i2 < tile.length; i2 = findClusterBreak2(tile.text, i2))positions.push(offset + i2); positions.push(offset + tile.length); let scan = this.scan(positions, i2 => { let off = positions[i2] - offset, end = positions[i2 + 1] - offset; return textRange(tile.dom, off, end).getClientRects() }); return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(positions[scan.i], 1) } scanTile(tile, offset) { if (!tile.length) return new PosAssoc(offset, 1); if (tile.children.length == 1) { let child2 = tile.children[0]; if (child2.isText()) return this.scanText(child2, offset); if (child2.isComposite()) return this.scanTile(child2, offset) } let positions = [offset]; for (let i2 = 0, pos2 = offset; i2 < tile.children.length; i2++)positions.push(pos2 += tile.children[i2].length); let scan = this.scan(positions, i2 => { let child2 = tile.children[i2]; return child2.flags & 48 ? null : (child2.dom.nodeType == 1 ? child2.dom : textRange(child2.dom, 0, child2.length)).getClientRects() }), child = tile.children[scan.i], pos = positions[scan.i]; return child.isText() ? this.scanText(child, pos) : child.isComposite() ? this.scanTile(child, pos) : scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(pos, 1) } }; var LineBreakPlaceholder = "\uFFFF", DOMReader = class { constructor(points, view) { this.points = points; this.view = view; this.lineSeparator = view.state.facet(EditorState.lineSeparator) } points; view; text = ""; lineSeparator; append(text) { this.text += text } lineBreak() { this.text += LineBreakPlaceholder } readRange(start, end) { if (!start) return this; let parent = start.parentNode; for (let cur = start; ;) { this.findPointBefore(parent, cur); let oldLen = this.text.length; this.readNode(cur); let tile = Tile.get(cur), next = cur.nextSibling; if (next == end) { tile?.breakAfter && !next && parent != this.view.contentDOM && this.lineBreak(); break } let nextTile = Tile.get(next); (tile && nextTile ? tile.breakAfter : (tile ? tile.breakAfter : isBlockElement(cur)) || isBlockElement(next) && (cur.nodeName != "BR" || tile?.isWidget()) && this.text.length > oldLen) && !isEmptyToEnd(next, end) && this.lineBreak(), cur = next } return this.findPointBefore(parent, end), this } readTextNode(node) { let text = node.nodeValue; for (let point of this.points) point.node == node && (point.pos = this.text.length + Math.min(point.offset, text.length)); for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g; ;) { let nextBreak = -1, breakSize = 1, m; if (this.lineSeparator ? (nextBreak = text.indexOf(this.lineSeparator, off), breakSize = this.lineSeparator.length) : (m = re.exec(text)) && (nextBreak = m.index, breakSize = m[0].length), this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)), nextBreak < 0) break; if (this.lineBreak(), breakSize > 1) for (let point of this.points) point.node == node && point.pos > this.text.length && (point.pos -= breakSize - 1); off = nextBreak + breakSize } } readNode(node) { let tile = Tile.get(node), fromView = tile && tile.overrideDOMText; if (fromView != null) { this.findPointInside(node, fromView.length); for (let i2 = fromView.iter(); !i2.next().done;)i2.lineBreak ? this.lineBreak() : this.append(i2.value) } else node.nodeType == 3 ? this.readTextNode(node) : node.nodeName == "BR" ? node.nextSibling && this.lineBreak() : node.nodeType == 1 && this.readRange(node.firstChild, null) } findPointBefore(node, next) { for (let point of this.points) point.node == node && node.childNodes[point.offset] == next && (point.pos = this.text.length) } findPointInside(node, length) { for (let point of this.points) (node.nodeType == 3 ? point.node == node : node.contains(point.node)) && (point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0)) } }; function isAtEnd(parent, node, offset) { for (; ;) { if (!node || offset < maxOffset(node)) return !1; if (node == parent) return !0; offset = domIndex(node) + 1, node = node.parentNode } } function isEmptyToEnd(node, end) { let widgets; for (; !(node == end || !node); node = node.nextSibling) { let view = Tile.get(node); if (!view?.isWidget()) return !1; view && (widgets || (widgets = [])).push(view) } if (widgets) { for (let w of widgets) if (w.overrideDOMText?.length) return !1 } return !0 } var DOMPoint = class { constructor(node, offset) { this.node = node; this.offset = offset } node; offset; pos = -1 }; var DOMChange = class { constructor(view, start, end, typeOver) { this.typeOver = typeOver; this.domChanged = start > -1; let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView, curSel = view.state.selection; if (view.state.readOnly && start > -1) this.newSel = null; else if (start > -1 && (this.bounds = domBoundsAround(view.docView.tile, start, end, 0))) { let selPoints = iHead || iAnchor ? [] : selectionPoints(view), reader = new DOMReader(selPoints, view); reader.readRange(this.bounds.startDOM, this.bounds.endDOM), this.text = reader.text, this.newSel = selectionFromPoints(selPoints, this.bounds.from) } else { let domSel = view.observer.selectionRange, head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? curSel.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset), anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? curSel.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset), vp = view.viewport; if ((browser_default.ios || browser_default.chrome) && curSel.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) { let from = Math.min(head, anchor), to = Math.max(head, anchor), offFrom = vp.from - from, offTo = vp.to - to; (offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length) && (head = 0, anchor = view.state.doc.length) } if (view.inputState.composing > -1 && curSel.ranges.length > 1) this.newSel = curSel.replaceRange(EditorSelection.range(anchor, head)); else if (view.lineWrapping && anchor == head && !(curSel.main.empty && curSel.main.head == head) && view.inputState.lastTouchTime > Date.now() - 100) { let before = view.coordsAtPos(head, -1), assoc = 0; before && (assoc = view.inputState.lastTouchY <= before.bottom ? -1 : 1), this.newSel = EditorSelection.create([EditorSelection.cursor(head, assoc)]) } else this.newSel = EditorSelection.single(anchor, head) } } typeOver; bounds = null; text = ""; newSel; domChanged }; function domBoundsAround(tile, from, to, offset) { if (tile.isComposite()) { let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; for (let i2 = 0, pos = offset, prevEnd = offset; i2 < tile.children.length; i2++) { let child = tile.children[i2], end = pos + child.length; if (pos < from && end > to) return domBoundsAround(child, from, to, pos); if (end >= from && fromI == -1 && (fromI = i2, fromStart = pos), pos > to && child.dom.parentNode == tile.dom) { toI = i2, toEnd = prevEnd; break } prevEnd = end, pos = end + child.breakAfter } return { from: fromStart, to: toEnd < 0 ? offset + tile.length : toEnd, startDOM: (fromI ? tile.children[fromI - 1].dom.nextSibling : null) || tile.dom.firstChild, endDOM: toI < tile.children.length && toI >= 0 ? tile.children[toI].dom : null } } else return tile.isText() ? { from: offset, to: offset + tile.length, startDOM: tile.dom, endDOM: tile.dom.nextSibling } : null } function applyDOMChange(view, domChange) { + let change, { newSel } = domChange, { state } = view, sel = state.selection.main, lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1; if (domChange.bounds) { let { from, to } = domChange.bounds, preferredPos = sel.from, preferredSide = null; (lastKey === 8 || browser_default.android && domChange.text.length < to - from) && (preferredPos = sel.to, preferredSide = "end"); let cmp = state.doc.sliceString(from, to, LineBreakPlaceholder), selEnd, diff; !sel.empty && sel.from >= from && sel.to <= to && (domChange.typeOver || cmp != domChange.text) && cmp.slice(0, sel.from - from) == domChange.text.slice(0, sel.from - from) && cmp.slice(sel.to - from) == domChange.text.slice(selEnd = domChange.text.length - (cmp.length - (sel.to - from))) ? change = { from: sel.from, to: sel.to, insert: Text.of(domChange.text.slice(sel.from - from, selEnd).split(LineBreakPlaceholder)) } : (diff = findDiff(cmp, domChange.text, preferredPos - from, preferredSide)) && (browser_default.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder && diff.toB--, change = { from: from + diff.from, to: from + diff.toA, insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }) } else newSel && (!view.hasFocus && state.facet(editable) || sameSelPos(newSel, sel)) && (newSel = null); if (!change && !newSel) return !1; if ((browser_default.mac || browser_default.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off" ? (newSel && change.insert.length == 2 && (newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1)), change = { from: change.from, to: change.to, insert: Text.of([change.insert.toString().replace(".", " ")]) }) : state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50 ? change = { from: sel.from, to: sel.to, insert: state.toText(view.inputState.insertingText) } : browser_default.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == ` + `&& view.lineWrapping && (newSel && (newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1)), change = { from: sel.from, to: sel.to, insert: Text.of([" "]) }), change) return applyDOMChangeInner(view, change, newSel, lastKey); if (newSel && !sameSelPos(newSel, sel)) { let scrollIntoView2 = !1, userEvent = "select"; return view.inputState.lastSelectionTime > Date.now() - 50 && (view.inputState.lastSelectionOrigin == "select" && (scrollIntoView2 = !0), userEvent = view.inputState.lastSelectionOrigin, userEvent == "select.pointer" && (newSel = skipAtomsForSelection(state.facet(atomicRanges).map(f => f(view)), newSel))), view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView2, userEvent }), !0 } else return !1 +} function applyDOMChangeInner(view, change, newSel, lastKey = -1) { if (browser_default.ios && view.inputState.flushIOSKey(change)) return !0; let sel = view.state.selection.main; if (browser_default.android && (change.to == sel.to && (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46))) return !0; let text = change.insert.toString(); view.inputState.composing >= 0 && view.inputState.composing++; let defaultTr, defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel)); return view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)) || view.dispatch(defaultInsert()), !0 } function applyDefaultInsert(view, change, newSel) { let tr, startState = view.state, sel = startState.selection.main, inAtomic = -1; if (change.from == change.to && change.from < sel.from || change.from > sel.to) { let side = change.from < sel.from ? -1 : 1, pos = side < 0 ? sel.from : sel.to, moved = skipAtomicRanges(startState.facet(atomicRanges).map(f => f(view)), pos, side); change.from == moved && (inAtomic = moved) } if (inAtomic > -1) tr = { changes: change, selection: EditorSelection.cursor(change.from + change.insert.length, -1) }; else if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) { let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "", after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after)) } else { let changes = startState.changes(change), mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0; if (startState.selection.ranges.length > 1 && (view.inputState.composing >= 0 || view.inputState.compositionPendingChange) && change.to <= sel.to + 10 && change.to >= sel.to - 10) { let replaced = view.state.sliceDoc(change.from, change.to), compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head); if (composition) { let dLen = change.insert.length - (change.to - change.from); compositionRange = { from: composition.from, to: composition.to - dLen } } else compositionRange = view.state.doc.lineAt(sel.head); let offset = sel.to - change.to; tr = startState.changeByRange(range => { if (range.from == sel.from && range.to == sel.to) return { changes, range: mainSel || range.map(changes) }; let to = range.to - offset, from = to - replaced.length; if (view.state.sliceDoc(from, to) != replaced || to >= compositionRange.from && from <= compositionRange.to) return { range }; let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; return { changes: rangeChanges, range: mainSel ? EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) : range.map(rangeChanges) } }) } else tr = { changes, selection: mainSel && startState.selection.replaceRange(mainSel) } } let userEvent = "input.type"; return (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) && (view.inputState.compositionPendingChange = !1, userEvent += ".compose", view.inputState.compositionFirstChange && (userEvent += ".start", view.inputState.compositionFirstChange = !1)), startState.update(tr, { userEvent, scrollIntoView: !0 }) } function findDiff(a, b, preferredPos, preferredSide) { let minLen = Math.min(a.length, b.length), from = 0; for (; from < minLen && a.charCodeAt(from) == b.charCodeAt(from);)from++; if (from == minLen && a.length == b.length) return null; let toA = a.length, toB = b.length; for (; toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1);)toA--, toB--; if (preferredSide == "end") { let adjust = Math.max(0, from - Math.min(toA, toB)); preferredPos -= toA + adjust - from } if (toA < from && a.length < b.length) { let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; from -= move, toB = from + (toB - toA), toA = from } else if (toB < from) { let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; from -= move, toA = from + (toA - toB), toB = from } return { from, toA, toB } } function selectionPoints(view) { let result = []; if (view.root.activeElement != view.contentDOM) return result; let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; return anchorNode && (result.push(new DOMPoint(anchorNode, anchorOffset)), (focusNode != anchorNode || focusOffset != anchorOffset) && result.push(new DOMPoint(focusNode, focusOffset))), result } function selectionFromPoints(points, base2) { if (points.length == 0) return null; let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base2, head + base2) : null } function sameSelPos(selection, range) { return range.head == selection.main.head && range.anchor == selection.main.anchor } var InputState = class { constructor(view) { this.view = view; this.handleEvent = this.handleEvent.bind(this), this.notifiedFocused = view.hasFocus, browser_default.safari && view.contentDOM.addEventListener("input", () => null), browser_default.gecko && firefoxCopyCutHack(view.contentDOM.ownerDocument) } view; lastKeyCode = 0; lastKeyTime = 0; lastTouchTime = 0; lastTouchX = 0; lastTouchY = 0; lastFocusTime = 0; lastScrollTop = 0; lastScrollLeft = 0; lastWheelEvent = 0; pendingIOSKey = void 0; tabFocusMode = -1; lastSelectionOrigin = null; lastSelectionTime = 0; lastContextMenu = 0; scrollHandlers = []; handlers = Object.create(null); composing = -1; compositionFirstChange = null; compositionEndedAt = 0; compositionPendingKey = !1; compositionPendingChange = !1; insertingText = ""; insertingTextAt = 0; mouseSelection = null; draggedContent = null; notifiedFocused; setSelectionOrigin(origin) { this.lastSelectionOrigin = origin, this.lastSelectionTime = Date.now() } handleEvent(event) { !eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event) || event.type == "keydown" && this.keydown(event) || (this.view.updateState != 0 ? Promise.resolve().then(() => this.runHandlers(event.type, event)) : this.runHandlers(event.type, event)) } runHandlers(type, event) { let handlers2 = this.handlers[type]; if (handlers2) { for (let observer of handlers2.observers) observer(this.view, event); for (let handler of handlers2.handlers) { if (event.defaultPrevented) break; if (handler(this.view, event)) { event.preventDefault(); break } } } } ensureHandlers(plugins) { let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM; for (let type in handlers2) if (type != "scroll") { let passive = !handlers2[type].handlers.length, exists = prev[type]; exists && passive != !exists.handlers.length && (dom.removeEventListener(type, this.handleEvent), exists = null), exists || dom.addEventListener(type, this.handleEvent, { passive }) } for (let type in prev) type != "scroll" && !handlers2[type] && dom.removeEventListener(type, this.handleEvent); this.handlers = handlers2 } keydown(event) { if (this.lastKeyCode = event.keyCode, this.lastKeyTime = Date.now(), event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode)) return !0; if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0 && (this.tabFocusMode = -1), browser_default.android && browser_default.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) return this.view.observer.delayAndroidKey(event.key, event.keyCode), !0; let pending; return browser_default.ios && !event.synthetic && !event.altKey && !event.metaKey && !event.shiftKey && ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey) ? (this.pendingIOSKey = pending || event, setTimeout(() => this.flushIOSKey(), 250), !0) : (event.keyCode != 229 && this.view.observer.forceFlush(), !1) } flushIOSKey(change) { let key = this.pendingIOSKey; return !key || key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()) ? !1 : (this.pendingIOSKey = void 0, dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : void 0)) } ignoreDuringComposition(event) { return !/^key/.test(event.type) || event.synthetic ? !1 : this.composing > 0 ? !0 : browser_default.safari && !browser_default.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100 ? (this.compositionPendingKey = !1, !0) : !1 } startMouseSelection(mouseSelection) { this.mouseSelection && this.mouseSelection.destroy(), this.mouseSelection = mouseSelection } update(update) { this.view.observer.update(update), this.mouseSelection && this.mouseSelection.update(update), this.draggedContent && update.docChanged && (this.draggedContent = this.draggedContent.map(update.changes)), update.transactions.length && (this.lastKeyCode = this.lastSelectionTime = 0) } destroy() { this.mouseSelection && this.mouseSelection.destroy() } }; function bindHandler(plugin2, handler) { return (view, event) => { try { return handler.call(plugin2, event, view) } catch (e) { logException(view.state, e) } } } function computeHandlers(plugins) { let result = Object.create(null); function record(type) { return result[type] || (result[type] = { observers: [], handlers: [] }) } for (let plugin2 of plugins) { let spec = plugin2.spec, handlers2 = spec && spec.plugin.domEventHandlers, observers2 = spec && spec.plugin.domEventObservers; if (handlers2) for (let type in handlers2) { let f = handlers2[type]; f && record(type).handlers.push(bindHandler(plugin2.value, f)) } if (observers2) for (let type in observers2) { let f = observers2[type]; f && record(type).observers.push(bindHandler(plugin2.value, f)) } } for (let type in handlers) record(type).handlers.push(handlers[type]); for (let type in observers) record(type).observers.push(observers[type]); return result } var PendingKeys = [{ key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, { key: "Enter", keyCode: 13, inputType: "insertLineBreak" }, { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }], EmacsyPendingKeys = "dthko", modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225], dragScrollMargin = 6; function dragScrollSpeed(dist2) { return Math.max(0, dist2) * .7 + 8 } function dist(a, b) { return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY)) } var MouseSelection = class { constructor(view, startEvent, style, mustSelect) { this.view = view; this.startEvent = startEvent; this.style = style; this.mustSelect = mustSelect; this.lastEvent = startEvent, this.scrollParents = scrollableParents(view.contentDOM), this.atoms = view.state.facet(atomicRanges).map(f => f(view)); let doc2 = view.contentDOM.ownerDocument; doc2.addEventListener("mousemove", this.move = this.move.bind(this)), doc2.addEventListener("mouseup", this.up = this.up.bind(this)), this.extend = startEvent.shiftKey, this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent), this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : !1 } view; startEvent; style; mustSelect; dragging; extend; multiple; lastEvent; scrollParents; scrollSpeed = { x: 0, y: 0 }; scrolling = -1; atoms; start(event) { this.dragging === !1 && this.select(event) } move(event) { if (event.buttons == 0) return this.destroy(); if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) return; this.select(this.lastEvent = event); let sx = 0, sy = 0, left = 0, top2 = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight; this.scrollParents.x && ({ left, right } = this.scrollParents.x.getBoundingClientRect()), this.scrollParents.y && ({ top: top2, bottom } = this.scrollParents.y.getBoundingClientRect()); let margins = getScrollMargins(this.view); event.clientX - margins.left <= left + dragScrollMargin ? sx = -dragScrollSpeed(left - event.clientX) : event.clientX + margins.right >= right - dragScrollMargin && (sx = dragScrollSpeed(event.clientX - right)), event.clientY - margins.top <= top2 + dragScrollMargin ? sy = -dragScrollSpeed(top2 - event.clientY) : event.clientY + margins.bottom >= bottom - dragScrollMargin && (sy = dragScrollSpeed(event.clientY - bottom)), this.setScrollSpeed(sx, sy) } up(event) { this.dragging == null && this.select(this.lastEvent), this.dragging || event.preventDefault(), this.destroy() } destroy() { this.setScrollSpeed(0, 0); let doc2 = this.view.contentDOM.ownerDocument; doc2.removeEventListener("mousemove", this.move), doc2.removeEventListener("mouseup", this.up), this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null } setScrollSpeed(sx, sy) { this.scrollSpeed = { x: sx, y: sy }, sx || sy ? this.scrolling < 0 && (this.scrolling = setInterval(() => this.scroll(), 50)) : this.scrolling > -1 && (clearInterval(this.scrolling), this.scrolling = -1) } scroll() { let { x, y } = this.scrollSpeed; x && this.scrollParents.x && (this.scrollParents.x.scrollLeft += x, x = 0), y && this.scrollParents.y && (this.scrollParents.y.scrollTop += y, y = 0), (x || y) && this.view.win.scrollBy(x, y), this.dragging === !1 && this.select(this.lastEvent) } select(event) { let { view } = this, selection = skipAtomsForSelection(this.atoms, this.style.get(event, this.extend, this.multiple)); (this.mustSelect || !selection.eq(view.state.selection, this.dragging === !1)) && this.view.dispatch({ selection, userEvent: "select.pointer" }), this.mustSelect = !1 } update(update) { update.transactions.some(tr => tr.isUserEvent("input.type")) ? this.destroy() : this.style.update(update) && setTimeout(() => this.select(this.lastEvent), 20) } }; function addsSelectionRange(view, event) { let facet = view.state.facet(clickAddsSelectionRange); return facet.length ? facet[0](event) : browser_default.mac ? event.metaKey : event.ctrlKey } function dragMovesSelection2(view, event) { let facet = view.state.facet(dragMovesSelection); return facet.length ? facet[0](event) : browser_default.mac ? !event.altKey : !event.ctrlKey } function isInPrimarySelection(view, event) { let { main } = view.state.selection; if (main.empty) return !1; let sel = getSelection(view.root); if (!sel || sel.rangeCount == 0) return !0; let rects = sel.getRangeAt(0).getClientRects(); for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2]; if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY) return !0 } return !1 } function eventBelongsToEditor(view, event) { if (!event.bubbles) return !0; if (event.defaultPrevented) return !1; for (let node = event.target, tile; node != view.contentDOM; node = node.parentNode)if (!node || node.nodeType == 11 || (tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.ignoreEvent(event)) return !1; return !0 } var handlers = Object.create(null), observers = Object.create(null), brokenClipboardAPI = browser_default.ie && browser_default.ie_version < 15 || browser_default.ios && browser_default.webkit_version < 604; function capturePaste(view) { let parent = view.dom.parentNode; if (!parent) return; let target = parent.appendChild(document.createElement("textarea")); target.style.cssText = "position: fixed; left: -10000px; top: 10px", target.focus(), setTimeout(() => { view.focus(), target.remove(), doPaste(view, target.value) }, 50) } function textFilter(state, facet, text) { for (let filter of state.facet(facet)) text = filter(text, state); return text } function doPaste(view, input) { input = textFilter(view.state, clipboardInputFilter, input); let { state } = view, changes, i2 = 1, text = state.toText(input), byLine = text.lines == state.selection.ranges.length; if (lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString()) { let lastLine = -1; changes = state.changeByRange(range => { let line = state.doc.lineAt(range.from); if (line.from == lastLine) return { range }; lastLine = line.from; let insert2 = state.toText((byLine ? text.line(i2++).text : input) + state.lineBreak); return { changes: { from: line.from, insert: insert2 }, range: EditorSelection.cursor(range.from + insert2.length) } }) } else byLine ? changes = state.changeByRange(range => { let line = text.line(i2++); return { changes: { from: range.from, to: range.to, insert: line.text }, range: EditorSelection.cursor(range.from + line.length) } }) : changes = state.replaceSelection(text); view.dispatch(changes, { userEvent: "input.paste", scrollIntoView: !0 }) } observers.scroll = view => { view.inputState.lastScrollTop = view.scrollDOM.scrollTop, view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft }; observers.wheel = observers.mousewheel = view => { view.inputState.lastWheelEvent = Date.now() }; handlers.keydown = (view, event) => (view.inputState.setSelectionOrigin("select"), event.keyCode == 27 && view.inputState.tabFocusMode != 0 && (view.inputState.tabFocusMode = Date.now() + 2e3), !1); observers.touchstart = (view, e) => { let iState = view.inputState, touch = e.targetTouches[0]; iState.lastTouchTime = Date.now(), touch && (iState.lastTouchX = touch.clientX, iState.lastTouchY = touch.clientY), iState.setSelectionOrigin("select.pointer") }; observers.touchmove = view => { view.inputState.setSelectionOrigin("select.pointer") }; handlers.mousedown = (view, event) => { if (view.observer.flush(), view.inputState.lastTouchTime > Date.now() - 2e3) return !1; let style = null; for (let makeStyle of view.state.facet(mouseSelectionStyle)) if (style = makeStyle(view, event), style) break; if (!style && event.button == 0 && (style = basicMouseSelection(view, event)), style) { let mustFocus = !view.hasFocus; view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)), mustFocus && view.observer.ignore(() => { focusPreventScroll(view.contentDOM); let active = view.root.activeElement; active && !active.contains(view.contentDOM) && active.blur() }); let mouseSel = view.inputState.mouseSelection; if (mouseSel) return mouseSel.start(event), mouseSel.dragging === !1 } else view.inputState.setSelectionOrigin("select.pointer"); return !1 }; function rangeForClick(view, pos, bias, type) { if (type == 1) return EditorSelection.cursor(pos, bias); if (type == 2) return groupAt(view.state, pos, bias); { let visual = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos), from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; return to < view.state.doc.length && to == line.to && to++, EditorSelection.range(from, to) } } var BadMouseDetail = browser_default.ie && browser_default.ie_version <= 11, lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; function getClickType(event) { if (!BadMouseDetail) return event.detail; let last = lastMouseDown, lastTime = lastMouseDownTime; return lastMouseDown = event, lastMouseDownTime = Date.now(), lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1 } function basicMouseSelection(view, event) { let start = view.posAndSideAtCoords({ x: event.clientX, y: event.clientY }, !1), type = getClickType(event), startSel = view.state.selection; return { update(update) { update.docChanged && (start.pos = update.changes.mapPos(start.pos), startSel = startSel.map(update.changes)) }, get(event2, extend, multiple) { let cur = view.posAndSideAtCoords({ x: event2.clientX, y: event2.clientY }, !1), removed, range = rangeForClick(view, cur.pos, cur.assoc, type); if (start.pos != cur.pos && !extend) { let startRange = rangeForClick(view, start.pos, start.assoc, type), from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); range = from < range.from ? EditorSelection.range(from, to, range.assoc) : EditorSelection.range(to, from, range.assoc) } return extend ? startSel.replaceRange(startSel.main.extend(range.from, range.to, range.assoc)) : multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)) ? removed : multiple ? startSel.addRange(range) : EditorSelection.create([range]) } } } function removeRangeAround(sel, pos) { for (let i2 = 0; i2 < sel.ranges.length; i2++) { let { from, to } = sel.ranges[i2]; if (from <= pos && to >= pos) return EditorSelection.create(sel.ranges.slice(0, i2).concat(sel.ranges.slice(i2 + 1)), sel.mainIndex == i2 ? 0 : sel.mainIndex - (sel.mainIndex > i2 ? 1 : 0)) } return null } handlers.dragstart = (view, event) => { let { selection: { main: range } } = view.state; if (event.target.draggable) { let tile = view.docView.tile.nearest(event.target); if (tile && tile.isWidget()) { let from = tile.posAtStart, to = from + tile.length; (from >= range.to || to <= range.from) && (range = EditorSelection.range(from, to)) } } let { inputState } = view; return inputState.mouseSelection && (inputState.mouseSelection.dragging = !0), inputState.draggedContent = range, event.dataTransfer && (event.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to))), event.dataTransfer.effectAllowed = "copyMove"), !1 }; handlers.dragend = view => (view.inputState.draggedContent = null, !1); function dropText(view, event, text, direct) { if (text = textFilter(view.state, clipboardInputFilter, text), !text) return; let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, !1), { draggedContent } = view.inputState, del = direct && draggedContent && dragMovesSelection2(view, event) ? { from: draggedContent.from, to: draggedContent.to } : null, ins = { from: dropPos, insert: text }, changes = view.state.changes(del ? [del, ins] : ins); view.focus(), view.dispatch({ changes, selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, userEvent: del ? "move.drop" : "input.drop" }), view.inputState.draggedContent = null } handlers.drop = (view, event) => { if (!event.dataTransfer) return !1; if (view.state.readOnly) return !0; let files = event.dataTransfer.files; if (files && files.length) { let text = Array(files.length), read = 0, finishFile = () => { ++read == files.length && dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), !1) }; for (let i2 = 0; i2 < files.length; i2++) { let reader = new FileReader; reader.onerror = finishFile, reader.onload = () => { /[\x00-\x08\x0e-\x1f]{2}/.test(reader.result) || (text[i2] = reader.result), finishFile() }, reader.readAsText(files[i2]) } return !0 } else { let text = event.dataTransfer.getData("Text"); if (text) return dropText(view, event, text, !0), !0 } return !1 }; handlers.paste = (view, event) => { if (view.state.readOnly) return !0; view.observer.flush(); let data = brokenClipboardAPI ? null : event.clipboardData; return data ? (doPaste(view, data.getData("text/plain") || data.getData("text/uri-list")), !0) : (capturePaste(view), !1) }; function captureCopy(view, text) { let parent = view.dom.parentNode; if (!parent) return; let target = parent.appendChild(document.createElement("textarea")); target.style.cssText = "position: fixed; left: -10000px; top: 10px", target.value = text, target.focus(), target.selectionEnd = text.length, target.selectionStart = 0, setTimeout(() => { target.remove(), view.focus() }, 50) } function copiedRange(state) { let content2 = [], ranges = [], linewise = !1; for (let range of state.selection.ranges) range.empty || (content2.push(state.sliceDoc(range.from, range.to)), ranges.push(range)); if (!content2.length) { let upto = -1; for (let { from } of state.selection.ranges) { let line = state.doc.lineAt(from); line.number > upto && (content2.push(line.text), ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) })), upto = line.number } linewise = !0 } return { text: textFilter(state, clipboardOutputFilter, content2.join(state.lineBreak)), ranges, linewise } } var lastLinewiseCopy = null; handlers.copy = handlers.cut = (view, event) => { if (!hasSelection(view.contentDOM, view.observer.selectionRange)) return !1; let { text, ranges, linewise } = copiedRange(view.state); if (!text && !linewise) return !1; lastLinewiseCopy = linewise ? text : null, event.type == "cut" && !view.state.readOnly && view.dispatch({ changes: ranges, scrollIntoView: !0, userEvent: "delete.cut" }); let data = brokenClipboardAPI ? null : event.clipboardData; return data ? (data.clearData(), data.setData("text/plain", text), !0) : (captureCopy(view, text), !1) }; var isFocusChange = Annotation.define(); function focusChangeTransaction(state, focus) { let effects = []; for (let getEffect of state.facet(focusChangeEffect)) { let effect = getEffect(state, focus); effect && effects.push(effect) } return effects.length ? state.update({ effects, annotations: isFocusChange.of(!0) }) : null } function updateForFocusChange(view) { setTimeout(() => { let focus = view.hasFocus; if (focus != view.inputState.notifiedFocused) { let tr = focusChangeTransaction(view.state, focus); tr ? view.dispatch(tr) : view.update([]) } }, 10) } observers.focus = view => { view.inputState.lastFocusTime = Date.now(), !view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft) && (view.scrollDOM.scrollTop = view.inputState.lastScrollTop, view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft), updateForFocusChange(view) }; observers.blur = view => { view.observer.clearSelectionRange(), updateForFocusChange(view) }; observers.compositionstart = observers.compositionupdate = view => { view.observer.editContext || (view.inputState.compositionFirstChange == null && (view.inputState.compositionFirstChange = !0), view.inputState.composing < 0 && (view.inputState.composing = 0)) }; observers.compositionend = view => { view.observer.editContext || (view.inputState.composing = -1, view.inputState.compositionEndedAt = Date.now(), view.inputState.compositionPendingKey = !0, view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0, view.inputState.compositionFirstChange = null, browser_default.chrome && browser_default.android ? view.observer.flushSoon() : view.inputState.compositionPendingChange ? Promise.resolve().then(() => view.observer.flush()) : setTimeout(() => { view.inputState.composing < 0 && view.docView.hasComposition && view.update([]) }, 50)) }; observers.contextmenu = view => { view.inputState.lastContextMenu = Date.now() }; handlers.beforeinput = (view, event) => { if ((event.inputType == "insertText" || event.inputType == "insertCompositionText") && (view.inputState.insertingText = event.data, view.inputState.insertingTextAt = Date.now()), event.inputType == "insertReplacementText" && view.observer.editContext) { let text = event.dataTransfer?.getData("text/plain"), ranges = event.getTargetRanges(); if (text && ranges.length) { let r = ranges[0], from = view.posAtDOM(r.startContainer, r.startOffset), to = view.posAtDOM(r.endContainer, r.endOffset); return applyDOMChangeInner(view, { from, to, insert: view.state.toText(text) }, null), !0 } } let pending; if (browser_default.chrome && browser_default.android && (pending = PendingKeys.find(key => key.inputType == event.inputType)) && (view.observer.delayAndroidKey(pending.key, pending.keyCode), pending.key == "Backspace" || pending.key == "Delete")) { let startViewHeight = window.visualViewport?.height || 0; setTimeout(() => { (window.visualViewport?.height || 0) > startViewHeight + 10 && view.hasFocus && (view.contentDOM.blur(), view.focus()) }, 100) } return browser_default.ios && event.inputType == "deleteContentForward" && view.observer.flushSoon(), browser_default.safari && event.inputType == "insertText" && view.inputState.composing >= 0 && setTimeout(() => observers.compositionend(view, event), 20), !1 }; var appliedFirefoxHack = new Set; function firefoxCopyCutHack(doc2) { appliedFirefoxHack.has(doc2) || (appliedFirefoxHack.add(doc2), doc2.addEventListener("copy", () => { }), doc2.addEventListener("cut", () => { })) } var wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"], heightChangeFlag = !1; function clearHeightChangeFlag() { heightChangeFlag = !1 } var HeightOracle = class { constructor(lineWrapping) { this.lineWrapping = lineWrapping } lineWrapping; doc = Text.empty; heightSamples = {}; lineHeight = 14; charWidth = 7; textHeight = 14; lineLength = 30; heightForGap(from, to) { let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; return this.lineWrapping && (lines += Math.max(0, Math.ceil((to - from - lines * this.lineLength * .5) / this.lineLength))), this.lineHeight * lines } heightForLine(length) { return this.lineWrapping ? (1 + Math.max(0, Math.ceil((length - this.lineLength) / Math.max(1, this.lineLength - 5)))) * this.lineHeight : this.lineHeight } setDoc(doc2) { return this.doc = doc2, this } mustRefreshForWrapping(whiteSpace) { return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping } mustRefreshForHeights(lineHeights) { let newHeight = !1; for (let i2 = 0; i2 < lineHeights.length; i2++) { let h = lineHeights[i2]; h < 0 ? i2++ : this.heightSamples[Math.floor(h * 10)] || (newHeight = !0, this.heightSamples[Math.floor(h * 10)] = !0) } return newHeight } refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) { let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1, changed = Math.abs(lineHeight - this.lineHeight) > .3 || this.lineWrapping != lineWrapping || Math.abs(charWidth - this.charWidth) > .1; if (this.lineWrapping = lineWrapping, this.lineHeight = lineHeight, this.charWidth = charWidth, this.textHeight = textHeight, this.lineLength = lineLength, changed) { this.heightSamples = {}; for (let i2 = 0; i2 < knownHeights.length; i2++) { let h = knownHeights[i2]; h < 0 ? i2++ : this.heightSamples[Math.floor(h * 10)] = !0 } } return changed } }, MeasuredHeights = class { constructor(from, heights) { this.from = from; this.heights = heights } from; heights; index = 0; get more() { return this.index < this.heights.length } }, BlockInfo = class _BlockInfo { constructor(from, length, top2, height, _content) { this.from = from; this.length = length; this.top = top2; this.height = height; this._content = _content } from; length; top; height; _content; get type() { return typeof this._content == "number" ? 0 : Array.isArray(this._content) ? this._content : this._content.type } get to() { return this.from + this.length } get bottom() { return this.top + this.height } get widget() { return this._content instanceof PointDecoration ? this._content.widget : null } get widgetLineBreaks() { return typeof this._content == "number" ? this._content : 0 } join(other) { let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]); return new _BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2) } }, QueryType = (QueryType3 => (QueryType3[QueryType3.ByPos = 0] = "ByPos", QueryType3[QueryType3.ByHeight = 1] = "ByHeight", QueryType3[QueryType3.ByPosNoHeight = 2] = "ByPosNoHeight", QueryType3))(QueryType || {}); var Epsilon = .001, HeightMap = class _HeightMap { constructor(length, height, flags = 2) { this.length = length; this.height = height; this.flags = flags } length; height; flags; get outdated() { return (this.flags & 2) > 0 } set outdated(value) { this.flags = (value ? 2 : 0) | this.flags & -3 } setHeight(height) { this.height != height && (Math.abs(this.height - height) > Epsilon && (heightChangeFlag = !0), this.height = height) } replace(_from, _to, nodes) { return _HeightMap.of(nodes) } decomposeLeft(_to, result) { result.push(this) } decomposeRight(_from, result) { result.push(this) } applyChanges(decorations2, oldDoc, oracle, changes) { let me = this, doc2 = oracle.doc; for (let i2 = changes.length - 1; i2 >= 0; i2--) { let { fromA, toA, fromB, toB } = changes[i2], start = me.lineAt(fromA, 2, oracle.setDoc(oldDoc), 0, 0), end = start.to >= toA ? start : me.lineAt(toA, 2, oracle, 0, 0); for (toB += end.to - toA, toA = end.to; i2 > 0 && start.from <= changes[i2 - 1].toA;)fromA = changes[i2 - 1].fromA, fromB = changes[i2 - 1].fromB, i2--, fromA < start.from && (start = me.lineAt(fromA, 2, oracle, 0, 0)); fromB += start.from - fromA, fromA = start.from; let nodes = NodeBuilder.build(oracle.setDoc(doc2), decorations2, fromB, toB); me = replace(me, me.replace(fromA, toA, nodes)) } return me.updateHeight(oracle, 0) } static empty() { return new HeightMapText(0, 0, 0) } static of(nodes) { if (nodes.length == 1) return nodes[0]; let i2 = 0, j = nodes.length, before = 0, after = 0; for (; ;)if (i2 == j) if (before > after * 2) { let split = nodes[i2 - 1]; split.break ? nodes.splice(--i2, 1, split.left, null, split.right) : nodes.splice(--i2, 1, split.left, split.right), j += 1 + split.break, before -= split.size } else if (after > before * 2) { let split = nodes[j]; split.break ? nodes.splice(j, 1, split.left, null, split.right) : nodes.splice(j, 1, split.left, split.right), j += 2 + split.break, after -= split.size } else break; else if (before < after) { let next = nodes[i2++]; next && (before += next.size) } else { let next = nodes[--j]; next && (after += next.size) } let brk = 0; return nodes[i2 - 1] == null ? (brk = 1, i2--) : nodes[i2] == null && (brk = 1, j++), new HeightMapBranch(_HeightMap.of(nodes.slice(0, i2)), brk, _HeightMap.of(nodes.slice(j))) } }; function replace(old, val) { return old == val ? old : (old.constructor != val.constructor && (heightChangeFlag = !0), val) } HeightMap.prototype.size = 1; var SpaceDeco = Decoration.replace({}), HeightMapBlock = class extends HeightMap { constructor(length, height, deco) { super(length, height); this.deco = deco } deco; spaceAbove = 0; mainBlock(top2, offset) { return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.deco || 0) } blockAt(height, _oracle, top2, offset) { return this.spaceAbove && height < top2 + this.spaceAbove ? new BlockInfo(offset, 0, top2, this.spaceAbove, SpaceDeco) : this.mainBlock(top2, offset) } lineAt(_value, _type, oracle, top2, offset) { let main = this.mainBlock(top2, offset); return this.spaceAbove ? this.blockAt(0, oracle, top2, offset).join(main) : main } forEachLine(from, to, oracle, top2, offset, f) { from <= offset + this.length && to >= offset && f(this.lineAt(0, 0, oracle, top2, offset)) } setMeasuredHeight(measured) { let next = measured.heights[measured.index++]; next < 0 ? (this.spaceAbove = -next, next = measured.heights[measured.index++]) : this.spaceAbove = 0, this.setHeight(next) } updateHeight(oracle, offset = 0, _force = !1, measured) { return measured && measured.from <= offset && measured.more && this.setMeasuredHeight(measured), this.outdated = !1, this } toString() { return `block(${this.length})` } }, HeightMapText = class _HeightMapText extends HeightMapBlock { collapsed = 0; widgetHeight = 0; breaks = 0; constructor(length, height, above) { super(length, height, null), this.spaceAbove = above } mainBlock(top2, offset) { return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.breaks) } replace(_from, _to, nodes) { let node = nodes[0]; return nodes.length == 1 && (node instanceof _HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10 ? (node instanceof HeightMapGap ? node = new _HeightMapText(node.length, this.height, this.spaceAbove) : node.height = this.height, this.outdated || (node.outdated = !1), node) : HeightMap.of(nodes) } updateHeight(oracle, offset = 0, force = !1, measured) { return measured && measured.from <= offset && measured.more ? this.setMeasuredHeight(measured) : (force || this.outdated) && (this.spaceAbove = 0, this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight)), this.outdated = !1, this } toString() { return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})` } }, HeightMapGap = class _HeightMapGap extends HeightMap { constructor(length) { super(length, 0) } heightMetrics(oracle, offset) { let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number, lines = lastLine - firstLine + 1, perLine, perChar = 0; if (oracle.lineWrapping) { let totalPerLine = Math.min(this.height, oracle.lineHeight * lines); perLine = totalPerLine / lines, this.length > lines + 1 && (perChar = (this.height - totalPerLine) / (this.length - lines - 1)) } else perLine = this.height / lines; return { firstLine, lastLine, perLine, perChar } } blockAt(height, oracle, top2, offset) { let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset); if (oracle.lineWrapping) { let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top2) / this.height)) * this.length)), line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar, lineTop = Math.max(top2, height - lineHeight / 2); return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0) } else { let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top2) / perLine))), { from, length } = oracle.doc.line(firstLine + line); return new BlockInfo(from, length, top2 + perLine * line, perLine, 0) } } lineAt(value, type, oracle, top2, offset) { if (type == 1) return this.blockAt(value, oracle, top2, offset); if (type == 2) { let { from, to } = oracle.doc.lineAt(value); return new BlockInfo(from, to - from, 0, 0, 0) } let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset), line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar, linesAbove = line.number - firstLine, lineTop = top2 + perLine * linesAbove + perChar * (line.from - offset - linesAbove); return new BlockInfo(line.from, line.length, Math.max(top2, Math.min(lineTop, top2 + this.height - lineHeight)), lineHeight, 0) } forEachLine(from, to, oracle, top2, offset, f) { from = Math.max(from, offset), to = Math.min(to, offset + this.length); let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset); for (let pos = from, lineTop = top2; pos <= to;) { let line = oracle.doc.lineAt(pos); if (pos == from) { let linesAbove = line.number - firstLine; lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove) } let lineHeight = perLine + perChar * line.length; f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0)), lineTop += lineHeight, pos = line.to + 1 } } replace(from, to, nodes) { let after = this.length - to; if (after > 0) { let last = nodes[nodes.length - 1]; last instanceof _HeightMapGap ? nodes[nodes.length - 1] = new _HeightMapGap(last.length + after) : nodes.push(null, new _HeightMapGap(after - 1)) } if (from > 0) { let first = nodes[0]; first instanceof _HeightMapGap ? nodes[0] = new _HeightMapGap(from + first.length) : nodes.unshift(new _HeightMapGap(from - 1), null) } return HeightMap.of(nodes) } decomposeLeft(to, result) { result.push(new _HeightMapGap(to - 1), null) } decomposeRight(from, result) { result.push(null, new _HeightMapGap(this.length - from - 1)) } updateHeight(oracle, offset = 0, force = !1, measured) { let end = offset + this.length; if (measured && measured.from <= offset + this.length && measured.more) { let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; for (measured.from > offset && nodes.push(new _HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); pos <= end && measured.more;) { let len = oracle.doc.lineAt(pos).length; nodes.length && nodes.push(null); let height = measured.heights[measured.index++], above = 0; height < 0 && (above = -height, height = measured.heights[measured.index++]), singleHeight == -1 ? singleHeight = height : Math.abs(height - singleHeight) >= Epsilon && (singleHeight = -2); let line = new HeightMapText(len, height, above); line.outdated = !1, nodes.push(line), pos += len + 1 } pos <= end && nodes.push(null, new _HeightMapGap(end - pos).updateHeight(oracle, pos)); let result = HeightMap.of(nodes); return (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon) && (heightChangeFlag = !0), replace(this, result) } else (force || this.outdated) && (this.setHeight(oracle.heightForGap(offset, offset + this.length)), this.outdated = !1); return this } toString() { return `gap(${this.length})` } }, HeightMapBranch = class extends HeightMap { constructor(left, brk, right) { super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0)); this.left = left; this.right = right; this.size = left.size + right.size } left; right; size; get break() { return this.flags & 1 } blockAt(height, oracle, top2, offset) { let mid = top2 + this.left.height; return height < mid ? this.left.blockAt(height, oracle, top2, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break) } lineAt(value, type, oracle, top2, offset) { let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break, left = type == 1 ? value < rightTop : value < rightOffset, base2 = left ? this.left.lineAt(value, type, oracle, top2, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset); if (this.break || (left ? base2.to < rightOffset : base2.from > rightOffset)) return base2; let subQuery = type == 2 ? 2 : 0; return left ? base2.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset)) : this.left.lineAt(rightOffset, subQuery, oracle, top2, offset).join(base2) } forEachLine(from, to, oracle, top2, offset, f) { let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break; if (this.break) from < rightOffset && this.left.forEachLine(from, to, oracle, top2, offset, f), to >= rightOffset && this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f); else { let mid = this.lineAt(rightOffset, 0, oracle, top2, offset); from < mid.from && this.left.forEachLine(from, mid.from - 1, oracle, top2, offset, f), mid.to >= from && mid.from <= to && f(mid), to > mid.to && this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f) } } replace(from, to, nodes) { let rightStart = this.left.length + this.break; if (to < rightStart) return this.balanced(this.left.replace(from, to, nodes), this.right); if (from > this.left.length) return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); let result = []; from > 0 && this.decomposeLeft(from, result); let left = result.length; for (let node of nodes) result.push(node); if (from > 0 && mergeGaps(result, left - 1), to < this.length) { let right = result.length; this.decomposeRight(to, result), mergeGaps(result, right) } return HeightMap.of(result) } decomposeLeft(to, result) { let left = this.left.length; if (to <= left) return this.left.decomposeLeft(to, result); result.push(this.left), this.break && (left++, to >= left && result.push(null)), to > left && this.right.decomposeLeft(to - left, result) } decomposeRight(from, result) { let left = this.left.length, right = left + this.break; if (from >= right) return this.right.decomposeRight(from - right, result); from < left && this.left.decomposeRight(from, result), this.break && from < right && result.push(null), result.push(this.right) } balanced(left, right) { return left.size > 2 * right.size || right.size > 2 * left.size ? HeightMap.of(this.break ? [left, null, right] : [left, right]) : (this.left = replace(this.left, left), this.right = replace(this.right, right), this.setHeight(left.height + right.height), this.outdated = left.outdated || right.outdated, this.size = left.size + right.size, this.length = left.length + this.break + right.length, this) } updateHeight(oracle, offset = 0, force = !1, measured) { let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; return measured && measured.from <= offset + left.length && measured.more ? rebalance = left = left.updateHeight(oracle, offset, force, measured) : left.updateHeight(oracle, offset, force), measured && measured.from <= rightStart + right.length && measured.more ? rebalance = right = right.updateHeight(oracle, rightStart, force, measured) : right.updateHeight(oracle, rightStart, force), rebalance ? this.balanced(left, right) : (this.height = this.left.height + this.right.height, this.outdated = !1, this) } toString() { return this.left + (this.break ? " " : "-") + this.right } }; function mergeGaps(nodes, around) { let before, after; nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap && nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)) } var relevantWidgetHeight = 5, NodeBuilder = class _NodeBuilder { constructor(pos, oracle) { this.pos = pos; this.oracle = oracle; this.writtenTo = pos } pos; oracle; nodes = []; writtenTo; lineStart = -1; lineEnd = -1; covering = null; get isCovered() { return this.covering && this.nodes[this.nodes.length - 1] == this.covering } span(_from, to) { if (this.lineStart > -1) { let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; last instanceof HeightMapText ? last.length += end - this.pos : (end > this.pos || !this.isCovered) && this.nodes.push(new HeightMapText(end - this.pos, -1, 0)), this.writtenTo = end, to > end && (this.nodes.push(null), this.writtenTo++, this.lineStart = -1) } this.pos = to } point(from, to, deco) { if (from < to || deco.heightRelevant) { let height = deco.widget ? deco.widget.estimatedHeight : 0, breaks = deco.widget ? deco.widget.lineBreaks : 0; height < 0 && (height = this.oracle.lineHeight); let len = to - from; deco.block ? this.addBlock(new HeightMapBlock(len, height, deco)) : (len || breaks || height >= relevantWidgetHeight) && this.addLineDeco(height, breaks, len) } else to > from && this.span(from, to); this.lineEnd > -1 && this.lineEnd < this.pos && (this.lineEnd = this.oracle.doc.lineAt(this.pos).to) } enterLine() { if (this.lineStart > -1) return; let { from, to } = this.oracle.doc.lineAt(this.pos); this.lineStart = from, this.lineEnd = to, this.writtenTo < from && ((this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) && this.nodes.push(this.blankContent(this.writtenTo, from - 1)), this.nodes.push(null)), this.pos > from && this.nodes.push(new HeightMapText(this.pos - from, -1, 0)), this.writtenTo = this.pos } blankContent(from, to) { let gap = new HeightMapGap(to - from); return this.oracle.doc.lineAt(from).to == to && (gap.flags |= 4), gap } ensureLine() { this.enterLine(); let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; if (last instanceof HeightMapText) return last; let line = new HeightMapText(0, -1, 0); return this.nodes.push(line), line } addBlock(block) { this.enterLine(); let deco = block.deco; deco && deco.startSide > 0 && !this.isCovered && this.ensureLine(), this.nodes.push(block), this.writtenTo = this.pos = this.pos + block.length, deco && deco.endSide > 0 && (this.covering = block) } addLineDeco(height, breaks, length) { let line = this.ensureLine(); line.length += length, line.collapsed += length, line.widgetHeight = Math.max(line.widgetHeight, height), line.breaks += breaks, this.writtenTo = this.pos = this.pos + length } finish(from) { let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered ? this.nodes.push(new HeightMapText(0, -1, 0)) : (this.writtenTo < this.pos || last == null) && this.nodes.push(this.blankContent(this.writtenTo, this.pos)); let pos = from; for (let node of this.nodes) node instanceof HeightMapText && node.updateHeight(this.oracle, pos), pos += node ? node.length : 1; return this.nodes } static build(oracle, decorations2, from, to) { let builder = new _NodeBuilder(from, oracle); return RangeSet.spans(decorations2, from, to, builder, 0), builder.finish(from) } }; function heightRelevantDecoChanges(a, b, diff) { let comp = new DecorationComparator2; return RangeSet.compare(a, b, diff, comp, 0), comp.changes } var DecorationComparator2 = class { changes = []; compareRange() { } comparePoint(from, to, a, b) { (from < to || a && a.heightRelevant || b && b.heightRelevant) && addRange(from, to, this.changes, 5) } }; function visiblePixelRange(dom, paddingTop) { let rect = dom.getBoundingClientRect(), doc2 = dom.ownerDocument, win = doc2.defaultView || window, left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right), top2 = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom); for (let parent = dom.parentNode; parent && parent != doc2.body;)if (parent.nodeType == 1) { let elt = parent, style = window.getComputedStyle(elt); if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") { let parentRect = elt.getBoundingClientRect(); left = Math.max(left, parentRect.left), right = Math.min(right, parentRect.right), top2 = Math.max(top2, parentRect.top), bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom) } parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode } else if (parent.nodeType == 11) parent = parent.host; else break; return { left: left - rect.left, right: Math.max(left, right) - rect.left, top: top2 - (rect.top + paddingTop), bottom: Math.max(top2, bottom) - (rect.top + paddingTop) } } function inWindow(elt) { let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window; return rect.left < win.innerWidth && rect.right > 0 && rect.top < win.innerHeight && rect.bottom > 0 } function fullPixelRange(dom, paddingTop) { let rect = dom.getBoundingClientRect(); return { left: 0, right: rect.right - rect.left, top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) } } var LineGap = class { constructor(from, to, size, displaySize) { this.from = from; this.to = to; this.size = size; this.displaySize = displaySize } from; to; size; displaySize; static same(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++) { let gA = a[i2], gB = b[i2]; if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) return !1 } return !0 } draw(viewState, wrapping) { return Decoration.replace({ widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping) }).range(this.from, this.to) } }, LineGapWidget = class extends WidgetType { constructor(size, vertical) { super(); this.size = size; this.vertical = vertical } size; vertical; eq(other) { return other.size == this.size && other.vertical == this.vertical } toDOM() { let elt = document.createElement("div"); return this.vertical ? elt.style.height = this.size + "px" : (elt.style.width = this.size + "px", elt.style.height = "2px", elt.style.display = "inline-block"), elt } get estimatedHeight() { return this.vertical ? this.size : -1 } }; var ViewState = class { constructor(view, state) { this.view = view; this.state = state; let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping"); this.heightOracle = new HeightOracle(guessWrapping), this.stateDeco = staticDeco(state), this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); for (let i2 = 0; i2 < 2 && (this.viewport = this.getViewport(0, null), !!this.updateForViewport()); i2++); this.updateViewportLines(), this.lineGaps = this.ensureLineGaps([]), this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, !1))), this.scrollParent = view.scrollDOM, this.computeVisibleRanges() } view; state; pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; inView = !0; paddingTop = 0; paddingBottom = 0; contentDOMWidth = 0; contentDOMHeight = 0; editorHeight = 0; editorWidth = 0; scaleX = 1; scaleY = 1; scrollParent; scrollOffset = 0; scrolledToBottom = !1; scrollAnchorPos = 0; scrollAnchorHeight = -1; heightOracle; heightMap; scaler = IdScaler; scrollTarget = null; printing = !1; mustMeasureContent = !0; stateDeco; defaultTextDirection = 0; visibleRanges = []; lineGaps; lineGapDeco; mustEnforceCursorAssoc = !1; updateForViewport() { let viewports = [this.viewport], { main } = this.state.selection; for (let i2 = 0; i2 <= 1; i2++) { let pos = i2 ? main.head : main.anchor; if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { let { from, to } = this.lineBlockAt(pos); viewports.push(new Viewport(from, to)) } } return this.viewports = viewports.sort((a, b) => a.from - b.from), this.updateScaler() } updateScaler() { let scaler = this.scaler; return this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle, this.heightMap, this.viewports), scaler.eq(this.scaler) ? 0 : 2 } updateViewportLines() { this.viewportLines = [], this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => { this.viewportLines.push(scaleBlock(block, this.scaler)) }) } update(update, scrollTarget = null) { this.state = update.state; let prevDeco = this.stateDeco; this.stateDeco = staticDeco(this.state); let contentChanges = update.changedRanges, heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))), prevHeight = this.heightMap.height, scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollOffset); clearHeightChangeFlag(), this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges), (this.heightMap.height != prevHeight || heightChangeFlag) && (update.flags |= 2), scrollAnchor ? (this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1), this.scrollAnchorHeight = scrollAnchor.top) : (this.scrollAnchorPos = -1, this.scrollAnchorHeight = prevHeight); let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport)) && (viewport = this.getViewport(0, scrollTarget)); let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to; this.viewport = viewport, update.flags |= this.updateForViewport(), (viewportChange || !update.changes.empty || update.flags & 2) && this.updateViewportLines(), (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) && this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))), update.flags |= this.computeVisibleRanges(update.changes), scrollTarget && (this.scrollTarget = scrollTarget), !this.mustEnforceCursorAssoc && (update.selectionSet || update.focusChanged) && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden) && (this.mustEnforceCursorAssoc = !0) } measure() { let { view } = this, dom = view.contentDOM, style = window.getComputedStyle(dom), oracle = this.heightOracle, whiteSpace = style.whiteSpace; this.defaultTextDirection = style.direction == "rtl" ? 1 : 0; let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace) || this.mustMeasureContent === "refresh", domRect = dom.getBoundingClientRect(), measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height; this.contentDOMHeight = domRect.height, this.mustMeasureContent = !1; let result = 0, bias = 0; if (domRect.width && domRect.height) { let { scaleX, scaleY } = getScale(dom, domRect); (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 || scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) && (this.scaleX = scaleX, this.scaleY = scaleY, result |= 16, refresh = measureContent = !0) } let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY, paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY; (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) && (this.paddingTop = paddingTop, this.paddingBottom = paddingBottom, result |= 18), this.editorWidth != view.scrollDOM.clientWidth && (oracle.lineWrapping && (measureContent = !0), this.editorWidth = view.scrollDOM.clientWidth, result |= 16); let scrollParent = scrollableParents(this.view.contentDOM, !1).y; scrollParent != this.scrollParent && (this.scrollParent = scrollParent, this.scrollAnchorHeight = -1, this.scrollOffset = 0); let scrollOffset = this.getScrollOffset(); this.scrollOffset != scrollOffset && (this.scrollAnchorHeight = -1, this.scrollOffset = scrollOffset), this.scrolledToBottom = isScrolledToBottom(this.scrollParent || view.win); let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop), dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; this.pixelViewport = pixelViewport; let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; if (inView != this.inView && (this.inView = inView, inView && (measureContent = !0)), !this.inView && !this.scrollTarget && !inWindow(view.dom)) return 0; let contentWidth = domRect.width; if ((this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) && (this.contentDOMWidth = domRect.width, this.editorHeight = view.scrollDOM.clientHeight, result |= 16), measureContent) { let lineHeights = view.docView.measureVisibleLineHeights(this.viewport); if (oracle.mustRefreshForHeights(lineHeights) && (refresh = !0), refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize(); refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, Math.max(5, contentWidth / charWidth), lineHeights), refresh && (view.docView.minWidth = 0, result |= 16) } dTop > 0 && dBottom > 0 ? bias = Math.max(dTop, dBottom) : dTop < 0 && dBottom < 0 && (bias = Math.min(dTop, dBottom)), clearHeightChangeFlag(); for (let vp of this.viewports) { let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp); this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights)) } heightChangeFlag && (result |= 2) } let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); return viewportChange && (result & 2 && (result |= this.updateScaler()), this.viewport = this.getViewport(bias, this.scrollTarget), result |= this.updateForViewport()), (result & 2 || viewportChange) && this.updateViewportLines(), (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) && this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view)), result |= this.computeVisibleRanges(), this.mustEnforceCursorAssoc && (this.mustEnforceCursorAssoc = !1, view.docView.enforceCursorAssoc()), result } get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top) } get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom) } getViewport(bias, scrollTarget) { let marginTop = .5 - Math.max(-.5, Math.min(.5, bias / 1e3 / 2)), map = this.heightMap, oracle = this.heightOracle, { visibleTop, visibleBottom } = this, viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1e3, 1, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1e3, 1, oracle, 0, 0).to); if (scrollTarget) { let { head } = scrollTarget.range; if (head < viewport.from || head > viewport.to) { let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top), block = map.lineAt(head, 0, oracle, 0, 0), topPos; scrollTarget.y == "center" ? topPos = (block.top + block.bottom) / 2 - viewHeight / 2 : scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from ? topPos = block.top : topPos = block.bottom - viewHeight, viewport = new Viewport(map.lineAt(topPos - 1e3 / 2, 1, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, 1, oracle, 0, 0).to) } } return viewport } mapViewport(viewport, changes) { let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); return new Viewport(this.heightMap.lineAt(from, 0, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, 0, this.heightOracle, 0, 0).to) } viewportIsAppropriate({ from, to }, bias = 0) { if (!this.inView) return !0; let { top: top2 } = this.heightMap.lineAt(from, 0, this.heightOracle, 0, 0), { bottom } = this.heightMap.lineAt(to, 0, this.heightOracle, 0, 0), { visibleTop, visibleBottom } = this; return (from == 0 || top2 <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top2 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3 } mapLineGaps(gaps, changes) { if (!gaps.length || changes.empty) return gaps; let mapped = []; for (let gap of gaps) changes.touchesRange(gap.from, gap.to) || mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize)); return mapped } ensureLineGaps(current, mayMeasure) { let wrapping = this.heightOracle.lineWrapping, margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1; if (this.defaultTextDirection != 0 && !wrapping) return []; let gaps = [], addGap = (from, to, line, structure) => { if (to - from < halfMargin) return; let sel = this.state.selection.main, avoid = [sel.from]; sel.empty || avoid.push(sel.to); for (let pos of avoid) if (pos > from && pos < to) { addGap(from, pos - 10, line, structure), addGap(pos + 10, to, line, structure); return } let gap = find(current, gap2 => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to) < halfMargin && !avoid.some(pos => gap2.from < pos && gap2.to > pos)); if (!gap) { if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) { let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), !1, !0).head; lineStart > from && (to = lineStart) } let size = this.gapSize(line, from, to, structure), displaySize = wrapping || size < 2e6 ? size : 2e6; gap = new LineGap(from, to, size, displaySize) } gaps.push(gap) }, checkLine = line => { if (line.length < doubleMargin || line.type != 0) return; let structure = lineStructure(line.from, line.to, this.stateDeco); if (structure.total < doubleMargin) return; let target = this.scrollTarget ? this.scrollTarget.range.head : null, viewFrom, viewTo; if (wrapping) { let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight, top2, bot; if (target != null) { let targetFrac = findFraction(structure, target), spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height; top2 = targetFrac - spaceFrac, bot = targetFrac + spaceFrac } else top2 = (this.visibleTop - line.top - marginHeight) / line.height, bot = (this.visibleBottom - line.top + marginHeight) / line.height; viewFrom = findPosition(structure, top2), viewTo = findPosition(structure, bot) } else { let totalWidth = structure.total * this.heightOracle.charWidth, marginWidth = margin * this.heightOracle.charWidth, horizOffset = 0; if (totalWidth > 2e6) for (let old of current) old.from >= line.from && old.from < line.to && old.size != old.displaySize && old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left && (horizOffset = old.size - old.displaySize); let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset, left, right; if (target != null) { let targetFrac = findFraction(structure, target), spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth; left = targetFrac - spaceFrac, right = targetFrac + spaceFrac } else left = (pxLeft - marginWidth) / totalWidth, right = (pxRight + marginWidth) / totalWidth; viewFrom = findPosition(structure, left), viewTo = findPosition(structure, right) } viewFrom > line.from && addGap(line.from, viewFrom, line, structure), viewTo < line.to && addGap(viewTo, line.to, line, structure) }; for (let line of this.viewportLines) Array.isArray(line.type) ? line.type.forEach(checkLine) : checkLine(line); return gaps } gapSize(line, from, to, structure) { let fraction = findFraction(structure, to) - findFraction(structure, from); return this.heightOracle.lineWrapping ? line.height * fraction : structure.total * this.heightOracle.charWidth * fraction } updateLineGaps(gaps) { LineGap.same(gaps, this.lineGaps) || (this.lineGaps = gaps, this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)))) } computeVisibleRanges(changes) { let deco = this.stateDeco; this.lineGaps.length && (deco = deco.concat(this.lineGapDeco)); let ranges = []; RangeSet.spans(deco, this.viewport.from, this.viewport.to, { span(from, to) { ranges.push({ from, to }) }, point() { } }, 20); let changed = 0; if (ranges.length != this.visibleRanges.length) changed = 12; else for (let i2 = 0; i2 < ranges.length && !(changed & 8); i2++) { let old = this.visibleRanges[i2], nw = ranges[i2]; (old.from != nw.from || old.to != nw.to) && (changed |= 4, changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to || (changed |= 8)) } return this.visibleRanges = ranges, changed } lineBlockAt(pos) { return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, 0, this.heightOracle, 0, 0), this.scaler) } lineBlockAtHeight(height) { return height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom && this.viewportLines.find(l => l.top <= height && l.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), 1, this.heightOracle, 0, 0), this.scaler) } getScrollOffset() { return (this.scrollParent == this.view.scrollDOM ? this.scrollParent.scrollTop : (this.scrollParent ? this.scrollParent.getBoundingClientRect().top : 0) - this.view.contentDOM.getBoundingClientRect().top) * this.scaleY } scrollAnchorAt(scrollOffset) { let block = this.lineBlockAtHeight(scrollOffset + 8); return block.from >= this.viewport.from || this.viewportLines[0].top - scrollOffset > 200 ? block : this.viewportLines[0] } elementAtHeight(height) { return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler) } get docHeight() { return this.scaler.toDOM(this.heightMap.height) } get contentHeight() { return this.docHeight + this.paddingTop + this.paddingBottom } }, Viewport = class { constructor(from, to) { this.from = from; this.to = to } from; to }; function lineStructure(from, to, stateDeco) { let ranges = [], pos = from, total = 0; return RangeSet.spans(stateDeco, from, to, { span() { }, point(from2, to2) { from2 > pos && (ranges.push({ from: pos, to: from2 }), total += from2 - pos), pos = to2 } }, 20), pos < to && (ranges.push({ from: pos, to }), total += to - pos), { total, ranges } } function findPosition({ total, ranges }, ratio) { if (ratio <= 0) return ranges[0].from; if (ratio >= 1) return ranges[ranges.length - 1].to; let dist2 = Math.floor(total * ratio); for (let i2 = 0; ; i2++) { let { from, to } = ranges[i2], size = to - from; if (dist2 <= size) return from + dist2; dist2 -= size } } function findFraction(structure, pos) { let counted = 0; for (let { from, to } of structure.ranges) { if (pos <= to) { counted += pos - from; break } counted += to - from } return counted / structure.total } function find(array, f) { for (let val of array) if (f(val)) return val } var IdScaler = { toDOM(n) { return n }, fromDOM(n) { return n }, scale: 1, eq(other) { return other == this } }; function staticDeco(state) { let deco = state.facet(decorations).filter(d => typeof d != "function"), outer = state.facet(outerDecorations).filter(d => typeof d != "function"); return outer.length && deco.push(RangeSet.join(outer)), deco } var BigScaler = class _BigScaler { scale; viewports; constructor(oracle, heightMap, viewports) { let vpHeight = 0, base2 = 0, domBase = 0; this.viewports = viewports.map(({ from, to }) => { let top2 = heightMap.lineAt(from, 0, oracle, 0, 0).top, bottom = heightMap.lineAt(to, 0, oracle, 0, 0).bottom; return vpHeight += bottom - top2, { from, to, top: top2, bottom, domTop: 0, domBottom: 0 } }), this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight); for (let obj of this.viewports) obj.domTop = domBase + (obj.top - base2) * this.scale, domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top), base2 = obj.bottom } toDOM(n) { for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) { let vp = i2 < this.viewports.length ? this.viewports[i2] : null; if (!vp || n < vp.top) return domBase + (n - base2) * this.scale; if (n <= vp.bottom) return vp.domTop + (n - vp.top); base2 = vp.bottom, domBase = vp.domBottom } } fromDOM(n) { for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) { let vp = i2 < this.viewports.length ? this.viewports[i2] : null; if (!vp || n < vp.domTop) return base2 + (n - domBase) / this.scale; if (n <= vp.domBottom) return vp.top + (n - vp.domTop); base2 = vp.bottom, domBase = vp.domBottom } } eq(other) { return other instanceof _BigScaler ? this.scale == other.scale && this.viewports.length == other.viewports.length && this.viewports.every((vp, i2) => vp.from == other.viewports[i2].from && vp.to == other.viewports[i2].to) : !1 } }; function scaleBlock(block, scaler) { if (scaler.scale == 1) return block; let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content) } var theme = Facet.define({ combine: strs => strs.join(" ") }), darkTheme = Facet.define({ combine: values => values.indexOf(!0) > -1 }), baseThemeID = StyleModule.newName(), baseLightID = StyleModule.newName(), baseDarkID = StyleModule.newName(), lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; function buildTheme(main, spec, scopes) { return new StyleModule(spec, { finish(sel) { return /&/.test(sel) ? sel.replace(/&\w*/, m => { if (m == "&") return main; if (!scopes || !scopes[m]) throw new RangeError(`Unsupported selector: ${m}`); return scopes[m] }) : main + " " + sel } }) } var baseTheme = buildTheme("." + baseThemeID, { "&": { position: "relative !important", boxSizing: "border-box", "&.cm-focused": { outline: "1px dotted #212121" }, display: "flex !important", flexDirection: "column" }, ".cm-scroller": { display: "flex !important", alignItems: "flex-start !important", fontFamily: "monospace", lineHeight: 1.4, height: "100%", overflowX: "auto", position: "relative", zIndex: 0, overflowAnchor: "none" }, ".cm-content": { margin: 0, flexGrow: 2, flexShrink: 0, display: "block", whiteSpace: "pre", wordWrap: "normal", boxSizing: "border-box", minHeight: "100%", padding: "4px 0", outline: "none", "&[contenteditable=true]": { WebkitUserModify: "read-write-plaintext-only" } }, ".cm-lineWrapping": { whiteSpace_fallback: "pre-wrap", whiteSpace: "break-spaces", wordBreak: "break-word", overflowWrap: "anywhere", flexShrink: 1 }, "&light .cm-content": { caretColor: "black" }, "&dark .cm-content": { caretColor: "white" }, ".cm-line": { display: "block", padding: "0 2px 0 6px" }, ".cm-layer": { position: "absolute", left: 0, top: 0, contain: "size style", "& > *": { position: "absolute" } }, "&light .cm-selectionBackground": { background: "#d9d9d9" }, "&dark .cm-selectionBackground": { background: "#222" }, "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": { background: "#d7d4f0" }, "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": { background: "#233" }, ".cm-cursorLayer": { pointerEvents: "none" }, "&.cm-focused > .cm-scroller > .cm-cursorLayer": { animation: "steps(1) cm-blink 1.2s infinite" }, "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} }, ".cm-cursor, .cm-dropCursor": { borderLeft: "1.2px solid black", marginLeft: "-0.6px", pointerEvents: "none" }, ".cm-cursor": { display: "none" }, "&dark .cm-cursor": { borderLeftColor: "#ddd" }, ".cm-selectionHandle": { backgroundColor: "currentColor", width: "1.5px" }, ".cm-selectionHandle-start::before, .cm-selectionHandle-end::before": { content: '""', backgroundColor: "inherit", borderRadius: "50%", width: "8px", height: "8px", position: "absolute", left: "-3.25px" }, ".cm-selectionHandle-start::before": { top: "-8px" }, ".cm-selectionHandle-end::before": { bottom: "-8px" }, ".cm-dropCursor": { position: "absolute" }, "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": { display: "block" }, ".cm-iso": { unicodeBidi: "isolate" }, ".cm-announced": { position: "fixed", top: "-10000px" }, "@media print": { ".cm-announced": { display: "none" } }, "&light .cm-activeLine": { backgroundColor: "#cceeff44" }, "&dark .cm-activeLine": { backgroundColor: "#99eeff33" }, "&light .cm-specialChar": { color: "red" }, "&dark .cm-specialChar": { color: "#f78" }, ".cm-gutters": { flexShrink: 0, display: "flex", height: "100%", boxSizing: "border-box", zIndex: 200 }, ".cm-gutters-before": { insetInlineStart: 0 }, ".cm-gutters-after": { insetInlineEnd: 0 }, "&light .cm-gutters": { backgroundColor: "#f5f5f5", color: "#6c6c6c", border: "0px solid #ddd", "&.cm-gutters-before": { borderRightWidth: "1px" }, "&.cm-gutters-after": { borderLeftWidth: "1px" } }, "&dark .cm-gutters": { backgroundColor: "#333338", color: "#ccc" }, ".cm-gutter": { display: "flex !important", flexDirection: "column", flexShrink: 0, boxSizing: "border-box", minHeight: "100%", overflow: "hidden" }, ".cm-gutterElement": { boxSizing: "border-box" }, ".cm-lineNumbers .cm-gutterElement": { padding: "0 3px 0 5px", minWidth: "20px", textAlign: "right", whiteSpace: "nowrap" }, "&light .cm-activeLineGutter": { backgroundColor: "#e2f2ff" }, "&dark .cm-activeLineGutter": { backgroundColor: "#222227" }, ".cm-panels": { boxSizing: "border-box", position: "sticky", left: 0, right: 0, zIndex: 300 }, "&light .cm-panels": { backgroundColor: "#f5f5f5", color: "black" }, "&light .cm-panels-top": { borderBottom: "1px solid #ddd" }, "&light .cm-panels-bottom": { borderTop: "1px solid #ddd" }, "&dark .cm-panels": { backgroundColor: "#333338", color: "white" }, ".cm-dialog": { padding: "2px 19px 4px 6px", position: "relative", "& label": { fontSize: "80%" } }, ".cm-dialog-close": { position: "absolute", top: "3px", right: "4px", backgroundColor: "inherit", border: "none", font: "inherit", fontSize: "14px", padding: "0" }, ".cm-tab": { display: "inline-block", overflow: "hidden", verticalAlign: "bottom" }, ".cm-widgetBuffer": { verticalAlign: "text-top", height: "1em", width: 0, display: "inline" }, ".cm-placeholder": { color: "#888", display: "inline-block", verticalAlign: "top", userSelect: "none" }, ".cm-highlightSpace": { backgroundImage: "radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)", backgroundPosition: "center" }, ".cm-highlightTab": { backgroundImage: `url('data:image/svg+xml,')`, backgroundSize: "auto 100%", backgroundPosition: "right 90%", backgroundRepeat: "no-repeat" }, ".cm-trailingSpace": { backgroundColor: "#ff332255" }, ".cm-button": { verticalAlign: "middle", color: "inherit", fontSize: "70%", padding: ".2em 1em", borderRadius: "1px" }, "&light .cm-button": { backgroundImage: "linear-gradient(#eff1f5, #d9d9df)", border: "1px solid #888", "&:active": { backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)" } }, "&dark .cm-button": { backgroundImage: "linear-gradient(#393939, #111)", border: "1px solid #888", "&:active": { backgroundImage: "linear-gradient(#111, #333)" } }, ".cm-textfield": { verticalAlign: "middle", color: "inherit", fontSize: "70%", border: "1px solid silver", padding: ".2em .5em" }, "&light .cm-textfield": { backgroundColor: "white" }, "&dark .cm-textfield": { border: "1px solid #555", backgroundColor: "inherit" } }, lightDarkIDs); var observeOptions = { childList: !0, characterData: !0, subtree: !0, attributes: !0, characterDataOldValue: !0 }, useCharData = browser_default.ie && browser_default.ie_version <= 11, DOMObserver = class { constructor(view) { this.view = view; this.dom = view.contentDOM, this.observer = new MutationObserver(mutations => { for (let mut of mutations) this.queue.push(mut); (browser_default.ie && browser_default.ie_version <= 11 || browser_default.ios && view.composing) && mutations.some(m => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length) ? this.flushSoon() : this.flush() }), window.EditContext && browser_default.android && view.constructor.EDIT_CONTEXT !== !1 && !(browser_default.chrome && browser_default.chrome_version < 126) && (this.editContext = new EditContextManager(view), view.state.facet(editable) && (view.contentDOM.editContext = this.editContext.editContext)), useCharData && (this.onCharData = event => { this.queue.push({ target: event.target, type: "characterData", oldValue: event.prevValue }), this.flushSoon() }), this.onSelectionChange = this.onSelectionChange.bind(this), this.onResize = this.onResize.bind(this), this.onPrint = this.onPrint.bind(this), this.onScroll = this.onScroll.bind(this), window.matchMedia && (this.printQuery = window.matchMedia("print")), typeof ResizeObserver == "function" && (this.resizeScroll = new ResizeObserver(() => { this.view.docView?.lastUpdate < Date.now() - 75 && this.onResize() }), this.resizeScroll.observe(view.scrollDOM)), this.addWindowListeners(this.win = view.win), this.start(), typeof IntersectionObserver == "function" && (this.intersection = new IntersectionObserver(entries => { this.parentCheck < 0 && (this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3)), entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting && (this.intersecting = !this.intersecting, this.intersecting != this.view.inView && this.onScrollChanged(document.createEvent("Event"))) }, { threshold: [0, .001] }), this.intersection.observe(this.dom), this.gapIntersection = new IntersectionObserver(entries => { entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 && this.onScrollChanged(document.createEvent("Event")) }, {})), this.listenForScroll(), this.readSelectionRange() } view; dom; win; observer; active = !1; editContext = null; selectionRange = new DOMSelectionState; selectionChanged = !1; delayedFlush = -1; resizeTimeout = -1; queue = []; delayedAndroidKey = null; flushingAndroidKey = -1; lastChange = 0; onCharData; scrollTargets = []; intersection = null; resizeScroll = null; intersecting = !1; gapIntersection = null; gaps = []; printQuery = null; parentCheck = -1; onScrollChanged(e) { this.view.inputState.runHandlers("scroll", e), this.intersecting && this.view.measure() } onScroll(e) { this.intersecting && this.flush(!1), this.editContext && this.view.requestMeasure(this.editContext.measureReq), this.onScrollChanged(e) } onResize() { this.resizeTimeout < 0 && (this.resizeTimeout = setTimeout(() => { this.resizeTimeout = -1, this.view.requestMeasure() }, 50)) } onPrint(event) { (event.type == "change" || !event.type) && !event.matches || (this.view.viewState.printing = !0, this.view.measure(), setTimeout(() => { this.view.viewState.printing = !1, this.view.requestMeasure() }, 500)) } updateGaps(gaps) { if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i2) => g != gaps[i2]))) { this.gapIntersection.disconnect(); for (let gap of gaps) this.gapIntersection.observe(gap); this.gaps = gaps } } onSelectionChange(event) { let wasChanged = this.selectionChanged; if (!this.readSelectionRange() || this.delayedAndroidKey) return; let { view } = this, sel = this.selectionRange; if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel)) return; let context = sel.anchorNode && view.docView.tile.nearest(sel.anchorNode); if (context && context.isWidget() && context.widget.ignoreEvent(event)) { wasChanged || (this.selectionChanged = !1); return } (browser_default.ie && browser_default.ie_version <= 11 || browser_default.android && browser_default.chrome) && !view.state.selection.main.empty && sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) ? this.flushSoon() : this.flush(!1) } readSelectionRange() { let { view } = this, selection = getSelection(view.root); if (!selection) return !1; let range = browser_default.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection) || selection; if (!range || this.selectionRange.eq(range)) return !1; let local = hasSelection(this.dom, range); return local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range) ? (this.view.inputState.lastFocusTime = 0, view.docView.updateSelection(), !1) : (this.selectionRange.setRange(range), local && (this.selectionChanged = !0), !0) } setSelectionRange(anchor, head) { this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset), this.selectionChanged = !1 } clearSelectionRange() { this.selectionRange.set(null, 0, null, 0) } listenForScroll() { this.parentCheck = -1; let i2 = 0, changed = null; for (let dom = this.dom; dom;)if (dom.nodeType == 1) !changed && i2 < this.scrollTargets.length && this.scrollTargets[i2] == dom ? i2++ : changed || (changed = this.scrollTargets.slice(0, i2)), changed && changed.push(dom), dom = dom.assignedSlot || dom.parentNode; else if (dom.nodeType == 11) dom = dom.host; else break; if (i2 < this.scrollTargets.length && !changed && (changed = this.scrollTargets.slice(0, i2)), changed) { for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll); for (let dom of this.scrollTargets = changed) dom.addEventListener("scroll", this.onScroll) } } ignore(f) { if (!this.active) return f(); try { return this.stop(), f() } finally { this.start(), this.clear() } } start() { this.active || (this.observer.observe(this.dom, observeOptions), useCharData && this.dom.addEventListener("DOMCharacterDataModified", this.onCharData), this.active = !0) } stop() { this.active && (this.active = !1, this.observer.disconnect(), useCharData && this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData)) } clear() { this.processRecords(), this.queue.length = 0, this.selectionChanged = !1 } delayAndroidKey(key, keyCode) { if (!this.delayedAndroidKey) { let flush = () => { let key2 = this.delayedAndroidKey; key2 && (this.clearDelayedAndroidKey(), this.view.inputState.lastKeyCode = key2.keyCode, this.view.inputState.lastKeyTime = Date.now(), !this.flush() && key2.force && dispatchKey(this.dom, key2.key, key2.keyCode)) }; this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush) } (!this.delayedAndroidKey || key == "Enter") && (this.delayedAndroidKey = { key, keyCode, force: this.lastChange < Date.now() - 50 || !!this.delayedAndroidKey?.force }) } clearDelayedAndroidKey() { this.win.cancelAnimationFrame(this.flushingAndroidKey), this.delayedAndroidKey = null, this.flushingAndroidKey = -1 } flushSoon() { this.delayedFlush < 0 && (this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1, this.flush() })) } forceFlush() { this.delayedFlush >= 0 && (this.view.win.cancelAnimationFrame(this.delayedFlush), this.delayedFlush = -1), this.flush() } pendingRecords() { for (let mut of this.observer.takeRecords()) this.queue.push(mut); return this.queue } processRecords() { let records = this.pendingRecords(); records.length && (this.queue = []); let from = -1, to = -1, typeOver = !1; for (let record of records) { let range = this.readMutation(record); range && (range.typeOver && (typeOver = !0), from == -1 ? { from, to } = range : (from = Math.min(range.from, from), to = Math.max(range.to, to))) } return { from, to, typeOver } } readChange() { let { from, to, typeOver } = this.processRecords(), newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); if (from < 0 && !newSel) return null; from > -1 && (this.lastChange = Date.now()), this.view.inputState.lastFocusTime = 0, this.selectionChanged = !1; let change = new DOMChange(this.view, from, to, typeOver); return this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null }, change } flush(readSelection = !0) { if (this.delayedFlush >= 0 || this.delayedAndroidKey) return !1; readSelection && this.readSelectionRange(); let domChange = this.readChange(); if (!domChange) return this.view.requestMeasure(), !1; let startState = this.view.state, handled = applyDOMChange(this.view, domChange); return this.view.state == startState && (domChange.domChanged || domChange.newSel && !sameSelPos(this.view.state.selection, domChange.newSel.main)) && this.view.update([]), handled } readMutation(rec) { let tile = this.view.docView.tile.nearest(rec.target); if (!tile || tile.isWidget()) return null; if (tile.markDirty(rec.type == "attributes"), rec.type == "childList") { let childBefore = findChild(tile, rec.previousSibling || rec.target.previousSibling, -1), childAfter = findChild(tile, rec.nextSibling || rec.target.nextSibling, 1); return { from: childBefore ? tile.posAfter(childBefore) : tile.posAtStart, to: childAfter ? tile.posBefore(childAfter) : tile.posAtEnd, typeOver: !1 } } else return rec.type == "characterData" ? { from: tile.posAtStart, to: tile.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue } : null } setWindow(win) { win != this.win && (this.removeWindowListeners(this.win), this.win = win, this.addWindowListeners(this.win)) } addWindowListeners(win) { win.addEventListener("resize", this.onResize), this.printQuery ? this.printQuery.addEventListener ? this.printQuery.addEventListener("change", this.onPrint) : this.printQuery.addListener(this.onPrint) : win.addEventListener("beforeprint", this.onPrint), win.addEventListener("scroll", this.onScroll), win.document.addEventListener("selectionchange", this.onSelectionChange) } removeWindowListeners(win) { win.removeEventListener("scroll", this.onScroll), win.removeEventListener("resize", this.onResize), this.printQuery ? this.printQuery.removeEventListener ? this.printQuery.removeEventListener("change", this.onPrint) : this.printQuery.removeListener(this.onPrint) : win.removeEventListener("beforeprint", this.onPrint), win.document.removeEventListener("selectionchange", this.onSelectionChange) } update(update) { this.editContext && (this.editContext.update(update), update.startState.facet(editable) != update.state.facet(editable) && (update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null)) } destroy() { this.stop(), this.intersection?.disconnect(), this.gapIntersection?.disconnect(), this.resizeScroll?.disconnect(); for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll); this.removeWindowListeners(this.win), clearTimeout(this.parentCheck), clearTimeout(this.resizeTimeout), this.win.cancelAnimationFrame(this.delayedFlush), this.win.cancelAnimationFrame(this.flushingAndroidKey), this.editContext && (this.view.contentDOM.editContext = null, this.editContext.destroy()) } }; function findChild(tile, dom, dir) { for (; dom;) { let curTile = Tile.get(dom); if (curTile && curTile.parent == tile) return curTile; let parent = dom.parentNode; dom = parent != tile.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling } return null } function buildSelectionRangeFromRange(view, range) { let anchorNode = range.startContainer, anchorOffset = range.startOffset, focusNode = range.endContainer, focusOffset = range.endOffset, curAnchor = view.docView.domAtPos(view.state.selection.main.anchor, 1); return isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset) && ([anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]), { anchorNode, anchorOffset, focusNode, focusOffset } } function safariSelectionRangeHack(view, selection) { if (selection.getComposedRanges) { let range = selection.getComposedRanges(view.root)[0]; if (range) return buildSelectionRangeFromRange(view, range) } let found = null; function read(event) { event.preventDefault(), event.stopImmediatePropagation(), found = event.getTargetRanges()[0] } return view.contentDOM.addEventListener("beforeinput", read, !0), view.dom.ownerDocument.execCommand("indent"), view.contentDOM.removeEventListener("beforeinput", read, !0), found ? buildSelectionRangeFromRange(view, found) : null } var EditContextManager = class { + editContext; measureReq; from = 0; to = 0; pendingContextChange = null; handlers = Object.create(null); composing = null; constructor(view) { + this.resetRange(view.state); let context = this.editContext = new window.EditContext({ text: view.state.doc.sliceString(this.from, this.to), selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))), selectionEnd: this.toContextPos(view.state.selection.main.head) }); this.handlers.textupdate = e => { + let main = view.state.selection.main, { anchor, head } = main, from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd); view.inputState.composing >= 0 && !this.composing && (this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: !1 }); let deletes = to - from > e.text.length; from == this.from && anchor < this.from ? from = anchor : to == this.to && anchor > this.to && (to = anchor); let diff = findDiff(view.state.sliceDoc(from, to), e.text, (deletes ? main.from : main.to) - from, deletes ? "end" : null); if (!diff) { let newSel = EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd)); sameSelPos(newSel, main) || view.dispatch({ selection: newSel, userEvent: "select" }); return } let change = { + from: diff.from + from, to: diff.toA + from, insert: Text.of(e.text.slice(diff.from, diff.toB).split(` +`)) + }; if ((browser_default.mac || browser_default.android) && change.from == head - 1 && /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off" && (change = { from, to, insert: Text.of([e.text.replace(".", " ")]) }), this.pendingContextChange = change, !view.state.readOnly) { let newLen = this.to - this.from + (change.to - change.from + change.insert.length); applyDOMChangeInner(view, change, EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen))) } this.pendingContextChange && (this.revertPending(view.state), this.setSelection(view.state)), change.from < change.to && !change.insert.length && view.inputState.composing >= 0 && !/[\\p{Alphabetic}\\p{Number}_]/.test(context.text.slice(Math.max(0, e.updateRangeStart - 1), Math.min(context.text.length, e.updateRangeStart + 1))) && this.handlers.compositionend(e) + }, this.handlers.characterboundsupdate = e => { let rects = [], prev = null; for (let i2 = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i2 < end; i2++) { let rect = view.coordsForChar(i2); prev = rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top) || prev || new DOMRect, rects.push(prev) } context.updateCharacterBounds(e.rangeStart, rects) }, this.handlers.textformatupdate = e => { let deco = []; for (let format of e.getTextFormats()) { let lineStyle = format.underlineStyle, thickness = format.underlineThickness; if (!/none/i.test(lineStyle) && !/none/i.test(thickness)) { let from = this.toEditorPos(format.rangeStart), to = this.toEditorPos(format.rangeEnd); if (from < to) { let style = `text-decoration: underline ${/^[a-z]/.test(lineStyle) ? lineStyle + " " : lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${/thin/i.test(thickness) ? 1 : 2}px`; deco.push(Decoration.mark({ attributes: { style } }).range(from, to)) } } } view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) }) }, this.handlers.compositionstart = () => { view.inputState.composing < 0 && (view.inputState.composing = 0, view.inputState.compositionFirstChange = !0) }, this.handlers.compositionend = () => { if (view.inputState.composing = -1, view.inputState.compositionFirstChange = null, this.composing) { let { drifted } = this.composing; this.composing = null, drifted && this.reset(view.state) } }; for (let event in this.handlers) context.addEventListener(event, this.handlers[event]); this.measureReq = { read: view2 => { this.editContext.updateControlBounds(view2.contentDOM.getBoundingClientRect()); let sel = getSelection(view2.root); sel && sel.rangeCount && this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect()) } } + } applyEdits(update) { let off = 0, abort = !1, pending = this.pendingContextChange; return update.changes.iterChanges((fromA, toA, _fromB, _toB, insert2) => { if (abort) return; let dLen = insert2.length - (toA - fromA); if (pending && toA >= pending.to) if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert2)) { pending = this.pendingContextChange = null, off += dLen, this.to += dLen; return } else pending = null, this.revertPending(update.state); if (fromA += off, toA += off, toA <= this.from) this.from += dLen, this.to += dLen; else if (fromA < this.to) { if (fromA < this.from || toA > this.to || this.to - this.from + insert2.length > 3e4) { abort = !0; return } this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert2.toString()), this.to += dLen } off += dLen }), pending && !abort && this.revertPending(update.state), !abort } update(update) { let reverted = this.pendingContextChange, startSel = update.startState.selection.main; this.composing && (this.composing.drifted || !update.changes.touchesRange(startSel.from, startSel.to) && update.transactions.some(tr => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to))) ? (this.composing.drifted = !0, this.composing.editorBase = update.changes.mapPos(this.composing.editorBase)) : !this.applyEdits(update) || !this.rangeIsValid(update.state) ? (this.pendingContextChange = null, this.reset(update.state)) : (update.docChanged || update.selectionSet || reverted) && this.setSelection(update.state), (update.geometryChanged || update.docChanged || update.selectionSet) && update.view.requestMeasure(this.measureReq) } resetRange(state) { let { head } = state.selection.main; this.from = Math.max(0, head - 1e4), this.to = Math.min(state.doc.length, head + 1e4) } reset(state) { this.resetRange(state), this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to)), this.setSelection(state) } revertPending(state) { let pending = this.pendingContextChange; this.pendingContextChange = null, this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to)) } setSelection(state) { let { main } = state.selection, start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor))), end = this.toContextPos(main.head); (this.editContext.selectionStart != start || this.editContext.selectionEnd != end) && this.editContext.updateSelection(start, end) } rangeIsValid(state) { let { head } = state.selection.main; return !(this.from > 0 && head - this.from < 500 || this.to < state.doc.length && this.to - head < 500 || this.to - this.from > 1e4 * 3) } toEditorPos(contextPos, clipLen = this.to - this.from) { contextPos = Math.min(contextPos, clipLen); let c = this.composing; return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from } toContextPos(editorPos) { let c = this.composing; return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from } destroy() { for (let event in this.handlers) this.editContext.removeEventListener(event, this.handlers[event]) } +}; var EditorView = class _EditorView { get state() { return this.viewState.state } get viewport() { return this.viewState.viewport } get visibleRanges() { return this.viewState.visibleRanges } get inView() { return this.viewState.inView } get composing() { return !!this.inputState && this.inputState.composing > 0 } get compositionStarted() { return !!this.inputState && this.inputState.composing >= 0 } dispatchTransactions; _root; get root() { return this._root } get win() { return this.dom.ownerDocument.defaultView || window } dom; scrollDOM; contentDOM; announceDOM; viewState; docView; plugins = []; pluginMap = new Map; editorAttrs = {}; contentAttrs = {}; bidiCache = []; destroyed = !1; updateState = 2; observer; measureScheduled = -1; measureRequests = []; constructor(config = {}) { this.contentDOM = document.createElement("div"), this.scrollDOM = document.createElement("div"), this.scrollDOM.tabIndex = -1, this.scrollDOM.className = "cm-scroller", this.scrollDOM.appendChild(this.contentDOM), this.announceDOM = document.createElement("div"), this.announceDOM.className = "cm-announced", this.announceDOM.setAttribute("aria-live", "polite"), this.dom = document.createElement("div"), this.dom.appendChild(this.announceDOM), this.dom.appendChild(this.scrollDOM), config.parent && config.parent.appendChild(this.dom); let { dispatch } = config; this.dispatchTransactions = config.dispatchTransactions || dispatch && (trs => trs.forEach(tr => dispatch(tr, this))) || (trs => this.update(trs)), this.dispatch = this.dispatch.bind(this), this._root = config.root || getRoot(config.parent) || document, this.viewState = new ViewState(this, config.state || EditorState.create(config)), config.scrollTo && config.scrollTo.is(scrollIntoView) && (this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state)), this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); for (let plugin2 of this.plugins) plugin2.update(this); this.observer = new DOMObserver(this), this.inputState = new InputState(this), this.inputState.ensureHandlers(this.plugins), this.docView = new DocView(this), this.mountStyles(), this.updateAttrs(), this.updateState = 0, this.requestMeasure(), document.fonts?.ready && document.fonts.ready.then(() => { this.viewState.mustMeasureContent = "refresh", this.requestMeasure() }) } dispatch(...input) { let trs = input.length == 1 && input[0] instanceof Transaction ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)]; this.dispatchTransactions(trs, this) } update(transactions) { if (this.updateState != 0) throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); let redrawn = !1, attrsChanged = !1, update, state = this.state; for (let tr of transactions) { if (tr.startState != state) throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); state = tr.state } if (this.destroyed) { this.viewState.state = state; return } let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null; transactions.some(tr => tr.annotation(isFocusChange)) ? (this.inputState.notifiedFocused = focus, focusFlag = 1) : focus != this.inputState.notifiedFocused && (this.inputState.notifiedFocused = focus, dispatchFocus = focusChangeTransaction(state, focus), dispatchFocus || (focusFlag = 1)); let pendingKey = this.observer.delayedAndroidKey, domChange = null; if (pendingKey ? (this.observer.clearDelayedAndroidKey(), domChange = this.observer.readChange(), (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection)) && (domChange = null)) : this.observer.clear(), state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) return this.setState(state); update = ViewUpdate.create(this, state, transactions), update.flags |= focusFlag; let scrollTarget = this.viewState.scrollTarget; try { this.updateState = 2; for (let tr of transactions) { if (scrollTarget && (scrollTarget = scrollTarget.map(tr.changes)), tr.scrollIntoView) { let { main } = tr.state.selection, { x, y } = this.state.facet(_EditorView.cursorScrollMargin); scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1), "nearest", "nearest", y, x) } for (let e of tr.effects) e.is(scrollIntoView) && (scrollTarget = e.value.clip(this.state)) } this.viewState.update(update, scrollTarget), this.bidiCache = CachedOrder.update(this.bidiCache, update.changes), update.empty || (this.updatePlugins(update), this.inputState.update(update)), redrawn = this.docView.update(update), this.state.facet(styleModule) != this.styleModules && this.mountStyles(), attrsChanged = this.updateAttrs(), this.showAnnouncements(transactions), this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))) } finally { this.updateState = 0 } if (update.startState.facet(theme) != update.state.facet(theme) && (this.viewState.mustMeasureContent = !0), (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) && this.requestMeasure(), redrawn && this.docViewUpdate(), !update.empty) for (let listener of this.state.facet(updateListener)) try { listener(update) } catch (e) { logException(this.state, e, "update listener") } (dispatchFocus || domChange) && Promise.resolve().then(() => { dispatchFocus && this.state == dispatchFocus.startState && this.dispatch(dispatchFocus), domChange && !applyDOMChange(this, domChange) && pendingKey.force && dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode) }) } setState(newState) { if (this.updateState != 0) throw new Error("Calls to EditorView.setState are not allowed while an update is in progress"); if (this.destroyed) { this.viewState.state = newState; return } this.updateState = 2; let hadFocus = this.hasFocus; try { for (let plugin2 of this.plugins) plugin2.destroy(this); this.viewState = new ViewState(this, newState), this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)), this.pluginMap.clear(); for (let plugin2 of this.plugins) plugin2.update(this); this.docView.destroy(), this.docView = new DocView(this), this.inputState.ensureHandlers(this.plugins), this.mountStyles(), this.updateAttrs(), this.bidiCache = [] } finally { this.updateState = 0 } hadFocus && this.focus(), this.requestMeasure() } updatePlugins(update) { let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); if (prevSpecs != specs) { let newPlugins = []; for (let spec of specs) { let found = prevSpecs.indexOf(spec); if (found < 0) newPlugins.push(new PluginInstance(spec)); else { let plugin2 = this.plugins[found]; plugin2.mustUpdate = update, newPlugins.push(plugin2) } } for (let plugin2 of this.plugins) plugin2.mustUpdate != update && plugin2.destroy(this); this.plugins = newPlugins, this.pluginMap.clear() } else for (let p of this.plugins) p.mustUpdate = update; for (let i2 = 0; i2 < this.plugins.length; i2++)this.plugins[i2].update(this); prevSpecs != specs && this.inputState.ensureHandlers(this.plugins) } docViewUpdate() { for (let plugin2 of this.plugins) { let val = plugin2.value; if (val && val.docViewUpdate) try { val.docViewUpdate(this) } catch (e) { logException(this.state, e, "doc view update listener") } } } measure(flush = !0) { if (this.destroyed) return; if (this.measureScheduled > -1 && this.win.cancelAnimationFrame(this.measureScheduled), this.observer.delayedAndroidKey) { this.measureScheduled = -1, this.requestMeasure(); return } this.measureScheduled = 0, flush && this.observer.forceFlush(); let updated = null, scroll = this.viewState.scrollParent, scrollOffset = this.viewState.getScrollOffset(), { scrollAnchorPos, scrollAnchorHeight } = this.viewState; Math.abs(scrollOffset - this.viewState.scrollOffset) > 1 && (scrollAnchorHeight = -1), this.viewState.scrollAnchorHeight = -1; try { for (let i2 = 0; ; i2++) { if (scrollAnchorHeight < 0) if (isScrolledToBottom(scroll || this.win)) scrollAnchorPos = -1, scrollAnchorHeight = this.viewState.heightMap.height; else { let block = this.viewState.scrollAnchorAt(scrollOffset); scrollAnchorPos = block.from, scrollAnchorHeight = block.top } this.updateState = 1; let changed = this.viewState.measure(); if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) break; if (i2 > 5) { console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize"); break } let measuring = []; changed & 4 || ([this.measureRequests, measuring] = [measuring, this.measureRequests]); let measured = measuring.map(m => { try { return m.read(this) } catch (e) { return logException(this.state, e), BadMeasure } }), update = ViewUpdate.create(this, this.state, []), redrawn = !1; update.flags |= changed, updated ? updated.flags |= changed : updated = update, this.updateState = 2, update.empty || (this.updatePlugins(update), this.inputState.update(update), this.updateAttrs(), redrawn = this.docView.update(update), redrawn && this.docViewUpdate()); for (let i3 = 0; i3 < measuring.length; i3++)if (measured[i3] != BadMeasure) try { let m = measuring[i3]; m.write && m.write(measured[i3], this) } catch (e) { logException(this.state, e) } if (redrawn && this.docView.updateSelection(!0), !update.viewportChanged && this.measureRequests.length == 0) { if (this.viewState.editorHeight) if (this.viewState.scrollTarget) { this.docView.scrollIntoView(this.viewState.scrollTarget), this.viewState.scrollTarget = null, scrollAnchorHeight = -1; continue } else { let diff = ((scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight) / this.scaleY; if ((diff > 1 || diff < -1) && (scroll == this.scrollDOM || this.hasFocus || Math.max(this.inputState.lastWheelEvent, this.inputState.lastTouchTime) > Date.now() - 100)) { scrollOffset = scrollOffset + diff, scroll ? scroll.scrollTop += diff : this.win.scrollBy(0, diff), scrollAnchorHeight = -1; continue } } break } } } finally { this.updateState = 0, this.measureScheduled = -1 } if (updated && !updated.empty) for (let listener of this.state.facet(updateListener)) listener(updated) } get themeClasses() { return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme) } updateAttrs() { let editorAttrs = attrsFromFacet(this, editorAttributes, { class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses }), contentAttrs = { spellcheck: "false", autocorrect: "off", autocapitalize: "off", writingsuggestions: "false", translate: "no", contenteditable: this.state.facet(editable) ? "true" : "false", class: "cm-content", style: `${browser_default.tabSize}: ${this.state.tabSize}`, role: "textbox", "aria-multiline": "true" }; this.state.readOnly && (contentAttrs["aria-readonly"] = "true"), attrsFromFacet(this, contentAttributes, contentAttrs); let changed = this.observer.ignore(() => { let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs), changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs); return changedContent || changedEditor }); return this.editorAttrs = editorAttrs, this.contentAttrs = contentAttrs, changed } showAnnouncements(trs) { let first = !0; for (let tr of trs) for (let effect of tr.effects) if (effect.is(_EditorView.announce)) { first && (this.announceDOM.textContent = ""), first = !1; let div = this.announceDOM.appendChild(document.createElement("div")); div.textContent = effect.value } } mountStyles() { this.styleModules = this.state.facet(styleModule); let nonce = this.state.facet(_EditorView.cspNonce); StyleModule.mount(this.root, this.styleModules.concat(baseTheme).reverse(), nonce ? { nonce } : void 0) } readMeasured() { if (this.updateState == 2) throw new Error("Reading the editor layout isn't allowed during an update"); this.updateState == 0 && this.measureScheduled > -1 && this.measure(!1) } requestMeasure(request) { if (this.measureScheduled < 0 && (this.measureScheduled = this.win.requestAnimationFrame(() => this.measure())), request) { if (this.measureRequests.indexOf(request) > -1) return; if (request.key != null) { for (let i2 = 0; i2 < this.measureRequests.length; i2++)if (this.measureRequests[i2].key === request.key) { this.measureRequests[i2] = request; return } } this.measureRequests.push(request) } } plugin(plugin2) { let known = this.pluginMap.get(plugin2); return (known === void 0 || known && known.plugin != plugin2) && this.pluginMap.set(plugin2, known = this.plugins.find(p => p.plugin == plugin2) || null), known && known.update(this).value } get documentTop() { return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop } get documentPadding() { return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom } } get scaleX() { return this.viewState.scaleX } get scaleY() { return this.viewState.scaleY } elementAtHeight(height) { return this.readMeasured(), this.viewState.elementAtHeight(height) } lineBlockAtHeight(height) { return this.readMeasured(), this.viewState.lineBlockAtHeight(height) } get viewportLineBlocks() { return this.viewState.viewportLines } lineBlockAt(pos) { return this.viewState.lineBlockAt(pos) } get contentHeight() { return this.viewState.contentHeight } moveByChar(start, forward, by) { return skipAtoms(this, start, moveByChar(this, start, forward, by)) } moveByGroup(start, forward) { return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))) } visualLineSide(line, end) { let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from), span = order[end ? order.length - 1 : 0]; return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1) } moveToLineBoundary(start, forward, includeWrap = !0) { return moveToLineBoundary(this, start, forward, includeWrap) } moveVertically(start, forward, distance) { return skipAtoms(this, start, moveVertically(this, start, forward, distance)) } domAtPos(pos, side = 1) { return this.docView.domAtPos(pos, side) } posAtDOM(node, offset = 0) { return this.docView.posFromDOM(node, offset) } posAtCoords(coords, precise = !0) { this.readMeasured(); let found = posAtCoords(this, coords, precise); return found && found.pos } posAndSideAtCoords(coords, precise = !0) { return this.readMeasured(), posAtCoords(this, coords, precise) } coordsAtPos(pos, side = 1) { this.readMeasured(); let rect = this.docView.coordsAt(pos, side); if (!rect || rect.left == rect.right) return rect; let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line), span = order[BidiSpan.find(order, pos - line.from, -1, side)]; return flattenRect(rect, span.dir == 0 == side > 0) } coordsForChar(pos) { return this.readMeasured(), this.docView.coordsForChar(pos) } get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth } get defaultLineHeight() { return this.viewState.heightOracle.lineHeight } get textDirection() { return this.viewState.defaultTextDirection } textDirectionAt(pos) { return !this.state.facet(perLineTextDirection) || pos < this.viewport.from || pos > this.viewport.to ? this.textDirection : (this.readMeasured(), this.docView.textDirectionAt(pos)) } get lineWrapping() { return this.viewState.heightOracle.lineWrapping } bidiSpans(line) { if (line.length > MaxBidiLine) return trivialOrder(line.length); let dir = this.textDirectionAt(line.from), isolates; for (let entry of this.bidiCache) if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line)))) return entry.order; isolates || (isolates = getIsolatedRanges(this, line)); let order = computeOrder(line.text, dir, isolates); return this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, !0, order)), order } get hasFocus() { return (this.dom.ownerDocument.hasFocus() || browser_default.safari && this.inputState?.lastContextMenu > Date.now() - 3e4) && this.root.activeElement == this.contentDOM } focus() { this.observer.ignore(() => { focusPreventScroll(this.contentDOM), this.docView.updateSelection() }) } setRoot(root) { this._root != root && (this._root = root, this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window), this.mountStyles()) } destroy() { this.root.activeElement == this.contentDOM && this.contentDOM.blur(); for (let plugin2 of this.plugins) plugin2.destroy(this); this.plugins = [], this.inputState.destroy(), this.docView.destroy(), this.dom.remove(), this.observer.destroy(), this.measureScheduled > -1 && this.win.cancelAnimationFrame(this.measureScheduled), this.destroyed = !0 } static scrollIntoView(pos, options = {}) { return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y ?? "nearest", options.x ?? "nearest", options.yMargin ?? 5, options.xMargin ?? 5)) } scrollSnapshot() { let { scrollTop, scrollLeft } = this.scrollDOM, ref = this.viewState.scrollAnchorAt(scrollTop); return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, !0)) } setTabFocusMode(to) { to == null ? this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1 : typeof to == "boolean" ? this.inputState.tabFocusMode = to ? 0 : -1 : this.inputState.tabFocusMode != 0 && (this.inputState.tabFocusMode = Date.now() + to) } static styleModule = styleModule; static domEventHandlers(handlers2) { return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 }) } static domEventObservers(observers2) { return ViewPlugin.define(() => ({}), { eventObservers: observers2 }) } static inputHandler = inputHandler; static clipboardInputFilter = clipboardInputFilter; static clipboardOutputFilter = clipboardOutputFilter; static scrollHandler = scrollHandler; static focusChangeEffect = focusChangeEffect; static perLineTextDirection = perLineTextDirection; static exceptionSink = exceptionSink; static updateListener = updateListener; static editable = editable; static mouseSelectionStyle = mouseSelectionStyle; static dragMovesSelection = dragMovesSelection; static clickAddsSelectionRange = clickAddsSelectionRange; static decorations = decorations; static blockWrappers = blockWrappers; static outerDecorations = outerDecorations; static atomicRanges = atomicRanges; static bidiIsolatedRanges = bidiIsolatedRanges; static cursorScrollMargin = Facet.define({ combine: inputs => { let x = 5, y = 5; for (let i2 of inputs) typeof i2 == "number" ? x = y = i2 : { x, y } = i2; return { x, y } } }); static scrollMargins = scrollMargins; static theme(spec, options) { let prefix = StyleModule.newName(), result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; return options && options.dark && result.push(darkTheme.of(!0)), result } static darkTheme = darkTheme; static baseTheme(spec) { return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))) } static cspNonce = Facet.define({ combine: values => values.length ? values[0] : "" }); static contentAttributes = contentAttributes; static editorAttributes = editorAttributes; static lineWrapping = _EditorView.contentAttributes.of({ class: "cm-lineWrapping" }); static announce = StateEffect.define(); static findFromDOM(dom) { let content2 = dom.querySelector(".cm-content"); return (content2 && Tile.get(content2) || Tile.get(dom))?.root?.view || null } }, MaxBidiLine = 4096, BadMeasure = {}, CachedOrder = class _CachedOrder { constructor(from, to, dir, isolates, fresh, order) { this.from = from; this.to = to; this.dir = dir; this.isolates = isolates; this.fresh = fresh; this.order = order } from; to; dir; isolates; fresh; order; static update(cache, changes) { if (changes.empty && !cache.some(c => c.fresh)) return cache; let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : 0; for (let i2 = Math.max(0, cache.length - 10); i2 < cache.length; i2++) { let entry = cache[i2]; entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to) && result.push(new _CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, !1, entry.order)) } return result } }; function attrsFromFacet(view, facet, base2) { for (let sources = view.state.facet(facet), i2 = sources.length - 1; i2 >= 0; i2--) { let source = sources[i2], value = typeof source == "function" ? source(view) : source; value && combineAttrs(value, base2) } return base2 } var base = { 8: "Backspace", 9: "Tab", 10: "Enter", 12: "NumLock", 13: "Enter", 16: "Shift", 17: "Control", 18: "Alt", 20: "CapsLock", 27: "Escape", 32: " ", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "ArrowLeft", 38: "ArrowUp", 39: "ArrowRight", 40: "ArrowDown", 44: "PrintScreen", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Meta", 92: "Meta", 106: "*", 107: "+", 108: ",", 109: "-", 110: ".", 111: "/", 144: "NumLock", 145: "ScrollLock", 160: "Shift", 161: "Shift", 162: "Control", 163: "Control", 164: "Alt", 165: "Alt", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'" }, shift = { 48: ")", 49: "!", 50: "@", 51: "#", 52: "$", 53: "%", 54: "^", 55: "&", 56: "*", 57: "(", 59: ":", 61: "+", 173: "_", 186: ":", 187: "+", 188: "<", 189: "_", 190: ">", 191: "?", 192: "~", 219: "{", 220: "|", 221: "}", 222: '"' }, mac = typeof navigator < "u" && /Mac/.test(navigator.platform), ie2 = typeof navigator < "u" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); for (i = 0; i < 10; i++)base[48 + i] = base[96 + i] = String(i); var i; for (i = 1; i <= 24; i++)base[i + 111] = "F" + i; var i; for (i = 65; i <= 90; i++)base[i] = String.fromCharCode(i + 32), shift[i] = String.fromCharCode(i); var i; for (code in base) shift.hasOwnProperty(code) || (shift[code] = base[code]); var code; function keyName(event) { var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified", name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; return name2 == "Esc" && (name2 = "Escape"), name2 == "Del" && (name2 = "Delete"), name2 == "Left" && (name2 = "ArrowLeft"), name2 == "Up" && (name2 = "ArrowUp"), name2 == "Right" && (name2 = "ArrowRight"), name2 == "Down" && (name2 = "ArrowDown"), name2 } var currentPlatform = browser_default.mac ? "mac" : browser_default.windows ? "win" : browser_default.linux ? "linux" : "key"; function normalizeKeyName(name2, platform) { let parts = name2.split(/-(?!$)/), result = parts[parts.length - 1]; result == "Space" && (result = " "); let alt, ctrl, shift2, meta2; for (let i2 = 0; i2 < parts.length - 1; ++i2) { let mod = parts[i2]; if (/^(cmd|meta|m)$/i.test(mod)) meta2 = !0; else if (/^a(lt)?$/i.test(mod)) alt = !0; else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = !0; else if (/^s(hift)?$/i.test(mod)) shift2 = !0; else if (/^mod$/i.test(mod)) platform == "mac" ? meta2 = !0 : ctrl = !0; else throw new Error("Unrecognized modifier name: " + mod) } return alt && (result = "Alt-" + result), ctrl && (result = "Ctrl-" + result), meta2 && (result = "Meta-" + result), shift2 && (result = "Shift-" + result), result } function modifiers(name2, event, shift2) { return event.altKey && (name2 = "Alt-" + name2), event.ctrlKey && (name2 = "Ctrl-" + name2), event.metaKey && (name2 = "Meta-" + name2), shift2 !== !1 && event.shiftKey && (name2 = "Shift-" + name2), name2 } var handleKeyEvents = Prec.default(EditorView.domEventHandlers({ keydown(event, view) { return runHandlers(getKeymap(view.state), event, view, "editor") } })), keymap = Facet.define({ enables: handleKeyEvents }), Keymaps = new WeakMap; function getKeymap(state) { let bindings = state.facet(keymap), map = Keymaps.get(bindings); return map || Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))), map } function runScopeHandlers(view, event, scope) { return runHandlers(getKeymap(view.state), event, view, scope) } var storedPrefix = null, PrefixTimeout = 4e3; function buildKeymap(bindings, platform = currentPlatform) { let bound = Object.create(null), isPrefix = Object.create(null), checkPrefix = (name2, is) => { let current = isPrefix[name2]; if (current == null) isPrefix[name2] = is; else if (current != is) throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix") }, add2 = (scope, key, command2, preventDefault, stopPropagation) => { let scopeObj = bound[scope] || (bound[scope] = Object.create(null)), parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); for (let i2 = 1; i2 < parts.length; i2++) { let prefix = parts.slice(0, i2).join(" "); checkPrefix(prefix, !0), scopeObj[prefix] || (scopeObj[prefix] = { preventDefault: !0, stopPropagation: !1, run: [view => { let ourObj = storedPrefix = { view, prefix, scope }; return setTimeout(() => { storedPrefix == ourObj && (storedPrefix = null) }, PrefixTimeout), !0 }] }) } let full = parts.join(" "); checkPrefix(full, !1); let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: !1, stopPropagation: !1, run: scopeObj._any?.run?.slice() || [] }); command2 && binding.run.push(command2), preventDefault && (binding.preventDefault = !0), stopPropagation && (binding.stopPropagation = !0) }; for (let b of bindings) { let scopes = b.scope ? b.scope.split(" ") : ["editor"]; if (b.any) for (let scope of scopes) { let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); scopeObj._any || (scopeObj._any = { preventDefault: !1, stopPropagation: !1, run: [] }); let { any } = b; for (let key in scopeObj) scopeObj[key].run.push(view => any(view, currentKeyEvent)) } let name2 = b[platform] || b.key; if (name2) for (let scope of scopes) add2(scope, name2, b.run, b.preventDefault, b.stopPropagation), b.shift && add2(scope, "Shift-" + name2, b.shift, b.preventDefault, b.stopPropagation) } return bound } var currentKeyEvent = null; function runHandlers(map, event, view, scope) { currentKeyEvent = event; let name2 = keyName(event), charCode = codePointAt2(name2, 0), isChar = codePointSize2(charCode) == name2.length && name2 != " ", prefix = "", handled = !1, prevented = !1, stopPropagation = !1; storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope && (prefix = storedPrefix.prefix + " ", modifierCodes.indexOf(event.keyCode) < 0 && (prevented = !0, storedPrefix = null)); let ran = new Set, runFor = binding => { if (binding) { for (let cmd2 of binding.run) if (!ran.has(cmd2) && (ran.add(cmd2), cmd2(view))) return binding.stopPropagation && (stopPropagation = !0), !0; binding.preventDefault && (binding.stopPropagation && (stopPropagation = !0), prevented = !0) } return !1 }, scopeObj = map[scope], baseName, shiftName; return scopeObj && (runFor(scopeObj[prefix + modifiers(name2, event, !isChar)]) ? handled = !0 : isChar && (event.altKey || event.metaKey || event.ctrlKey) && !(browser_default.windows && event.ctrlKey && event.altKey) && !(browser_default.mac && event.altKey && !(event.ctrlKey || event.metaKey)) && (baseName = base[event.keyCode]) && baseName != name2 ? (runFor(scopeObj[prefix + modifiers(baseName, event, !0)]) || event.shiftKey && (shiftName = shift[event.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event, !1)])) && (handled = !0) : isChar && event.shiftKey && runFor(scopeObj[prefix + modifiers(name2, event, !0)]) && (handled = !0), !handled && runFor(scopeObj._any) && (handled = !0)), prevented && (handled = !0), handled && stopPropagation && event.stopPropagation(), currentKeyEvent = null, handled } var RectangleMarker = class _RectangleMarker { constructor(className, left, top2, width, height) { this.className = className; this.left = left; this.top = top2; this.width = width; this.height = height } className; left; top; width; height; draw() { let elt = document.createElement("div"); return elt.className = this.className, this.adjust(elt), elt } update(elt, prev) { return prev.className != this.className ? !1 : (this.adjust(elt), !0) } adjust(elt) { elt.style.left = this.left + "px", elt.style.top = this.top + "px", this.width != null && (elt.style.width = this.width + "px"), elt.style.height = this.height + "px" } eq(p) { return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className } static forRange(view, className, range) { if (range.empty) { let pos = view.coordsAtPos(range.head, range.assoc || 1); if (!pos) return []; let base2 = getBase(view); return [new _RectangleMarker(className, pos.left - base2.left, pos.top - base2.top, null, pos.bottom - pos.top)] } else return rectanglesForRange(view, className, range) } }; function getBase(view) { let rect = view.scrollDOM.getBoundingClientRect(); return { left: (view.textDirection == 0 ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX) - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY } } function wrappedLine(view, pos, side, inside) { let coords = view.coordsAtPos(pos, side * 2); if (!coords) return inside; let editorRect = view.dom.getBoundingClientRect(), y = (coords.top + coords.bottom) / 2, left = view.posAtCoords({ x: editorRect.left + 1, y }), right = view.posAtCoords({ x: editorRect.right - 1, y }); return left == null || right == null ? inside : { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) } } function rectanglesForRange(view, className, range) { if (range.to <= view.viewport.from || range.from >= view.viewport.to) return []; let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to), ltr = view.textDirection == 0, content2 = view.contentDOM, contentRect = content2.getBoundingClientRect(), base2 = getBase(view), lineElt = content2.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt), leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0), rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0), startBlock = blockAt(view, from, 1), endBlock = blockAt(view, to, -1), visualStart = startBlock.type == 0 ? startBlock : null, visualEnd = endBlock.type == 0 ? endBlock : null; if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks) && (visualStart = wrappedLine(view, from, 1, visualStart)), visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks) && (visualEnd = wrappedLine(view, to, -1, visualEnd)), visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) return pieces(drawForLine(range.from, range.to, visualStart)); { let top2 = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, !1), bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, !0), between = []; return (visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top2.bottom + view.defaultLineHeight / 2 < bottom.top ? between.push(piece(leftSide, top2.bottom, rightSide, bottom.top)) : top2.bottom < bottom.top && view.elementAtHeight((top2.bottom + bottom.top) / 2).type == 0 && (top2.bottom = bottom.top = (top2.bottom + bottom.top) / 2), pieces(top2).concat(between).concat(pieces(bottom)) } function piece(left, top2, right, bottom) { return new RectangleMarker(className, left - base2.left, top2 - base2.top, Math.max(0, right - left), bottom - top2) } function pieces({ top: top2, bottom, horizontal }) { let pieces2 = []; for (let i2 = 0; i2 < horizontal.length; i2 += 2)pieces2.push(piece(horizontal[i2], top2, horizontal[i2 + 1], bottom)); return pieces2 } function drawForLine(from2, to2, line) { let top2 = 1e9, bottom = -1e9, horizontal = []; function addSpan(from3, fromOpen, to3, toOpen, dir) { let fromCoords = view.coordsAtPos(from3, from3 == line.to ? -2 : 2), toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2); !fromCoords || !toCoords || (top2 = Math.min(fromCoords.top, toCoords.top, top2), bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom), dir == 0 ? horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right) : horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right)) } let start = from2 ?? line.from, end = to2 ?? line.to; for (let r of view.visibleRanges) if (r.to > start && r.from < end) for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end); ;) { let docLine = view.state.doc.lineAt(pos); for (let span of view.bidiSpans(docLine)) { let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; if (spanFrom >= endPos) break; spanTo > pos && addSpan(Math.max(spanFrom, pos), from2 == null && spanFrom <= start, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir) } if (pos = docLine.to + 1, pos >= endPos) break } return horizontal.length == 0 && addSpan(start, from2 == null, end, to2 == null, view.textDirection), { top: top2, bottom, horizontal } } function drawForWidget(block, top2) { let y = contentRect.top + (top2 ? block.top : block.bottom); return { top: y, bottom: y, horizontal: [] } } } function sameMarker(a, b) { return a.constructor == b.constructor && a.eq(b) } var LayerView = class { constructor(view, layer2) { this.view = view; this.layer = layer2; this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) }, this.dom = view.scrollDOM.appendChild(document.createElement("div")), this.dom.classList.add("cm-layer"), layer2.above && this.dom.classList.add("cm-layer-above"), layer2.class && this.dom.classList.add(layer2.class), this.scale(), this.dom.setAttribute("aria-hidden", "true"), this.setOrder(view.state), view.requestMeasure(this.measureReq), layer2.mount && layer2.mount(this.dom, view) } view; layer; measureReq; dom; drawn = []; scaleX = 1; scaleY = 1; update(update) { update.startState.facet(layerOrder) != update.state.facet(layerOrder) && this.setOrder(update.state), (this.layer.update(update, this.dom) || update.geometryChanged) && (this.scale(), update.view.requestMeasure(this.measureReq)) } docViewUpdate(view) { this.layer.updateOnDocViewUpdate !== !1 && view.requestMeasure(this.measureReq) } setOrder(state) { let pos = 0, order = state.facet(layerOrder); for (; pos < order.length && order[pos] != this.layer;)pos++; this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos) } measure() { return this.layer.markers(this.view) } scale() { let { scaleX, scaleY } = this.view; (scaleX != this.scaleX || scaleY != this.scaleY) && (this.scaleX = scaleX, this.scaleY = scaleY, this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`) } draw(markers) { if (markers.length != this.drawn.length || markers.some((p, i2) => !sameMarker(p, this.drawn[i2]))) { let old = this.dom.firstChild, oldI = 0; for (let marker of markers) marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI]) ? (old = old.nextSibling, oldI++) : this.dom.insertBefore(marker.draw(), old); for (; old;) { let next = old.nextSibling; old.remove(), old = next } this.drawn = markers, browser_default.webkit && (this.dom.style.display = this.dom.firstChild ? "" : "none") } } destroy() { this.layer.destroy && this.layer.destroy(this.dom, this.view), this.dom.remove() } }, layerOrder = Facet.define(); function layer(config) { return [ViewPlugin.define(v => new LayerView(v, config)), layerOrder.of(config)] } var selectionConfig = Facet.define({ combine(configs) { return combineConfig(configs, { cursorBlinkRate: 1200, drawRangeCursor: !0, iosSelectionHandles: !0 }, { cursorBlinkRate: (a, b) => Math.min(a, b), drawRangeCursor: (a, b) => a || b }) } }); function drawSelection(config = {}) { return [selectionConfig.of(config), cursorLayer, selectionLayer, hideNativeSelection, nativeSelectionHidden.of(!0)] } function getDrawSelectionConfig(state) { return state.facet(selectionConfig) } function configChanged(update) { return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig) } var cursorLayer = layer({ above: !0, markers(view) { let { state } = view, conf = state.facet(selectionConfig), cursors = []; for (let r of state.selection.ranges) { let prim = r == state.selection.main; if (r.empty || conf.drawRangeCursor && !(prim && browser_default.ios && conf.iosSelectionHandles)) { let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary", cursor = r.empty ? r : EditorSelection.cursor(r.head, r.assoc); for (let piece of RectangleMarker.forRange(view, className, cursor)) cursors.push(piece) } } return cursors }, update(update, dom) { update.transactions.some(tr => tr.selection) && (dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"); let confChange = configChanged(update); return confChange && setBlinkRate(update.state, dom), update.docChanged || update.selectionSet || confChange }, mount(dom, view) { setBlinkRate(view.state, dom) }, class: "cm-cursorLayer" }); function setBlinkRate(state, dom) { dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms" } var selectionLayer = layer({ above: !1, markers(view) { let markers = [], { main, ranges } = view.state.selection; for (let r of ranges) if (!r.empty) for (let marker of RectangleMarker.forRange(view, "cm-selectionBackground", r)) markers.push(marker); if (browser_default.ios && !main.empty && view.state.facet(selectionConfig).iosSelectionHandles) { for (let piece of RectangleMarker.forRange(view, "cm-selectionHandle cm-selectionHandle-start", EditorSelection.cursor(main.from, 1))) markers.push(piece); for (let piece of RectangleMarker.forRange(view, "cm-selectionHandle cm-selectionHandle-end", EditorSelection.cursor(main.to, 1))) markers.push(piece) } return markers }, update(update, dom) { return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update) }, class: "cm-selectionLayer" }), hideNativeSelection = Prec.highest(EditorView.theme({ ".cm-line": { "& ::selection, &::selection": { backgroundColor: "transparent !important" }, caretColor: "transparent !important" }, ".cm-content": { caretColor: "transparent !important", "& :focus": { caretColor: "initial !important", "&::selection, & ::selection": { backgroundColor: "Highlight !important" } } } })); var setDropCursorPos = StateEffect.define({ map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos) } }), dropCursorPos = StateField.define({ create() { return null }, update(pos, tr) { return pos != null && (pos = tr.changes.mapPos(pos)), tr.effects.reduce((pos2, e) => e.is(setDropCursorPos) ? e.value : pos2, pos) } }), drawDropCursor = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) } } view; cursor = null; measureReq; update(update) { let cursorPos = update.state.field(dropCursorPos); cursorPos == null ? this.cursor != null && (this.cursor?.remove(), this.cursor = null) : (this.cursor || (this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")), this.cursor.className = "cm-dropCursor"), (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) && this.view.requestMeasure(this.measureReq)) } readPos() { let { view } = this, pos = view.state.field(dropCursorPos), rect = pos != null && view.coordsAtPos(pos); if (!rect) return null; let outer = view.scrollDOM.getBoundingClientRect(); return { left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY, height: rect.bottom - rect.top } } drawCursor(pos) { if (this.cursor) { let { scaleX, scaleY } = this.view; pos ? (this.cursor.style.left = pos.left / scaleX + "px", this.cursor.style.top = pos.top / scaleY + "px", this.cursor.style.height = pos.height / scaleY + "px") : this.cursor.style.left = "-100000px" } } destroy() { this.cursor && this.cursor.remove() } setDropPos(pos) { this.view.state.field(dropCursorPos) != pos && this.view.dispatch({ effects: setDropCursorPos.of(pos) }) } }, { eventObservers: { dragover(event) { this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })) }, dragleave(event) { (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) && this.setDropPos(null) }, dragend() { this.setDropPos(null) }, drop() { this.setDropPos(null) } } }); function dropCursor() { return [dropCursorPos, drawDropCursor] } function iterMatches(doc2, re, from, to, f) { re.lastIndex = 0; for (let cursor = doc2.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length)if (!cursor.lineBreak) for (; m = re.exec(cursor.value);)f(pos + m.index, m) } function matchRanges(view, maxLength) { let visible = view.visibleRanges; if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to) return visible; let result = []; for (let { from, to } of visible) from = Math.max(view.state.doc.lineAt(from).from, from - maxLength), to = Math.min(view.state.doc.lineAt(to).to, to + maxLength), result.length && result[result.length - 1].to >= from ? result[result.length - 1].to = to : result.push({ from, to }); return result } var MatchDecorator = class { regexp; addMatch; boundary; maxLength; constructor(config) { let { regexp, decoration, decorate, boundary, maxLength = 1e3 } = config; if (!regexp.global) throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); if (this.regexp = regexp, decorate) this.addMatch = (match, view, from, add2) => decorate(add2, from, from + match[0].length, match, view); else if (typeof decoration == "function") this.addMatch = (match, view, from, add2) => { let deco = decoration(match, view, from); deco && add2(from, from + match[0].length, deco) }; else if (decoration) this.addMatch = (match, _view, from, add2) => add2(from, from + match[0].length, decoration); else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator"); this.boundary = boundary, this.maxLength = maxLength } createDeco(view) { let build = new RangeSetBuilder, add2 = build.add.bind(build); for (let { from, to } of matchRanges(view, this.maxLength)) iterMatches(view.state.doc, this.regexp, from, to, (from2, m) => this.addMatch(m, view, from2, add2)); return build.finish() } updateDeco(update, deco) { let changeFrom = 1e9, changeTo = -1; return update.docChanged && update.changes.iterChanges((_f, _t, from, to) => { to >= update.view.viewport.from && from <= update.view.viewport.to && (changeFrom = Math.min(from, changeFrom), changeTo = Math.max(to, changeTo)) }), update.viewportMoved || changeTo - changeFrom > 1e3 ? this.createDeco(update.view) : changeTo > -1 ? this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo) : deco } updateRange(view, deco, updateFrom, updateTo) { for (let r of view.visibleRanges) { let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); if (to >= from) { let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine, start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); if (this.boundary) { for (; from > fromLine.from; from--)if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { start = from; break } for (; to < toLine.to; to++)if (this.boundary.test(toLine.text[to - toLine.from])) { end = to; break } } let ranges = [], m, add2 = (from2, to2, deco2) => ranges.push(deco2.range(from2, to2)); if (fromLine == toLine) for (this.regexp.lastIndex = start - fromLine.from; (m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from;)this.addMatch(m, view, m.index + fromLine.from, add2); else iterMatches(view.state.doc, this.regexp, start, end, (from2, m2) => this.addMatch(m2, view, from2, add2)); deco = deco.update({ filterFrom: start, filterTo: end, filter: (from2, to2) => from2 < start || to2 > end, add: ranges }) } } return deco } }; var UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g", Specials = new RegExp(`[\0-\b +-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`, UnicodeRegexpSupport), Names = { 0: "null", 7: "bell", 8: "backspace", 10: "newline", 11: "vertical tab", 13: "carriage return", 27: "escape", 8203: "zero width space", 8204: "zero width non-joiner", 8205: "zero width joiner", 8206: "left-to-right mark", 8207: "right-to-left mark", 8232: "line separator", 8237: "left-to-right override", 8238: "right-to-left override", 8294: "left-to-right isolate", 8295: "right-to-left isolate", 8297: "pop directional isolate", 8233: "paragraph separator", 65279: "zero width no-break space", 65532: "object replacement" }, _supportsTabSize = null; function supportsTabSize() { if (_supportsTabSize == null && typeof document < "u" && document.body) { let styles = document.body.style; _supportsTabSize = (styles.tabSize ?? styles.MozTabSize) != null } return _supportsTabSize || !1 } var specialCharConfig = Facet.define({ combine(configs) { let config = combineConfig(configs, { render: null, specialChars: Specials, addSpecialChars: null }); return (config.replaceTabs = !supportsTabSize()) && (config.specialChars = new RegExp(" |" + config.specialChars.source, UnicodeRegexpSupport)), config.addSpecialChars && (config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport)), config } }); function highlightSpecialChars(config = {}) { return [specialCharConfig.of(config), specialCharPlugin()] } var _plugin = null; function specialCharPlugin() { return _plugin || (_plugin = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)), this.decorations = this.decorator.createDeco(view) } view; decorations = Decoration.none; decorationCache = Object.create(null); decorator; makeDecorator(conf) { return new MatchDecorator({ regexp: conf.specialChars, decoration: (m, view, pos) => { let { doc: doc2 } = view.state, code2 = codePointAt2(m[0], 0); if (code2 == 9) { let line = doc2.lineAt(pos), size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); return Decoration.replace({ widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX) }) } return this.decorationCache[code2] || (this.decorationCache[code2] = Decoration.replace({ widget: new SpecialCharWidget(conf, code2) })) }, boundary: conf.replaceTabs ? void 0 : /[^]/ }) } update(update) { let conf = update.state.facet(specialCharConfig); update.startState.facet(specialCharConfig) != conf ? (this.decorator = this.makeDecorator(conf), this.decorations = this.decorator.createDeco(update.view)) : this.decorations = this.decorator.updateDeco(update, this.decorations) } }, { decorations: v => v.decorations })) } var DefaultPlaceholder = "\u2022"; function placeholder(code2) { return code2 >= 32 ? DefaultPlaceholder : code2 == 10 ? "\u2424" : String.fromCharCode(9216 + code2) } var SpecialCharWidget = class extends WidgetType { constructor(options, code2) { super(); this.options = options; this.code = code2 } options; code; eq(other) { return other.code == this.code } toDOM(view) { let ph = placeholder(this.code), desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)), custom = this.options.render && this.options.render(this.code, desc, ph); if (custom) return custom; let span = document.createElement("span"); return span.textContent = ph, span.title = desc, span.setAttribute("aria-label", desc), span.className = "cm-specialChar", span } ignoreEvent() { return !1 } }, TabWidget = class extends WidgetType { constructor(width) { super(); this.width = width } width; eq(other) { return other.width == this.width } toDOM() { let span = document.createElement("span"); return span.textContent = " ", span.className = "cm-tab", span.style.width = this.width + "px", span } ignoreEvent() { return !1 } }; var plugin = ViewPlugin.fromClass(class { height = 1e3; attrs = { style: "padding-bottom: 1000px" }; update(update) { let { view } = update, height = view.viewState.editorHeight - view.defaultLineHeight - view.documentPadding.top - .5; height >= 0 && height != this.height && (this.height = height, this.attrs = { style: `padding-bottom: ${height}px` }) } }); function scrollPastEnd() { return [plugin, contentAttributes.of(view => view.plugin(plugin)?.attrs || null)] } function highlightActiveLine() { return activeLineHighlighter } var lineDeco = Decoration.line({ class: "cm-activeLine" }), activeLineHighlighter = ViewPlugin.fromClass(class { decorations; constructor(view) { this.decorations = this.getDeco(view) } update(update) { (update.docChanged || update.selectionSet) && (this.decorations = this.getDeco(update.view)) } getDeco(view) { let lastLineStart = -1, deco = []; for (let r of view.state.selection.ranges) { let line = view.lineBlockAt(r.head); line.from > lastLineStart && (deco.push(lineDeco.range(line.from)), lastLineStart = line.from) } return Decoration.set(deco) } }, { decorations: v => v.decorations }); var Placeholder = class extends WidgetType { constructor(content2) { super(); this.content = content2 } content; toDOM(view) { let wrap = document.createElement("span"); return wrap.className = "cm-placeholder", wrap.style.pointerEvents = "none", wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : typeof this.content == "function" ? this.content(view) : this.content.cloneNode(!0)), wrap.setAttribute("aria-hidden", "true"), wrap } coordsAt(dom) { let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : []; if (!rects.length) return null; let style = window.getComputedStyle(dom.parentNode), rect = flattenRect(rects[0], style.direction != "rtl"), lineHeight = parseInt(style.lineHeight); return rect.bottom - rect.top > lineHeight * 1.5 ? { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight } : rect } ignoreEvent() { return !1 } }; function placeholder2(content2) { let plugin2 = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.placeholder = content2 ? Decoration.set([Decoration.widget({ widget: new Placeholder(content2), side: 1 }).range(0)]) : Decoration.none } view; placeholder; get decorations() { return this.view.state.doc.length ? Decoration.none : this.placeholder } }, { decorations: v => v.decorations }); return typeof content2 == "string" ? [plugin2, EditorView.contentAttributes.of({ "aria-placeholder": content2 })] : plugin2 } var MaxOff = 2e3; function rectangleFor(state, a, b) { let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line), ranges = []; if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); for (let i2 = startLine; i2 <= endLine; i2++) { let line = state.doc.line(i2); line.length <= endOff && ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)) } } else { let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); for (let i2 = startLine; i2 <= endLine; i2++) { let line = state.doc.line(i2), start = findColumn(line.text, startCol, state.tabSize, !0); if (start < 0) ranges.push(EditorSelection.cursor(line.to)); else { let end = findColumn(line.text, endCol, state.tabSize); ranges.push(EditorSelection.range(line.from + start, line.from + end)) } } } return ranges } function absoluteColumn(view, x) { let ref = view.coordsAtPos(view.viewport.from); return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1 } function getPos(view, event) { let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, !1), line = view.state.doc.lineAt(offset), off = offset - line.from, col = off > MaxOff ? -1 : off == line.length ? absoluteColumn(view, event.clientX) : countColumn(line.text, view.state.tabSize, offset - line.from); return { line: line.number, col, off } } function rectangleSelectionStyle(view, event) { let start = getPos(view, event), startSel = view.state.selection; return start ? { update(update) { if (update.docChanged) { let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from), newLine = update.state.doc.lineAt(newStart); start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }, startSel = startSel.map(update.changes) } }, get(event2, _extend, multiple) { let cur = getPos(view, event2); if (!cur) return startSel; let ranges = rectangleFor(view.state, start, cur); return ranges.length ? multiple ? EditorSelection.create(ranges.concat(startSel.ranges)) : EditorSelection.create(ranges) : startSel } } : null } function rectangularSelection(options) { let filter = options?.eventFilter || (e => e.altKey && e.button == 0); return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null) } var keys = { Alt: [18, e => !!e.altKey], Control: [17, e => !!e.ctrlKey], Shift: [16, e => !!e.shiftKey], Meta: [91, e => !!e.metaKey] }, showCrosshair = { style: "cursor: crosshair" }; function crosshairCursor(options = {}) { let [code2, getter] = keys[options.key || "Alt"], plugin2 = ViewPlugin.fromClass(class { constructor(view) { this.view = view } view; isDown = !1; set(isDown) { this.isDown != isDown && (this.isDown = isDown, this.view.update([])) } }, { eventObservers: { keydown(e) { this.set(e.keyCode == code2 || getter(e)) }, keyup(e) { (e.keyCode == code2 || !getter(e)) && this.set(!1) }, mousemove(e) { this.set(getter(e)) } } }); return [plugin2, EditorView.contentAttributes.of(view => view.plugin(plugin2)?.isDown ? showCrosshair : null)] } var Outside = "-10000px"; var TooltipViewManager = class { constructor(view, facet, createTooltipView, removeTooltipView) { this.facet = facet; this.createTooltipView = createTooltipView; this.removeTooltipView = removeTooltipView; this.input = view.state.facet(facet), this.tooltips = this.input.filter(t2 => t2); let prev = null; this.tooltipViews = this.tooltips.map(t2 => prev = createTooltipView(t2, prev)) } facet; createTooltipView; removeTooltipView; input; tooltips; tooltipViews; update(update, above) { let input = update.state.facet(this.facet), tooltips2 = input.filter(x => x); if (input === this.input) { for (let t2 of this.tooltipViews) t2.update && t2.update(update); return !1 } let tooltipViews = [], newAbove = above ? [] : null; for (let i2 = 0; i2 < tooltips2.length; i2++) { let tip = tooltips2[i2], known = -1; if (tip) { for (let i3 = 0; i3 < this.tooltips.length; i3++) { let other = this.tooltips[i3]; other && other.create == tip.create && (known = i3) } if (known < 0) tooltipViews[i2] = this.createTooltipView(tip, i2 ? tooltipViews[i2 - 1] : null), newAbove && (newAbove[i2] = !!tip.above); else { let tooltipView = tooltipViews[i2] = this.tooltipViews[known]; newAbove && (newAbove[i2] = above[known]), tooltipView.update && tooltipView.update(update) } } } for (let t2 of this.tooltipViews) tooltipViews.indexOf(t2) < 0 && (this.removeTooltipView(t2), t2.destroy?.()); return above && (newAbove.forEach((val, i2) => above[i2] = val), above.length = newAbove.length), this.input = input, this.tooltips = tooltips2, this.tooltipViews = tooltipViews, !0 } }; function tooltips(config = {}) { return tooltipConfig.of(config) } function windowSpace(view) { let docElt = view.dom.ownerDocument.documentElement; return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth } } var tooltipConfig = Facet.define({ combine: values => ({ position: browser_default.ios ? "absolute" : values.find(conf => conf.position)?.position || "fixed", parent: values.find(conf => conf.parent)?.parent || null, tooltipSpace: values.find(conf => conf.tooltipSpace)?.tooltipSpace || windowSpace }) }), knownHeight = new WeakMap, tooltipPlugin = ViewPlugin.fromClass(class { constructor(view) { this.view = view; let config = view.state.facet(tooltipConfig); this.position = config.position, this.parent = config.parent, this.classes = view.themeClasses, this.createContainer(), this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }, this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null, this.manager = new TooltipViewManager(view, showTooltip, (t2, p) => this.createTooltip(t2, p), t2 => { this.resizeObserver && this.resizeObserver.unobserve(t2.dom), t2.dom.remove() }), this.above = this.manager.tooltips.map(t2 => !!t2.above), this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1 && this.measureSoon() }, { threshold: [1] }) : null, this.observeIntersection(), view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)), this.maybeMeasure() } view; manager; above = []; measureReq; inView = !0; position; madeAbsolute = !1; parent; classes; intersectionObserver; resizeObserver; lastTransaction = 0; measureTimeout = -1; createContainer() { this.parent ? (this.container = document.createElement("div"), this.container.style.position = "relative", this.container.className = this.view.themeClasses, this.parent.appendChild(this.container)) : this.container = this.view.dom } observeIntersection() { if (this.intersectionObserver) { this.intersectionObserver.disconnect(); for (let tooltip of this.manager.tooltipViews) this.intersectionObserver.observe(tooltip.dom) } } measureSoon() { this.measureTimeout < 0 && (this.measureTimeout = setTimeout(() => { this.measureTimeout = -1, this.maybeMeasure() }, 50)) } update(update) { update.transactions.length && (this.lastTransaction = Date.now()); let updated = this.manager.update(update, this.above); updated && this.observeIntersection(); let shouldMeasure = updated || update.geometryChanged, newConfig = update.state.facet(tooltipConfig); if (newConfig.position != this.position && !this.madeAbsolute) { this.position = newConfig.position; for (let t2 of this.manager.tooltipViews) t2.dom.style.position = this.position; shouldMeasure = !0 } if (newConfig.parent != this.parent) { this.parent && this.container.remove(), this.parent = newConfig.parent, this.createContainer(); for (let t2 of this.manager.tooltipViews) this.container.appendChild(t2.dom); shouldMeasure = !0 } else this.parent && this.view.themeClasses != this.classes && (this.classes = this.container.className = this.view.themeClasses); shouldMeasure && this.maybeMeasure() } createTooltip(tooltip, prev) { let tooltipView = tooltip.create(this.view), before = prev ? prev.dom : null; if (tooltipView.dom.classList.add("cm-tooltip"), tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { let arrow = document.createElement("div"); arrow.className = "cm-tooltip-arrow", tooltipView.dom.appendChild(arrow) } return tooltipView.dom.style.position = this.position, tooltipView.dom.style.top = Outside, tooltipView.dom.style.left = "0px", this.container.insertBefore(tooltipView.dom, before), tooltipView.mount && tooltipView.mount(this.view), this.resizeObserver && this.resizeObserver.observe(tooltipView.dom), tooltipView } destroy() { this.view.win.removeEventListener("resize", this.measureSoon); for (let tooltipView of this.manager.tooltipViews) tooltipView.dom.remove(), tooltipView.destroy?.(); this.parent && this.container.remove(), this.resizeObserver?.disconnect(), this.intersectionObserver?.disconnect(), clearTimeout(this.measureTimeout) } readMeasure() { let scaleX = 1, scaleY = 1, makeAbsolute = !1; if (this.position == "fixed" && this.manager.tooltipViews.length) { let { dom } = this.manager.tooltipViews[0]; if (browser_default.safari) { let rect = dom.getBoundingClientRect(); makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1 } else makeAbsolute = !!dom.offsetParent && dom.offsetParent != this.container.ownerDocument.body } if (makeAbsolute || this.position == "absolute") if (this.parent) { let rect = this.parent.getBoundingClientRect(); rect.width && rect.height && (scaleX = rect.width / this.parent.offsetWidth, scaleY = rect.height / this.parent.offsetHeight) } else ({ scaleX, scaleY } = this.view.viewState); let visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view); return { visible: { left: visible.left + margins.left, top: visible.top + margins.top, right: visible.right - margins.right, bottom: visible.bottom - margins.bottom }, parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(), pos: this.manager.tooltips.map((t2, i2) => { let tv = this.manager.tooltipViews[i2]; return tv.getCoords ? tv.getCoords(t2.pos) : this.view.coordsAtPos(t2.pos) }), size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), scaleX, scaleY, makeAbsolute } } writeMeasure(measured) { if (measured.makeAbsolute) { this.madeAbsolute = !0, this.position = "absolute"; for (let t2 of this.manager.tooltipViews) t2.dom.style.position = "absolute" } let { visible, space, scaleX, scaleY } = measured, others = []; for (let i2 = 0; i2 < this.manager.tooltips.length; i2++) { let tooltip = this.manager.tooltips[i2], tView = this.manager.tooltipViews[i2], { dom } = tView, pos = measured.pos[i2], size = measured.size[i2]; if (!pos || tooltip.clip !== !1 && (pos.bottom <= Math.max(visible.top, space.top) || pos.top >= Math.min(visible.bottom, space.bottom) || pos.right < Math.max(visible.left, space.left) - .1 || pos.left > Math.min(visible.right, space.right) + .1)) { dom.style.top = Outside; continue } let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null, arrowHeight = arrow ? 7 : 0, width = size.right - size.left, height = knownHeight.get(tView) ?? size.bottom - size.top, offset = tView.offset || noOffset, ltr = this.view.textDirection == 0, left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 : 0) - offset.x), space.right - width), above = this.above[i2]; !tooltip.strictSide && (above ? pos.top - height - arrowHeight - offset.y < space.top : pos.bottom + height + arrowHeight + offset.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top && (above = this.above[i2] = !above); let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight; if (spaceVert < height && tView.resize !== !1) { if (spaceVert < this.view.defaultLineHeight) { dom.style.top = Outside; continue } knownHeight.set(tView, height), dom.style.height = (height = spaceVert) / scaleY + "px" } else dom.style.height && (dom.style.height = ""); let top2 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y, right = left + width; if (tView.overlap !== !0) for (let r of others) r.left < right && r.right > left && r.top < top2 + height && r.bottom > top2 && (top2 = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2); if (this.position == "absolute" ? (dom.style.top = (top2 - measured.parent.top) / scaleY + "px", setLeftStyle(dom, (left - measured.parent.left) / scaleX)) : (dom.style.top = top2 / scaleY + "px", setLeftStyle(dom, left / scaleX)), arrow) { let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7); arrow.style.left = arrowLeft / scaleX + "px" } tView.overlap !== !0 && others.push({ left, top: top2, right, bottom: top2 + height }), dom.classList.toggle("cm-tooltip-above", above), dom.classList.toggle("cm-tooltip-below", !above), tView.positioned && tView.positioned(measured.space) } } maybeMeasure() { if (this.manager.tooltips.length && (this.view.inView && this.view.requestMeasure(this.measureReq), this.inView != this.view.inView && (this.inView = this.view.inView, !this.inView))) for (let tv of this.manager.tooltipViews) tv.dom.style.top = Outside } }, { eventObservers: { scroll() { this.maybeMeasure() } } }); function setLeftStyle(elt, value) { let current = parseInt(elt.style.left, 10); (isNaN(current) || Math.abs(value - current) > 1) && (elt.style.left = value + "px") } var baseTheme2 = EditorView.baseTheme({ ".cm-tooltip": { zIndex: 500, boxSizing: "border-box" }, "&light .cm-tooltip": { border: "1px solid #bbb", backgroundColor: "#f5f5f5" }, "&light .cm-tooltip-section:not(:first-child)": { borderTop: "1px solid #bbb" }, "&dark .cm-tooltip": { backgroundColor: "#333338", color: "white" }, ".cm-tooltip-arrow": { height: "7px", width: "14px", position: "absolute", zIndex: -1, overflow: "hidden", "&:before, &:after": { content: "''", position: "absolute", width: 0, height: 0, borderLeft: "7px solid transparent", borderRight: "7px solid transparent" }, ".cm-tooltip-above &": { bottom: "-7px", "&:before": { borderTop: "7px solid #bbb" }, "&:after": { borderTop: "7px solid #f5f5f5", bottom: "1px" } }, ".cm-tooltip-below &": { top: "-7px", "&:before": { borderBottom: "7px solid #bbb" }, "&:after": { borderBottom: "7px solid #f5f5f5", top: "1px" } } }, "&dark .cm-tooltip .cm-tooltip-arrow": { "&:before": { borderTopColor: "#333338", borderBottomColor: "#333338" }, "&:after": { borderTopColor: "transparent", borderBottomColor: "transparent" } } }), noOffset = { x: 0, y: 0 }, showTooltip = Facet.define({ enables: [tooltipPlugin, baseTheme2] }), showHoverTooltip = Facet.define({ combine: inputs => inputs.reduce((a, i2) => a.concat(i2), []) }), HoverTooltipHost = class _HoverTooltipHost { constructor(view) { this.view = view; this.dom = document.createElement("div"), this.dom.classList.add("cm-tooltip-hover"), this.manager = new TooltipViewManager(view, showHoverTooltip, (t2, p) => this.createHostedView(t2, p), t2 => t2.dom.remove()) } view; manager; dom; mounted = !1; static create(view) { return new _HoverTooltipHost(view) } createHostedView(tooltip, prev) { let hostedView = tooltip.create(this.view); return hostedView.dom.classList.add("cm-tooltip-section"), this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild), this.mounted && hostedView.mount && hostedView.mount(this.view), hostedView } mount(view) { for (let hostedView of this.manager.tooltipViews) hostedView.mount && hostedView.mount(view); this.mounted = !0 } positioned(space) { for (let hostedView of this.manager.tooltipViews) hostedView.positioned && hostedView.positioned(space) } update(update) { this.manager.update(update) } destroy() { for (let t2 of this.manager.tooltipViews) t2.destroy?.() } passProp(name2) { let value; for (let view of this.manager.tooltipViews) { let given = view[name2]; if (given !== void 0) { if (value === void 0) value = given; else if (value !== given) return } } return value } get offset() { return this.passProp("offset") } get getCoords() { return this.passProp("getCoords") } get overlap() { return this.passProp("overlap") } get resize() { return this.passProp("resize") } }, showHoverTooltipHost = showTooltip.compute([showHoverTooltip], state => { let tooltips2 = state.facet(showHoverTooltip); return tooltips2.length === 0 ? null : { pos: Math.min(...tooltips2.map(t2 => t2.pos)), end: Math.max(...tooltips2.map(t2 => t2.end ?? t2.pos)), create: HoverTooltipHost.create, above: tooltips2[0].above, arrow: tooltips2.some(t2 => t2.arrow) } }); var HoverPlugin = class { constructor(view, source, field, setHover, hoverTime) { this.view = view; this.source = source; this.field = field; this.setHover = setHover; this.hoverTime = hoverTime; this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }, this.checkHover = this.checkHover.bind(this), view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)), view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)) } view; source; field; setHover; hoverTime; lastMove; hoverTimeout = -1; restartTimeout = -1; pending = null; update() { this.pending && (this.pending = null, clearTimeout(this.restartTimeout), this.restartTimeout = setTimeout(() => this.startHover(), 20)) } get active() { return this.view.state.field(this.field) } checkHover() { if (this.hoverTimeout = -1, this.active.length) return; let hovered = Date.now() - this.lastMove.time; hovered < this.hoverTime ? this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered) : this.startHover() } startHover() { clearTimeout(this.restartTimeout); let { view, lastMove } = this, tile = view.docView.tile.nearest(lastMove.target); if (!tile) return; let pos, side = 1; if (tile.isWidget()) pos = tile.posAtStart; else { if (pos = view.posAtCoords(lastMove), pos == null) return; let posCoords = view.coordsAtPos(pos); if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth) return; let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos), rtl = bidi && bidi.dir == 1 ? -1 : 1; side = lastMove.x < posCoords.left ? -rtl : rtl } let open = this.source(view, pos, side); if (open?.then) { let pending = this.pending = { pos }; open.then(result => { this.pending == pending && (this.pending = null, result && !(Array.isArray(result) && !result.length) && view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) })) }, e => logException(view.state, e, "hover tooltip")) } else open && !(Array.isArray(open) && !open.length) && view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) }) } get tooltip() { let plugin2 = this.view.plugin(tooltipPlugin), index = plugin2 ? plugin2.manager.tooltips.findIndex(t2 => t2.create == HoverTooltipHost.create) : -1; return index > -1 ? plugin2.manager.tooltipViews[index] : null } mousemove(event) { this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }, this.hoverTimeout < 0 && (this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime)); let { active, tooltip } = this; if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) { let { pos } = active[0] || this.pending, end = active[0]?.end ?? pos; (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6)) && (this.view.dispatch({ effects: this.setHover.of([]) }), this.pending = null) } } mouseleave(event) { clearTimeout(this.hoverTimeout), this.hoverTimeout = -1; let { active } = this; if (active.length) { let { tooltip } = this; tooltip && tooltip.dom.contains(event.relatedTarget) ? this.watchTooltipLeave(tooltip.dom) : this.view.dispatch({ effects: this.setHover.of([]) }) } } watchTooltipLeave(tooltip) { let watch = event => { tooltip.removeEventListener("mouseleave", watch), this.active.length && !this.view.dom.contains(event.relatedTarget) && this.view.dispatch({ effects: this.setHover.of([]) }) }; tooltip.addEventListener("mouseleave", watch) } destroy() { clearTimeout(this.hoverTimeout), clearTimeout(this.restartTimeout), this.view.dom.removeEventListener("mouseleave", this.mouseleave), this.view.dom.removeEventListener("mousemove", this.mousemove) } }, tooltipMargin = 4; function isInTooltip(tooltip, event) { let { left, right, top: top2, bottom } = tooltip.getBoundingClientRect(), arrow; if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) { let arrowRect = arrow.getBoundingClientRect(); top2 = Math.min(arrowRect.top, top2), bottom = Math.max(arrowRect.bottom, bottom) } return event.clientX >= left - tooltipMargin && event.clientX <= right + tooltipMargin && event.clientY >= top2 - tooltipMargin && event.clientY <= bottom + tooltipMargin } function isOverRange(view, from, to, x, y, margin) { let rect = view.scrollDOM.getBoundingClientRect(), docBottom = view.documentTop + view.documentPadding.top + view.contentHeight; if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y) return !1; let pos = view.posAtCoords({ x, y }, !1); return pos >= from && pos <= to } function hoverTooltip(source, options = {}) { let setHover = StateEffect.define(), hoverState = StateField.define({ create() { return [] }, update(value, tr) { if (value.length && (options.hideOnChange && (tr.docChanged || tr.selection) ? value = [] : options.hideOn && (value = value.filter(v => !options.hideOn(tr, v))), tr.docChanged)) { let mapped = []; for (let tooltip of value) { let newPos = tr.changes.mapPos(tooltip.pos, -1, 1); if (newPos != null) { let copy = Object.assign(Object.create(null), tooltip); copy.pos = newPos, copy.end != null && (copy.end = tr.changes.mapPos(copy.end)), mapped.push(copy) } } value = mapped } for (let effect of tr.effects) effect.is(setHover) && (value = effect.value), effect.is(closeHoverTooltipEffect) && (value = []); return value }, provide: f => showHoverTooltip.from(f) }); return { active: hoverState, extension: [hoverState, ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300)), showHoverTooltipHost] } } function getTooltip(view, tooltip) { let plugin2 = view.plugin(tooltipPlugin); if (!plugin2) return null; let found = plugin2.manager.tooltips.indexOf(tooltip); return found < 0 ? null : plugin2.manager.tooltipViews[found] } function hasHoverTooltips(state) { return state.facet(showHoverTooltip).some(x => x) } var closeHoverTooltipEffect = StateEffect.define(), closeHoverTooltips = closeHoverTooltipEffect.of(null); function repositionTooltips(view) { let plugin2 = view.plugin(tooltipPlugin); plugin2 && plugin2.maybeMeasure() } var panelConfig = Facet.define({ combine(configs) { let topContainer, bottomContainer; for (let c of configs) topContainer = topContainer || c.topContainer, bottomContainer = bottomContainer || c.bottomContainer; return { topContainer, bottomContainer } } }); function panels(config) { return config ? [panelConfig.of(config)] : [] } function getPanel(view, panel) { let plugin2 = view.plugin(panelPlugin), index = plugin2 ? plugin2.specs.indexOf(panel) : -1; return index > -1 ? plugin2.panels[index] : null } var panelPlugin = ViewPlugin.fromClass(class { input; specs; panels; top; bottom; constructor(view) { this.input = view.state.facet(showPanel), this.specs = this.input.filter(s => s), this.panels = this.specs.map(spec => spec(view)); let conf = view.state.facet(panelConfig); this.top = new PanelGroup(view, !0, conf.topContainer), this.bottom = new PanelGroup(view, !1, conf.bottomContainer), this.top.sync(this.panels.filter(p => p.top)), this.bottom.sync(this.panels.filter(p => !p.top)); for (let p of this.panels) p.dom.classList.add("cm-panel"), p.mount && p.mount() } update(update) { let conf = update.state.facet(panelConfig); this.top.container != conf.topContainer && (this.top.sync([]), this.top = new PanelGroup(update.view, !0, conf.topContainer)), this.bottom.container != conf.bottomContainer && (this.bottom.sync([]), this.bottom = new PanelGroup(update.view, !1, conf.bottomContainer)), this.top.syncClasses(), this.bottom.syncClasses(); let input = update.state.facet(showPanel); if (input != this.input) { let specs = input.filter(x => x), panels2 = [], top2 = [], bottom = [], mount = []; for (let spec of specs) { let known = this.specs.indexOf(spec), panel; known < 0 ? (panel = spec(update.view), mount.push(panel)) : (panel = this.panels[known], panel.update && panel.update(update)), panels2.push(panel), (panel.top ? top2 : bottom).push(panel) } this.specs = specs, this.panels = panels2, this.top.sync(top2), this.bottom.sync(bottom); for (let p of mount) p.dom.classList.add("cm-panel"), p.mount && p.mount() } else for (let p of this.panels) p.update && p.update(update) } destroy() { this.top.sync([]), this.bottom.sync([]) } }, { provide: plugin2 => EditorView.scrollMargins.of(view => { let value = view.plugin(plugin2); return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() } }) }), PanelGroup = class { constructor(view, top2, container) { this.view = view; this.top = top2; this.container = container; this.syncClasses() } view; top; container; dom = void 0; classes = ""; panels = []; sync(panels2) { for (let p of this.panels) p.destroy && panels2.indexOf(p) < 0 && p.destroy(); this.panels = panels2, this.syncDOM() } syncDOM() { if (this.panels.length == 0) { this.dom && (this.dom.remove(), this.dom = void 0); return } if (!this.dom) { this.dom = document.createElement("div"), this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom", this.dom.style[this.top ? "top" : "bottom"] = "0"; let parent = this.container || this.view.dom; parent.insertBefore(this.dom, this.top ? parent.firstChild : null) } let curDOM = this.dom.firstChild; for (let panel of this.panels) if (panel.dom.parentNode == this.dom) { for (; curDOM != panel.dom;)curDOM = rm2(curDOM); curDOM = curDOM.nextSibling } else this.dom.insertBefore(panel.dom, curDOM); for (; curDOM;)curDOM = rm2(curDOM) } scrollMargin() { return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top) } syncClasses() { if (!(!this.container || this.classes == this.view.themeClasses)) { for (let cls of this.classes.split(" ")) cls && this.container.classList.remove(cls); for (let cls of (this.classes = this.view.themeClasses).split(" ")) cls && this.container.classList.add(cls) } } }; function rm2(node) { let next = node.nextSibling; return node.remove(), next } var showPanel = Facet.define({ enables: panelPlugin }); function crelt() { var elt = arguments[0]; typeof elt == "string" && (elt = document.createElement(elt)); var i2 = 1, next = arguments[1]; if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { for (var name2 in next) if (Object.prototype.hasOwnProperty.call(next, name2)) { var value = next[name2]; typeof value == "string" ? elt.setAttribute(name2, value) : value != null && (elt[name2] = value) } i2++ } for (; i2 < arguments.length; i2++)add(elt, arguments[i2]); return elt } function add(elt, child) { if (typeof child == "string") elt.appendChild(document.createTextNode(child)); else if (child != null) if (child.nodeType != null) elt.appendChild(child); else if (Array.isArray(child)) for (var i2 = 0; i2 < child.length; i2++)add(elt, child[i2]); else throw new RangeError("Unsupported child node: " + child) } function showDialog(view, config) { let resolve, promise = new Promise(r => resolve = r), panelCtor = view2 => createDialog(view2, config, resolve); view.state.field(dialogField, !1) ? view.dispatch({ effects: openDialogEffect.of(panelCtor) }) : view.dispatch({ effects: StateEffect.appendConfig.of(dialogField.init(() => [panelCtor])) }); let close = closeDialogEffect.of(panelCtor); return { close, result: promise.then(form => ((view.win.queueMicrotask || (f => view.win.setTimeout(f, 10)))(() => { view.state.field(dialogField).indexOf(panelCtor) > -1 && view.dispatch({ effects: close }) }), form)) } } function getDialog(view, className) { let dialogs = view.state.field(dialogField, !1) || []; for (let open of dialogs) { let panel = getPanel(view, open); if (panel && panel.dom.classList.contains(className)) return panel } return null } var dialogField = StateField.define({ create() { return [] }, update(dialogs, tr) { for (let e of tr.effects) e.is(openDialogEffect) ? dialogs = [e.value].concat(dialogs) : e.is(closeDialogEffect) && (dialogs = dialogs.filter(d => d != e.value)); return dialogs }, provide: f => showPanel.computeN([f], state => state.field(f)) }), openDialogEffect = StateEffect.define(), closeDialogEffect = StateEffect.define(); function createDialog(view, config, result) { let content2 = config.content ? config.content(view, () => done(null)) : null; if (!content2) { if (content2 = crelt("form"), config.input) { let input = crelt("input", config.input); /^(text|password|number|email|tel|url)$/.test(input.type) && input.classList.add("cm-textfield"), input.name || (input.name = "input"), content2.appendChild(crelt("label", (config.label || "") + ": ", input)) } else content2.appendChild(document.createTextNode(config.label || "")); content2.appendChild(document.createTextNode(" ")), content2.appendChild(crelt("button", { class: "cm-button", type: "submit" }, config.submitLabel || "OK")) } let forms = content2.nodeName == "FORM" ? [content2] : content2.querySelectorAll("form"); for (let i2 = 0; i2 < forms.length; i2++) { let form = forms[i2]; form.addEventListener("keydown", event => { event.keyCode == 27 ? (event.preventDefault(), done(null)) : event.keyCode == 13 && (event.preventDefault(), done(form)) }), form.addEventListener("submit", event => { event.preventDefault(), done(form) }) } let panel = crelt("div", content2, crelt("button", { onclick: () => done(null), "aria-label": view.state.phrase("close"), class: "cm-dialog-close", type: "button" }, ["\xD7"])); config.class && (panel.className = config.class), panel.classList.add("cm-dialog"); function done(form) { panel.contains(panel.ownerDocument.activeElement) && view.focus(), result(form) } return { dom: panel, top: config.top, mount: () => { if (config.focus) { let focus; typeof config.focus == "string" ? focus = content2.querySelector(config.focus) : focus = content2.querySelector("input") || content2.querySelector("button"), focus && "select" in focus ? focus.select() : focus && "focus" in focus && focus.focus() } } } } var GutterMarker = class extends RangeValue { compare(other) { return this == other || this.constructor == other.constructor && this.eq(other) } eq(other) { return !1 } destroy(dom) { } }; GutterMarker.prototype.elementClass = ""; GutterMarker.prototype.toDOM = void 0; GutterMarker.prototype.mapMode = 2; GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; GutterMarker.prototype.point = !0; var gutterLineClass = Facet.define(), gutterWidgetClass = Facet.define(), defaults = { class: "", renderEmptyElements: !1, elementStyle: "", markers: () => RangeSet.empty, lineMarker: () => null, widgetMarker: () => null, lineMarkerChange: null, initialSpacer: null, updateSpacer: null, domEventHandlers: {}, side: "before" }, activeGutters = Facet.define(); function gutter(config) { return [gutters(), activeGutters.of({ ...defaults, ...config })] } var unfixGutters = Facet.define({ combine: values => values.some(x => x) }); function gutters(config) { let result = [gutterView]; return config && config.fixed === !1 && result.push(unfixGutters.of(!0)), result } var gutterView = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.prevViewport = view.viewport, this.dom = document.createElement("div"), this.dom.className = "cm-gutters cm-gutters-before", this.dom.setAttribute("aria-hidden", "true"), this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px", this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)), this.fixed = !view.state.facet(unfixGutters); for (let gutter2 of this.gutters) gutter2.config.side == "after" ? this.getDOMAfter().appendChild(gutter2.dom) : this.dom.appendChild(gutter2.dom); this.fixed && (this.dom.style.position = "sticky"), this.syncGutters(!1), view.scrollDOM.insertBefore(this.dom, view.contentDOM) } view; gutters; dom; domAfter = null; fixed; prevViewport; getDOMAfter() { return this.domAfter || (this.domAfter = document.createElement("div"), this.domAfter.className = "cm-gutters cm-gutters-after", this.domAfter.setAttribute("aria-hidden", "true"), this.domAfter.style.minHeight = this.view.contentHeight / this.view.scaleY + "px", this.domAfter.style.position = this.fixed ? "sticky" : "", this.view.scrollDOM.appendChild(this.domAfter)), this.domAfter } update(update) { if (this.updateGutters(update)) { let vpA = this.prevViewport, vpB = update.view.viewport, vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); this.syncGutters(vpOverlap < (vpB.to - vpB.from) * .8) } if (update.geometryChanged) { let min = this.view.contentHeight / this.view.scaleY + "px"; this.dom.style.minHeight = min, this.domAfter && (this.domAfter.style.minHeight = min) } this.view.state.facet(unfixGutters) != !this.fixed && (this.fixed = !this.fixed, this.dom.style.position = this.fixed ? "sticky" : "", this.domAfter && (this.domAfter.style.position = this.fixed ? "sticky" : "")), this.prevViewport = update.view.viewport } syncGutters(detach) { let after = this.dom.nextSibling; detach && (this.dom.remove(), this.domAfter && this.domAfter.remove()); let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from), classSet = [], contexts = this.gutters.map(gutter2 => new UpdateContext(gutter2, this.view.viewport, -this.view.documentPadding.top)); for (let line of this.view.viewportLineBlocks) if (classSet.length && (classSet = []), Array.isArray(line.type)) { let first = !0; for (let b of line.type) if (b.type == 0 && first) { advanceCursor(lineClasses, classSet, b.from); for (let cx of contexts) cx.line(this.view, b, classSet); first = !1 } else if (b.widget) for (let cx of contexts) cx.widget(this.view, b) } else if (line.type == 0) { advanceCursor(lineClasses, classSet, line.from); for (let cx of contexts) cx.line(this.view, line, classSet) } else if (line.widget) for (let cx of contexts) cx.widget(this.view, line); for (let cx of contexts) cx.finish(); detach && (this.view.scrollDOM.insertBefore(this.dom, after), this.domAfter && this.view.scrollDOM.appendChild(this.domAfter)) } updateGutters(update) { let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters), change = update.docChanged || update.heightChanged || update.viewportChanged || !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); if (prev == cur) for (let gutter2 of this.gutters) gutter2.update(update) && (change = !0); else { change = !0; let gutters2 = []; for (let conf of cur) { let known = prev.indexOf(conf); known < 0 ? gutters2.push(new SingleGutterView(this.view, conf)) : (this.gutters[known].update(update), gutters2.push(this.gutters[known])) } for (let g of this.gutters) g.dom.remove(), gutters2.indexOf(g) < 0 && g.destroy(); for (let g of gutters2) g.config.side == "after" ? this.getDOMAfter().appendChild(g.dom) : this.dom.appendChild(g.dom); this.gutters = gutters2 } return change } destroy() { for (let view of this.gutters) view.destroy(); this.dom.remove(), this.domAfter && this.domAfter.remove() } }, { provide: plugin2 => EditorView.scrollMargins.of(view => { let value = view.plugin(plugin2); if (!value || value.gutters.length == 0 || !value.fixed) return null; let before = value.dom.offsetWidth * view.scaleX, after = value.domAfter ? value.domAfter.offsetWidth * view.scaleX : 0; return view.textDirection == 0 ? { left: before, right: after } : { right: before, left: after } }) }); function asArray2(val) { return Array.isArray(val) ? val : [val] } function advanceCursor(cursor, collect, pos) { for (; cursor.value && cursor.from <= pos;)cursor.from == pos && collect.push(cursor.value), cursor.next() } var UpdateContext = class { constructor(gutter2, viewport, height) { this.gutter = gutter2; this.height = height; this.cursor = RangeSet.iter(gutter2.markers, viewport.from) } gutter; height; cursor; i = 0; addElement(view, block, markers) { let { gutter: gutter2 } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY; if (this.i == gutter2.elements.length) { let newElt = new GutterElement(view, height, above, markers); gutter2.elements.push(newElt), gutter2.dom.appendChild(newElt.dom) } else gutter2.elements[this.i].update(view, height, above, markers); this.height = block.bottom, this.i++ } line(view, line, extraMarkers) { let localMarkers = []; advanceCursor(this.cursor, localMarkers, line.from), extraMarkers.length && (localMarkers = localMarkers.concat(extraMarkers)); let forLine = this.gutter.config.lineMarker(view, line, localMarkers); forLine && localMarkers.unshift(forLine); let gutter2 = this.gutter; localMarkers.length == 0 && !gutter2.config.renderEmptyElements || this.addElement(view, line, localMarkers) } widget(view, block) { let marker = this.gutter.config.widgetMarker(view, block.widget, block), markers = marker ? [marker] : null; for (let cls of view.state.facet(gutterWidgetClass)) { let marker2 = cls(view, block.widget, block); marker2 && (markers || (markers = [])).push(marker2) } markers && this.addElement(view, block, markers) } finish() { let gutter2 = this.gutter; for (; gutter2.elements.length > this.i;) { let last = gutter2.elements.pop(); gutter2.dom.removeChild(last.dom), last.destroy() } } }, SingleGutterView = class { constructor(view, config) { this.view = view; this.config = config; this.dom = document.createElement("div"), this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); for (let prop in config.domEventHandlers) this.dom.addEventListener(prop, event => { let target = event.target, y; if (target != this.dom && this.dom.contains(target)) { for (; target.parentNode != this.dom;)target = target.parentNode; let rect = target.getBoundingClientRect(); y = (rect.top + rect.bottom) / 2 } else y = event.clientY; let line = view.lineBlockAtHeight(y - view.documentTop); config.domEventHandlers[prop](view, line, event) && event.preventDefault() }); this.markers = asArray2(config.markers(view)), config.initialSpacer && (this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]), this.dom.appendChild(this.spacer.dom), this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none") } view; config; dom; elements = []; markers; spacer = null; update(update) { let prevMarkers = this.markers; if (this.markers = asArray2(this.config.markers(update.view)), this.spacer && this.config.updateSpacer) { let updated = this.config.updateSpacer(this.spacer.markers[0], update); updated != this.spacer.markers[0] && this.spacer.update(update.view, 0, 0, [updated]) } let vp = update.view.viewport; return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : !1) } destroy() { for (let elt of this.elements) elt.destroy() } }, GutterElement = class { dom; height = -1; above = 0; markers = []; constructor(view, height, above, markers) { this.dom = document.createElement("div"), this.dom.className = "cm-gutterElement", this.update(view, height, above, markers) } update(view, height, above, markers) { this.height != height && (this.height = height, this.dom.style.height = height + "px"), this.above != above && (this.dom.style.marginTop = (this.above = above) ? above + "px" : ""), sameMarkers(this.markers, markers) || this.setMarkers(view, markers) } setMarkers(view, markers) { let cls = "cm-gutterElement", domPos = this.dom.firstChild; for (let iNew = 0, iOld = 0; ;) { let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = !1; if (marker) { let c = marker.elementClass; c && (cls += " " + c); for (let i2 = iOld; i2 < this.markers.length; i2++)if (this.markers[i2].compare(marker)) { skipTo = i2, matched = !0; break } } else skipTo = this.markers.length; for (; iOld < skipTo;) { let next = this.markers[iOld++]; if (next.toDOM) { next.destroy(domPos); let after = domPos.nextSibling; domPos.remove(), domPos = after } } if (!marker) break; marker.toDOM && (matched ? domPos = domPos.nextSibling : this.dom.insertBefore(marker.toDOM(view), domPos)), matched && iOld++ } this.dom.className = cls, this.markers = markers } destroy() { this.setMarkers(null, []) } }; function sameMarkers(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (!a[i2].compare(b[i2])) return !1; return !0 } var lineNumberMarkers = Facet.define(), lineNumberWidgetMarker = Facet.define(), lineNumberConfig = Facet.define({ combine(values) { return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { domEventHandlers(a, b) { let result = Object.assign({}, a); for (let event in b) { let exists = result[event], add2 = b[event]; result[event] = exists ? (view, line, event2) => exists(view, line, event2) || add2(view, line, event2) : add2 } return result } }) } }), NumberMarker = class extends GutterMarker { constructor(number2) { super(); this.number = number2 } number; eq(other) { return this.number == other.number } toDOM() { return document.createTextNode(this.number) } }; function formatNumber(view, number2) { return view.state.facet(lineNumberConfig).formatNumber(number2, view.state) } var lineNumberGutter = activeGutters.compute([lineNumberConfig], state => ({ class: "cm-lineNumbers", renderEmptyElements: !1, markers(view) { return view.state.facet(lineNumberMarkers) }, lineMarker(view, line, others) { return others.some(m => m.toDOM) ? null : new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)) }, widgetMarker: (view, widget, block) => { for (let m of view.state.facet(lineNumberWidgetMarker)) { let result = m(view, widget, block); if (result) return result } return null }, lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), initialSpacer(view) { return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))) }, updateSpacer(spacer, update) { let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); return max == spacer.number ? spacer : new NumberMarker(max) }, domEventHandlers: state.facet(lineNumberConfig).domEventHandlers, side: "before" })); function lineNumbers(config = {}) { return [lineNumberConfig.of(config), gutters(), lineNumberGutter] } function maxLineNumber(lines) { let last = 9; for (; last < lines;)last = last * 10 + 9; return last } var activeLineGutterMarker = new class extends GutterMarker { elementClass = "cm-activeLineGutter" }, activeLineGutterHighlighter = gutterLineClass.compute(["selection"], state => { let marks = [], last = -1; for (let range of state.selection.ranges) { let linePos = state.doc.lineAt(range.head).from; linePos > last && (last = linePos, marks.push(activeLineGutterMarker.range(linePos))) } return RangeSet.of(marks) }); function highlightActiveLineGutter() { return activeLineGutterHighlighter } function matcher(decorator) { return ViewPlugin.define(view => ({ decorations: decorator.createDeco(view), update(u) { this.decorations = decorator.updateDeco(u, this.decorations) } }), { decorations: v => v.decorations }) } var tabDeco = Decoration.mark({ class: "cm-highlightTab" }), spaceDeco = Decoration.mark({ class: "cm-highlightSpace" }), whitespaceHighlighter = matcher(new MatchDecorator({ regexp: /\t| /g, decoration: match => match[0] == " " ? tabDeco : spaceDeco, boundary: /\S/ })); function highlightWhitespace() { return whitespaceHighlighter } var trailingHighlighter = matcher(new MatchDecorator({ regexp: /\s+$/g, decoration: Decoration.mark({ class: "cm-trailingSpace" }) })); function highlightTrailingWhitespace() { return trailingHighlighter } var __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType, ChangedRange, computeOrder, moveVisually, clearHeightChangeFlag, getHeightChangeFlag: () => heightChangeFlag }; var DefaultBufferLength = 1024, nextPropID = 0, Range4 = class { constructor(from, to) { this.from = from; this.to = to } }, NodeProp = class _NodeProp { constructor(config = {}) { this.id = nextPropID++, this.perNode = !!config.perNode, this.deserialize = config.deserialize || (() => { throw new Error("This node type doesn't define a deserialize function") }), this.combine = config.combine || null } add(match) { if (this.perNode) throw new RangeError("Can't add per-node props to node types"); return typeof match != "function" && (match = NodeType.match(match)), type => { let result = match(type); return result === void 0 ? null : [this, result] } } static { this.closedBy = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.openedBy = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.group = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.isolate = new _NodeProp({ deserialize: value => { if (value && value != "rtl" && value != "ltr" && value != "auto") throw new RangeError("Invalid value for isolate: " + value); return value || "auto" } }) } static { this.contextHash = new _NodeProp({ perNode: !0 }) } static { this.lookAhead = new _NodeProp({ perNode: !0 }) } static { this.mounted = new _NodeProp({ perNode: !0 }) } }, MountedTree = class { constructor(tree, overlay, parser, bracketed = !1) { this.tree = tree; this.overlay = overlay; this.parser = parser; this.bracketed = bracketed } static get(tree) { return tree && tree.props && tree.props[NodeProp.mounted.id] } }; var noProps = Object.create(null), NodeType = class _NodeType { constructor(name2, props, id, flags = 0) { this.name = name2; this.props = props; this.id = id; this.flags = flags } static define(spec) { let props = spec.props && spec.props.length ? Object.create(null) : noProps, flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0), type = new _NodeType(spec.name || "", props, spec.id, flags); if (spec.props) { for (let src of spec.props) if (Array.isArray(src) || (src = src(type)), src) { if (src[0].perNode) throw new RangeError("Can't store a per-node prop on a node type"); props[src[0].id] = src[1] } } return type } prop(prop) { return this.props[prop.id] } get isTop() { return (this.flags & 1) > 0 } get isSkipped() { return (this.flags & 2) > 0 } get isError() { return (this.flags & 4) > 0 } get isAnonymous() { return (this.flags & 8) > 0 } is(name2) { if (typeof name2 == "string") { if (this.name == name2) return !0; let group = this.prop(NodeProp.group); return group ? group.indexOf(name2) > -1 : !1 } return this.id == name2 } static { this.none = new _NodeType("", Object.create(null), 0, 8) } static match(map) { let direct = Object.create(null); for (let prop in map) for (let name2 of prop.split(" ")) direct[name2] = map[prop]; return node => { for (let groups = node.prop(NodeProp.group), i2 = -1; i2 < (groups ? groups.length : 0); i2++) { let found = direct[i2 < 0 ? node.name : groups[i2]]; if (found) return found } } } }, NodeSet = class _NodeSet { constructor(types2) { this.types = types2; for (let i2 = 0; i2 < types2.length; i2++)if (types2[i2].id != i2) throw new RangeError("Node type ids should correspond to array positions when creating a node set") } extend(...props) { let newTypes = []; for (let type of this.types) { let newProps = null; for (let source of props) { let add2 = source(type); if (add2) { newProps || (newProps = Object.assign({}, type.props)); let value = add2[1], prop = add2[0]; prop.combine && prop.id in newProps && (value = prop.combine(newProps[prop.id], value)), newProps[prop.id] = value } } newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type) } return new _NodeSet(newTypes) } }, CachedNode = new WeakMap, CachedInnerNode = new WeakMap; var Tree = class _Tree { constructor(type, children, positions, length, props) { this.type = type; this.children = children; this.positions = positions; this.length = length; this.props = null; if (props && props.length) { this.props = Object.create(null); for (let [prop, value] of props) this.props[typeof prop == "number" ? prop : prop.id] = value } } toString() { let mounted = MountedTree.get(this); if (mounted && !mounted.overlay) return mounted.tree.toString(); let children = ""; for (let ch of this.children) { let str = ch.toString(); str && (children && (children += ","), children += str) } return this.type.name ? (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "") : children } static { this.empty = new _Tree(NodeType.none, [], [], 0) } cursor(mode = 0) { return new TreeCursor(this.topNode, mode) } cursorAt(pos, side = 0, mode = 0) { let scope = CachedNode.get(this) || this.topNode, cursor = new TreeCursor(scope); return cursor.moveTo(pos, side), CachedNode.set(this, cursor._tree), cursor } get topNode() { return new TreeNode(this, 0, 0, null) } resolve(pos, side = 0) { let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, !1); return CachedNode.set(this, node), node } resolveInner(pos, side = 0) { let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, !0); return CachedInnerNode.set(this, node), node } resolveStack(pos, side = 0) { return stackIterator(this, pos, side) } iterate(spec) { let { enter, leave, from = 0, to = this.length } = spec, mode = spec.mode || 0, anon = (mode & 2) > 0; for (let c = this.cursor(mode | 2); ;) { let entered = !1; if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== !1)) { if (c.firstChild()) continue; entered = !0 } for (; entered && leave && (anon || !c.type.isAnonymous) && leave(c), !c.nextSibling();) { if (!c.parent()) return; entered = !0 } } } prop(prop) { return prop.perNode ? this.props ? this.props[prop.id] : void 0 : this.type.prop(prop) } get propValues() { let result = []; if (this.props) for (let id in this.props) result.push([+id, this.props[id]]); return result } balance(config = {}) { return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new _Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new _Tree(NodeType.none, children, positions, length))) } static build(data) { return buildTree(data) } }, FlatBufferCursor = class _FlatBufferCursor { constructor(buffer, index) { this.buffer = buffer; this.index = index } get id() { return this.buffer[this.index - 4] } get start() { return this.buffer[this.index - 3] } get end() { return this.buffer[this.index - 2] } get size() { return this.buffer[this.index - 1] } get pos() { return this.index } next() { this.index -= 4 } fork() { return new _FlatBufferCursor(this.buffer, this.index) } }, TreeBuffer = class _TreeBuffer { constructor(buffer, length, set) { this.buffer = buffer; this.length = length; this.set = set } get type() { return NodeType.none } toString() { let result = []; for (let index = 0; index < this.buffer.length;)result.push(this.childString(index)), index = this.buffer[index + 3]; return result.join(",") } childString(index) { let id = this.buffer[index], endIndex = this.buffer[index + 3], type = this.set.types[id], result = type.name; if (/\W/.test(result) && !type.isError && (result = JSON.stringify(result)), index += 4, endIndex == index) return result; let children = []; for (; index < endIndex;)children.push(this.childString(index)), index = this.buffer[index + 3]; return result + "(" + children.join(",") + ")" } findChild(startIndex, endIndex, dir, pos, side) { let { buffer } = this, pick = -1; for (let i2 = startIndex; i2 != endIndex && !(checkSide(side, pos, buffer[i2 + 1], buffer[i2 + 2]) && (pick = i2, dir > 0)); i2 = buffer[i2 + 3]); return pick } slice(startI, endI, from) { let b = this.buffer, copy = new Uint16Array(endI - startI), len = 0; for (let i2 = startI, j = 0; i2 < endI;) { copy[j++] = b[i2++], copy[j++] = b[i2++] - from; let to = copy[j++] = b[i2++] - from; copy[j++] = b[i2++] - startI, len = Math.max(len, to) } return new _TreeBuffer(copy, len, this.set) } }; function checkSide(side, pos, from, to) { switch (side) { case -2: return from < pos; case -1: return to >= pos && from < pos; case 0: return from < pos && to > pos; case 1: return from <= pos && to > pos; case 2: return to > pos; case 4: return !0 } } function resolveNode(node, pos, side, overlays) { for (; node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos);) { let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; if (!parent) return node; node = parent } let mode = overlays ? 0 : 8; if (overlays) for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent)scan instanceof TreeNode && scan.index < 0 && parent.enter(pos, side, mode)?.from != scan.from && (node = parent); for (; ;) { let inner = node.enter(pos, side, mode); if (!inner) return node; node = inner } } var BaseNode = class { cursor(mode = 0) { return new TreeCursor(this, mode) } getChild(type, before = null, after = null) { let r = getChildren(this, type, before, after); return r.length ? r[0] : null } getChildren(type, before = null, after = null) { return getChildren(this, type, before, after) } resolve(pos, side = 0) { return resolveNode(this, pos, side, !1) } resolveInner(pos, side = 0) { return resolveNode(this, pos, side, !0) } matchContext(context) { return matchNodeContext(this.parent, context) } enterUnfinishedNodesBefore(pos) { let scan = this.childBefore(pos), node = this; for (; scan;) { let last = scan.lastChild; if (!last || last.to != scan.to) break; last.type.isError && last.from == last.to ? (node = scan, scan = last.prevSibling) : scan = last } return node } get node() { return this } get next() { return this.parent } }, TreeNode = class _TreeNode extends BaseNode { constructor(_tree, from, index, _parent) { super(); this._tree = _tree; this.from = from; this.index = index; this._parent = _parent } get type() { return this._tree.type } get name() { return this._tree.type.name } get to() { return this.from + this._tree.length } nextChild(i2, dir, pos, side, mode = 0) { for (let parent = this; ;) { for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i2 != e; i2 += dir) { let next = children[i2], start = positions[i2] + parent.from, mounted; if (!(!(mode & 16 && next instanceof Tree && (mounted = MountedTree.get(next)) && !mounted.overlay && mounted.bracketed && pos >= start && pos <= start + next.length) && !checkSide(side, pos, start, start + next.length))) { if (next instanceof TreeBuffer) { if (mode & 1) continue; let index = next.findChild(0, next.buffer.length, dir, pos - start, side); if (index > -1) return new BufferNode(new BufferContext(parent, next, i2, start), null, index) } else if (mode & 2 || !next.type.isAnonymous || hasChild(next)) { let mounted2; if (!(mode & 4) && (mounted2 = MountedTree.get(next)) && !mounted2.overlay) return new _TreeNode(mounted2.tree, start, i2, parent); let inner = new _TreeNode(next, start, i2, parent); return mode & 2 || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode) } } } if (mode & 2 || !parent.type.isAnonymous || (parent.index >= 0 ? i2 = parent.index + dir : i2 = dir < 0 ? -1 : parent._parent._tree.children.length, parent = parent._parent, !parent)) return null } } get firstChild() { return this.nextChild(0, 1, 0, 4) } get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4) } childAfter(pos) { return this.nextChild(0, 1, pos, 2) } childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2) } prop(prop) { return this._tree.prop(prop) } enter(pos, side, mode = 0) { let mounted; if (!(mode & 8) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) { let rPos = pos - this.from, enterBracketed = mode & 16 && mounted.bracketed; for (let { from, to } of mounted.overlay) if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) && (side < 0 || enterBracketed ? to >= rPos : to > rPos)) return new _TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this) } return this.nextChild(0, 1, pos, side, mode) } nextSignificantParent() { let val = this; for (; val.type.isAnonymous && val._parent;)val = val._parent; return val } get parent() { return this._parent ? this._parent.nextSignificantParent() : null } get nextSibling() { return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null } get prevSibling() { return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null } get tree() { return this._tree } toTree() { return this._tree } toString() { return this._tree.toString() } }; function getChildren(node, type, before, after) { let cur = node.cursor(), result = []; if (!cur.firstChild()) return result; if (before != null) { for (let found = !1; !found;)if (found = cur.type.is(before), !cur.nextSibling()) return result } for (; ;) { if (after != null && cur.type.is(after)) return result; if (cur.type.is(type) && result.push(cur.node), !cur.nextSibling()) return after == null ? result : [] } } function matchNodeContext(node, context, i2 = context.length - 1) { for (let p = node; i2 >= 0; p = p.parent) { if (!p) return !1; if (!p.type.isAnonymous) { if (context[i2] && context[i2] != p.name) return !1; i2-- } } return !0 } var BufferContext = class { constructor(parent, buffer, index, start) { this.parent = parent; this.buffer = buffer; this.index = index; this.start = start } }, BufferNode = class _BufferNode extends BaseNode { constructor(context, _parent, index) { super(); this.context = context; this._parent = _parent; this.index = index; this.type = context.buffer.set.types[context.buffer.buffer[index]] } get name() { return this.type.name } get from() { return this.context.start + this.context.buffer.buffer[this.index + 1] } get to() { return this.context.start + this.context.buffer.buffer[this.index + 2] } child(dir, pos, side) { let { buffer } = this.context, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); return index < 0 ? null : new _BufferNode(this.context, this, index) } get firstChild() { return this.child(1, 0, 4) } get lastChild() { return this.child(-1, 0, 4) } childAfter(pos) { return this.child(1, pos, 2) } childBefore(pos) { return this.child(-1, pos, -2) } prop(prop) { return this.type.prop(prop) } enter(pos, side, mode = 0) { if (mode & 1) return null; let { buffer } = this.context, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); return index < 0 ? null : new _BufferNode(this.context, this, index) } get parent() { return this._parent || this.context.parent.nextSignificantParent() } externalSibling(dir) { return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4) } get nextSibling() { let { buffer } = this.context, after = buffer.buffer[this.index + 3]; return after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length) ? new _BufferNode(this.context, this._parent, after) : this.externalSibling(1) } get prevSibling() { let { buffer } = this.context, parentStart = this._parent ? this._parent.index + 4 : 0; return this.index == parentStart ? this.externalSibling(-1) : new _BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)) } get tree() { return null } toTree() { let children = [], positions = [], { buffer } = this.context, startI = this.index + 4, endI = buffer.buffer[this.index + 3]; if (endI > startI) { let from = buffer.buffer[this.index + 1]; children.push(buffer.slice(startI, endI, from)), positions.push(0) } return new Tree(this.type, children, positions, this.to - this.from) } toString() { return this.context.buffer.childString(this.index) } }; function iterStack(heads) { if (!heads.length) return null; let pick = 0, picked = heads[0]; for (let i2 = 1; i2 < heads.length; i2++) { let node = heads[i2]; (node.from > picked.from || node.to < picked.to) && (picked = node, pick = i2) } let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent, newHeads = heads.slice(); return next ? newHeads[pick] = next : newHeads.splice(pick, 1), new StackIterator(newHeads, picked) } var StackIterator = class { constructor(heads, node) { this.heads = heads; this.node = node } get next() { return iterStack(this.heads) } }; function stackIterator(tree, pos, side) { let inner = tree.resolveInner(pos, side), layers = null; for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent)if (scan.index < 0) { let parent = scan.parent; (layers || (layers = [inner])).push(parent.resolve(pos, side)), scan = parent } else { let mount = MountedTree.get(scan.tree); if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) { let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan); (layers || (layers = [inner])).push(resolveNode(root, pos, side, !1)) } } return layers ? iterStack(layers) : inner } var TreeCursor = class { constructor(node, mode = 0) { this.buffer = null; this.stack = []; this.index = 0; this.bufferNode = null; if (this.mode = mode & -17, node instanceof TreeNode) this.yieldNode(node); else { this._tree = node.context.parent, this.buffer = node.context; for (let n = node._parent; n; n = n._parent)this.stack.unshift(n.index); this.bufferNode = node, this.yieldBuf(node.index) } } get name() { return this.type.name } yieldNode(node) { return node ? (this._tree = node, this.type = node.type, this.from = node.from, this.to = node.to, !0) : !1 } yieldBuf(index, type) { this.index = index; let { start, buffer } = this.buffer; return this.type = type || buffer.set.types[buffer.buffer[index]], this.from = start + buffer.buffer[index + 1], this.to = start + buffer.buffer[index + 2], !0 } yield(node) { return node ? node instanceof TreeNode ? (this.buffer = null, this.yieldNode(node)) : (this.buffer = node.context, this.yieldBuf(node.index, node.type)) : !1 } toString() { return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString() } enterChild(dir, pos, side) { if (!this.buffer) return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); let { buffer } = this.buffer, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); return index < 0 ? !1 : (this.stack.push(this.index), this.yieldBuf(index)) } firstChild() { return this.enterChild(1, 0, 4) } lastChild() { return this.enterChild(-1, 0, 4) } childAfter(pos) { return this.enterChild(1, pos, 2) } childBefore(pos) { return this.enterChild(-1, pos, -2) } enter(pos, side, mode = this.mode) { return this.buffer ? mode & 1 ? !1 : this.enterChild(1, pos, side) : this.yield(this._tree.enter(pos, side, mode)) } parent() { if (!this.buffer) return this.yieldNode(this.mode & 2 ? this._tree._parent : this._tree.parent); if (this.stack.length) return this.yieldBuf(this.stack.pop()); let parent = this.mode & 2 ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); return this.buffer = null, this.yieldNode(parent) } sibling(dir) { if (!this.buffer) return this._tree._parent ? this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)) : !1; let { buffer } = this.buffer, d = this.stack.length - 1; if (dir < 0) { let parentStart = d < 0 ? 0 : this.stack[d] + 4; if (this.index != parentStart) return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)) } else { let after = buffer.buffer[this.index + 3]; if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) return this.yieldBuf(after) } return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : !1 } nextSibling() { return this.sibling(1) } prevSibling() { return this.sibling(-1) } atLastNode(dir) { let index, parent, { buffer } = this; if (buffer) { if (dir > 0) { if (this.index < buffer.buffer.buffer.length) return !1 } else for (let i2 = 0; i2 < this.index; i2++)if (buffer.buffer.buffer[i2 + 3] < this.index) return !1; ({ index, parent } = buffer) } else ({ index, _parent: parent } = this._tree); for (; parent; { index, _parent: parent } = parent)if (index > -1) for (let i2 = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i2 != e; i2 += dir) { let child = parent._tree.children[i2]; if (this.mode & 2 || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) return !1 } return !0 } move(dir, enter) { if (enter && this.enterChild(dir, 0, 4)) return !0; for (; ;) { if (this.sibling(dir)) return !0; if (this.atLastNode(dir) || !this.parent()) return !1 } } next(enter = !0) { return this.move(1, enter) } prev(enter = !0) { return this.move(-1, enter) } moveTo(pos, side = 0) { for (; (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) && this.parent();); for (; this.enterChild(1, pos, side);); return this } get node() { if (!this.buffer) return this._tree; let cache = this.bufferNode, result = null, depth2 = 0; if (cache && cache.context == this.buffer) scan: for (let index = this.index, d = this.stack.length; d >= 0;) { for (let c = cache; c; c = c._parent)if (c.index == index) { if (index == this.index) return c; result = c, depth2 = d + 1; break scan } index = this.stack[--d] } for (let i2 = depth2; i2 < this.stack.length; i2++)result = new BufferNode(this.buffer, result, this.stack[i2]); return this.bufferNode = new BufferNode(this.buffer, result, this.index) } get tree() { return this.buffer ? null : this._tree._tree } iterate(enter, leave) { for (let depth2 = 0; ;) { let mustLeave = !1; if (this.type.isAnonymous || enter(this) !== !1) { if (this.firstChild()) { depth2++; continue } this.type.isAnonymous || (mustLeave = !0) } for (; ;) { if (mustLeave && leave && leave(this), mustLeave = this.type.isAnonymous, !depth2) return; if (this.nextSibling()) break; this.parent(), depth2--, mustLeave = !0 } } } matchContext(context) { if (!this.buffer) return matchNodeContext(this.node.parent, context); let { buffer } = this.buffer, { types: types2 } = buffer.set; for (let i2 = context.length - 1, d = this.stack.length - 1; i2 >= 0; d--) { if (d < 0) return matchNodeContext(this._tree, context, i2); let type = types2[buffer.buffer[this.stack[d]]]; if (!type.isAnonymous) { if (context[i2] && context[i2] != type.name) return !1; i2-- } } return !0 } }; function hasChild(tree) { return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)) } function buildTree(data) { let { buffer, nodeSet: nodeSet2, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet2.types.length } = data, cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer, types2 = nodeSet2.types, contextHash = 0, lookAhead = 0; function takeNode(parentStart, minPos, children2, positions2, inRepeat, depth2) { let { id, start, end, size } = cursor, lookAheadAtStart = lookAhead, contextAtStart = contextHash; if (size < 0) if (cursor.next(), size == -1) { let node2 = reused[id]; children2.push(node2), positions2.push(start - parentStart); return } else if (size == -3) { contextHash = id; return } else if (size == -4) { lookAhead = id; return } else throw new RangeError(`Unrecognized record size: ${size}`); let type = types2[id], node, buffer2, startPos = start - parentStart; if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) { let data2 = new Uint16Array(buffer2.size - buffer2.skip), endPos = cursor.pos - buffer2.size, index = data2.length; for (; cursor.pos > endPos;)index = copyToBuffer(buffer2.start, data2, index); node = new TreeBuffer(data2, end - buffer2.start, nodeSet2), startPos = buffer2.start - parentStart } else { let endPos = cursor.pos - size; cursor.next(); let localChildren = [], localPositions = [], localInRepeat = id >= minRepeatType ? id : -1, lastGroup = 0, lastEnd = end; for (; cursor.pos > endPos;)localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0 ? (cursor.end <= lastEnd - maxBufferLength && (makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart), lastGroup = localChildren.length, lastEnd = cursor.end), cursor.next()) : depth2 > 2500 ? takeFlatNode(start, endPos, localChildren, localPositions) : takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth2 + 1); if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length && makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart), localChildren.reverse(), localPositions.reverse(), localInRepeat > -1 && lastGroup > 0) { let make = makeBalanced(type, contextAtStart); node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make) } else node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart) } children2.push(node), positions2.push(startPos) } function takeFlatNode(parentStart, minPos, children2, positions2) { let nodes = [], nodeCount = 0, stopAt = -1; for (; cursor.pos > minPos;) { let { id, start, end, size } = cursor; if (size > 4) cursor.next(); else { if (stopAt > -1 && start < stopAt) break; stopAt < 0 && (stopAt = end - maxBufferLength), nodes.push(id, start, end), nodeCount++, cursor.next() } } if (nodeCount) { let buffer2 = new Uint16Array(nodeCount * 4), start = nodes[nodes.length - 2]; for (let i2 = nodes.length - 3, j = 0; i2 >= 0; i2 -= 3)buffer2[j++] = nodes[i2], buffer2[j++] = nodes[i2 + 1] - start, buffer2[j++] = nodes[i2 + 2] - start, buffer2[j++] = j; children2.push(new TreeBuffer(buffer2, nodes[2] - start, nodeSet2)), positions2.push(start - parentStart) } } function makeBalanced(type, contextHash2) { return (children2, positions2, length2) => { let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) { if (!lastI && last.type == type && last.length == length2) return last; (lookAheadProp = last.prop(NodeProp.lookAhead)) && (lookAhead2 = positions2[lastI] + last.length + lookAheadProp) } return makeTree(type, children2, positions2, length2, lookAhead2, contextHash2) } } function makeRepeatLeaf(children2, positions2, base2, i2, from, to, type, lookAhead2, contextHash2) { let localChildren = [], localPositions = []; for (; children2.length > i2;)localChildren.push(children2.pop()), localPositions.push(positions2.pop() + base2 - from); children2.push(makeTree(nodeSet2.types[type], localChildren, localPositions, to - from, lookAhead2 - to, contextHash2)), positions2.push(from - base2) } function makeTree(type, children2, positions2, length2, lookAhead2, contextHash2, props) { if (contextHash2) { let pair = [NodeProp.contextHash, contextHash2]; props = props ? [pair].concat(props) : [pair] } if (lookAhead2 > 25) { let pair = [NodeProp.lookAhead, lookAhead2]; props = props ? [pair].concat(props) : [pair] } return new Tree(type, children2, positions2, length2, props) } function findBufferSize(maxSize, inRepeat) { let fork = cursor.fork(), size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength, result = { size: 0, start: 0, skip: 0 }; scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { let nodeSize2 = fork.size; if (fork.id == inRepeat && nodeSize2 >= 0) { result.size = size, result.start = start, result.skip = skip, skip += 4, size += 4, fork.next(); continue } let startPos = fork.pos - nodeSize2; if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart) break; let localSkipped = fork.id >= minRepeatType ? 4 : 0, nodeStart = fork.start; for (fork.next(); fork.pos > startPos;) { if (fork.size < 0) if (fork.size == -3 || fork.size == -4) localSkipped += 4; else break scan; else fork.id >= minRepeatType && (localSkipped += 4); fork.next() } start = nodeStart, size += nodeSize2, skip += localSkipped } return (inRepeat < 0 || size == maxSize) && (result.size = size, result.start = start, result.skip = skip), result.size > 4 ? result : void 0 } function copyToBuffer(bufferStart, buffer2, index) { let { id, start, end, size } = cursor; if (cursor.next(), size >= 0 && id < minRepeatType) { let startIndex = index; if (size > 4) { let endPos = cursor.pos - (size - 4); for (; cursor.pos > endPos;)index = copyToBuffer(bufferStart, buffer2, index) } buffer2[--index] = startIndex, buffer2[--index] = end - bufferStart, buffer2[--index] = start - bufferStart, buffer2[--index] = id } else size == -3 ? contextHash = id : size == -4 && (lookAhead = id); return index } let children = [], positions = []; for (; cursor.pos > 0;)takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0); let length = data.length ?? (children.length ? positions[0] + children[0].length : 0); return new Tree(types2[data.topID], children.reverse(), positions.reverse(), length) } var nodeSizeCache = new WeakMap; function nodeSize(balanceType, node) { if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) return 1; let size = nodeSizeCache.get(node); if (size == null) { size = 1; for (let child of node.children) { if (child.type != balanceType || !(child instanceof Tree)) { size = 1; break } size += nodeSize(balanceType, child) } nodeSizeCache.set(node, size) } return size } function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) { let total = 0; for (let i2 = from; i2 < to; i2++)total += nodeSize(balanceType, children[i2]); let maxChild = Math.ceil(total * 1.5 / 8), localChildren = [], localPositions = []; function divide(children2, positions2, from2, to2, offset) { for (let i2 = from2; i2 < to2;) { let groupFrom = i2, groupStart = positions2[i2], groupSize = nodeSize(balanceType, children2[i2]); for (i2++; i2 < to2; i2++) { let nextSize = nodeSize(balanceType, children2[i2]); if (groupSize + nextSize >= maxChild) break; groupSize += nextSize } if (i2 == groupFrom + 1) { if (groupSize > maxChild) { let only = children2[groupFrom]; divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset); continue } localChildren.push(children2[groupFrom]) } else { let length2 = positions2[i2 - 1] + children2[i2 - 1].length - groupStart; localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i2, groupStart, length2, null, mkTree)) } localPositions.push(groupStart + offset - start) } } return divide(children, positions, from, to, 0), (mkTop || mkTree)(localChildren, localPositions, length) } var TreeFragment = class _TreeFragment { constructor(from, to, tree, offset, openStart = !1, openEnd = !1) { this.from = from; this.to = to; this.tree = tree; this.offset = offset; this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0) } get openStart() { return (this.open & 1) > 0 } get openEnd() { return (this.open & 2) > 0 } static addTree(tree, fragments = [], partial = !1) { let result = [new _TreeFragment(0, tree.length, tree, 0, !1, partial)]; for (let f of fragments) f.to > tree.length && result.push(f); return result } static applyChanges(fragments, changes, minGap = 128) { if (!changes.length) return fragments; let result = [], fI = 1, nextF = fragments.length ? fragments[0] : null; for (let cI = 0, pos = 0, off = 0; ; cI++) { let nextC = cI < changes.length ? changes[cI] : null, nextPos = nextC ? nextC.fromA : 1e9; if (nextPos - pos >= minGap) for (; nextF && nextF.from < nextPos;) { let cut = nextF; if (pos >= cut.from || nextPos <= cut.to || off) { let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; cut = fFrom >= fTo ? null : new _TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC) } if (cut && result.push(cut), nextF.to > nextPos) break; nextF = fI < fragments.length ? fragments[fI++] : null } if (!nextC) break; pos = nextC.toA, off = nextC.toA - nextC.toB } return result } }, Parser = class { startParse(input, fragments, ranges) { return typeof input == "string" && (input = new StringInput(input)), ranges = ranges ? ranges.length ? ranges.map(r => new Range4(r.from, r.to)) : [new Range4(0, 0)] : [new Range4(0, input.length)], this.createParse(input, fragments || [], ranges) } parse(input, fragments, ranges) { let parse = this.startParse(input, fragments, ranges); for (; ;) { let done = parse.advance(); if (done) return done } } }, StringInput = class { constructor(string2) { this.string = string2 } get length() { return this.string.length } chunk(from) { return this.string.slice(from) } get lineChunks() { return !1 } read(from, to) { return this.string.slice(from, to) } }; var stoppedInner = new NodeProp({ perNode: !0 }); var languageDataProp = new NodeProp; function defineLanguageFacet(baseData) { return Facet.define({ combine: baseData ? values => values.concat(baseData) : void 0 }) } var sublanguageProp = new NodeProp, Language = class { constructor(data, parser, extraExtensions = [], name2 = "") { this.data = data; this.name = name2; EditorState.prototype.hasOwnProperty("tree") || Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this) } }), this.parser = parser, this.extension = [language.of(this), EditorState.languageData.of((state, pos, side) => { let top2 = topNodeAt(state, pos, side), data2 = top2.type.prop(languageDataProp); if (!data2) return []; let base2 = state.facet(data2), sub = top2.type.prop(sublanguageProp); if (sub) { let innerNode = top2.resolve(pos - top2.from, side); for (let sublang of sub) if (sublang.test(innerNode, state)) { let data3 = state.facet(sublang.facet); return sublang.type == "replace" ? data3 : data3.concat(base2) } } return base2 })].concat(extraExtensions) } data; name; extension; parser; isActiveAt(state, pos, side = -1) { return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data } findRegions(state) { let lang = state.facet(language); if (lang?.data == this.data) return [{ from: 0, to: state.doc.length }]; if (!lang || !lang.allowsNesting) return []; let result = [], explore = (tree, from) => { if (tree.prop(languageDataProp) == this.data) { result.push({ from, to: from + tree.length }); return } let mount = tree.prop(NodeProp.mounted); if (mount) { if (mount.tree.prop(languageDataProp) == this.data) { if (mount.overlay) for (let r of mount.overlay) result.push({ from: r.from + from, to: r.to + from }); else result.push({ from, to: from + tree.length }); return } else if (mount.overlay) { let size = result.length; if (explore(mount.tree, mount.overlay[0].from + from), result.length > size) return } } for (let i2 = 0; i2 < tree.children.length; i2++) { let ch = tree.children[i2]; ch instanceof Tree && explore(ch, tree.positions[i2] + from) } }; return explore(syntaxTree(state), 0), result } get allowsNesting() { return !0 } static state; static setState = StateEffect.define() }; function topNodeAt(state, pos, side) { let topLang = state.facet(language), tree = syntaxTree(state).topNode; if (!topLang || topLang.allowsNesting) for (let node = tree; node; node = node.enter(pos, side, 17))node.type.isTop && (tree = node); return tree } function syntaxTree(state) { let field = state.field(Language.state, !1); return field ? field.tree : Tree.empty } var DocInput = class { constructor(doc2) { this.doc = doc2; this.cursor = doc2.iter() } doc; cursor; cursorPos = 0; string = ""; get length() { return this.doc.length } syncTo(pos) { return this.string = this.cursor.next(pos - this.cursorPos).value, this.cursorPos = pos + this.string.length, this.cursorPos - this.string.length } chunk(pos) { return this.syncTo(pos), this.string } get lineChunks() { return !0 } read(from, to) { let stringStart = this.cursorPos - this.string.length; return from < stringStart || to >= this.cursorPos ? this.doc.sliceString(from, to) : this.string.slice(from - stringStart, to - stringStart) } }; var currentContext = null, ParseContext = class _ParseContext { constructor(parser, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) { this.parser = parser; this.state = state; this.fragments = fragments; this.tree = tree; this.treeLen = treeLen; this.viewport = viewport; this.skipped = skipped; this.scheduleOn = scheduleOn } parser; state; fragments; tree; treeLen; viewport; skipped; scheduleOn; parse = null; tempSkipped = []; static create(parser, state, viewport) { return new _ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null) } startParse() { return this.parser.startParse(new DocInput(this.state.doc), this.fragments) } work(until, upto) { return upto != null && upto >= this.state.doc.length && (upto = void 0), this.tree != Tree.empty && this.isDone(upto ?? this.state.doc.length) ? (this.takeTree(), !0) : this.withContext(() => { if (typeof until == "number") { let endTime = Date.now() + until; until = () => Date.now() > endTime } for (this.parse || (this.parse = this.startParse()), upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length && this.parse.stopAt(upto); ;) { let done = this.parse.advance(); if (done) if (this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)), this.treeLen = this.parse.stoppedAt ?? this.state.doc.length, this.tree = done, this.parse = null, this.treeLen < (upto ?? this.state.doc.length)) this.parse = this.startParse(); else return !0; if (until()) return !1 } }) } takeTree() { let pos, tree; this.parse && (pos = this.parse.parsedPos) >= this.treeLen && ((this.parse.stoppedAt == null || this.parse.stoppedAt > pos) && this.parse.stopAt(pos), this.withContext(() => { for (; !(tree = this.parse.advance());); }), this.treeLen = pos, this.tree = tree, this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, !0)), this.parse = null) } withContext(f) { let prev = currentContext; currentContext = this; try { return f() } finally { currentContext = prev } } withoutTempSkipped(fragments) { for (let r; r = this.tempSkipped.pop();)fragments = cutFragments(fragments, r.from, r.to); return fragments } changes(changes, newState) { let { fragments, tree, treeLen, viewport, skipped } = this; if (this.takeTree(), !changes.empty) { let ranges = []; if (changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })), fragments = TreeFragment.applyChanges(fragments, ranges), tree = Tree.empty, treeLen = 0, viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }, this.skipped.length) { skipped = []; for (let r of this.skipped) { let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); from < to && skipped.push({ from, to }) } } } return new _ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn) } updateViewport(viewport) { if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) return !1; this.viewport = viewport; let startLen = this.skipped.length; for (let i2 = 0; i2 < this.skipped.length; i2++) { let { from, to } = this.skipped[i2]; from < viewport.to && to > viewport.from && (this.fragments = cutFragments(this.fragments, from, to), this.skipped.splice(i2--, 1)) } return this.skipped.length >= startLen ? !1 : (this.reset(), !0) } reset() { this.parse && (this.takeTree(), this.parse = null) } skipUntilInView(from, to) { this.skipped.push({ from, to }) } static getSkippingParser(until) { return new class extends Parser { createParse(input, fragments, ranges) { let from = ranges[0].from, to = ranges[ranges.length - 1].to; return { parsedPos: from, advance() { let cx = currentContext; if (cx) { for (let r of ranges) cx.tempSkipped.push(r); until && (cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until) } return this.parsedPos = to, new Tree(NodeType.none, [], [], to - from) }, stoppedAt: null, stopAt() { } } } } } isDone(upto) { upto = Math.min(upto, this.state.doc.length); let frags = this.fragments; return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto } static get() { return currentContext } }; function cutFragments(fragments, from, to) { return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]) } var LanguageState = class _LanguageState { constructor(context) { this.context = context; this.tree = context.tree } context; tree; apply(tr) { if (!tr.docChanged && this.tree == this.context.tree) return this; let newCx = this.context.changes(tr.changes, tr.state), upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); return newCx.work(20, upto) || newCx.takeTree(), new _LanguageState(newCx) } static init(state) { let vpTo = Math.min(3e3, state.doc.length), parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo }); return parseState.work(20, vpTo) || parseState.takeTree(), new _LanguageState(parseState) } }; Language.state = StateField.define({ create: LanguageState.init, update(value, tr) { for (let e of tr.effects) if (e.is(Language.setState)) return e.value; return tr.startState.facet(language) != tr.state.facet(language) ? LanguageState.init(tr.state) : value.apply(tr) } }); var requestIdle = callback => { let timeout = setTimeout(() => callback(), 500); return () => clearTimeout(timeout) }; typeof requestIdleCallback < "u" && (requestIdle = callback => { let idle = -1, timeout = setTimeout(() => { idle = requestIdleCallback(callback, { timeout: 400 }) }, 100); return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle) }); var isInputPending = typeof navigator < "u" && navigator.scheduling?.isInputPending ? () => navigator.scheduling.isInputPending() : null, parseWorker = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.work = this.work.bind(this), this.scheduleWork() } view; working = null; workScheduled = 0; chunkEnd = -1; chunkBudget = -1; update(update) { let cx = this.view.state.field(Language.state).context; (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) && this.scheduleWork(), (update.docChanged || update.selectionSet) && (this.view.hasFocus && (this.chunkBudget += 50), this.scheduleWork()), this.checkAsyncSchedule(cx) } scheduleWork() { if (this.working) return; let { state } = this.view, field = state.field(Language.state); (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) && (this.working = requestIdle(this.work)) } work(deadline) { this.working = null; let now = Date.now(); if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus) && (this.chunkEnd = now + 3e4, this.chunkBudget = 3e3), this.chunkBudget <= 0) return; let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); if (field.tree == field.context.tree && field.context.isDone(vpTo + 1e5)) return; let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9), viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3, done = field.context.work(() => isInputPending && isInputPending() || Date.now() > endTime, vpTo + (viewportFirst ? 0 : 1e5)); this.chunkBudget -= Date.now() - now, (done || this.chunkBudget <= 0) && (field.context.takeTree(), this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) })), this.chunkBudget > 0 && !(done && !viewportFirst) && this.scheduleWork(), this.checkAsyncSchedule(field.context) } checkAsyncSchedule(cx) { cx.scheduleOn && (this.workScheduled++, cx.scheduleOn.then(() => this.scheduleWork()).catch(err => logException(this.view.state, err)).then(() => this.workScheduled--), cx.scheduleOn = null) } destroy() { this.working && this.working() } isWorking() { return !!(this.working || this.workScheduled > 0) } }, { eventHandlers: { focus() { this.scheduleWork() } } }), language = Facet.define({ combine(languages) { return languages.length ? languages[0] : null }, enables: language2 => [Language.state, parseWorker, EditorView.contentAttributes.compute([language2], state => { let lang = state.facet(language2); return lang && lang.name ? { "data-language": lang.name } : {} })] }), LanguageSupport = class { constructor(language2, support = []) { this.language = language2; this.support = support; this.extension = [language2, support] } language; support; extension }; var indentService = Facet.define(), indentUnit = Facet.define({ combine: values => { if (!values.length) return " "; let unit = values[0]; if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0])) throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); return unit } }); function getIndentUnit(state) { let unit = state.facet(indentUnit); return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length } function indentString(state, cols) { let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0]; if (ch == " ") { for (; cols >= ts;)result += " ", cols -= ts; ch = " " } for (let i2 = 0; i2 < cols; i2++)result += ch; return result } function getIndentation(context, pos) { context instanceof EditorState && (context = new IndentContext(context)); for (let service of context.state.facet(indentService)) { let result = service(context, pos); if (result !== void 0) return result } let tree = syntaxTree(context.state); return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null } var IndentContext = class { constructor(state, options = {}) { this.state = state; this.options = options; this.unit = getIndentUnit(state) } state; options; unit; lineAt(pos, bias = 1) { let line = this.state.doc.lineAt(pos), { simulateBreak, simulateDoubleBreak } = this.options; return simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to ? simulateDoubleBreak && simulateBreak == pos ? { text: "", from: pos } : (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) ? { text: line.text.slice(simulateBreak - line.from), from: simulateBreak } : { text: line.text.slice(0, simulateBreak - line.from), from: line.from } : line } textAfterPos(pos, bias = 1) { if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) return ""; let { text, from } = this.lineAt(pos, bias); return text.slice(pos - from, Math.min(text.length, pos + 100 - from)) } column(pos, bias = 1) { let { text, from } = this.lineAt(pos, bias), result = this.countColumn(text, pos - from), override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; return override > -1 && (result += override - this.countColumn(text, text.search(/\S|$/))), result } countColumn(line, pos = line.length) { return countColumn(line, this.state.tabSize, pos) } lineIndent(pos, bias = 1) { let { text, from } = this.lineAt(pos, bias), override = this.options.overrideIndentation; if (override) { let overriden = override(from); if (overriden > -1) return overriden } return this.countColumn(text, text.search(/\S|$/)) } get simulatedBreak() { return this.options.simulateBreak || null } }, indentNodeProp = new NodeProp; function syntaxIndentation(cx, ast, pos) { let stack = ast.resolveStack(pos), inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos); if (inner != stack.node) { let add2 = []; for (let cur = inner; cur && !(cur.from < stack.node.from || cur.to > stack.node.to || cur.from == stack.node.from && cur.type == stack.node.type); cur = cur.parent)add2.push(cur); for (let i2 = add2.length - 1; i2 >= 0; i2--)stack = { node: add2[i2], next: stack } } return indentFor(stack, cx, pos) } function indentFor(stack, cx, pos) { for (let cur = stack; cur; cur = cur.next) { let strategy = indentStrategy(cur.node); if (strategy) return strategy(TreeIndentContext.create(cx, pos, cur)) } return 0 } function ignoreClosed(cx) { return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak } function indentStrategy(tree) { let strategy = tree.type.prop(indentNodeProp); if (strategy) return strategy; let first = tree.firstChild, close; if (first && (close = first.type.prop(NodeProp.closedBy))) { let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; return cx => delimitedStrategy(cx, !0, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0) } return tree.parent == null ? topIndent : null } function topIndent() { return 0 } var TreeIndentContext = class _TreeIndentContext extends IndentContext { constructor(base2, pos, context) { super(base2.state, base2.options); this.base = base2; this.pos = pos; this.context = context } base; pos; context; get node() { return this.context.node } static create(base2, pos, context) { return new _TreeIndentContext(base2, pos, context) } get textAfter() { return this.textAfterPos(this.pos) } get baseIndent() { return this.baseIndentFor(this.node) } baseIndentFor(node) { let line = this.state.doc.lineAt(node.from); for (; ;) { let atBreak = node.resolve(line.from); for (; atBreak.parent && atBreak.parent.from == atBreak.from;)atBreak = atBreak.parent; if (isParent(atBreak, node)) break; line = this.state.doc.lineAt(atBreak.from) } return this.lineIndent(line.from) } continue() { return indentFor(this.context.next, this.base, this.pos) } }; function isParent(parent, of) { for (let cur = of; cur; cur = cur.parent)if (parent == cur) return !0; return !1 } function bracketedAligned(context) { let tree = context.node, openToken = tree.childAfter(tree.from), last = tree.lastChild; if (!openToken) return null; let sim = context.options.simulateBreak, openLine = context.state.doc.lineAt(openToken.from), lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); for (let pos = openToken.to; ;) { let next = tree.childAfter(pos); if (!next || next == last) return null; if (!next.type.isSkipped) { if (next.from >= lineEnd) return null; let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length; return { from: openToken.from, to: openToken.to + space } } pos = next.to } } function delimitedStrategy(context, align, units, closing, closedAt) { let after = context.textAfter, space = after.match(/^\s*/)[0].length, closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space, aligned = align ? bracketedAligned(context) : null; return aligned ? closed ? context.column(aligned.from) : context.column(aligned.to) : context.baseIndent + (closed ? 0 : context.unit * units) } var foldService = Facet.define(), foldNodeProp = new NodeProp; function syntaxFolding(state, start, end) { let tree = syntaxTree(state); if (tree.length < end) return null; let stack = tree.resolveStack(end, 1), found = null; for (let iter = stack; iter; iter = iter.next) { let cur = iter.node; if (cur.to <= end || cur.from > end) continue; if (found && cur.from < start) break; let prop = cur.type.prop(foldNodeProp); if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { let value = prop(cur, state); value && value.from <= end && value.from >= start && value.to > end && (found = value) } } return found } function isUnfinished(node) { let ch = node.lastChild; return ch && ch.to == node.to && ch.type.isError } function foldable(state, lineStart, lineEnd) { for (let service of state.facet(foldService)) { let result = service(state, lineStart, lineEnd); if (result) return result } return syntaxFolding(state, lineStart, lineEnd) } function mapRange(range, mapping) { let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); return from >= to ? void 0 : { from, to } } var foldEffect = StateEffect.define({ map: mapRange }), unfoldEffect = StateEffect.define({ map: mapRange }); function selectedLines(view) { let lines = []; for (let { head } of view.state.selection.ranges) lines.some(l => l.from <= head && l.to >= head) || lines.push(view.lineBlockAt(head)); return lines } var foldState = StateField.define({ create() { return Decoration.none }, update(folded, tr) { tr.isUserEvent("delete") && tr.changes.iterChangedRanges((fromA, toA) => folded = clearTouchedFolds(folded, fromA, toA)), folded = folded.map(tr.changes); for (let e of tr.effects) if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) { let { preparePlaceholder } = tr.state.facet(foldConfig), widget = preparePlaceholder ? Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) }) : foldWidget; folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] }) } else e.is(unfoldEffect) && (folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, filterFrom: e.value.from, filterTo: e.value.to })); return tr.selection && (folded = clearTouchedFolds(folded, tr.selection.main.head)), folded }, provide: f => EditorView.decorations.from(f), toJSON(folded, state) { let ranges = []; return folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to) }), ranges }, fromJSON(value) { if (!Array.isArray(value) || value.length % 2) throw new RangeError("Invalid JSON for fold state"); let ranges = []; for (let i2 = 0; i2 < value.length;) { let from = value[i2++], to = value[i2++]; if (typeof from != "number" || typeof to != "number") throw new RangeError("Invalid JSON for fold state"); ranges.push(foldWidget.range(from, to)) } return Decoration.set(ranges, !0) } }); function clearTouchedFolds(folded, from, to = from) { let touched = !1; return folded.between(from, to, (a, b) => { a < to && b > from && (touched = !0) }), touched ? folded.update({ filterFrom: from, filterTo: to, filter: (a, b) => a >= to || b <= from }) : folded } function findFold(state, from, to) { let found = null; return state.field(foldState, !1)?.between(from, to, (from2, to2) => { (!found || found.from > from2) && (found = { from: from2, to: to2 }) }), found } function foldExists(folded, from, to) { let found = !1; return folded.between(from, from, (a, b) => { a == from && b == to && (found = !0) }), found } function maybeEnable(state, other) { return state.field(foldState, !1) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())) } var foldCode = view => { for (let line of selectedLines(view)) { let range = foldable(view.state, line.from, line.to); if (range) return view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }), !0 } return !1 }, unfoldCode = view => { if (!view.state.field(foldState, !1)) return !1; let effects = []; for (let line of selectedLines(view)) { let folded = findFold(view.state, line.from, line.to); folded && effects.push(unfoldEffect.of(folded), announceFold(view, folded, !1)) } return effects.length && view.dispatch({ effects }), effects.length > 0 }; function announceFold(view, range, fold = !0) { let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`) } var foldAll = view => { let { state } = view, effects = []; for (let pos = 0; pos < state.doc.length;) { let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); range && effects.push(foldEffect.of(range)), pos = (range ? view.lineBlockAt(range.to) : line).to + 1 } return effects.length && view.dispatch({ effects: maybeEnable(view.state, effects) }), !!effects.length }, unfoldAll = view => { let field = view.state.field(foldState, !1); if (!field || !field.size) return !1; let effects = []; return field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })) }), view.dispatch({ effects }), !0 }; var foldKeymap = [{ key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, { key: "Ctrl-Alt-[", run: foldAll }, { key: "Ctrl-Alt-]", run: unfoldAll }], defaultConfig = { placeholderDOM: null, preparePlaceholder: null, placeholderText: "\u2026" }, foldConfig = Facet.define({ combine(values) { return combineConfig(values, defaultConfig) } }); function codeFolding(config) { let result = [foldState, baseTheme3]; return config && result.push(foldConfig.of(config)), result } function widgetToDOM(view, prepared) { let { state } = view, conf = state.facet(foldConfig), onclick = event => { let line = view.lineBlockAt(view.posAtDOM(event.target)), folded = findFold(view.state, line.from, line.to); folded && view.dispatch({ effects: unfoldEffect.of(folded) }), event.preventDefault() }; if (conf.placeholderDOM) return conf.placeholderDOM(view, onclick, prepared); let element = document.createElement("span"); return element.textContent = conf.placeholderText, element.setAttribute("aria-label", state.phrase("folded code")), element.title = state.phrase("unfold"), element.className = "cm-foldPlaceholder", element.onclick = onclick, element } var foldWidget = Decoration.replace({ widget: new class extends WidgetType { toDOM(view) { return widgetToDOM(view, null) } } }), PreparedFoldWidget = class extends WidgetType { constructor(value) { super(); this.value = value } value; eq(other) { return this.value == other.value } toDOM(view) { return widgetToDOM(view, this.value) } }, foldGutterDefaults = { openText: "\u2304", closedText: "\u203A", markerDOM: null, domEventHandlers: {}, foldingChanged: () => !1 }, FoldMarker = class extends GutterMarker { constructor(config, open) { super(); this.config = config; this.open = open } config; open; eq(other) { return this.config == other.config && this.open == other.open } toDOM(view) { if (this.config.markerDOM) return this.config.markerDOM(this.open); let span = document.createElement("span"); return span.textContent = this.open ? this.config.openText : this.config.closedText, span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"), span } }; function foldGutter(config = {}) { let fullConfig = { ...foldGutterDefaults, ...config }, canFold = new FoldMarker(fullConfig, !0), canUnfold = new FoldMarker(fullConfig, !1), markers = ViewPlugin.fromClass(class { markers; from; constructor(view) { this.from = view.viewport.from, this.markers = this.buildMarkers(view) } update(update) { (update.docChanged || update.viewportChanged || update.startState.facet(language) != update.state.facet(language) || update.startState.field(foldState, !1) != update.state.field(foldState, !1) || syntaxTree(update.startState) != syntaxTree(update.state) || fullConfig.foldingChanged(update)) && (this.markers = this.buildMarkers(update.view)) } buildMarkers(view) { let builder = new RangeSetBuilder; for (let line of view.viewportLineBlocks) { let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null; mark && builder.add(line.from, line.from, mark) } return builder.finish() } }), { domEventHandlers } = fullConfig; return [markers, gutter({ class: "cm-foldGutter", markers(view) { return view.plugin(markers)?.markers || RangeSet.empty }, initialSpacer() { return new FoldMarker(fullConfig, !1) }, domEventHandlers: { ...domEventHandlers, click: (view, line, event) => { if (domEventHandlers.click && domEventHandlers.click(view, line, event)) return !0; let folded = findFold(view.state, line.from, line.to); if (folded) return view.dispatch({ effects: unfoldEffect.of(folded) }), !0; let range = foldable(view.state, line.from, line.to); return range ? (view.dispatch({ effects: foldEffect.of(range) }), !0) : !1 } } }), codeFolding()] } var baseTheme3 = EditorView.baseTheme({ ".cm-foldPlaceholder": { backgroundColor: "#eee", border: "1px solid #ddd", color: "#888", borderRadius: ".2em", margin: "0 1px", padding: "0 1px", cursor: "pointer" }, ".cm-foldGutter span": { padding: "0 1px", cursor: "pointer" } }); var nextTagID = 0, Tag = class _Tag { constructor(name2, set, base2, modified) { this.name = name2; this.set = set; this.base = base2; this.modified = modified } name; set; base; modified; id = nextTagID++; toString() { let { name: name2 } = this; for (let mod of this.modified) mod.name && (name2 = `${mod.name}(${name2})`); return name2 } static define(nameOrParent, parent) { let name2 = typeof nameOrParent == "string" ? nameOrParent : "?"; if (nameOrParent instanceof _Tag && (parent = nameOrParent), parent?.base) throw new Error("Can not derive from a modified tag"); let tag = new _Tag(name2, [], null, []); if (tag.set.push(tag), parent) for (let t2 of parent.set) tag.set.push(t2); return tag } static defineModifier(name2) { let mod = new Modifier(name2); return tag => tag.modified.indexOf(mod) > -1 ? tag : Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)) } }, nextModifierID = 0, Modifier = class _Modifier { constructor(name2) { this.name = name2 } name; instances = []; id = nextModifierID++; static get(base2, mods) { if (!mods.length) return base2; let exists = mods[0].instances.find(t2 => t2.base == base2 && sameArray2(mods, t2.modified)); if (exists) return exists; let set = [], tag = new Tag(base2.name, set, base2, mods); for (let m of mods) m.instances.push(tag); let configs = powerSet(mods); for (let parent of base2.set) if (!parent.modified.length) for (let config of configs) set.push(_Modifier.get(parent, config)); return tag } }; function sameArray2(a, b) { return a.length == b.length && a.every((x, i2) => x == b[i2]) } function powerSet(array) { let sets = [[]]; for (let i2 = 0; i2 < array.length; i2++)for (let j = 0, e = sets.length; j < e; j++)sets.push(sets[j].concat(array[i2])); return sets.sort((a, b) => b.length - a.length) } function styleTags(spec) { let byName = Object.create(null); for (let prop in spec) { let tags2 = spec[prop]; Array.isArray(tags2) || (tags2 = [tags2]); for (let part of prop.split(" ")) if (part) { let pieces = [], mode = 2, rest = part; for (let pos = 0; ;) { if (rest == "..." && pos > 0 && pos + 3 == part.length) { mode = 1; break } let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); if (!m) throw new RangeError("Invalid path: " + part); if (pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]), pos += m[0].length, pos == part.length) break; let next = part[pos++]; if (pos == part.length && next == "!") { mode = 0; break } if (next != "/") throw new RangeError("Invalid path: " + part); rest = part.slice(pos) } let last = pieces.length - 1, inner = pieces[last]; if (!inner) throw new RangeError("Invalid path: " + part); let rule = new Rule(tags2, mode, last > 0 ? pieces.slice(0, last) : null); byName[inner] = rule.sort(byName[inner]) } } return ruleNodeProp.add(byName) } var ruleNodeProp = new NodeProp({ combine(a, b) { let cur, root, take; for (; a || b;) { if (!a || b && a.depth >= b.depth ? (take = b, b = b.next) : (take = a, a = a.next), cur && cur.mode == take.mode && !take.context && !cur.context) continue; let copy = new Rule(take.tags, take.mode, take.context); cur ? cur.next = copy : root = copy, cur = copy } return root } }); var Rule = class _Rule { constructor(tags2, mode, context, next) { this.tags = tags2; this.mode = mode; this.context = context; this.next = next } tags; mode; context; next; get opaque() { return this.mode == 0 } get inherit() { return this.mode == 1 } sort(other) { return !other || other.depth < this.depth ? (this.next = other, this) : (other.next = this.sort(other.next), other) } get depth() { return this.context ? this.context.length : 0 } static empty = new _Rule([], 2, null) }; function tagHighlighter(tags2, options) { let map = Object.create(null); for (let style of tags2) if (!Array.isArray(style.tag)) map[style.tag.id] = style.class; else for (let tag of style.tag) map[tag.id] = style.class; let { scope, all = null } = options || {}; return { style: tags3 => { let cls = all; for (let tag of tags3) for (let sub of tag.set) { let tagClass = map[sub.id]; if (tagClass) { cls = cls ? cls + " " + tagClass : tagClass; break } } return cls }, scope } } function highlightTags(highlighters, tags2) { let result = null; for (let highlighter of highlighters) { let value = highlighter.style(tags2); value && (result = result ? result + " " + value : value) } return result } function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) { let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle); builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters), builder.flush(to) } var HighlightBuilder = class { constructor(at, highlighters, span) { this.at = at; this.highlighters = highlighters; this.span = span } at; highlighters; span; class = ""; startSpan(at, cls) { cls != this.class && (this.flush(at), at > this.at && (this.at = at), this.class = cls) } flush(to) { to > this.at && this.class && this.span(this.at, to, this.class) } highlightRange(cursor, from, to, inheritedClass, highlighters) { let { type, from: start, to: end } = cursor; if (start >= to || end <= from) return; type.isTop && (highlighters = this.highlighters.filter(h => !h.scope || h.scope(type))); let cls = inheritedClass, rule = getStyleTags(cursor) || Rule.empty, tagCls = highlightTags(highlighters, rule.tags); if (tagCls && (cls && (cls += " "), cls += tagCls, rule.mode == 1 && (inheritedClass += (inheritedClass ? " " : "") + tagCls)), this.startSpan(Math.max(from, start), cls), rule.opaque) return; let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); if (mounted && mounted.overlay) { let inner = cursor.node.enter(mounted.overlay[0].from + start, 1), innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type)), hasChild2 = cursor.firstChild(); for (let i2 = 0, pos = start; ; i2++) { let next = i2 < mounted.overlay.length ? mounted.overlay[i2] : null, nextPos = next ? next.from + start : end, rangeFrom2 = Math.max(from, pos), rangeTo2 = Math.min(to, nextPos); if (rangeFrom2 < rangeTo2 && hasChild2) for (; cursor.from < rangeTo2 && (this.highlightRange(cursor, rangeFrom2, rangeTo2, inheritedClass, highlighters), this.startSpan(Math.min(rangeTo2, cursor.to), cls), !(cursor.to >= nextPos || !cursor.nextSibling()));); if (!next || nextPos > to) break; pos = next.to + start, pos > from && (this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters), this.startSpan(Math.min(to, pos), cls)) } hasChild2 && cursor.parent() } else if (cursor.firstChild()) { mounted && (inheritedClass = ""); do if (!(cursor.to <= from)) { if (cursor.from >= to) break; this.highlightRange(cursor, from, to, inheritedClass, highlighters), this.startSpan(Math.min(to, cursor.to), cls) } while (cursor.nextSibling()); cursor.parent() } } }; function getStyleTags(node) { let rule = node.type.prop(ruleNodeProp); for (; rule && rule.context && !node.matchContext(rule.context);)rule = rule.next; return rule || null } var t = Tag.define, comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t(), tags = { comment, lineComment: t(comment), blockComment: t(comment), docComment: t(comment), name, variableName: t(name), typeName, tagName: t(typeName), propertyName, attributeName: t(propertyName), className: t(name), labelName: t(name), namespace: t(name), macroName: t(name), literal, string, docString: t(string), character: t(string), attributeValue: t(string), number, integer: t(number), float: t(number), bool: t(literal), regexp: t(literal), escape: t(literal), color: t(literal), url: t(literal), keyword, self: t(keyword), null: t(keyword), atom: t(keyword), unit: t(keyword), modifier: t(keyword), operatorKeyword: t(keyword), controlKeyword: t(keyword), definitionKeyword: t(keyword), moduleKeyword: t(keyword), operator, derefOperator: t(operator), arithmeticOperator: t(operator), logicOperator: t(operator), bitwiseOperator: t(operator), compareOperator: t(operator), updateOperator: t(operator), definitionOperator: t(operator), typeOperator: t(operator), controlOperator: t(operator), punctuation, separator: t(punctuation), bracket, angleBracket: t(bracket), squareBracket: t(bracket), paren: t(bracket), brace: t(bracket), content, heading, heading1: t(heading), heading2: t(heading), heading3: t(heading), heading4: t(heading), heading5: t(heading), heading6: t(heading), contentSeparator: t(content), list: t(content), quote: t(content), emphasis: t(content), strong: t(content), link: t(content), monospace: t(content), strikethrough: t(content), inserted: t(), deleted: t(), changed: t(), invalid: t(), meta, documentMeta: t(meta), annotation: t(meta), processingInstruction: t(meta), definition: Tag.defineModifier("definition"), constant: Tag.defineModifier("constant"), function: Tag.defineModifier("function"), standard: Tag.defineModifier("standard"), local: Tag.defineModifier("local"), special: Tag.defineModifier("special") }; for (let name2 in tags) { let val = tags[name2]; val instanceof Tag && (val.name = name2) } var classHighlighter = tagHighlighter([{ tag: tags.link, class: "tok-link" }, { tag: tags.heading, class: "tok-heading" }, { tag: tags.emphasis, class: "tok-emphasis" }, { tag: tags.strong, class: "tok-strong" }, { tag: tags.keyword, class: "tok-keyword" }, { tag: tags.atom, class: "tok-atom" }, { tag: tags.bool, class: "tok-bool" }, { tag: tags.url, class: "tok-url" }, { tag: tags.labelName, class: "tok-labelName" }, { tag: tags.inserted, class: "tok-inserted" }, { tag: tags.deleted, class: "tok-deleted" }, { tag: tags.literal, class: "tok-literal" }, { tag: tags.string, class: "tok-string" }, { tag: tags.number, class: "tok-number" }, { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, { tag: tags.variableName, class: "tok-variableName" }, { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, { tag: tags.special(tags.variableName), class: "tok-variableName2" }, { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, { tag: tags.typeName, class: "tok-typeName" }, { tag: tags.namespace, class: "tok-namespace" }, { tag: tags.className, class: "tok-className" }, { tag: tags.macroName, class: "tok-macroName" }, { tag: tags.propertyName, class: "tok-propertyName" }, { tag: tags.operator, class: "tok-operator" }, { tag: tags.comment, class: "tok-comment" }, { tag: tags.meta, class: "tok-meta" }, { tag: tags.invalid, class: "tok-invalid" }, { tag: tags.punctuation, class: "tok-punctuation" }]); var HighlightStyle = class _HighlightStyle { constructor(specs, options) { this.specs = specs; let modSpec; function def(spec) { let cls = StyleModule.newName(); return (modSpec || (modSpec = Object.create(null)))["." + cls] = spec, cls } let all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : void 0, scopeOpt = options.scope; this.scope = scopeOpt instanceof Language ? type => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? type => type == scopeOpt : void 0, this.style = tagHighlighter(specs.map(style => ({ tag: style.tag, class: style.class || def(Object.assign({}, style, { tag: null })) })), { all }).style, this.module = modSpec ? new StyleModule(modSpec) : null, this.themeType = options.themeType } specs; module; themeType; style; scope; static define(specs, options) { return new _HighlightStyle(specs, options || {}) } }, highlighterFacet = Facet.define(), fallbackHighlighter = Facet.define({ combine(values) { return values.length ? [values[0]] : null } }); function getHighlighters(state) { let main = state.facet(highlighterFacet); return main.length ? main : state.facet(fallbackHighlighter) } function syntaxHighlighting(highlighter, options) { let ext = [treeHighlighter], themeType; return highlighter instanceof HighlightStyle && (highlighter.module && ext.push(EditorView.styleModule.of(highlighter.module)), themeType = highlighter.themeType), options?.fallback ? ext.push(fallbackHighlighter.of(highlighter)) : themeType ? ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [])) : ext.push(highlighterFacet.of(highlighter)), ext } var TreeHighlighter = class { decorations; decoratedTo; tree; markCache = Object.create(null); constructor(view) { this.tree = syntaxTree(view.state), this.decorations = this.buildDeco(view, getHighlighters(view.state)), this.decoratedTo = view.viewport.to } update(update) { let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state), styleChange = highlighters != getHighlighters(update.startState), { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1); tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to ? (this.decorations = this.decorations.map(update.changes), this.decoratedTo = decoratedToMapped) : (tree != this.tree || update.viewportChanged || styleChange) && (this.tree = tree, this.decorations = this.buildDeco(update.view, highlighters), this.decoratedTo = viewport.to) } buildDeco(view, highlighters) { if (!highlighters || !this.tree.length) return Decoration.none; let builder = new RangeSetBuilder; for (let { from, to } of view.visibleRanges) highlightTree(this.tree, highlighters, (from2, to2, style) => { builder.add(from2, to2, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))) }, from, to); return builder.finish() } }, treeHighlighter = Prec.high(ViewPlugin.fromClass(TreeHighlighter, { decorations: v => v.decorations })), defaultHighlightStyle = HighlightStyle.define([{ tag: tags.meta, color: "#404740" }, { tag: tags.link, textDecoration: "underline" }, { tag: tags.heading, textDecoration: "underline", fontWeight: "bold" }, { tag: tags.emphasis, fontStyle: "italic" }, { tag: tags.strong, fontWeight: "bold" }, { tag: tags.strikethrough, textDecoration: "line-through" }, { tag: tags.keyword, color: "#708" }, { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], color: "#219" }, { tag: [tags.literal, tags.inserted], color: "#164" }, { tag: [tags.string, tags.deleted], color: "#a11" }, { tag: [tags.regexp, tags.escape, tags.special(tags.string)], color: "#e40" }, { tag: tags.definition(tags.variableName), color: "#00f" }, { tag: tags.local(tags.variableName), color: "#30a" }, { tag: [tags.typeName, tags.namespace], color: "#085" }, { tag: tags.className, color: "#167" }, { tag: [tags.special(tags.variableName), tags.macroName], color: "#256" }, { tag: tags.definition(tags.propertyName), color: "#00c" }, { tag: tags.comment, color: "#940" }, { tag: tags.invalid, color: "#f00" }]); var baseTheme4 = EditorView.baseTheme({ "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } }), DefaultScanDist = 1e4, DefaultBrackets = "()[]{}", bracketMatchingConfig = Facet.define({ combine(configs) { return combineConfig(configs, { afterCursor: !0, brackets: DefaultBrackets, maxScanDistance: DefaultScanDist, renderMatch: defaultRenderMatch }) } }), matchingMark = Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = Decoration.mark({ class: "cm-nonmatchingBracket" }); function defaultRenderMatch(match) { let decorations2 = [], mark = match.matched ? matchingMark : nonmatchingMark; return decorations2.push(mark.range(match.start.from, match.start.to)), match.end && decorations2.push(mark.range(match.end.from, match.end.to)), decorations2 } function bracketDeco(state) { let decorations2 = [], config = state.facet(bracketMatchingConfig); for (let range of state.selection.ranges) { if (!range.empty) continue; let match = matchBrackets(state, range.head, -1, config) || range.head > 0 && matchBrackets(state, range.head - 1, 1, config) || config.afterCursor && (matchBrackets(state, range.head, 1, config) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1, config)); match && (decorations2 = decorations2.concat(config.renderMatch(match, state))) } return Decoration.set(decorations2, !0) } var bracketMatcher = ViewPlugin.fromClass(class { decorations; paused = !1; constructor(view) { this.decorations = bracketDeco(view.state) } update(update) { (update.docChanged || update.selectionSet || this.paused) && (update.view.composing ? (this.decorations = this.decorations.map(update.changes), this.paused = !0) : (this.decorations = bracketDeco(update.state), this.paused = !1)) } }, { decorations: v => v.decorations }), bracketMatchingUnique = [bracketMatcher, baseTheme4]; function bracketMatching(config = {}) { return [bracketMatchingConfig.of(config), bracketMatchingUnique] } var bracketMatchingHandle = new NodeProp; function matchingNodes(node, dir, brackets) { let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); if (byProp) return byProp; if (node.name.length == 1) { let index = brackets.indexOf(node.name); if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) return [brackets[index + dir]] } return null } function findHandle(node) { let hasHandle = node.type.prop(bracketMatchingHandle); return hasHandle ? hasHandle(node.node) : node } function matchBrackets(state, pos, dir, config = {}) { let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets, tree = syntaxTree(state), node = tree.resolveInner(pos, dir); for (let cur = node; cur; cur = cur.parent) { let matches = matchingNodes(cur.type, dir, brackets); if (matches && cur.from < cur.to) { let handle = findHandle(cur); if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to)) return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets) } } return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets) } function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) { let parent = token.parent, firstToken = { from: handle.from, to: handle.to }, depth2 = 0, cursor = parent?.cursor(); if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) do if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { if (depth2 == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { let endHandle = findHandle(cursor); return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : void 0, matched: !0 } } else if (matchingNodes(cursor.type, dir, brackets)) depth2++; else if (matchingNodes(cursor.type, -dir, brackets)) { if (depth2 == 0) { let endHandle = findHandle(cursor); return { start: firstToken, end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0, matched: !1 } } depth2-- } } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); return { start: firstToken, matched: !1 } } function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { if (dir < 0 ? !pos : pos == state.doc.length) return null; let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1), bracket2 = brackets.indexOf(startCh); if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0) return null; let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }, iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth2 = 0; for (let distance = 0; !iter.next().done && distance <= maxScanDistance;) { let text = iter.value; dir < 0 && (distance += text.length); let basePos = pos + distance * dir; for (let pos2 = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos2 != end; pos2 += dir) { let found = brackets.indexOf(text[pos2]); if (!(found < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType)) if (found % 2 == 0 == dir > 0) depth2++; else { if (depth2 == 1) return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found >> 1 == bracket2 >> 1 }; depth2-- } } dir > 0 && (distance += text.length) } return iter.done ? { start: startToken, matched: !1 } : null } function countCol(string2, end, tabSize, startIndex = 0, startValue = 0) { end == null && (end = string2.search(/[^\s\u00a0]/), end == -1 && (end = string2.length)); let n = startValue; for (let i2 = startIndex; i2 < end; i2++)string2.charCodeAt(i2) == 9 ? n += tabSize - n % tabSize : n++; return n } var StringStream = class { constructor(string2, tabSize, indentUnit2, overrideIndent) { this.string = string2; this.tabSize = tabSize; this.indentUnit = indentUnit2; this.overrideIndent = overrideIndent } string; tabSize; indentUnit; overrideIndent; pos = 0; start = 0; lastColumnPos = 0; lastColumnValue = 0; eol() { return this.pos >= this.string.length } sol() { return this.pos == 0 } peek() { return this.string.charAt(this.pos) || void 0 } next() { if (this.pos < this.string.length) return this.string.charAt(this.pos++) } eat(match) { let ch = this.string.charAt(this.pos), ok; if (typeof match == "string" ? ok = ch == match : ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch)), ok) return ++this.pos, ch } eatWhile(match) { let start = this.pos; for (; this.eat(match);); return this.pos > start } eatSpace() { let start = this.pos; for (; /[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos; return this.pos > start } skipToEnd() { this.pos = this.string.length } skipTo(ch) { let found = this.string.indexOf(ch, this.pos); if (found > -1) return this.pos = found, !0 } backUp(n) { this.pos -= n } column() { return this.lastColumnPos < this.start && (this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue), this.lastColumnPos = this.start), this.lastColumnValue } indentation() { return this.overrideIndent ?? countCol(this.string, null, this.tabSize) } match(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { let cased = str => caseInsensitive ? str.toLowerCase() : str, substr = this.string.substr(this.pos, pattern.length); return cased(substr) == cased(pattern) ? (consume !== !1 && (this.pos += pattern.length), !0) : null } else { let match = this.string.slice(this.pos).match(pattern); return match && match.index > 0 ? null : (match && consume !== !1 && (this.pos += match[0].length), match) } } current() { return this.string.slice(this.start, this.pos) } }; function fullParser(spec) { return { name: spec.name || "", token: spec.token, blankLine: spec.blankLine || (() => { }), startState: spec.startState || (() => !0), copyState: spec.copyState || defaultCopyState, indent: spec.indent || (() => null), languageData: spec.languageData || {}, tokenTable: spec.tokenTable || noTokens, mergeTokens: spec.mergeTokens !== !1 } } function defaultCopyState(state) { if (typeof state != "object") return state; let newState = {}; for (let prop in state) { let val = state[prop]; newState[prop] = val instanceof Array ? val.slice() : val } return newState } var IndentedFrom = new WeakMap, StreamLanguage = class _StreamLanguage extends Language { streamParser; stateAfter; tokenTable; topNode; constructor(parser) { let data = defineLanguageFacet(parser.languageData), p = fullParser(parser), self, impl = new class extends Parser { createParse(input, fragments, ranges) { return new Parse(self, input, fragments, ranges) } }; super(data, impl, [], parser.name), this.topNode = docID(data, this), self = this, this.streamParser = p, this.stateAfter = new NodeProp({ perNode: !0 }), this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable } static define(spec) { return new _StreamLanguage(spec) } getIndent(cx) { let from, { overrideIndentation } = cx.options; overrideIndentation && (from = IndentedFrom.get(cx.state), from != null && from < cx.pos - 1e4 && (from = void 0)); let start = findState(this, cx.node.tree, cx.node.from, cx.node.from, from ?? cx.pos), statePos, state; if (start ? (state = start.state, statePos = start.pos + 1) : (state = this.streamParser.startState(cx.unit), statePos = cx.node.from), cx.pos - statePos > 1e4) return null; for (; statePos < cx.pos;) { let line2 = cx.state.doc.lineAt(statePos), end = Math.min(cx.pos, line2.to); if (line2.length) { let indentation = overrideIndentation ? overrideIndentation(line2.from) : -1, stream = new StringStream(line2.text, cx.state.tabSize, cx.unit, indentation < 0 ? void 0 : indentation); for (; stream.pos < end - line2.from;)readToken(this.streamParser.token, stream, state) } else this.streamParser.blankLine(state, cx.unit); if (end == cx.pos) break; statePos = line2.to + 1 } let line = cx.lineAt(cx.pos); return overrideIndentation && from == null && IndentedFrom.set(cx.state, line.from), this.streamParser.indent(state, /^\s*(.*)/.exec(line.text)[1], cx) } get allowsNesting() { return !1 } }; function findState(lang, tree, off, startPos, before) { let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter); if (state) return { state: lang.streamParser.copyState(state), pos: off + tree.length }; for (let i2 = tree.children.length - 1; i2 >= 0; i2--) { let child = tree.children[i2], pos = off + tree.positions[i2], found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before); if (found) return found } return null } function cutTree(lang, tree, from, to, inside) { if (inside && from <= 0 && to >= tree.length) return tree; !inside && from == 0 && tree.type == lang.topNode && (inside = !0); for (let i2 = tree.children.length - 1; i2 >= 0; i2--) { let pos = tree.positions[i2], child = tree.children[i2], inner; if (pos < to && child instanceof Tree) { if (!(inner = cutTree(lang, child, from - pos, to - pos, inside))) break; return inside ? new Tree(tree.type, tree.children.slice(0, i2).concat(inner), tree.positions.slice(0, i2 + 1), pos + inner.length) : inner } } return null } function findStartInFragments(lang, fragments, startPos, endPos, editorState) { for (let f of fragments) { let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0), found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree; if (found && found.pos <= endPos && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, !1))) return { state: found.state, tree } } return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty } } var Parse = class { + constructor(lang, input, fragments, ranges) { this.lang = lang; this.input = input; this.fragments = fragments; this.ranges = ranges; this.to = ranges[ranges.length - 1].to; let context = ParseContext.get(), from = ranges[0].from, { state, tree } = findStartInFragments(lang, fragments, from, this.to, context?.state); this.state = state, this.parsedPos = this.chunkStart = from + tree.length; for (let i2 = 0; i2 < tree.children.length; i2++)this.chunks.push(tree.children[i2]), this.chunkPos.push(tree.positions[i2]); context && this.parsedPos < context.viewport.from - 1e5 && ranges.some(r => r.from <= context.viewport.from && r.to >= context.viewport.from) && (this.state = this.lang.streamParser.startState(getIndentUnit(context.state)), context.skipUntilInView(this.parsedPos, context.viewport.from), this.parsedPos = context.viewport.from), this.moveRangeIndex() } lang; input; fragments; ranges; state; parsedPos; stoppedAt = null; chunks = []; chunkPos = []; chunkStart; chunk = []; chunkReused = void 0; rangeIndex = 0; to; advance() { let context = ParseContext.get(), parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt), end = Math.min(parseEnd, this.chunkStart + 512); for (context && (end = Math.min(end, context.viewport.to)); this.parsedPos < end;)this.parseLine(context); return this.chunkStart < this.parsedPos && this.finishChunk(), this.parsedPos >= parseEnd ? this.finish() : context && this.parsedPos >= context.viewport.to ? (context.skipUntilInView(this.parsedPos, parseEnd), this.finish()) : null } stopAt(pos) { this.stoppedAt = pos } lineAfter(pos) { + let chunk = this.input.chunk(pos); if (this.input.lineChunks) chunk == ` +`&& (chunk = ""); else { + let eol = chunk.indexOf(` +`); eol > -1 && (chunk = chunk.slice(0, eol)) + } return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos) + } nextLine() { let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length; for (let index = this.rangeIndex; ;) { let rangeEnd2 = this.ranges[index].to; if (rangeEnd2 >= end || (line = line.slice(0, rangeEnd2 - (end - line.length)), index++, index == this.ranges.length)) break; let rangeStart = this.ranges[index].from, after = this.lineAfter(rangeStart); line += after, end = rangeStart + after.length } return { line, end } } skipGapsTo(pos, offset, side) { for (; ;) { let end = this.ranges[this.rangeIndex].to, offPos = pos + offset; if (side > 0 ? end > offPos : end >= offPos) break; let start = this.ranges[++this.rangeIndex].from; offset += start - end } return offset } moveRangeIndex() { for (; this.ranges[this.rangeIndex].to < this.parsedPos;)this.rangeIndex++ } emitToken(id, from, to, offset) { let size = 4; if (this.ranges.length > 1) { offset = this.skipGapsTo(from, offset, 1), from += offset; let len0 = this.chunk.length; offset = this.skipGapsTo(to, offset, -1), to += offset, size += this.chunk.length - len0 } let last = this.chunk.length - 4; return this.lang.streamParser.mergeTokens && size == 4 && last >= 0 && this.chunk[last] == id && this.chunk[last + 2] == from ? this.chunk[last + 2] = to : this.chunk.push(id, from, to, size), offset } parseLine(context) { let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang, stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2); if (stream.eol()) streamParser.blankLine(this.state, stream.indentUnit); else for (; !stream.eol();) { let token = readToken(streamParser.token, stream, this.state); if (token && (offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, offset)), stream.start > 1e4) break } this.parsedPos = end, this.moveRangeIndex(), this.parsedPos < this.to && this.parsedPos++ } finishChunk() { let tree = Tree.build({ buffer: this.chunk, start: this.chunkStart, length: this.parsedPos - this.chunkStart, nodeSet, topID: 0, maxBufferLength: 512, reused: this.chunkReused }); tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]), this.chunks.push(tree), this.chunkPos.push(this.chunkStart - this.ranges[0].from), this.chunk = [], this.chunkReused = void 0, this.chunkStart = this.parsedPos } finish() { return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance() } +}; function readToken(token, stream, state) { stream.start = stream.pos; for (let i2 = 0; i2 < 10; i2++) { let result = token(stream, state); if (stream.pos > stream.start) return result } throw new Error("Stream parser failed to advance stream.") } var noTokens = Object.create(null), typeArray = [NodeType.none], nodeSet = new NodeSet(typeArray), warned = [], byTag = Object.create(null), defaultTable = Object.create(null); for (let [legacyName, name2] of [["variable", "variableName"], ["variable-2", "variableName.special"], ["string-2", "string.special"], ["def", "variableName.definition"], ["tag", "tagName"], ["attribute", "attributeName"], ["type", "typeName"], ["builtin", "variableName.standard"], ["qualifier", "modifier"], ["error", "invalid"], ["header", "heading"], ["property", "propertyName"]]) defaultTable[legacyName] = createTokenType(noTokens, name2); var TokenTable = class { constructor(extra) { this.extra = extra } extra; table = Object.assign(Object.create(null), defaultTable); resolve(tag) { return tag ? this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag)) : 0 } }, defaultTokenTable = new TokenTable(noTokens); function warnForPart(part, msg) { warned.indexOf(part) > -1 || (warned.push(part), console.warn(msg)) } function createTokenType(extra, tagStr) { let tags2 = []; for (let name3 of tagStr.split(" ")) { let found = []; for (let part of name3.split(".")) { let value = extra[part] || tags[part]; value ? typeof value == "function" ? found.length ? found = found.map(value) : warnForPart(part, `Modifier ${part} used at start of tag`) : found.length ? warnForPart(part, `Tag ${part} used as modifier`) : found = Array.isArray(value) ? value : [value] : warnForPart(part, `Unknown highlighting tag ${part}`) } for (let tag of found) tags2.push(tag) } if (!tags2.length) return 0; let name2 = tagStr.replace(/ /g, "_"), key = name2 + " " + tags2.map(t2 => t2.id), known = byTag[key]; if (known) return known.id; let type = byTag[key] = NodeType.define({ id: typeArray.length, name: name2, props: [styleTags({ [name2]: tags2 })] }); return typeArray.push(type), type.id } function docID(data, lang) { let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data), indentNodeProp.add(() => cx => lang.getIndent(cx))], top: !0 }); return typeArray.push(type), type } var toggleComment = target => { let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from); return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : !1 }; function command(f, option) { return ({ state, dispatch }) => { if (state.readOnly) return !1; let tr = f(option, state); return tr ? (dispatch(state.update(tr)), !0) : !1 } } var toggleLineComment = command(changeLineComment, 0), lineComment = command(changeLineComment, 1), lineUncomment = command(changeLineComment, 2), toggleBlockComment = command(changeBlockComment, 0), blockComment = command(changeBlockComment, 1), blockUncomment = command(changeBlockComment, 2), toggleBlockCommentByLine = command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0); function getConfig(state, pos) { let data = state.languageDataAt("commentTokens", pos, 1); return data.length ? data[0] : {} } var SearchMargin = 50; function findBlockComment(state, { open, close }, from, to) { let textBefore = state.sliceDoc(from - SearchMargin, from), textAfter = state.sliceDoc(to, to + SearchMargin), spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length, beforeOff = textBefore.length - spaceBefore; if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close.length) == close) return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; let startText, endText; to - from <= 2 * SearchMargin ? startText = endText = state.sliceDoc(from, to) : (startText = state.sliceDoc(from, from + SearchMargin), endText = state.sliceDoc(to - SearchMargin, to)); let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length, endOff = endText.length - endSpace - close.length; return startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close ? { open: { pos: from + startSpace + open.length, margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, close: { pos: to - endSpace - close.length, margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } } : null } function selectedLineRanges(state) { let ranges = []; for (let r of state.selection.ranges) { let fromLine = state.doc.lineAt(r.from), toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); toLine.from > fromLine.from && toLine.from == r.to && (toLine = r.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r.to - 1)); let last = ranges.length - 1; last >= 0 && ranges[last].to > fromLine.from ? ranges[last].to = toLine.to : ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to }) } return ranges } function changeBlockComment(option, state, ranges = state.selection.ranges) { let tokens = ranges.map(r => getConfig(state, r.from).block); if (!tokens.every(c => c)) return null; let comments = ranges.map((r, i2) => findBlockComment(state, tokens[i2], r.from, r.to)); if (option != 2 && !comments.every(c => c)) return { changes: state.changes(ranges.map((range, i2) => comments[i2] ? [] : [{ from: range.from, insert: tokens[i2].open + " " }, { from: range.to, insert: " " + tokens[i2].close }])) }; if (option != 1 && comments.some(c => c)) { let changes = []; for (let i2 = 0, comment2; i2 < comments.length; i2++)if (comment2 = comments[i2]) { let token = tokens[i2], { open, close } = comment2; changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }) } return { changes } } return null } function changeLineComment(option, state, ranges = state.selection.ranges) { let lines = [], prevLine = -1; ranges: for (let { from, to } of ranges) { let startI = lines.length, minIndent = 1e9, token; for (let pos = from; pos <= to;) { let line = state.doc.lineAt(pos); if (token == null && (token = getConfig(state, line.from).line, !token)) continue ranges; if (line.from > prevLine && (from == to || to > line.from)) { prevLine = line.from; let indent = /^\s*/.exec(line.text)[0].length, empty2 = indent == line.length, comment2 = line.text.slice(indent, indent + token.length) == token ? indent : -1; indent < line.text.length && indent < minIndent && (minIndent = indent), lines.push({ line, comment: comment2, token, indent, empty: empty2, single: !1 }) } pos = line.to + 1 } if (minIndent < 1e9) for (let i2 = startI; i2 < lines.length; i2++)lines[i2].indent < lines[i2].line.text.length && (lines[i2].indent = minIndent); lines.length == startI + 1 && (lines[startI].single = !0) } if (option != 2 && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { let changes = []; for (let { line, token, indent, empty: empty2, single } of lines) (single || !empty2) && changes.push({ from: line.from + indent, insert: token + " " }); let changeSet = state.changes(changes); return { changes: changeSet, selection: state.selection.map(changeSet, 1) } } else if (option != 1 && lines.some(l => l.comment >= 0)) { let changes = []; for (let { line, comment: comment2, token } of lines) if (comment2 >= 0) { let from = line.from + comment2, to = from + token.length; line.text[to - line.from] == " " && to++, changes.push({ from, to }) } return { changes } } return null } var fromHistory = Annotation.define(), isolateHistory = Annotation.define(), invertedEffects = Facet.define(), historyConfig = Facet.define({ combine(configs) { return combineConfig(configs, { minDepth: 100, newGroupDelay: 500, joinToEvent: (_t, isAdjacent2) => isAdjacent2 }, { minDepth: Math.max, newGroupDelay: Math.min, joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj) }) } }), historyField_ = StateField.define({ create() { return HistoryState.empty }, update(state, tr) { let config = tr.state.facet(historyConfig), fromHist = tr.annotation(fromHistory); if (fromHist) { let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side, other = from == 0 ? state.undone : state.done; return item ? other = updateBranch(other, other.length, config.minDepth, item) : other = addSelection(other, tr.startState.selection), new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest) } let isolate = tr.annotation(isolateHistory); if ((isolate == "full" || isolate == "before") && (state = state.isolate()), tr.annotation(Transaction.addToHistory) === !1) return tr.changes.empty ? state : state.addMapping(tr.changes.desc); let event = HistEvent.fromTransaction(tr), time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); return event ? state = state.addChanges(event, time, userEvent, config, tr) : tr.selection && (state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay)), (isolate == "full" || isolate == "after") && (state = state.isolate()), state }, toJSON(value) { return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) } }, fromJSON(json) { return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)) } }); function history(config = {}) { return [historyField_, historyConfig.of(config), EditorView.domEventHandlers({ beforeinput(e, view) { let command2 = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; return command2 ? (e.preventDefault(), command2(view)) : !1 } })] } function cmd(side, selection) { return function ({ state, dispatch }) { if (!selection && state.readOnly) return !1; let historyState = state.field(historyField_, !1); if (!historyState) return !1; let tr = historyState.pop(side, state, selection); return tr ? (dispatch(tr), !0) : !1 } } var undo = cmd(0, !1), redo = cmd(1, !1), undoSelection = cmd(0, !0), redoSelection = cmd(1, !0); function depth(side) { return function (state) { let histState = state.field(historyField_, !1); if (!histState) return 0; let branch = side == 0 ? histState.done : histState.undone; return branch.length - (branch.length && !branch[0].changes ? 1 : 0) } } var undoDepth = depth(0), redoDepth = depth(1), HistEvent = class _HistEvent { constructor(changes, effects, mapped, startSelection, selectionsAfter) { this.changes = changes; this.effects = effects; this.mapped = mapped; this.startSelection = startSelection; this.selectionsAfter = selectionsAfter } changes; effects; mapped; startSelection; selectionsAfter; setSelAfter(after) { return new _HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after) } toJSON() { return { changes: this.changes?.toJSON(), mapped: this.mapped?.toJSON(), startSelection: this.startSelection?.toJSON(), selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) } } static fromJSON(json) { return new _HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)) } static fromTransaction(tr, selection) { let effects = none2; for (let invert of tr.startState.facet(invertedEffects)) { let result = invert(tr); result.length && (effects = effects.concat(result)) } return !effects.length && tr.changes.empty ? null : new _HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection || tr.startState.selection, none2) } static selection(selections) { return new _HistEvent(void 0, none2, void 0, void 0, selections) } }; function updateBranch(branch, to, maxLen, newEvent) { let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0, newBranch = branch.slice(start, to); return newBranch.push(newEvent), newBranch } function isAdjacent(a, b) { let ranges = [], isAdjacent2 = !1; return a.iterChangedRanges((f, t2) => ranges.push(f, t2)), b.iterChangedRanges((_f, _t, f, t2) => { for (let i2 = 0; i2 < ranges.length;) { let from = ranges[i2++], to = ranges[i2++]; t2 >= from && f <= to && (isAdjacent2 = !0) } }), isAdjacent2 } function eqSelectionShape(a, b) { return a.ranges.length == b.ranges.length && a.ranges.filter((r, i2) => r.empty != b.ranges[i2].empty).length === 0 } function conc(a, b) { return a.length ? b.length ? a.concat(b) : a : b } var none2 = [], MaxSelectionsPerEvent = 200; function addSelection(branch, selection) { if (branch.length) { let lastEvent = branch[branch.length - 1], sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); return sels.length && sels[sels.length - 1].eq(selection) ? branch : (sels.push(selection), updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels))) } else return [HistEvent.selection([selection])] } function popSelection(branch) { let last = branch[branch.length - 1], newBranch = branch.slice(); return newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)), newBranch } function addMappingToBranch(branch, mapping) { if (!branch.length) return branch; let length = branch.length, selections = none2; for (; length;) { let event = mapEvent(branch[length - 1], mapping, selections); if (event.changes && !event.changes.empty || event.effects.length) { let result = branch.slice(0, length); return result[length - 1] = event, result } else mapping = event.mapped, length--, selections = event.selectionsAfter } return selections.length ? [HistEvent.selection(selections)] : none2 } function mapEvent(event, mapping, extraSelections) { let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none2, extraSelections); if (!event.changes) return HistEvent.selection(selections); let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, !0), fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections) } var joinableUserEvent = /^(input\.type|delete)($|\.)/, HistoryState = class _HistoryState { constructor(done, undone, prevTime = 0, prevUserEvent = void 0) { this.done = done; this.undone = undone; this.prevTime = prevTime; this.prevUserEvent = prevUserEvent } done; undone; prevTime; prevUserEvent; isolate() { return this.prevTime ? new _HistoryState(this.done, this.undone) : this } addChanges(event, time, userEvent, config, tr) { let done = this.done, lastEvent = done[done.length - 1]; return lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config.newGroupDelay && config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes)) || userEvent == "input.type.compose") ? done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none2)) : done = updateBranch(done, done.length, config.minDepth, event), new _HistoryState(done, none2, time, userEvent) } addSelection(selection, time, userEvent, newGroupDelay) { let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none2; return last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection) ? this : new _HistoryState(addSelection(this.done, selection), this.undone, time, userEvent) } addMapping(mapping) { return new _HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent) } pop(side, state, onlySelection) { let branch = side == 0 ? this.done : this.undone; if (branch.length == 0) return null; let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || (event.startSelection ? event.startSelection.map(event.changes.invertedDesc, 1) : state.selection); if (onlySelection && event.selectionsAfter.length) return state.update({ selection: event.selectionsAfter[event.selectionsAfter.length - 1], annotations: fromHistory.of({ side, rest: popSelection(branch), selection }), userEvent: side == 0 ? "select.undo" : "select.redo", scrollIntoView: !0 }); if (event.changes) { let rest = branch.length == 1 ? none2 : branch.slice(0, branch.length - 1); return event.mapped && (rest = addMappingToBranch(rest, event.mapped)), state.update({ changes: event.changes, selection: event.startSelection, effects: event.effects, annotations: fromHistory.of({ side, rest, selection }), filter: !1, userEvent: side == 0 ? "undo" : "redo", scrollIntoView: !0 }) } else return null } static empty = new _HistoryState(none2, none2) }, historyKeymap = [{ key: "Mod-z", run: undo, preventDefault: !0 }, { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: !0 }, { linux: "Ctrl-Shift-z", run: redo, preventDefault: !0 }, { key: "Mod-u", run: undoSelection, preventDefault: !0 }, { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: !0 }]; function updateSel(sel, by) { return EditorSelection.create(sel.ranges.map(by), sel.mainIndex) } function setSel(state, selection) { return state.update({ selection, scrollIntoView: !0, userEvent: "select" }) } function moveSel({ state, dispatch }, how) { let selection = updateSel(state.selection, how); return selection.eq(state.selection, !0) ? !1 : (dispatch(setSel(state, selection)), !0) } function rangeEnd(range, forward) { return EditorSelection.cursor(forward ? range.to : range.from) } function cursorByChar(view, forward) { return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)) } function ltrAtCursor(view) { return view.textDirectionAt(view.state.selection.main.head) == 0 } var cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view)), cursorCharRight = view => cursorByChar(view, ltrAtCursor(view)); function cursorByGroup(view, forward) { return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)) } var cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view)), cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view)); var segmenter = typeof Intl < "u" && Intl.Segmenter ? new Intl.Segmenter(void 0, { granularity: "word" }) : null; function interestingNode(state, node, bracketProp) { if (node.type.prop(bracketProp)) return !0; let len = node.to - node.from; return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild } function moveBySyntax(state, start, forward) { let pos = syntaxTree(state).resolveInner(start.head), bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; for (let at = start.head; ;) { let next = forward ? pos.childAfter(at) : pos.childBefore(at); if (!next) break; interestingNode(state, next, bracketProp) ? pos = next : at = forward ? next.to : next.from } let bracket2 = pos.type.prop(bracketProp), match, newPos; return bracket2 && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched ? newPos = forward ? match.end.to : match.end.from : newPos = forward ? pos.to : pos.from, EditorSelection.cursor(newPos, forward ? -1 : 1) } var cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))), cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); function cursorByLine(view, forward) { return moveSel(view, range => { if (!range.empty) return rangeEnd(range, forward); let moved = view.moveVertically(range, forward); return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward) }) } var cursorLineUp = view => cursorByLine(view, !1), cursorLineDown = view => cursorByLine(view, !0); function pageInfo(view) { let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2, marginTop = 0, marginBottom = 0, height; if (selfScroll) { for (let source of view.state.facet(EditorView.scrollMargins)) { let margins = source(view); margins?.top && (marginTop = Math.max(margins?.top, marginTop)), margins?.bottom && (marginBottom = Math.max(margins?.bottom, marginBottom)) } height = view.scrollDOM.clientHeight - marginTop - marginBottom } else height = (view.dom.ownerDocument.defaultView || window).innerHeight; return { marginTop, marginBottom, selfScroll, height: Math.max(view.defaultLineHeight, height - 5) } } function cursorByPage(view, forward) { let page = pageInfo(view), { state } = view, selection = updateSel(state.selection, range => range.empty ? view.moveVertically(range, forward, page.height) : rangeEnd(range, forward)); if (selection.eq(state.selection)) return !1; let effect; if (page.selfScroll) { let startPos = view.coordsAtPos(state.selection.main.head), scrollRect = view.scrollDOM.getBoundingClientRect(), scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom; startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom && (effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop })) } return view.dispatch(setSel(state, selection), { effects: effect }), !0 } var cursorPageUp = view => cursorByPage(view, !1), cursorPageDown = view => cursorByPage(view, !0); function moveByLineBoundary(view, start, forward) { let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); if (moved.head == start.head && moved.head != (forward ? line.to : line.from) && (moved = view.moveToLineBoundary(start, forward, !1)), !forward && moved.head == line.from && line.length) { let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; space && start.head != line.from + space && (moved = EditorSelection.cursor(line.from + space)) } return moved } var cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, !0)), cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, !1)), cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))), cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))), cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)), cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); function toMatchingBracket(state, dispatch, extend) { let found = !1, selection = updateSel(state.selection, range => { let matching = matchBrackets(state, range.head, -1) || matchBrackets(state, range.head, 1) || range.head > 0 && matchBrackets(state, range.head - 1, 1) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1); if (!matching || !matching.end) return range; found = !0; let head = matching.start.from == range.head ? matching.end.to : matching.end.from; return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head) }); return found ? (dispatch(setSel(state, selection)), !0) : !1 } var cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, !1); function extendSel(target, how) { let selection = updateSel(target.state.selection, range => { let head = how(range); return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || void 0, head.assoc) }); return selection.eq(target.state.selection) ? !1 : (target.dispatch(setSel(target.state, selection)), !0) } function selectByChar(view, forward) { return extendSel(view, range => view.moveByChar(range, forward)) } var selectCharLeft = view => selectByChar(view, !ltrAtCursor(view)), selectCharRight = view => selectByChar(view, ltrAtCursor(view)); function selectByGroup(view, forward) { return extendSel(view, range => view.moveByGroup(range, forward)) } var selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view)), selectGroupRight = view => selectByGroup(view, ltrAtCursor(view)); var selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))), selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); function selectByLine(view, forward) { return extendSel(view, range => view.moveVertically(range, forward)) } var selectLineUp = view => selectByLine(view, !1), selectLineDown = view => selectByLine(view, !0); function selectByPage(view, forward) { return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height)) } var selectPageUp = view => selectByPage(view, !1), selectPageDown = view => selectByPage(view, !0), selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, !0)), selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, !1)), selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))), selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))), selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)), selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)), cursorDocStart = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: 0 })), !0), cursorDocEnd = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.doc.length })), !0), selectDocStart = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })), !0), selectDocEnd = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })), !0), selectAll = ({ state, dispatch }) => (dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })), !0), selectLine = ({ state, dispatch }) => { let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); return dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })), !0 }, selectParentSyntax = ({ state, dispatch }) => { let selection = updateSel(state.selection, range => { let tree = syntaxTree(state), stack = tree.resolveStack(range.from, 1); if (range.empty) { let stackBefore = tree.resolveStack(range.from, -1); stackBefore.node.from >= stack.node.from && stackBefore.node.to <= stack.node.to && (stack = stackBefore) } for (let cur = stack; cur; cur = cur.next) { let { node } = cur; if ((node.from < range.from && node.to >= range.to || node.to > range.to && node.from <= range.from) && cur.next) return EditorSelection.range(node.to, node.from) } return range }); return selection.eq(state.selection) ? !1 : (dispatch(setSel(state, selection)), !0) }; function addCursorVertically(view, forward) { let { state } = view, sel = state.selection, ranges = state.selection.ranges.slice(); for (let range of state.selection.ranges) { let line = state.doc.lineAt(range.head); if (forward ? line.to < view.state.doc.length : line.from > 0) for (let cur = range; ;) { let next = view.moveVertically(cur, forward); if (next.head < line.from || next.head > line.to) { ranges.some(r => r.head == next.head) || ranges.push(next); break } else { if (next.head == cur.head) break; cur = next } } } return ranges.length == sel.ranges.length ? !1 : (view.dispatch(setSel(state, EditorSelection.create(ranges, ranges.length - 1))), !0) } var addCursorAbove = view => addCursorVertically(view, !1), addCursorBelow = view => addCursorVertically(view, !0), simplifySelection = ({ state, dispatch }) => { let cur = state.selection, selection = null; return cur.ranges.length > 1 ? selection = EditorSelection.create([cur.main]) : cur.main.empty || (selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)])), selection ? (dispatch(setSel(state, selection)), !0) : !1 }; function deleteBy(target, by) { if (target.state.readOnly) return !1; let event = "delete.selection", { state } = target, changes = state.changeByRange(range => { let { from, to } = range; if (from == to) { let towards = by(range); towards < from ? (event = "delete.backward", towards = skipAtomic(target, towards, !1)) : towards > from && (event = "delete.forward", towards = skipAtomic(target, towards, !0)), from = Math.min(from, towards), to = Math.max(to, towards) } else from = skipAtomic(target, from, !1), to = skipAtomic(target, to, !0); return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) } }); return changes.changes.empty ? !1 : (target.dispatch(state.update(changes, { scrollIntoView: !0, userEvent: event, effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : void 0 })), !0) } function skipAtomic(target, pos, forward) { if (target instanceof EditorView) for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) ranges.between(pos, pos, (from, to) => { from < pos && to > pos && (pos = forward ? to : from) }); return pos } var deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, range => { let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos; if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { if (before[before.length - 1] == " ") return pos - 1; let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); for (let i2 = 0; i2 < drop && before[before.length - 1 - i2] == " "; i2++)pos--; targetPos = pos } else targetPos = findClusterBreak2(line.text, pos - line.from, forward, forward) + line.from, targetPos == pos && line.number != (forward ? state.doc.lines : 1) ? targetPos += forward ? 1 : -1 : !forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)) && (targetPos = findClusterBreak2(line.text, targetPos - line.from, !1, !1) + line.from); return targetPos }), deleteCharBackward = view => deleteByChar(view, !1, !0); var deleteCharForward = view => deleteByChar(view, !0, !1), deleteByGroup = (target, forward) => deleteBy(target, range => { let pos = range.head, { state } = target, line = state.doc.lineAt(pos), categorize = state.charCategorizer(pos); for (let cat = null; ;) { if (pos == (forward ? line.to : line.from)) { pos == range.head && line.number != (forward ? state.doc.lines : 1) && (pos += forward ? 1 : -1); break } let next = findClusterBreak2(line.text, pos - line.from, forward) + line.from, nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from), nextCat = categorize(nextChar); if (cat != null && nextCat != cat) break; (nextChar != " " || pos != range.head) && (cat = nextCat), pos = next } return pos }), deleteGroupBackward = target => deleteByGroup(target, !1), deleteGroupForward = target => deleteByGroup(target, !0); var deleteToLineEnd = view => deleteBy(view, range => { let lineEnd = view.lineBlockAt(range.head).to; return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1) }); var deleteLineBoundaryBackward = view => deleteBy(view, range => { let lineStart = view.moveToLineBoundary(range, !1).head; return range.head > lineStart ? lineStart : Math.max(0, range.head - 1) }), deleteLineBoundaryForward = view => deleteBy(view, range => { let lineStart = view.moveToLineBoundary(range, !0).head; return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1) }); var splitLine = ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, range: EditorSelection.cursor(range.from) })); return dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "input" })), !0 }, transposeChars = ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => { if (!range.empty || range.from == 0 || range.from == state.doc.length) return { range }; let pos = range.from, line = state.doc.lineAt(pos), from = pos == line.from ? pos - 1 : findClusterBreak2(line.text, pos - line.from, !1) + line.from, to = pos == line.to ? pos + 1 : findClusterBreak2(line.text, pos - line.from, !0) + line.from; return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, range: EditorSelection.cursor(to) } }); return changes.changes.empty ? !1 : (dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "move.character" })), !0) }; function selectedLineBlocks(state) { let blocks = [], upto = -1; for (let range of state.selection.ranges) { let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); if (!range.empty && range.to == endLine.from && (endLine = state.doc.lineAt(range.to - 1)), upto >= startLine.number) { let prev = blocks[blocks.length - 1]; prev.to = endLine.to, prev.ranges.push(range) } else blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); upto = endLine.number + 1 } return blocks } function moveLine(state, dispatch, forward) { if (state.readOnly) return !1; let changes = [], ranges = []; for (let block of selectedLineBlocks(state)) { if (forward ? block.to == state.doc.length : block.from == 0) continue; let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1), size = nextLine.length + 1; if (forward) { changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); for (let r of block.ranges) ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))) } else { changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); for (let r of block.ranges) ranges.push(EditorSelection.range(r.anchor - size, r.head - size)) } } return changes.length ? (dispatch(state.update({ changes, scrollIntoView: !0, selection: EditorSelection.create(ranges, state.selection.mainIndex), userEvent: "move.line" })), !0) : !1 } var moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, !1), moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, !0); function copyLine(state, dispatch, forward) { if (state.readOnly) return !1; let changes = []; for (let block of selectedLineBlocks(state)) forward ? changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }) : changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); let changeSet = state.changes(changes); return dispatch(state.update({ changes: changeSet, selection: state.selection.map(changeSet, forward ? 1 : -1), scrollIntoView: !0, userEvent: "input.copyline" })), !0 } var copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, !1), copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, !0), deleteLine = view => { if (view.state.readOnly) return !1; let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => (from > 0 ? from-- : to < state.doc.length && to++, { from, to }))), selection = updateSel(state.selection, range => { let dist2; if (view.lineWrapping) { let block = view.lineBlockAt(range.head), pos = view.coordsAtPos(range.head, range.assoc || 1); pos && (dist2 = block.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2) } return view.moveVertically(range, !0, dist2) }).map(changes); return view.dispatch({ changes, selection, scrollIntoView: !0, userEvent: "delete.line" }), !0 }; function isBetweenBrackets(state, pos) { if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) return { from: pos, to: pos }; let context = syntaxTree(state).resolveInner(pos), before = context.childBefore(pos), after = context.childAfter(pos), closedBy; return before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from && !/\S/.test(state.sliceDoc(before.to, after.from)) ? { from: before.to, to: after.from } : null } var insertNewlineAndIndent = newlineAndIndent(!1), insertBlankLine = newlineAndIndent(!0); function newlineAndIndent(atEof) { return ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => { let { from, to } = range, line = state.doc.lineAt(from), explode = !atEof && from == to && isBetweenBrackets(state, from); atEof && (from = to = (to <= line.to ? line : state.doc.lineAt(to)).to); let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }), indent = getIndentation(cx, from); for (indent == null && (indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize)); to < line.to && /\s/.test(line.text[to - line.from]);)to++; explode ? { from, to } = explode : from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)) && (from = line.from); let insert2 = ["", indentString(state, indent)]; return explode && insert2.push(indentString(state, cx.lineIndent(line.from, -1))), { changes: { from, to, insert: Text.of(insert2) }, range: EditorSelection.cursor(from + 1 + insert2[1].length) } }); return dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "input" })), !0 } } function changeBySelectedLine(state, f) { let atLine = -1; return state.changeByRange(range => { let changes = []; for (let pos = range.from; pos <= range.to;) { let line = state.doc.lineAt(pos); line.number > atLine && (range.empty || range.to > line.from) && (f(line, changes, range), atLine = line.number), pos = line.to + 1 } let changeSet = state.changes(changes); return { changes, range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) } }) } var indentSelection = ({ state, dispatch }) => { if (state.readOnly) return !1; let updated = Object.create(null), context = new IndentContext(state, { overrideIndentation: start => { let found = updated[start]; return found ?? -1 } }), changes = changeBySelectedLine(state, (line, changes2, range) => { let indent = getIndentation(context, line.from); if (indent == null) return; /\S/.test(line.text) || (indent = 0); let cur = /^\s*/.exec(line.text)[0], norm = indentString(state, indent); (cur != norm || range.from < line.from + cur.length) && (updated[line.from] = indent, changes2.push({ from: line.from, to: line.from + cur.length, insert: norm })) }); return changes.changes.empty || dispatch(state.update(changes, { userEvent: "indent" })), !0 }, indentMore = ({ state, dispatch }) => state.readOnly ? !1 : (dispatch(state.update(changeBySelectedLine(state, (line, changes) => { changes.push({ from: line.from, insert: state.facet(indentUnit) }) }), { userEvent: "input.indent" })), !0), indentLess = ({ state, dispatch }) => state.readOnly ? !1 : (dispatch(state.update(changeBySelectedLine(state, (line, changes) => { let space = /^\s*/.exec(line.text)[0]; if (!space) return; let col = countColumn(space, state.tabSize), keep = 0, insert2 = indentString(state, Math.max(0, col - getIndentUnit(state))); for (; keep < space.length && keep < insert2.length && space.charCodeAt(keep) == insert2.charCodeAt(keep);)keep++; changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert2.slice(keep) }) }), { userEvent: "delete.dedent" })), !0), toggleTabFocusMode = view => (view.setTabFocusMode(), !0); var emacsStyleKeymap = [{ key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: !0 }, { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, { key: "Ctrl-d", run: deleteCharForward }, { key: "Ctrl-h", run: deleteCharBackward }, { key: "Ctrl-k", run: deleteToLineEnd }, { key: "Ctrl-Alt-h", run: deleteGroupBackward }, { key: "Ctrl-o", run: splitLine }, { key: "Ctrl-t", run: transposeChars }, { key: "Ctrl-v", run: cursorPageDown }], standardKeymap = [{ key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: !0 }, { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: !0 }, { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: !0 }, { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: !0 }, { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: !0 }, { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: !0 }, { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: !0 }, { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: !0 }, { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: !0 }, { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: !0 }, { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent }, { key: "Mod-a", run: selectAll }, { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward, preventDefault: !0 }, { key: "Delete", run: deleteCharForward, preventDefault: !0 }, { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward, preventDefault: !0 }, { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward, preventDefault: !0 }, { mac: "Mod-Backspace", run: deleteLineBoundaryBackward, preventDefault: !0 }, { mac: "Mod-Delete", run: deleteLineBoundaryForward, preventDefault: !0 }].concat(emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))), defaultKeymap = [{ key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, { key: "Alt-ArrowUp", run: moveLineUp }, { key: "Shift-Alt-ArrowUp", run: copyLineUp }, { key: "Alt-ArrowDown", run: moveLineDown }, { key: "Shift-Alt-ArrowDown", run: copyLineDown }, { key: "Mod-Alt-ArrowUp", run: addCursorAbove }, { key: "Mod-Alt-ArrowDown", run: addCursorBelow }, { key: "Escape", run: simplifySelection }, { key: "Mod-Enter", run: insertBlankLine }, { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, { key: "Mod-i", run: selectParentSyntax, preventDefault: !0 }, { key: "Mod-[", run: indentLess }, { key: "Mod-]", run: indentMore }, { key: "Mod-Alt-\\", run: indentSelection }, { key: "Shift-Mod-k", run: deleteLine }, { key: "Shift-Mod-\\", run: cursorMatchingBracket }, { key: "Mod-/", run: toggleComment }, { key: "Alt-A", run: toggleBlockComment }, { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode }].concat(standardKeymap), indentWithTab = { key: "Tab", run: indentMore, shift: indentLess }; var basicNormalize = typeof String.prototype.normalize == "function" ? x => x.normalize("NFKD") : x => x, SearchCursor = class { constructor(text, query, from = 0, to = text.length, normalize, test) { this.test = test; this.iter = text.iterRange(from, to), this.bufferStart = from, this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize, this.query = this.normalize(query) } test; iter; value = { from: 0, to: 0 }; done = !1; matches = []; buffer = ""; bufferPos = 0; bufferStart; normalize; query; peek() { if (this.bufferPos == this.buffer.length) { if (this.bufferStart += this.buffer.length, this.iter.next(), this.iter.done) return -1; this.bufferPos = 0, this.buffer = this.iter.value } return codePointAt2(this.buffer, this.bufferPos) } next() { for (; this.matches.length;)this.matches.pop(); return this.nextOverlapping() } nextOverlapping() { for (; ;) { let next = this.peek(); if (next < 0) return this.done = !0, this; let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; this.bufferPos += codePointSize2(next); let norm = this.normalize(str); if (norm.length) for (let i2 = 0, pos = start; ; i2++) { let code2 = norm.charCodeAt(i2), match = this.match(code2, pos, this.bufferPos + this.bufferStart); if (i2 == norm.length - 1) { if (match) return this.value = match, this; break } pos == start && i2 < str.length && str.charCodeAt(i2) == code2 && pos++ } } } match(code2, pos, end) { let match = null; for (let i2 = 0; i2 < this.matches.length; i2 += 2) { let index = this.matches[i2], keep = !1; this.query.charCodeAt(index) == code2 && (index == this.query.length - 1 ? match = { from: this.matches[i2 + 1], to: end } : (this.matches[i2]++, keep = !0)), keep || (this.matches.splice(i2, 2), i2 -= 2) } return this.query.charCodeAt(0) == code2 && (this.query.length == 1 ? match = { from: pos, to: end } : this.matches.push(1, pos)), match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart) && (match = null), match } }; typeof Symbol < "u" && (SearchCursor.prototype[Symbol.iterator] = function () { return this }); var empty = { from: -1, to: -1, match: /.*/.exec("") }, baseFlags = "gm" + (/x/.unicode == null ? "" : "u"), RegExpCursor = class { constructor(text, query, options, from = 0, to = text.length) { this.text = text; this.to = to; if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) return new MultilineRegExpCursor(text, query, options, from, to); this.re = new RegExp(query, baseFlags + (options?.ignoreCase ? "i" : "")), this.test = options?.test, this.iter = text.iter(); let startLine = text.lineAt(from); this.curLineStart = startLine.from, this.matchPos = toCharEnd(text, from), this.getLine(this.curLineStart) } text; to; test; curLine = ""; done = !1; value = empty; getLine(skip) { this.iter.next(skip), this.iter.lineBreak ? this.curLine = "" : (this.curLine = this.iter.value, this.curLineStart + this.curLine.length > this.to && (this.curLine = this.curLine.slice(0, this.to - this.curLineStart)), this.iter.next()) } nextLine() { this.curLineStart = this.curLineStart + this.curLine.length + 1, this.curLineStart > this.to ? this.curLine = "" : this.getLine(0) } next() { for (let off = this.matchPos - this.curLineStart; ;) { this.re.lastIndex = off; let match = this.matchPos <= this.to && this.re.exec(this.curLine); if (match) { let from = this.curLineStart + match.index, to = from + match[0].length; if (this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)), from == this.curLineStart + this.curLine.length && this.nextLine(), (from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) return this.value = { from, to, match }, this; off = this.matchPos - this.curLineStart } else if (this.curLineStart + this.curLine.length < this.to) this.nextLine(), off = 0; else return this.done = !0, this } } }, flattened = new WeakMap, FlattenedDoc = class _FlattenedDoc { constructor(from, text) { this.from = from; this.text = text } from; text; get to() { return this.from + this.text.length } static get(doc2, from, to) { let cached = flattened.get(doc2); if (!cached || cached.from >= to || cached.to <= from) { let flat = new _FlattenedDoc(from, doc2.sliceString(from, to)); return flattened.set(doc2, flat), flat } if (cached.from == from && cached.to == to) return cached; let { text, from: cachedFrom } = cached; return cachedFrom > from && (text = doc2.sliceString(from, cachedFrom) + text, cachedFrom = from), cached.to < to && (text += doc2.sliceString(cached.to, to)), flattened.set(doc2, new _FlattenedDoc(cachedFrom, text)), new _FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)) } }; var MultilineRegExpCursor = class { constructor(text, query, options, from, to) { this.text = text; this.to = to; this.matchPos = toCharEnd(text, from), this.re = new RegExp(query, baseFlags + (options?.ignoreCase ? "i" : "")), this.test = options?.test, this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5e3)) } text; to; flat; matchPos; re; test; done = !1; value = empty; chunkEnd(pos) { return pos >= this.to ? this.to : this.text.lineAt(pos).to } next() { for (; ;) { let off = this.re.lastIndex = this.matchPos - this.flat.from, match = this.re.exec(this.flat.text); if (match && !match[0] && match.index == off && (this.re.lastIndex = off + 1, match = this.re.exec(this.flat.text)), match) { let from = this.flat.from + match.index, to = from + match[0].length; if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) return this.value = { from, to, match }, this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)), this } if (this.flat.to == this.to) return this.done = !0, this; this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)) } } }; typeof Symbol < "u" && (RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function () { return this }); function validRegExp(source) { try { return new RegExp(source, baseFlags), !0 } catch { return !1 } } function toCharEnd(text, pos) { if (pos >= text.length) return pos; let line = text.lineAt(pos), next; for (; pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 56320 && next < 57344;)pos++; return pos } var gotoLine = view => { let { state } = view, line = String(state.doc.lineAt(view.state.selection.main.head).number), { close, result } = showDialog(view, { label: state.phrase("Go to line"), input: { type: "text", name: "line", value: line }, focus: !0, submitLabel: state.phrase("go") }); return result.then(form => { let match = form && /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(form.elements.line.value); if (!match) { view.dispatch({ effects: close }); return } let startLine = state.doc.lineAt(state.selection.main.head), [, sign, ln, cl, percent] = match, col = cl ? +cl.slice(1) : 0, line2 = ln ? +ln : startLine.number; if (ln && percent) { let pc = line2 / 100; sign && (pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state.doc.lines), line2 = Math.round(state.doc.lines * pc) } else ln && sign && (line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number); let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line2))), selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))); view.dispatch({ effects: [close, EditorView.scrollIntoView(selection.from, { y: "center" })], selection }) }), !0 }; var defaultHighlightOptions = { highlightWordAroundCursor: !1, minSelectionLength: 1, maxMatches: 100, wholeWords: !1 }, highlightConfig = Facet.define({ combine(options) { return combineConfig(options, defaultHighlightOptions, { highlightWordAroundCursor: (a, b) => a || b, minSelectionLength: Math.min, maxMatches: Math.min }) } }); function highlightSelectionMatches(options) { let ext = [defaultTheme, matchHighlighter]; return options && ext.push(highlightConfig.of(options)), ext } var matchDeco = Decoration.mark({ class: "cm-selectionMatch" }), mainMatchDeco = Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); function insideWordBoundaries(check, state, from, to) { return (from == 0 || check(state.sliceDoc(from - 1, from)) != 0) && (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != 0) } function insideWord(check, state, from, to) { return check(state.sliceDoc(from, from + 1)) == 0 && check(state.sliceDoc(to - 1, to)) == 0 } var matchHighlighter = ViewPlugin.fromClass(class { decorations; constructor(view) { this.decorations = this.getDeco(view) } update(update) { (update.selectionSet || update.docChanged || update.viewportChanged) && (this.decorations = this.getDeco(update.view)) } getDeco(view) { let conf = view.state.facet(highlightConfig), { state } = view, sel = state.selection; if (sel.ranges.length > 1) return Decoration.none; let range = sel.main, query, check = null; if (range.empty) { if (!conf.highlightWordAroundCursor) return Decoration.none; let word = state.wordAt(range.head); if (!word) return Decoration.none; check = state.charCategorizer(range.head), query = state.sliceDoc(word.from, word.to) } else { let len = range.to - range.from; if (len < conf.minSelectionLength || len > 200) return Decoration.none; if (conf.wholeWords) { if (query = state.sliceDoc(range.from, range.to), check = state.charCategorizer(range.head), !(insideWordBoundaries(check, state, range.from, range.to) && insideWord(check, state, range.from, range.to))) return Decoration.none } else if (query = state.sliceDoc(range.from, range.to), !query) return Decoration.none } let deco = []; for (let part of view.visibleRanges) { let cursor = new SearchCursor(state.doc, query, part.from, part.to); for (; !cursor.next().done;) { let { from, to } = cursor.value; if ((!check || insideWordBoundaries(check, state, from, to)) && (range.empty && from <= range.from && to >= range.to ? deco.push(mainMatchDeco.range(from, to)) : (from >= range.to || to <= range.from) && deco.push(matchDeco.range(from, to)), deco.length > conf.maxMatches)) return Decoration.none } } return Decoration.set(deco) } }, { decorations: v => v.decorations }), defaultTheme = EditorView.baseTheme({ ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } }), selectWord = ({ state, dispatch }) => { let { selection } = state, newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); return newSel.eq(selection) ? !1 : (dispatch(state.update({ selection: newSel })), !0) }; function findNextOccurrence(state, query) { let { main, ranges } = state.selection, word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; for (let cycled = !1, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to); ;)if (cursor.next(), cursor.done) { if (cycled) return null; cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)), cycled = !0 } else { if (cycled && ranges.some(r => r.from == cursor.value.from)) continue; if (fullWord) { let word2 = state.wordAt(cursor.value.from); if (!word2 || word2.from != cursor.value.from || word2.to != cursor.value.to) continue } return cursor.value } } var selectNextOccurrence = ({ state, dispatch }) => { let { ranges } = state.selection; if (ranges.some(sel => sel.from === sel.to)) return selectWord({ state, dispatch }); let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) return !1; let range = findNextOccurrence(state, searchedText); return range ? (dispatch(state.update({ selection: state.selection.addRange(EditorSelection.range(range.from, range.to), !1), effects: EditorView.scrollIntoView(range.to) })), !0) : !1 }; var searchConfigFacet = Facet.define({ combine(configs) { return combineConfig(configs, { top: !1, caseSensitive: !1, literal: !1, regexp: !1, wholeWord: !1, createPanel: view => new SearchPanel(view), scrollToMatch: range => EditorView.scrollIntoView(range) }) } }); function search(config) { return config ? [searchConfigFacet.of(config), searchExtensions] : searchExtensions } var SearchQuery = class { + search; caseSensitive; literal; regexp; replace; valid; wholeWord; unquoted; test; constructor(config) { this.search = config.search, this.caseSensitive = !!config.caseSensitive, this.literal = !!config.literal, this.regexp = !!config.regexp, this.replace = config.replace || "", this.valid = !!this.search && (!this.regexp || validRegExp(this.search)), this.unquoted = this.unquote(this.search), this.wholeWord = !!config.wholeWord, this.test = config.test } unquote(text) { + return this.literal ? text : text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? ` +`: ch == "r" ? "\r" : ch == "t" ? " " : "\\") + } eq(other) { return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord && this.test == other.test } create() { return this.regexp ? new RegExpQuery(this) : new StringQuery(this) } getCursor(state, from = 0, to) { let st = state.doc ? state : EditorState.create({ doc: state }); return to == null && (to = st.doc.length), this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to) } +}, QueryType2 = class { constructor(spec) { this.spec = spec } spec }; function wrapStringTest(test, state, inner) { return (from, to, buffer, bufferPos) => { if (inner && !inner(from, to, buffer, bufferPos)) return !1; let match = from >= bufferPos && to <= bufferPos + buffer.length ? buffer.slice(from - bufferPos, to - bufferPos) : state.doc.sliceString(from, to); return test(match, state, from, to) } } function stringCursor(spec, state, from, to) { let test; return spec.wholeWord && (test = stringWordTest(state.doc, state.charCategorizer(state.selection.main.head))), spec.test && (test = wrapStringTest(spec.test, state, test)), new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : x => x.toLowerCase(), test) } function stringWordTest(doc2, categorizer) { return (from, to, buf, bufPos) => ((bufPos > from || bufPos + buf.length < to) && (bufPos = Math.max(0, from - 2), buf = doc2.sliceString(bufPos, Math.min(doc2.length, to + 2))), (categorizer(charBefore(buf, from - bufPos)) != 0 || categorizer(charAfter(buf, from - bufPos)) != 0) && (categorizer(charAfter(buf, to - bufPos)) != 0 || categorizer(charBefore(buf, to - bufPos)) != 0)) } var StringQuery = class extends QueryType2 { constructor(spec) { super(spec) } nextMatch(state, curFrom, curTo) { let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping(); if (cursor.done) { let end = Math.min(state.doc.length, curFrom + this.spec.unquoted.length); cursor = stringCursor(this.spec, state, 0, end).nextOverlapping() } return cursor.done || cursor.value.from == curFrom && cursor.value.to == curTo ? null : cursor.value } prevMatchInRange(state, from, to) { for (let pos = to; ;) { let start = Math.max(from, pos - 1e4 - this.spec.unquoted.length), cursor = stringCursor(this.spec, state, start, pos), range = null; for (; !cursor.nextOverlapping().done;)range = cursor.value; if (range) return range; if (start == from) return null; pos -= 1e4 } } prevMatch(state, curFrom, curTo) { let found = this.prevMatchInRange(state, 0, curFrom); return found || (found = this.prevMatchInRange(state, Math.max(0, curTo - this.spec.unquoted.length), state.doc.length)), found && (found.from != curFrom || found.to != curTo) ? found : null } getReplacement(_result) { return this.spec.unquote(this.spec.replace) } matchAll(state, limit) { let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = []; for (; !cursor.next().done;) { if (ranges.length >= limit) return null; ranges.push(cursor.value) } return ranges } highlight(state, from, to, add2) { let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length)); for (; !cursor.next().done;)add2(cursor.value.from, cursor.value.to) } }; function wrapRegexpTest(test, state, inner) { return (from, to, match) => (!inner || inner(from, to, match)) && test(match[0], state, from, to) } function regexpCursor(spec, state, from, to) { let test; return spec.wholeWord && (test = regexpWordTest(state.charCategorizer(state.selection.main.head))), spec.test && (test = wrapRegexpTest(spec.test, state, test)), new RegExpCursor(state.doc, spec.search, { ignoreCase: !spec.caseSensitive, test }, from, to) } function charBefore(str, index) { return str.slice(findClusterBreak2(str, index, !1), index) } function charAfter(str, index) { return str.slice(index, findClusterBreak2(str, index)) } function regexpWordTest(categorizer) { return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != 0 || categorizer(charAfter(match.input, match.index)) != 0) && (categorizer(charAfter(match.input, match.index + match[0].length)) != 0 || categorizer(charBefore(match.input, match.index + match[0].length)) != 0) } var RegExpQuery = class extends QueryType2 { nextMatch(state, curFrom, curTo) { let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next(); return cursor.done && (cursor = regexpCursor(this.spec, state, 0, curFrom).next()), cursor.done ? null : cursor.value } prevMatchInRange(state, from, to) { for (let size = 1; ; size++) { let start = Math.max(from, to - size * 1e4), cursor = regexpCursor(this.spec, state, start, to), range = null; for (; !cursor.next().done;)range = cursor.value; if (range && (start == from || range.from > start + 10)) return range; if (start == from) return null } } prevMatch(state, curFrom, curTo) { return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length) } getReplacement(result) { return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i2) => { if (i2 == "&") return result.match[0]; if (i2 == "$") return "$"; for (let l = i2.length; l > 0; l--) { let n = +i2.slice(0, l); if (n > 0 && n < result.match.length) return result.match[n] + i2.slice(l) } return m }) } matchAll(state, limit) { let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = []; for (; !cursor.next().done;) { if (ranges.length >= limit) return null; ranges.push(cursor.value) } return ranges } highlight(state, from, to, add2) { let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250), Math.min(to + 250, state.doc.length)); for (; !cursor.next().done;)add2(cursor.value.from, cursor.value.to) } }, setSearchQuery = StateEffect.define(), togglePanel = StateEffect.define(), searchState = StateField.define({ create(state) { return new SearchState(defaultQuery(state).create(), null) }, update(value, tr) { for (let effect of tr.effects) effect.is(setSearchQuery) ? value = new SearchState(effect.value.create(), value.panel) : effect.is(togglePanel) && (value = new SearchState(value.query, effect.value ? createSearchPanel : null)); return value }, provide: f => showPanel.from(f, val => val.panel) }); var SearchState = class { constructor(query, panel) { this.query = query; this.panel = panel } query; panel }, matchMark = Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }), searchHighlighter = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.decorations = this.highlight(view.state.field(searchState)) } view; decorations; update(update) { let state = update.state.field(searchState); (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) && (this.decorations = this.highlight(state)) } highlight({ query, panel }) { if (!panel || !query.spec.valid) return Decoration.none; let { view } = this, builder = new RangeSetBuilder; for (let i2 = 0, ranges = view.visibleRanges, l = ranges.length; i2 < l; i2++) { let { from, to } = ranges[i2]; for (; i2 < l - 1 && to > ranges[i2 + 1].from - 500;)to = ranges[++i2].to; query.highlight(view.state, from, to, (from2, to2) => { let selected = view.state.selection.ranges.some(r => r.from == from2 && r.to == to2); builder.add(from2, to2, selected ? selectedMatchMark : matchMark) }) } return builder.finish() } }, { decorations: v => v.decorations }); function searchCommand(f) { return view => { let state = view.state.field(searchState, !1); return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view) } } var findNext = searchCommand((view, { query }) => { let { to } = view.state.selection.main, next = query.nextMatch(view.state, to, to); if (!next) return !1; let selection = EditorSelection.single(next.from, next.to), config = view.state.facet(searchConfigFacet); return view.dispatch({ selection, effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)], userEvent: "select.search" }), selectSearchInput(view), !0 }), findPrevious = searchCommand((view, { query }) => { let { state } = view, { from } = state.selection.main, prev = query.prevMatch(state, from, from); if (!prev) return !1; let selection = EditorSelection.single(prev.from, prev.to), config = view.state.facet(searchConfigFacet); return view.dispatch({ selection, effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)], userEvent: "select.search" }), selectSearchInput(view), !0 }), selectMatches = searchCommand((view, { query }) => { let ranges = query.matchAll(view.state, 1e3); return !ranges || !ranges.length ? !1 : (view.dispatch({ selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), userEvent: "select.search.matches" }), !0) }), selectSelectionMatches = ({ state, dispatch }) => { let sel = state.selection; if (sel.ranges.length > 1 || sel.main.empty) return !1; let { from, to } = sel.main, ranges = [], main = 0; for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { if (ranges.length > 1e3) return !1; cur.value.from == from && (main = ranges.length), ranges.push(EditorSelection.range(cur.value.from, cur.value.to)) } return dispatch(state.update({ selection: EditorSelection.create(ranges, main), userEvent: "select.search.matches" })), !0 }, replaceNext = searchCommand((view, { query }) => { let { state } = view, { from, to } = state.selection.main; if (state.readOnly) return !1; let match = query.nextMatch(state, from, from); if (!match) return !1; let next = match, changes = [], selection, replacement, effects = []; next.from == from && next.to == to && (replacement = state.toText(query.getReplacement(next)), changes.push({ from: next.from, to: next.to, insert: replacement }), next = query.nextMatch(state, next.from, next.to), effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."))); let changeSet = view.state.changes(changes); return next && (selection = EditorSelection.single(next.from, next.to).map(changeSet), effects.push(announceMatch(view, next)), effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view))), view.dispatch({ changes: changeSet, selection, effects, userEvent: "input.replace" }), !0 }), replaceAll = searchCommand((view, { query }) => { if (view.state.readOnly) return !1; let changes = query.matchAll(view.state, 1e9).map(match => { let { from, to } = match; return { from, to, insert: query.getReplacement(match) } }); if (!changes.length) return !1; let announceText = view.state.phrase("replaced $ matches", changes.length) + "."; return view.dispatch({ changes, effects: EditorView.announce.of(announceText), userEvent: "input.replace.all" }), !0 }); function createSearchPanel(view) { return view.state.facet(searchConfigFacet).createPanel(view) } function defaultQuery(state, fallback) { let sel = state.selection.main, selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); if (fallback && !selText) return fallback; let config = state.facet(searchConfigFacet); return new SearchQuery({ search: fallback?.literal ?? config.literal ? selText : selText.replace(/\n/g, "\\n"), caseSensitive: fallback?.caseSensitive ?? config.caseSensitive, literal: fallback?.literal ?? config.literal, regexp: fallback?.regexp ?? config.regexp, wholeWord: fallback?.wholeWord ?? config.wholeWord }) } function getSearchInput(view) { let panel = getPanel(view, createSearchPanel); return panel && panel.dom.querySelector("[main-field]") } function selectSearchInput(view) { let input = getSearchInput(view); input && input == view.root.activeElement && input.select() } var openSearchPanel = view => { let state = view.state.field(searchState, !1); if (state && state.panel) { let searchInput = getSearchInput(view); if (searchInput && searchInput != view.root.activeElement) { let query = defaultQuery(view.state, state.query.spec); query.valid && view.dispatch({ effects: setSearchQuery.of(query) }), searchInput.focus(), searchInput.select() } } else view.dispatch({ effects: [togglePanel.of(!0), state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)] }); return !0 }, closeSearchPanel = view => { let state = view.state.field(searchState, !1); if (!state || !state.panel) return !1; let panel = getPanel(view, createSearchPanel); return panel && panel.dom.contains(view.root.activeElement) && view.focus(), view.dispatch({ effects: togglePanel.of(!1) }), !0 }, searchKeymap = [{ key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: !0 }, { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: !0 }, { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, { key: "Mod-Shift-l", run: selectSelectionMatches }, { key: "Mod-Alt-g", run: gotoLine }, { key: "Mod-d", run: selectNextOccurrence, preventDefault: !0 }], SearchPanel = class { constructor(view) { this.view = view; let query = this.query = view.state.field(searchState).query.spec; this.commit = this.commit.bind(this), this.searchField = crelt("input", { value: query.search, placeholder: phrase(view, "Find"), "aria-label": phrase(view, "Find"), class: "cm-textfield", name: "search", form: "", "main-field": "true", onchange: this.commit, onkeyup: this.commit }), this.replaceField = crelt("input", { value: query.replace, placeholder: phrase(view, "Replace"), "aria-label": phrase(view, "Replace"), class: "cm-textfield", name: "replace", form: "", onchange: this.commit, onkeyup: this.commit }), this.caseField = crelt("input", { type: "checkbox", name: "case", form: "", checked: query.caseSensitive, onchange: this.commit }), this.reField = crelt("input", { type: "checkbox", name: "re", form: "", checked: query.regexp, onchange: this.commit }), this.wordField = crelt("input", { type: "checkbox", name: "word", form: "", checked: query.wholeWord, onchange: this.commit }); function button(name2, onclick, content2) { return crelt("button", { class: "cm-button", name: name2, onclick, type: "button" }, content2) } this.dom = crelt("div", { onkeydown: e => this.keydown(e), class: "cm-search" }, [this.searchField, button("next", () => findNext(view), [phrase(view, "next")]), button("prev", () => findPrevious(view), [phrase(view, "previous")]), button("select", () => selectMatches(view), [phrase(view, "all")]), crelt("label", null, [this.caseField, phrase(view, "match case")]), crelt("label", null, [this.reField, phrase(view, "regexp")]), crelt("label", null, [this.wordField, phrase(view, "by word")]), ...view.state.readOnly ? [] : [crelt("br"), this.replaceField, button("replace", () => replaceNext(view), [phrase(view, "replace")]), button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])], crelt("button", { name: "close", onclick: () => closeSearchPanel(view), "aria-label": phrase(view, "close"), type: "button" }, ["\xD7"])]) } view; searchField; replaceField; caseField; reField; wordField; dom; query; commit() { let query = new SearchQuery({ search: this.searchField.value, caseSensitive: this.caseField.checked, regexp: this.reField.checked, wholeWord: this.wordField.checked, replace: this.replaceField.value }); query.eq(this.query) || (this.query = query, this.view.dispatch({ effects: setSearchQuery.of(query) })) } keydown(e) { runScopeHandlers(this.view, e, "search-panel") ? e.preventDefault() : e.keyCode == 13 && e.target == this.searchField ? (e.preventDefault(), (e.shiftKey ? findPrevious : findNext)(this.view)) : e.keyCode == 13 && e.target == this.replaceField && (e.preventDefault(), replaceNext(this.view)) } update(update) { for (let tr of update.transactions) for (let effect of tr.effects) effect.is(setSearchQuery) && !effect.value.eq(this.query) && this.setQuery(effect.value) } setQuery(query) { this.query = query, this.searchField.value = query.search, this.replaceField.value = query.replace, this.caseField.checked = query.caseSensitive, this.reField.checked = query.regexp, this.wordField.checked = query.wholeWord } mount() { this.searchField.select() } get pos() { return 80 } get top() { return this.view.state.facet(searchConfigFacet).top } }; function phrase(view, phrase2) { return view.state.phrase(phrase2) } var AnnounceMargin = 30, Break = /[\s\.,:;?!]/; function announceMatch(view, { from, to }) { let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to, start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin), text = view.state.sliceDoc(start, end); if (start != line.from) { for (let i2 = 0; i2 < AnnounceMargin; i2++)if (!Break.test(text[i2 + 1]) && Break.test(text[i2])) { text = text.slice(i2); break } } if (end != lineEnd) { for (let i2 = text.length - 1; i2 > text.length - AnnounceMargin; i2--)if (!Break.test(text[i2 - 1]) && Break.test(text[i2])) { text = text.slice(0, i2); break } } return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`) } var baseTheme5 = EditorView.baseTheme({ ".cm-panel.cm-search": { padding: "2px 6px 4px", position: "relative", "& [name=close]": { position: "absolute", top: "0", right: "4px", backgroundColor: "inherit", border: "none", font: "inherit", padding: 0, margin: 0 }, "& input, & button, & label": { margin: ".2em .6em .2em 0" }, "& input[type=checkbox]": { marginRight: ".2em" }, "& label": { fontSize: "80%", whiteSpace: "pre" } }, "&light .cm-searchMatch": { backgroundColor: "#ffff0054" }, "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" }, "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" }, "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" } }), searchExtensions = [searchState, Prec.low(searchHighlighter), baseTheme5]; export { Annotation, AnnotationType, BidiSpan, BlockInfo, BlockType, BlockWrapper, ChangeDesc, ChangeSet, CharCategory, Compartment, Decoration, Direction, EditorSelection, EditorState, EditorView, Facet, GutterMarker, HighlightStyle, LanguageSupport, Line, MapMode, MatchDecorator, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, RectangleMarker, SelectionRange, StateEffect, StateEffectType, StateField, StreamLanguage, Text, Transaction, ViewPlugin, ViewUpdate, WidgetType, __test, bracketMatching, closeHoverTooltips, closeSearchPanel, codeFolding, codePointAt2 as codePointAt, codePointSize2 as codePointSize, combineConfig, countColumn, crosshairCursor, defaultHighlightStyle, defaultKeymap, drawSelection, dropCursor, findClusterBreak2 as findClusterBreak, findColumn, foldGutter, foldKeymap, foldService, fromCodePoint, getDialog, getDrawSelectionConfig, getPanel, getTooltip, gotoLine, gutter, gutterLineClass, gutterWidgetClass, gutters, hasHoverTooltips, highlightActiveLine, highlightActiveLineGutter, highlightSelectionMatches, highlightSpecialChars, highlightTrailingWhitespace, highlightWhitespace, history, historyKeymap, hoverTooltip, indentLess, indentMore, indentService, indentUnit, indentWithTab, insertNewlineAndIndent, keymap, layer, lineNumberMarkers, lineNumberWidgetMarker, lineNumbers, logException, openSearchPanel, panels, placeholder2 as placeholder, rectangularSelection, redo, repositionTooltips, runScopeHandlers, scrollPastEnd, search, searchKeymap, selectAll, showDialog, showPanel, showTooltip, syntaxHighlighting, toggleComment, tooltips, undo }; diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..c45491f --- /dev/null +++ b/styles.css @@ -0,0 +1,4239 @@ +/* Programming+: a lab notebook for algorithms. Tokens first; light and dark; IBM Plex in two voices. */ +:root { + --paper: #f7f8fa; + --paper-2: #ffffff; + --paper-3: #eef0f4; + --ink: #16191f; + --ink-2: #5c6370; + --ink-3: #8a919c; + --line: #dde1e8; + --line-2: #c9cfd8; + --accent: #2f5bea; + --accent-ink: #ffffff; + --accent-bg: #e7edfd; + --marker: #f6c453; + --marker-bg: #fff3cf; + --last-bg: #e3ecfb; + --ok: #1f9d63; + --ok-bg: #e2f5ea; + --warn: #b5700d; + --warn-bg: #fdf0d6; + --err: #d64545; + --err-bg: #fbe3e3; + --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace; + --sans: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --r: 6px; + --r-lg: 10px; + --shadow: 0 10px 30px rgba(22, 25, 31, .10); + --tok-keyword: #1d46c7; + --tok-builtin: #7a3fc4; + --tok-string: #a8580d; + --tok-number: #0f7b6c; + --tok-comment: #8a919c; + --tok-label: #b4247a; + /* the P+ mark: a light tile on the light theme, a dark one on the dark theme */ + --brand-bg: #f6c453; + --brand-fg: #16191f; + --brand-edge: #e0ab35; + color-scheme: light; +} + +:root[data-theme="dark"] { + --paper: #141821; + --paper-2: #1b2029; + --paper-3: #232935; + --ink: #e9ecf1; + --ink-2: #a7afbc; + --ink-3: #7c8594; + --line: #2c333f; + --line-2: #3b4452; + --accent: #8db0ff; + --accent-ink: #0f1626; + --accent-bg: #1f2b4a; + --marker: #f0c05a; + --marker-bg: #4a3c12; + --last-bg: #1f3350; + --ok: #5fd39a; + --ok-bg: #16331f; + --warn: #f0b860; + --warn-bg: #3a2c12; + --err: #ff8585; + --err-bg: #3f1b1b; + --shadow: 0 10px 30px rgba(0, 0, 0, .45); + --tok-keyword: #8db0ff; + --tok-builtin: #c9a7ff; + --tok-string: #f2b56b; + --tok-number: #5fd3c6; + --tok-comment: #7c8594; + --tok-label: #f49ac2; + --brand-bg: #0e1117; + --brand-fg: #f0c05a; + --brand-edge: #2c333f; + color-scheme: dark; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]):not([data-theme="dark"]) { + --paper: #141821; + --paper-2: #1b2029; + --paper-3: #232935; + --ink: #e9ecf1; + --ink-2: #a7afbc; + --ink-3: #7c8594; + --line: #2c333f; + --line-2: #3b4452; + --accent: #8db0ff; + --accent-ink: #0f1626; + --accent-bg: #1f2b4a; + --marker: #f0c05a; + --marker-bg: #4a3c12; + --last-bg: #1f3350; + --ok: #5fd39a; + --ok-bg: #16331f; + --warn: #f0b860; + --warn-bg: #3a2c12; + --err: #ff8585; + --err-bg: #3f1b1b; + --shadow: 0 10px 30px rgba(0, 0, 0, .45); + --tok-keyword: #8db0ff; + --tok-builtin: #c9a7ff; + --tok-string: #f2b56b; + --tok-number: #5fd3c6; + --tok-comment: #7c8594; + --tok-label: #f49ac2; + --brand-bg: #0e1117; + --brand-fg: #f0c05a; + --brand-edge: #2c333f; + color-scheme: dark; + } +} + +/* legacy aliases used by older rules */ +:root { + --bg: var(--paper); + --bg-2: var(--paper-2); + --bg-3: var(--paper-3); + --fg: var(--ink); + --fg-2: var(--ink-2); + --note: var(--ink-3); + --current: var(--marker-bg); + --last: var(--last-bg); + --radius: var(--r-lg); +} + +* { + box-sizing: border-box; +} + +html, +body { + height: 100%; +} + +body { + margin: 0; + background: var(--paper); + color: var(--ink); + font: 14px/1.5 var(--sans); + -webkit-font-smoothing: antialiased; +} + +body.is-embed { + background: var(--paper-2); +} + +#app { + height: 100%; +} + +a { + color: var(--accent); + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +h1, +h2, +h3, +h4 { + margin: 0 0 .4em; + font-weight: 600; + line-height: 1.2; + letter-spacing: -.01em; +} + +h4 { + font-size: 13px; + color: var(--ink-2); + font-weight: 600; + margin: 14px 0 6px; + letter-spacing: 0; +} + +code, +.mono { + font-family: var(--mono); + font-size: 12.5px; +} + +.muted { + color: var(--ink-2); +} + +.small { + font-size: 12px; +} + +.hint { + font-size: 12.5px; + color: var(--ink-2); + background: var(--paper-3); + border-left: 3px solid var(--accent); + padding: 6px 10px; + border-radius: 4px; + margin: 0 0 10px; +} + +.math { + font-family: "STIX Two Math", "Cambria Math", var(--mono); + font-size: 13px; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +@media (prefers-reduced-motion: reduce) { + + *, + *::before, + *::after { + transition: none !important; + animation: none !important; + } +} + +/* ---------- controls ---------- */ +.btn { + font: inherit; + font-size: 13px; + padding: 5px 11px; + border: 1px solid var(--line-2); + border-radius: var(--r); + background: var(--paper-2); + color: var(--ink); + cursor: pointer; + transition: border-color .12s, background .12s; +} + +.btn:hover { + border-color: var(--ink-3); +} + +.btn-primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); + font-weight: 600; +} + +.btn-primary:hover { + filter: brightness(1.06); +} + +.btn-quiet { + background: transparent; + border-color: transparent; + color: var(--ink-2); +} + +.btn-quiet:hover { + background: var(--paper-3); + border-color: transparent; +} + +.btn-small { + padding: 2px 8px; + font-size: 12px; +} + +.btn-option { + margin: 4px 6px 0 0; + background: var(--accent-bg); + border-color: transparent; +} + +.btn.on { + background: var(--accent-bg); + border-color: var(--accent); + color: var(--accent); +} + +.linkish { + background: none; + border: 0; + padding: 0; + color: var(--accent); + cursor: pointer; + font: inherit; + text-decoration: underline dotted; +} + +.select, +.input { + font: inherit; + font-size: 13px; + padding: 5px 8px; + border: 1px solid var(--line-2); + border-radius: var(--r); + background: var(--paper-2); + color: var(--ink); +} + +.input { + min-width: 240px; +} + +.tool-label { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--ink-2); + font-size: 12.5px; +} + +.badge { + display: inline-block; + font-size: 11.5px; + padding: 1px 8px; + border-radius: 10px; + font-weight: 600; + margin-right: 6px; + line-height: 1.6; +} + +.badge-proved { + background: var(--ok-bg); + color: var(--ok); +} + +.badge-broken { + background: var(--err-bg); + color: var(--err); +} + +.badge-open { + background: var(--warn-bg); + color: var(--warn); +} + +.chip { + display: inline-block; + font-size: 11.5px; + padding: 1px 8px; + border-radius: 10px; + background: var(--paper-3); + color: var(--ink-2); + margin-right: 4px; + line-height: 1.6; +} + +.chip-saved { + background: var(--ok-bg); + color: var(--ok); +} + +.chip-level-intro { + background: var(--ok-bg); + color: var(--ok); +} + +.chip-level-advanced { + background: var(--warn-bg); + color: var(--warn); +} + +.chip-tag { + background: transparent; + border: 1px solid var(--line); +} + +kbd { + font-family: var(--mono); + font-size: 11px; + padding: 1px 6px; + border: 1px solid var(--line-2); + border-bottom-width: 2px; + border-radius: 4px; + background: var(--paper-2); + color: var(--ink); +} + +/* a segmented switch: Mojo | pseudo */ +.seg { + display: inline-flex; + border: 1px solid var(--line-2); + border-radius: 999px; + padding: 2px; + background: var(--paper-2); + gap: 2px; +} + +.seg-opt { + font: inherit; + font-size: 12.5px; + font-weight: 600; + padding: 3px 12px; + border: 0; + border-radius: 999px; + background: transparent; + color: var(--ink-2); + cursor: pointer; +} + +.seg-opt:hover { + color: var(--ink); +} + +.seg-opt.on { + background: var(--ink); + color: var(--paper); +} + +/* ---------- top bar ---------- */ +.toolbar { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 14px; + border-bottom: 1px solid var(--line); + background: var(--paper-2); + flex-wrap: wrap; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 8px; + font-weight: 700; + font-size: 15px; + color: var(--ink); + margin-right: 6px; + white-space: nowrap; + letter-spacing: -.01em; +} + +.brand:hover { + text-decoration: none; +} + +.brand-mark { + min-width: 22px; + height: 22px; + padding: 0 4px; + border-radius: 6px; + background: var(--brand-bg); + color: var(--brand-fg); + box-shadow: inset 0 0 0 1px var(--brand-edge); + display: inline-grid; + place-items: center; + font-family: var(--mono); + font-size: 11px; + font-weight: 700; +} + +.spacer { + flex: 1; +} + +.icon-btn { + width: 32px; + height: 32px; + padding: 0; + display: inline-grid; + place-items: center; + font-size: 15px; +} + +/* ---------- home ---------- */ +.home { + max-width: 1120px; + margin: 0 auto; + padding: 0 24px 64px; +} + +.home-nav { + display: flex; + align-items: center; + gap: 16px; + padding: 18px 0 8px; +} + +.home-nav a { + color: var(--ink-2); + font-size: 13.5px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); + gap: 40px; + align-items: center; + padding: 36px 0 44px; + border-bottom: 1px solid var(--line); +} + +.hero h1 { + font-size: 44px; + line-height: 1.08; + letter-spacing: -.025em; + margin: 0 0 16px; + max-width: 14ch; +} + +.hero .lede { + font-size: 17px; + color: var(--ink-2); + margin: 0 0 22px; + max-width: 48ch; + line-height: 1.5; +} + +.hero-actions { + display: flex; + gap: 10px; + flex-wrap: wrap; +} + +.hero-actions .btn { + padding: 9px 16px; + font-size: 14px; +} + +.demo { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + overflow: hidden; + box-shadow: var(--shadow); +} + +.demo-head { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-bottom: 1px solid var(--line); + font-size: 12.5px; + color: var(--ink-2); +} + +.demo-head b { + color: var(--ink); + font-weight: 600; +} + +.demo-code { + margin: 0; + padding: 12px 14px; + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.7; + white-space: pre; + overflow-x: auto; +} + +.demo-line { + display: block; + padding: 0 6px; + margin: 0 -6px; + border-radius: 3px; +} + +.demo-line.cur { + background: var(--marker-bg); + box-shadow: inset 3px 0 var(--marker); +} + +.demo-foot { + display: grid; + grid-template-columns: 1fr auto; + gap: 10px; + align-items: center; + padding: 10px 12px; + border-top: 1px solid var(--line); + background: var(--paper); +} + +.demo-vars { + display: flex; + gap: 14px; + font-family: var(--mono); + font-size: 12.5px; + flex-wrap: wrap; +} + +.demo-vars b { + font-weight: 600; +} + +.demo-vars .v-new { + background: var(--last-bg); + border-radius: 3px; + padding: 0 4px; +} + +.demo-ctl { + display: flex; + gap: 4px; +} + +.ruler { + display: inline-flex; + gap: 2px; + font-family: var(--mono); +} + +.ruler-cell { + display: inline-flex; + flex-direction: column; + align-items: center; + min-width: 20px; + line-height: 1.1; + border-radius: 3px; + padding: 2px 1px; +} + +.ruler-cell b { + font-weight: 600; + font-size: 13px; +} + +.ruler-cell i { + font-style: normal; + font-size: 9.5px; + color: var(--ink-3); +} + +.ruler-cell.read { + background: var(--marker-bg); + box-shadow: inset 0 -2px var(--marker); +} + +.ruler-cell.wrote { + background: var(--last-bg); +} + +.how { + padding: 36px 0 28px; + border-bottom: 1px solid var(--line); +} + +.how .hero-actions { + margin-top: 18px; +} + +.how h2, +.home-h2, +.reference h2 { + font-size: 24px; + letter-spacing: -.02em; + margin-bottom: 6px; +} + +.how>p, +.home-sub { + color: var(--ink-2); + max-width: 64ch; + margin: 0 0 18px; +} + +.ways { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 10px; +} + +.way { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 12px 12px 10px; + min-width: 0; +} + +.way h3 { + font-size: 14px; + margin: 0 0 2px; +} + +.way p { + margin: 0 0 8px; + font-size: 12.5px; + color: var(--ink-2); + min-height: 3.6em; +} + +.way pre { + margin: 0; + font-family: var(--mono); + font-size: 11px; + line-height: 1.5; + white-space: pre; + overflow: hidden; + color: var(--ink); + border-top: 1px solid var(--line); + padding-top: 8px; +} + +.problems-head { + display: flex; + align-items: baseline; + gap: 16px; + flex-wrap: wrap; + margin: 40px 0 12px; +} + +.filters { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 14px; +} + +.filter { + font: inherit; + font-size: 12.5px; + padding: 3px 10px; + border-radius: 12px; + border: 1px solid var(--line-2); + background: var(--paper-2); + color: var(--ink-2); + cursor: pointer; +} + +.filter.on { + background: var(--ink); + color: var(--paper); + border-color: var(--ink); +} + +.search { + min-width: 220px; +} + +.home-group { + font-size: 13px; + color: var(--ink-2); + margin: 20px 0 8px; + font-weight: 600; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 12px; +} + +.card { + display: block; + color: inherit; + background: var(--paper-2); + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 14px 16px 12px; + transition: border-color .12s; +} + +.card:hover { + border-color: var(--accent); + text-decoration: none; +} + +.card h3 { + font-size: 15px; + margin-bottom: 4px; +} + +.card p { + margin: 0 0 10px; + color: var(--ink-2); + font-size: 13px; +} + +.card-meta, +.card-foot { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.card-meta { + margin-bottom: 6px; +} + +.home-foot { + margin-top: 40px; + color: var(--ink-2); + font-size: 12.5px; + border-top: 1px solid var(--line); + padding-top: 14px; +} + +/* ---------- shell: an IDE layout ---------- */ +.shell { + display: flex; + flex-direction: column; + height: 100%; +} + +.workspace { + --dock: 68%; + flex: 1; + min-height: 0; + display: grid; + grid-template-rows: minmax(0, var(--dock)) 6px minmax(0, 1fr); +} + +.workspace.dock-collapsed { + grid-template-rows: minmax(0, 1fr) 0 auto; +} + +.workspace.dock-collapsed .splitter-y { + display: none; +} + +.workspace.dock-collapsed .dock-body { + display: none; +} + +.main { + --split: 54%; + min-height: 0; + display: grid; + grid-template-columns: minmax(280px, var(--split)) 6px minmax(320px, 1fr); +} + +.panes, +.side { + min-height: 0; + min-width: 0; + display: flex; + flex-direction: column; +} + +.side { + background: var(--paper); + border-left: 0; +} + +/* tabs: file tabs over the editor, panel tabs elsewhere */ +.tabs { + display: flex; + gap: 2px; + padding: 6px 10px 0; + border-bottom: 1px solid var(--line); + background: var(--paper); + overflow-x: auto; + align-items: flex-end; + flex-shrink: 0; +} + +.tab { + font: inherit; + font-size: 13px; + padding: 6px 12px; + border: 1px solid transparent; + border-bottom: 0; + border-radius: var(--r) var(--r) 0 0; + background: transparent; + color: var(--ink-2); + cursor: pointer; + white-space: nowrap; + display: inline-flex; + align-items: center; + gap: 6px; +} + +.tab:hover { + color: var(--ink); +} + +.tab.active { + background: var(--paper-2); + border-color: var(--line); + color: var(--ink); + font-weight: 600; + margin-bottom: -1px; +} + +.tab.tab-dim { + color: var(--ink-3); +} + +.pane-tabs .tab-dim .tab-dot { + opacity: .3; +} + +/* the Bridge sets the generated Mojo tab slightly apart from the four languages kept in step */ +.pane-tabs .tab-apart { + margin-left: 14px; +} + +/* where a pane stands against the others: edited here, in step, or not in step */ +.tab-state { + font-size: 11px; + margin-left: 5px; + color: var(--ink-3); +} + +.tab-link-stale .tab-state { + color: var(--warn); +} + +.pane-stale { + color: var(--warn); +} + +.badge-generated { + background: var(--warn-bg); + color: var(--warn); + border: 1px dashed currentColor; +} + +.tab.tab-dim.active { + color: var(--ink-2); +} + +.tab-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--ink-3); + opacity: .7; +} + +.tab-lingo .tab-dot { + background: var(--lang-lingo); +} + +.tab-matho .tab-dot { + background: var(--lang-matho); +} + +.tab-pseudo .tab-dot { + background: var(--lang-pseudo); +} + +.tab-speco .tab-dot { + background: var(--lang-speco); +} + +.tab-mojo .tab-dot { + background: var(--lang-mojo); +} + +.tab-asm .tab-dot { + background: var(--lang-asm); +} + +.tab-badge { + display: inline-block; + min-width: 16px; + padding: 0 5px; + border-radius: 8px; + font-size: 11px; + font-weight: 600; + background: var(--paper-3); + color: var(--ink-2); +} + +.tab-badge.err { + background: var(--err-bg); + color: var(--err); +} + +.tab-badge.warn { + background: var(--warn-bg); + color: var(--warn); +} + +.tabs .spacer { + flex: 1; +} + +.tabs-tool { + font-size: 12px; + color: var(--ink-2); + padding: 0 4px 6px; + white-space: nowrap; +} + +.badge { + white-space: nowrap; +} + +.tab-toggle { + margin-left: auto; + font-size: 14px; + padding: 4px 10px; +} + +.inspect-tabs .tab, +.dock-tabs .tab { + font-size: 12.5px; + padding: 5px 10px; +} + +.inspect-tabs .tab-toggle { + margin-left: 4px; + padding: 3px 8px; +} + +/* the editor column */ +.pane-split { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: minmax(0, 1fr); + background: var(--paper-2); +} + +.pane-host { + min-height: 0; + display: flex; +} + +.pane-host .ed { + flex: 1; +} + +.pane-head { + display: flex; + align-items: center; + gap: 10px; + padding: 4px 12px; + border-bottom: 1px solid var(--line); + background: var(--paper); + font-size: 12px; + min-height: 30px; + flex-shrink: 0; +} + +.pane-note { + color: var(--ink-2); + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.pane-note b { + font-weight: 600; + color: var(--ink); +} + +.tool-label.tool-check { + gap: 4px; + cursor: pointer; + white-space: nowrap; +} + +/* the side column: run setup, controls, next, variables, inspect */ +.setup { + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; +} + +.setup-head { + width: 100%; + display: flex; + align-items: center; + gap: 8px; + font: inherit; + font-size: 12px; + font-weight: 600; + color: var(--ink-2); + background: transparent; + border: 0; + padding: 6px 12px; + cursor: pointer; + text-align: left; +} + +.setup-head:hover { + color: var(--ink); +} + +.setup-caret { + width: 10px; + font-size: 10px; +} + +.setup-summary { + font-weight: 400; + font-family: var(--mono); + font-size: 11.5px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; +} + +.setup-grid { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + gap: 6px 10px; + align-items: start; + padding: 2px 12px 10px; +} + +.setup-label { + font-size: 12px; + color: var(--ink-2); + padding-top: 5px; + white-space: nowrap; +} + +.setup-grid .input, +.setup-grid .select { + width: 100%; + margin: 0; +} + +.setup-ta { + resize: vertical; + min-height: 44px; + line-height: 1.4; + font-size: 12.5px; + border: 1px solid var(--line-2); + border-radius: var(--r); + padding: 5px 8px; + background: var(--paper-2); + color: var(--ink); + font-family: var(--mono); + display: block; +} + +.run-bar { + padding: 6px 14px 4px; + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; + outline: none; + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; +} + +.run-bar .run-controls { + display: flex; + align-items: center; + gap: 14px; + flex: 1; + min-width: 0; + flex-wrap: wrap; +} + +.run-bar .run-controls .stepper { + flex: 1; + min-width: 320px; + margin: 0; +} + +.run-bar .run-controls .stepper-row2 { + margin: 0; +} + +.run-bar .run-status { + white-space: nowrap; +} + +.view-setup { + padding: 10px 14px 14px; +} + +.view-setup .setup-grid { + max-width: 760px; + padding: 0; +} + +.setup-note { + margin: 10px 0 0; + max-width: 76ch; +} + +.tab-note { + font-size: 11px; + color: var(--ink-3); + font-weight: 400; + max-width: 240px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tab.active .tab-note { + color: var(--ink-2); +} + +.run-bar:focus-visible { + box-shadow: inset 0 0 0 2px var(--accent); +} + +.run-controls .stepper { + margin-bottom: 4px; +} + +.run-controls .stepper-row2 { + margin-bottom: 2px; +} + +.run-controls .stepper .btn, +.run-controls .stepper-row2 .btn { + padding: 3px 8px; + font-size: 12px; +} + +.run-status { + font-size: 11.5px; + color: var(--ink-2); + min-height: 0; + font-variant-numeric: tabular-nums; +} + +.run-status:empty { + display: none; +} + +.next-host { + padding: 8px 12px 0; + background: var(--paper); + flex-shrink: 0; + border-bottom: 1px solid var(--line); +} + +.next-host .trace-next { + margin-bottom: 8px; +} + +.next-host .predict { + margin-bottom: 8px; +} + +.side-split { + --right: 50%; + flex: 1; + min-height: 0; + min-width: 0; + display: grid; + grid-template-rows: minmax(60px, var(--right)) 6px minmax(60px, 1fr); + grid-template-columns: minmax(0, 1fr); +} + +.side-split.inspect-max { + grid-template-rows: minmax(60px, 1fr); +} + +.side-split.inspect-max .panel-vars, +.side-split.inspect-max>.splitter { + display: none; +} + +.panel { + min-height: 0; + min-width: 0; + display: flex; + flex-direction: column; + background: var(--paper-2); +} + +.panel-title { + font-size: 12px; + font-weight: 600; + color: var(--ink-2); + padding: 6px 12px; + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; +} + +.panel-body { + flex: 1; + min-height: 0; + overflow: auto; + padding: 8px 12px 16px; +} + +.vars-host .vars-tbl { + margin-bottom: 8px; +} + +.inspect-host { + padding: 0; + overflow: hidden; + display: flex; + flex-direction: column; +} + +.inspect-view { + padding: 8px 12px 16px; + flex: 1; + min-height: 0; + overflow: auto; +} + +.inspect-view.view { + padding: 10px 12px 20px; + display: flex; + flex-direction: column; +} + +.inspect-view.view>.viz-scroll { + flex: 1; + min-height: 0; + max-height: none; + min-width: 0; + width: 100%; + align-self: stretch; +} + +.inspect-view.view>.viz-head { + flex-shrink: 0; +} + +.legend { + font-size: 11.5px; + color: var(--ink-2); + position: relative; + align-self: center; + margin-bottom: 4px; +} + +.legend summary { + cursor: pointer; + list-style: none; + padding: 2px 8px; + border-radius: 10px; + border: 1px solid var(--line); +} + +.legend summary::-webkit-details-marker { + display: none; +} + +.legend[open] summary { + background: var(--paper-3); +} + +.legend-list { + position: absolute; + right: 0; + top: calc(100% + 4px); + z-index: 5; + background: var(--paper-2); + border: 1px solid var(--line); + border-radius: var(--r); + box-shadow: var(--shadow); + padding: 8px 10px; + display: grid; + gap: 4px; + min-width: 190px; +} + +.legend-item { + display: flex; + align-items: center; + gap: 8px; + white-space: nowrap; +} + +/* the dock */ +.dock { + min-height: 0; + display: flex; + flex-direction: column; + background: var(--paper-2); + border-top: 1px solid var(--line); +} + +.dock-body { + flex: 1; + min-height: 0; + overflow: auto; +} + +.view { + padding: 10px 14px 20px; +} + +.view-output { + padding: 8px 14px 14px; +} + +.view-output .trace-output { + margin: 0; + border: 0; + background: transparent; + padding: 0; + font-size: 13px; +} + +.output-empty { + margin: 0; +} + +.splitter { + background: var(--line); + cursor: col-resize; + position: relative; + touch-action: none; +} + +.splitter::after { + content: ''; + position: absolute; + inset: 0 -4px; +} + +.splitter:hover, +.splitter.dragging, +.splitter:focus-visible { + background: var(--accent); + outline: none; +} + +body.resizing { + cursor: col-resize; + user-select: none; +} + +body.resizing-y { + cursor: row-resize; +} + +.splitter-y { + cursor: row-resize; +} + +.splitter-y::after { + inset: -4px 0; +} + +body.resizing iframe, +body.resizing textarea { + pointer-events: none; +} + +/* narrow screens: everything stacks */ +@media (max-width: 900px) { + .shell { + height: auto; + min-height: 100%; + } + + .workspace { + display: flex; + flex-direction: column; + } + + .main { + display: flex; + flex-direction: column; + } + + .main>.splitter, + .workspace>.splitter, + .side-split>.splitter { + display: none; + } + + .panes { + min-height: 320px; + } + + .pane-host .ed { + min-height: 300px; + } + + .side-split { + display: flex; + flex-direction: column; + } + + .panel-body { + max-height: 360px; + } + + .dock-body { + max-height: 50vh; + } +} + +/* step colors: what a step does, the same everywhere */ +:root { + --k-write: #2f5bea; + --k-decision: #b5700d; + --k-loop: #7a3fc4; + --k-call: #0f7b6c; + --k-return: #1f9d63; + --k-io: #b4247a; + --k-life: #8a919c; + --k-error: #d64545; + --k-other: #c9cfd8; + --lang-lingo: #1f9d63; + --lang-matho: #b5700d; + --lang-pseudo: #2f5bea; + --lang-speco: #7a3fc4; + --lang-mojo: #e0592a; + --lang-asm: #5c6370; +} + +:root[data-theme="dark"] { + --k-write: #8db0ff; + --k-decision: #f0b860; + --k-loop: #c9a7ff; + --k-call: #5fd3c6; + --k-return: #5fd39a; + --k-io: #f49ac2; + --k-life: #7c8594; + --k-error: #ff8585; + --k-other: #3b4452; + --lang-mojo: #ff8a5c; + --lang-asm: #a7afbc; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]):not([data-theme="dark"]) { + --k-write: #8db0ff; + --k-decision: #f0b860; + --k-loop: #c9a7ff; + --k-call: #5fd3c6; + --k-return: #5fd39a; + --k-io: #f49ac2; + --k-life: #7c8594; + --k-error: #ff8585; + --k-other: #3b4452; + --lang-mojo: #ff8a5c; + --lang-asm: #a7afbc; + } +} + +.k-dot { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--k-other); + margin-right: 5px; + vertical-align: middle; + flex-shrink: 0; +} + +.k-dot.k-write { + background: var(--k-write); +} + +.k-dot.k-decision { + background: var(--k-decision); +} + +.k-dot.k-loop { + background: var(--k-loop); +} + +.k-dot.k-call { + background: var(--k-call); +} + +.k-dot.k-return { + background: var(--k-return); +} + +.k-dot.k-io { + background: var(--k-io); +} + +.k-dot.k-life { + background: var(--k-life); +} + +.k-dot.k-error { + background: var(--k-error); +} + +.trace-tbl tr.k-write td:first-child { + box-shadow: inset 3px 0 var(--k-write); +} + +.trace-tbl tr.k-decision td:first-child { + box-shadow: inset 3px 0 var(--k-decision); +} + +.trace-tbl tr.k-loop td:first-child { + box-shadow: inset 3px 0 var(--k-loop); +} + +.trace-tbl tr.k-call td:first-child { + box-shadow: inset 3px 0 var(--k-call); +} + +.trace-tbl tr.k-return td:first-child { + box-shadow: inset 3px 0 var(--k-return); +} + +.trace-tbl tr.k-io td:first-child { + box-shadow: inset 3px 0 var(--k-io); +} + +.trace-tbl tr.k-life td:first-child { + box-shadow: inset 3px 0 var(--k-life); +} + +.trace-tbl tr.k-error td:first-child { + box-shadow: inset 3px 0 var(--k-error); +} + +.trace-tbl .step-no { + white-space: nowrap; +} + +.trace-next.k-write { + border-left-color: var(--k-write); +} + +.trace-next.k-decision { + border-left-color: var(--k-decision); +} + +.trace-next.k-loop { + border-left-color: var(--k-loop); +} + +.trace-next.k-call { + border-left-color: var(--k-call); +} + +.trace-next.k-return { + border-left-color: var(--k-return); +} + +.trace-next.k-io { + border-left-color: var(--k-io); +} + +.trace-next.k-life { + border-left-color: var(--k-life); +} + +.trace-next.k-error { + border-left-color: var(--k-error); + background: var(--err-bg); +} + +.trace-next.k-done { + border-left-color: var(--ok); + background: var(--ok-bg); +} + +.trace-next.k-empty { + border-left-color: var(--line-2); + background: var(--paper-3); + color: var(--ink-2); +} + +/* ---------- editor (CodeMirror 6, vendored) ---------- */ +.ed { + position: relative; + display: flex; + min-height: 120px; + min-width: 0; + background: var(--paper-2); + font-family: var(--mono); + font-size: 13px; + line-height: 20px; + overflow: hidden; +} + +.ed .cm-editor { + flex: 1; + min-width: 0; + height: 100%; + outline: none !important; +} + +.ed .cm-scroller { + font: inherit; + line-height: inherit; + overflow: auto; +} + +.ed .cm-content { + padding: 8px 0; + caret-color: var(--ink); + tab-size: 4; +} + +.ed .cm-line { + padding: 0 12px; +} + +.ed .cm-gutters { + background: var(--paper); + border-right: 1px solid var(--line); + color: var(--ink-3); + font-size: 11.5px; + user-select: none; +} + +.ed .cm-gutterElement { + display: flex; + align-items: center; +} + +.ed .cm-lineNumbers .cm-gutterElement { + padding: 0 4px 0 6px; + justify-content: flex-end; + min-width: 28px; + cursor: pointer; +} + +.ed .cm-lineNumbers .cm-gutterElement:hover { + color: var(--ink); +} + +.ed .ed-g-marks .cm-gutterElement { + width: 16px; + justify-content: center; +} + +.ed .ed-g-hits .cm-gutterElement { + width: 34px; + justify-content: flex-end; + padding-right: 2px; +} + +.ed .ed-g-arrow .cm-gutterElement { + width: 16px; + justify-content: center; +} + +.ed .ed-mark { + cursor: pointer; + font-size: 9px; +} + +.ed .ed-mark-error { + color: var(--err); +} + +.ed .ed-mark-warning { + color: var(--warn); +} + +.ed .ed-mark-note { + color: var(--ink-3); +} + +.ed .ed-hits { + color: var(--ink-3); + font-size: 10.5px; +} + +.ed .ed-arrow { + color: var(--accent); + font-size: 10px; +} + +.ed .cm-gutterElement.ed-gcurrent { + background: var(--marker-bg); +} + +.ed .cm-lineNumbers .cm-gutterElement.ed-gbreak { + color: var(--err); + font-weight: 700; +} + +.ed .cm-lineNumbers .cm-gutterElement.ed-gbreak::before { + content: '●'; + font-size: 8px; + margin-right: 3px; +} + +.ed .cm-placeholder { + color: var(--ink-3); + opacity: .8; + font-style: normal; +} + +.ed .cm-content ::selection, +.ed .cm-selectionBackground { + background: rgba(47, 91, 234, .22) !important; +} + +.ed .cm-cursor { + border-left-color: var(--ink); +} + +.ed .cm-matchingBracket { + background: var(--accent-bg); + outline: 1px solid var(--line-2); +} + +.ed .cm-nonmatchingBracket { + color: var(--err); +} + +.ed .cm-selectionMatch { + background: rgba(246, 196, 83, .35); +} + +.ed .cm-searchMatch { + background: var(--marker-bg); + outline: 1px solid var(--marker); +} + +.ed .cm-searchMatch-selected { + background: var(--marker); +} + +.ed .cm-panels { + background: var(--paper); + border-bottom: 1px solid var(--line); + color: var(--ink); + font-family: var(--sans); + font-size: 12px; +} + +.ed .cm-panel.cm-search { + padding: 6px 10px; +} + +.ed .cm-panel.cm-search input, +.ed .cm-panel.cm-search button { + font: inherit; + font-size: 12px; + border: 1px solid var(--line-2); + border-radius: 4px; + background: var(--paper-2); + color: var(--ink); + padding: 2px 6px; + margin: 0 4px 2px 0; +} + +.ed .cm-panel.cm-search label { + margin-right: 8px; +} + +.ed-ro .cm-content { + cursor: default; +} + +.ed-ro .cm-cursor { + display: none; +} + + +.ed-compact { + font-size: 12px; + line-height: 18px; +} + +.ed .ed-line-error { + box-shadow: inset 0 -2px var(--err); +} + +.ed .ed-line-warning { + box-shadow: inset 0 -1px var(--warn); +} + +.ed .ed-current { + background: var(--marker-bg); + box-shadow: inset 3px 0 var(--marker); +} + +.ed .ed-last { + background: var(--last-bg); +} + +.ed .ed-linked { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +.ed-msg { + font-style: italic; + font-size: 11.5px; + opacity: .9; + pointer-events: none; +} + +.ed-msg-error { + color: var(--err); +} + +.ed-msg-warning { + color: var(--warn); +} + +.ed-msg-note { + color: var(--ink-3); +} + +.tok-keyword { + color: var(--tok-keyword); + font-weight: 600; +} + +.tok-builtin { + color: var(--tok-builtin); +} + +.tok-string { + color: var(--tok-string); +} + +.tok-number { + color: var(--tok-number); +} + +.tok-comment { + color: var(--tok-comment); + font-style: italic; +} + +.tok-label { + color: var(--tok-label); + font-weight: 600; +} + +.tok-op { + color: var(--ink-2); +} + +.tok-error { + color: var(--err); + text-decoration: underline wavy; + text-decoration-skip-ink: none; +} + +.tok-punct { + color: var(--ink-3); +} + +/* Mojo: the words of ownership stand out, since they are what Programming+ teaches about Mojo */ +.tok-convention { + color: var(--tok-keyword); + font-style: italic; + font-weight: 600; +} + +.tok-transfer { + color: var(--accent); + font-weight: 700; +} + +.tok-name { + color: var(--ink); +} + +/* ---------- step through ---------- */ +.stepper { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 6px; +} + +.stepper .btn { + min-width: 34px; +} + +.stepper-slider { + flex: 1; + min-width: 120px; + accent-color: var(--accent); +} + +.stepper-count { + font-size: 12.5px; + color: var(--ink-2); + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.stepper-row2 { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 8px; + font-size: 12.5px; + color: var(--ink-2); +} + +.speed { + width: 90px; + accent-color: var(--accent); +} + +.trace-status { + font-size: 12.5px; + color: var(--ink-2); + /* one line, filled or empty: an empty status had a shorter box than a full one, so the stepper moved 4px */ + line-height: 19px; + height: 19px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-bottom: 6px; +} + +.trace-next { + background: var(--marker-bg); + border-left: 3px solid var(--marker); + padding: 6px 10px; + border-radius: 4px; + margin-bottom: 10px; + font-size: 13px; +} + +.trace-next .mono { + font-size: 12.5px; +} + +/* What runs next holds one height on every step: two lines, each cut with an ellipsis instead of wrapping + (the tooltip has the whole text). A message on its own, such as the end of the run, may use both lines. */ +.trace-next { + /* two line boxes of 19px; the padding comes on top (content-box) */ + line-height: 19px; + height: 38px; + box-sizing: content-box; + overflow: hidden; +} + +.trace-next-line { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + overflow: hidden; + overflow-wrap: anywhere; +} + +.trace-next-line:only-child { + -webkit-line-clamp: 2; +} + +.trace-next-sub { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.predict { + background: var(--paper-3); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + margin-bottom: 10px; + font-size: 13px; +} + +.predict-row { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + margin-top: 6px; +} + +.predict-score { + font-size: 12px; + color: var(--ink-2); + margin-left: auto; +} + +.predict-right { + color: var(--ok); + font-weight: 600; +} + +.predict-wrong { + color: var(--err); + font-weight: 600; +} + +.trace-output { + background: var(--paper); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + margin: 10px 0 0; + font-size: 12.5px; + white-space: pre-wrap; + font-family: var(--mono); +} + +.trace-cols { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} + +@media (max-width: 1100px) { + .trace-cols { + grid-template-columns: 1fr; + } +} + +.trace-col { + min-width: 0; +} + +.trace-empty { + padding: 12px 0; +} + +.tbl { + border-collapse: collapse; + width: 100%; + font-size: 12.5px; +} + +.tbl caption { + text-align: left; + font-weight: 600; + font-size: 12px; + color: var(--ink-2); + padding: 4px 0; +} + +.tbl th { + text-align: left; + font-weight: 600; + font-size: 11.5px; + color: var(--ink-2); + padding: 3px 6px; + border-bottom: 1px solid var(--line); +} + +.tbl td { + padding: 3px 6px; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.trace-tbl tr { + cursor: pointer; +} + +.trace-tbl tr:hover td { + background: var(--paper-3); +} + +.row-last td { + background: var(--last-bg); +} + +.row-next td { + background: var(--marker-bg); +} + +.just-wrote td, +.just-wrote { + background: var(--last-bg); +} + +.about-to-read td { + box-shadow: inset 3px 0 var(--marker); +} + +.vars-tbl { + margin-bottom: 10px; +} + +.var-hist { + color: var(--ink-3); + font-size: 11.5px; +} + +.var-hist .linkish { + color: var(--ink-2); +} + +.var-ruler { + padding: 2px 6px 6px; +} + +.flags { + display: flex; + gap: 6px; +} + +.flag { + font-family: var(--mono); + font-size: 12px; + padding: 2px 8px; + border: 1px solid var(--line); + border-radius: 4px; + color: var(--ink-2); +} + +.flag.on { + background: var(--accent-bg); + color: var(--accent); + border-color: transparent; + font-weight: 600; +} + +.flag.just-wrote { + outline: 2px solid var(--accent); +} + +.mem-region { + margin-bottom: 8px; +} + +.mem-label { + font-size: 11.5px; + color: var(--ink-2); + margin-bottom: 2px; + font-family: var(--mono); +} + +.mem-cells { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.mem-cell { + display: inline-flex; + flex-direction: column; + align-items: center; + width: 26px; + border: 1px solid var(--line); + border-radius: 3px; + font-family: var(--mono); + line-height: 1.1; + padding: 2px 0; +} + +.mem-cell b { + font-weight: 600; + font-size: 12px; +} + +.mem-cell i { + font-style: normal; + font-size: 9.5px; + color: var(--ink-2); +} + +.mem-cell.touched { + background: var(--marker-bg); + border-color: var(--marker); +} + +.explain ul { + margin: 4px 0 0; + padding-left: 18px; +} + +/* ---------- other views ---------- */ +.problems, +.obligations, +.failures, +.facts { + list-style: none; + margin: 0; + padding: 0; +} + +.problem { + display: grid; + grid-template-columns: 14px auto 1fr auto auto; + gap: 8px; + align-items: start; + padding: 7px 0; + border-bottom: 1px solid var(--line); + font-size: 13px; +} + +.problem-sev { + font-size: 10px; + padding-top: 3px; +} + +.problem-error .problem-sev { + color: var(--err); +} + +.problem-warning .problem-sev { + color: var(--warn); +} + +.problem-note .problem-sev { + color: var(--ink-3); +} + +.problem-guide { + font-size: 12px; + white-space: nowrap; +} + +.problem-question { + grid-column: 3 / -1; + background: var(--paper); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 6px 10px; +} + +.problem-q { + font-size: 12.5px; + color: var(--ink-2); +} + +.proof-counts { + margin-bottom: 10px; +} + +.proof-unit { + margin-bottom: 10px; + border: 1px solid var(--line); + border-radius: var(--r); + padding: 6px 10px; +} + +.proof-unit summary { + cursor: pointer; + font-size: 13px; +} + +.obligation { + display: grid; + grid-template-columns: auto auto 1fr; + gap: 8px; + align-items: baseline; + padding: 6px 0; + border-top: 1px solid var(--line); + font-size: 13px; +} + +.ob-detail { + grid-column: 1 / -1; + font-size: 12.5px; +} + +.ob-detail summary { + color: var(--ink-2); + cursor: pointer; + font-size: 12px; +} + +.facts li { + padding: 1px 0 1px 12px; +} + +.goal { + padding: 2px 0 2px 12px; + font-weight: 600; +} + +.tests-unit { + margin-bottom: 14px; +} + +.failures li { + padding: 3px 0; + font-size: 13px; +} + +.perf-tbl { + max-width: 520px; +} + +.perf-tbl td:first-child { + color: var(--ink-2); +} + +.bounds { + padding-left: 18px; +} + +.compile-out { + border-bottom: 1px solid var(--line); + background: var(--paper); + padding: 8px 12px; + max-height: 45%; + overflow: auto; + font-size: 12.5px; +} + +.compile-head { + display: flex; + gap: 10px; + align-items: center; + margin-bottom: 6px; +} + +.compile-err { + color: var(--err); + white-space: pre-wrap; + margin: 0 0 6px; + font-size: 12px; +} + +.compile-std { + white-space: pre-wrap; + margin: 0 0 6px; + font-size: 12px; +} + +.compile-section { + margin: 10px 0 14px; +} + +.compile-section h4 { + margin: 0 0 6px; + font-size: 13px; +} + +.asm-fn, +.asm-library { + border: 1px solid var(--line); + border-radius: 6px; + padding: 4px 8px; + margin: 6px 0; +} + +.asm-fn summary, +.asm-library summary { + cursor: pointer; + font-size: 12px; +} + +.asm-fn-library, +.asm-fn-entry { + border-style: dashed; +} + +.asm-fn-actions { + display: flex; + gap: 6px; + margin: 4px 0; +} + +.asm-src { + color: var(--ink-3); + user-select: none; +} + +button.asm-src { + font: inherit; + padding: 0; + border: 0; + background: none; + cursor: pointer; +} + +button.asm-src:hover { + color: var(--accent); +} + +.compile-asm { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.4; + white-space: pre; +} + +/* ---------- dialogs, tooltip ---------- */ +.share { + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 18px 20px; + width: min(720px, 92vw); + background: var(--paper-2); + color: var(--ink); + box-shadow: var(--shadow); +} + +.share::backdrop { + background: rgba(10, 12, 18, .4); +} + +.share h3 { + font-size: 17px; +} + +.share-row { + display: grid; + grid-template-columns: 110px 1fr auto; + gap: 8px; + align-items: center; + margin: 8px 0; +} + +.share-row label { + font-size: 12.5px; + color: var(--ink-2); +} + +.share-actions { + text-align: right; + margin-top: 10px; + display: flex; + gap: 8px; + justify-content: flex-end; +} + +.keys { + display: grid; + grid-template-columns: auto 1fr; + gap: 6px 14px; + font-size: 13px; + align-items: center; +} + +.tip { + position: fixed; + z-index: 50; + background: var(--paper-2); + color: var(--ink); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + box-shadow: var(--shadow); + font-size: 12.5px; + line-height: 1.4; + pointer-events: none; +} + +.tip-title { + display: flex; + justify-content: space-between; + gap: 12px; + margin-bottom: 3px; +} + +.tip-title code { + font-weight: 600; + font-size: 12.5px; +} + +.tip-where { + color: var(--ink-2); + font-size: 11px; +} + +/* ---------- reference ---------- */ +.reference { + margin: 36px 0 24px; +} + +.ref-nav { + display: flex; + gap: 14px; + flex-wrap: wrap; + margin: 6px 0 14px; + font-size: 13.5px; +} + +.ref-lang { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + margin-bottom: 10px; +} + +.ref-lang>summary { + list-style: none; + cursor: pointer; + padding: 12px 16px; + display: flex; + gap: 12px; + align-items: baseline; + flex-wrap: wrap; +} + +.ref-lang>summary::-webkit-details-marker { + display: none; +} + +.ref-lang>summary::before { + content: '▸'; + color: var(--ink-3); + font-size: 12px; +} + +.ref-lang[open]>summary::before { + content: '▾'; +} + +.ref-lang>summary h3 { + margin: 0; + font-size: 16px; +} + +.ref-body { + padding: 0 16px 16px; +} + +.ref-toc { + display: flex; + gap: 12px; + flex-wrap: wrap; + font-size: 12.5px; + margin-bottom: 8px; +} + +.ref-section { + margin-top: 18px; +} + +.ref-section h4 { + font-size: 14px; + color: var(--ink); +} + +.ref-table { + border-collapse: collapse; + width: 100%; + font-size: 13px; +} + +.ref-table th { + text-align: left; + font-size: 11.5px; + color: var(--ink-2); + font-weight: 600; + padding: 4px 8px; + border-bottom: 1px solid var(--line); +} + +.ref-table td { + padding: 6px 8px; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.ref-term { + white-space: nowrap; + max-width: 320px; +} + +.ref-term code { + white-space: pre-wrap; + font-size: 12.5px; +} + +.ref-meaning { + min-width: 220px; +} + +.ref-extra { + min-width: 200px; +} + +.ref-code { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.4; + white-space: pre; + background: var(--paper); + border: 1px solid var(--line); + border-radius: 5px; + padding: 6px 8px; + overflow-x: auto; + max-width: 520px; +} + +/* ---------- embed ---------- */ +.embed { + display: flex; + flex-direction: column; + height: 100%; + min-height: 100vh; + font-size: 13px; +} + +.embed-title { + display: flex; + justify-content: space-between; + align-items: center; + padding: 6px 12px; + border-bottom: 1px solid var(--line); + font-size: 12.5px; +} + +.embed-open { + font-size: 12px; +} + +.embed-reset { + margin-left: auto; + margin-right: 10px; +} + +.embed-pane-label { + font-size: 12px; + color: var(--ink-2); + padding: 6px 12px 0; +} + +.embed .ed { + min-height: 120px; + max-height: 45vh; + border-bottom: 1px solid var(--line); +} + +.embed-row { + display: flex; + gap: 6px; + align-items: center; + padding: 6px 12px; + border-bottom: 1px solid var(--line); +} + +.embed-call { + flex: 1; +} + +.embed-panel { + flex: 1; + overflow: auto; +} + +.embed .trace-cols { + grid-template-columns: 1fr; +} + +.embed-foot { + display: none; +} + +/* A fixed-height embed: the editors on top, the panel below, a draggable divider between them. + --embed-top (set by the divider) is the editors' share; they take most of the frame by default. */ +.embed:not(.embed-autosize) { + height: 100vh; + min-height: 0; +} + +.embed-split { + --embed-top: 70%; + flex: 1; + min-height: 0; + display: grid; + grid-template-rows: minmax(0, calc(var(--embed-top) - 3px)) 6px minmax(0, 1fr); +} + +.embed-top { + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; +} + +.embed-top>.embed-pane-label, +.embed-top>.embed-row { + flex: none; +} + +.embed-split .embed-top .ed { + flex: 1 1 0; + min-height: 48px; + max-height: none; + border-bottom: 0; +} + +.embed-top>.embed-row { + border-top: 1px solid var(--line); + border-bottom: 0; +} + +.embed-split>.splitter-y::before { + content: ''; + position: absolute; + left: 50%; + top: 50%; + width: 36px; + height: 2px; + margin: -1px 0 0 -18px; + border-radius: 1px; + background: var(--ink-3); + opacity: .6; +} + +.embed-split>.embed-panel { + min-height: 0; + overflow: auto; +} + +/* height="auto" embeds: the content decides the height, and the host grows the frame to match */ +.embed-autosize { + min-height: 0; + height: auto; +} + +.embed-autosize .ed { + max-height: none; +} + +.embed-autosize .embed-panel { + flex: none; + overflow: visible; +} + +.embed-autosize .viz-scroll { + max-height: none; +} + +@media (max-width: 900px) { + .workspace { + grid-template-columns: 1fr !important; + grid-template-rows: minmax(0, 1fr) 6px minmax(0, 1fr); + } + + .workspace>.splitter { + cursor: row-resize; + } + + .workspace.views-collapsed { + grid-template-rows: minmax(0, 1fr) 6px 40px; + } + + .workspace.views-collapsed .view-tabs { + flex-direction: row; + height: auto; + } + + .workspace.views-collapsed .view-tabs .tab { + writing-mode: horizontal-tb; + transform: none; + } + + .input { + min-width: 140px; + } + + .hero { + grid-template-columns: 1fr; + gap: 24px; + } + + .hero h1 { + font-size: 34px; + } + + .ways { + grid-template-columns: 1fr 1fr; + } + + .ref-table, + .ref-table thead, + .ref-table tbody, + .ref-table tr, + .ref-table td { + display: block; + } + + .ref-table th { + display: none; + } + + .ref-term { + white-space: normal; + } +} + +@media (max-width: 560px) { + .ways { + grid-template-columns: 1fr; + } + + .home { + padding: 0 16px 48px; + } +} + +.way pre { + max-height: 150px; + -webkit-mask-image: linear-gradient(#000 70%, transparent); + mask-image: linear-gradient(#000 70%, transparent); +} + +/* ------------------------------------------------------------------ */ +/* Home: pitch sections */ +/* ------------------------------------------------------------------ */ +.home-nav a.on { + color: var(--ink); + font-weight: 600; +} + +.lede-2 { + color: var(--ink-2); + max-width: 72ch; + margin: 0 0 20px; + font-size: 15px; + line-height: 1.55; +} + +.hub { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.35fr) minmax(0, 1fr); + gap: 12px; + align-items: stretch; +} + +.hub-col { + display: grid; + gap: 12px; + align-content: stretch; +} + +.hub .way { + display: flex; + flex-direction: column; +} + +.hub .way p { + min-height: 0; + flex: 0 0 auto; +} + +.hub .way pre { + flex: 1; +} + +.hub-center { + border: 1px solid var(--ink); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 16px 16px 12px; + min-width: 0; + box-shadow: var(--shadow); + position: relative; +} + +.hub-center::before { + content: ""; + position: absolute; + inset: -1px; + border-radius: inherit; + pointer-events: none; + box-shadow: 0 0 0 3px var(--marker-bg); +} + +.hub-center h3 { + font-size: 20px; + margin: 0 0 4px; + letter-spacing: -.01em; +} + +.hub-center>p { + margin: 0 0 10px; + font-size: 13px; + color: var(--ink-2); +} + +.hub-center pre { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.6; + white-space: pre; + overflow-x: auto; + border-top: 1px solid var(--line); + padding-top: 10px; +} + +.demo-out { + margin: 0; + padding: 6px 10px; + font-family: var(--mono); + font-size: 12.5px; + white-space: pre-wrap; + border: 1px solid var(--line); + border-radius: var(--r); + background: var(--paper-2); + max-height: 140px; + overflow: auto; + grid-column: 1 / -1; +} + +.demo-stop { + color: var(--err); +} + +.demo-frame { + color: var(--accent); + font-weight: 600; +} + +.ref-prints { + display: block; + margin-top: 4px; +} + +.input-lines { + resize: none; + min-height: 30px; + line-height: 1.4; + padding: 5px 8px; +} + +@media (max-width: 900px) { + .hub { + grid-template-columns: 1fr; + } + + .hub-center { + order: -1; + } +} + +.demo-vars>span { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.demo-vars .ruler { + display: inline-flex; +} + +.demo-foot { + display: flex; + flex-direction: column; + gap: 8px; + align-items: stretch; +} + +.demo-ctl { + display: flex; + gap: 4px; + flex-wrap: wrap; + align-items: center; +} + +.demo-ctl .btn { + white-space: nowrap; +} + +.demo-ctl a.btn { + margin-left: auto; +} + +.toolbar .input-lines { + min-width: 120px; + width: 180px; +} + +.toolbar:has(.input-lines) .input { + min-width: 170px; +} + +@media (max-width: 560px) { + .home-nav { + flex-wrap: wrap; + gap: 10px 12px; + } + + .home-nav .brand { + flex-basis: 100%; + } + + .home-nav .spacer { + display: none; + } +} + +/* ---------- pictures of the procedure: flowchart, data flow, trace table ---------- */ +.viz-head { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-bottom: 8px; + font-size: 12.5px; +} + +.viz-title { + font-family: var(--mono); + font-weight: 600; +} + +.viz-scroll { + overflow: auto; + max-width: 100%; + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 8px; +} + +.flow-svg { + display: block; + font-family: var(--mono); + font-size: 12px; +} + +.flow-svg text { + fill: var(--ink); +} + +.flow-shape { + stroke: var(--ink-2); + stroke-width: 1.2; +} + +.flow-term { + stroke-width: 2; +} + +.flow-edge { + fill: none; + stroke: var(--ink-2); + stroke-width: 1.4; +} + +.flow-back { + stroke-dasharray: 4 3; +} + +.flow-arrowhead { + fill: var(--ink-2); +} + +.flow-badge { + fill: var(--paper-3); + stroke: var(--line); +} + +.flow-badge-never { + fill: var(--warn-bg); + stroke: var(--warn); +} + +.flow-badge-text { + font-size: 10.5px; + fill: var(--ink-2); +} + +.flow-never .flow-shape { + stroke-dasharray: 3 3; + stroke: var(--ink-3); +} + +.flow-never text { + fill: var(--ink-3); +} + +.flow-edge-label { + font-size: 10.5px; + fill: var(--ink-2); +} + +.flow-edge-label-bg { + fill: var(--paper-2); +} + +.flow-clickable { + cursor: pointer; +} + +.flow-clickable:hover .flow-shape, +.flow-clickable:hover .df-node { + stroke: var(--accent); + stroke-width: 2; +} + +.df-node { + stroke: var(--ink-2); + stroke-width: 1.2; + fill: var(--paper-2); +} + +.df-node-in { + fill: var(--accent-bg); +} + +.df-node-out { + fill: var(--ok-bg); +} + +.df-node-loop { + stroke-dasharray: 5 3; +} + +.df-edge { + fill: none; + stroke: var(--ink-2); + stroke-width: 1.4; +} + +.df-edge-ctrl { + stroke-dasharray: 4 3; + stroke: var(--ink-3); +} + +.df-type { + font-size: 10px; + fill: var(--ink-3); +} + +.df-label { + font-size: 10px; + fill: var(--ink-2); +} + +.df-label-bg { + fill: var(--paper-2); +} + +.vals-scroll { + padding: 0; +} + +.vals-tbl { + border-collapse: collapse; + font-family: var(--mono); + font-size: 12px; + min-width: 100%; +} + +.vals-tbl th, +.vals-tbl td { + border: 1px solid var(--line); + padding: 3px 8px; + text-align: left; + white-space: nowrap; +} + +.vals-tbl thead th { + background: var(--paper-3); + color: var(--ink-2); + font-weight: 500; + text-align: center; + position: sticky; + top: 0; +} + +.vals-tbl thead tr:nth-child(2) th { + top: 25px; + font-size: 11px; +} + +.vals-corner, +.vals-var { + position: sticky; + left: 0; + background: var(--paper-3); + z-index: 1; + text-align: left !important; + font-weight: 600; +} + +.vals-tbl thead .vals-corner { + z-index: 2; +} + +.vals-step.linkish { + cursor: pointer; + text-decoration: underline dotted; +} + +.vals-changed { + font-weight: 600; + background: var(--accent-bg); +} + +.vals-same { + color: var(--ink-3); +} + +.vals-absent { + background: repeating-linear-gradient(45deg, transparent 0 4px, var(--paper-3) 4px 5px); +} + +.vals-unset { + color: var(--ink-3); + font-weight: 400; +} + +.vals-out { + background: var(--ok-bg); +} + +.view-table .viz-scroll, +.view-flow .viz-scroll, +.view-data .viz-scroll { + max-height: calc(100vh - 220px); +} + +.embed .viz-scroll { + max-height: none; +} + +/* The Lifetimes view: one lane per value, from made to destroyed or moved out */ +.life { + display: grid; + gap: 6px; + margin: 8px 0; +} + +.life-row { + display: grid; + grid-template-columns: minmax(120px, 18%) 1fr minmax(140px, 20%); + gap: 10px; + align-items: center; +} + +.life-id { + color: var(--ink-3); + font-size: 11px; +} + +.life-lane { + position: relative; + height: 22px; + border-bottom: 1px dashed var(--line); +} + +.life-bar { + position: absolute; + top: 7px; + height: 8px; + border-radius: 4px; + background: var(--accent); + opacity: 0.35; +} + +.life-bar-copied { + background: var(--tok-string); +} + +.life-bar-moved { + background: var(--tok-number); +} + +.life-bar-open { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} + +.life-mark { + position: absolute; + top: 4px; + width: 14px; + height: 14px; + margin-left: -7px; + padding: 0; + border: 2px solid var(--paper); + border-radius: 50%; + cursor: pointer; + background: var(--accent); +} + +.life-mark.legend { + position: relative; + display: inline-block; + top: 3px; + margin: 0 2px 0 8px; + cursor: default; +} + +.life-mark-copied { + background: var(--tok-string); +} + +.life-mark-moved { + background: var(--tok-number); +} + +.life-mark-moved-out { + background: var(--ink-3); + border-radius: 2px; +} + +.life-mark-named { + background: var(--paper); + border-color: var(--accent); + width: 10px; + height: 10px; + top: 6px; + margin-left: -5px; +} + +.life-mark-destroyed { + background: var(--err); + border-radius: 2px; +} + +.life-cursor { + position: absolute; + top: 0; + bottom: 0; + width: 2px; + margin-left: -1px; + background: var(--ink-2); + opacity: 0.5; + pointer-events: none; +} + +.life-legend { + margin-top: 8px; +} + +/* The Compiler view, by Mojo line: each line of the program, then the instructions it became */ +.asm-group { + border-left: 3px solid transparent; + padding: 2px 0 4px 8px; + margin: 4px 0; +} + +.asm-group-head { + display: flex; + gap: 10px; + align-items: baseline; +} + +.asm-group-src { + color: var(--ink-2); +} + +.asm-group-active { + border-left-color: var(--accent); + background: var(--paper-2); +} + +/* Two builds of one function, side by side */ +.build-pair { + margin: 10px 0; +} + +.build-cols { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.build-col { + min-width: 0; + overflow-x: auto; +} + +.cost-by-line { + margin-bottom: 14px; +} + +/* ------------------------------------------------------------------ */ +/* Home: Mojo-first pitch (features, mental model, specification) */ +/* ------------------------------------------------------------------ */ +.sample { + margin: 0; + font-family: var(--mono); + font-size: 11.5px; + line-height: 1.55; + white-space: pre; + overflow: hidden; + text-overflow: ellipsis; + color: var(--ink); +} + +.features { + padding: 40px 0 8px; + border-bottom: 1px solid var(--line); +} + +.features h2, +.spec-section h2 { + font-size: 24px; + letter-spacing: -.02em; + margin-bottom: 6px; +} + +.feat-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 14px; + margin-bottom: 36px; +} + +.feat { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 16px 16px 14px; + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.feat h3 { + font-size: 15px; + margin: 0; +} + +.feat>p { + margin: 0; + font-size: 13px; + color: var(--ink-2); + flex: 0 0 auto; +} + +.feat>p+* { + margin-top: auto; + border-top: 1px solid var(--line); + padding-top: 10px; +} + +.feat-diags { + list-style: none; + margin: 8px 0 0; + padding: 0; + font-size: 12px; +} + +.feat-diag { + display: flex; + gap: 6px; + align-items: baseline; + margin-bottom: 4px; +} + +.feat-diag-sev { + font-size: 9px; +} + +.feat-diag-error .feat-diag-sev { + color: var(--err); +} + +.feat-diag-note .feat-diag-sev, +.feat-diag-note { + color: var(--ink-3); +} + +.feat-steps { + list-style: none; + margin: 0; + padding: 0; + font-size: 12px; +} + +.feat-steps li { + display: flex; + align-items: baseline; + gap: 4px; + padding: 2px 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.feat-steps code { + font-size: 11.5px; +} + +.feat-legend { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + font-size: 11px; + color: var(--ink-2); + margin-top: 8px; +} + +.feat-verdict { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.feat-verdict p { + margin: 4px 0 0; + flex-basis: 100%; +} + +.feat-tests { + font-size: 12.5px; + display: grid; + gap: 8px; +} + +.ways-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + margin-bottom: 20px; +} + +.ways-3 .way pre { + font-size: 11.5px; +} + + +.spec-section { + display: grid; + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + gap: 32px; + align-items: center; + padding: 36px 0; + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); +} + +.spec-section .way { + padding: 16px; +} + +.spec-section .proof-counts { + margin-top: 12px; +} + +.chip-verified { + background: var(--ok-bg); + color: var(--ok); +} + +@media (max-width: 900px) { + + .feat-grid, + .ways { + grid-template-columns: 1fr; + } + + .spec-section { + grid-template-columns: 1fr; + } +} + +/* the variable's timeline: every value it takes, past, now, and to come */ +.var-track { + display: flex; + flex-wrap: wrap; + gap: 3px; + margin-top: 4px; + align-items: center; +} + +.var-chip { + font: inherit; + font-family: var(--mono); + font-size: 11px; + line-height: 1.2; + padding: 1px 6px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--paper); + color: var(--ink-2); + cursor: pointer; + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.var-chip-past { + background: var(--paper-3); + color: var(--ink); +} + +.var-chip-now { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); + font-weight: 600; +} + +.var-chip-next { + opacity: .45; + border-style: dashed; +} + +.var-chip:hover { + opacity: 1; + border-color: var(--accent); +} + +.var-chip-more { + border: 0; + background: transparent; + cursor: default; + color: var(--ink-3); +} + +/* the flowchart follows the stepper */ +.flow-node.flow-current .flow-shape { + stroke: var(--marker); + stroke-width: 3; +} + +.flow-node.flow-last .flow-shape { + stroke: var(--accent); + stroke-width: 2.4; +} + +.flow-node.flow-current.flow-last .flow-shape { + stroke: var(--marker); +} + +/* the data flow lights up what the step reads and writes */ +.df-nodeg.df-reads .df-node { + stroke: var(--marker); + stroke-width: 3; +} + +.df-nodeg.df-wrote .df-node { + stroke: var(--accent); + stroke-width: 3; +} + +.df-edge.df-edge-active { + stroke: var(--accent); + stroke-width: 2.6; +} + +/* the table of values marks the step that just ran */ +.vals-tbl .vals-now { + box-shadow: inset 0 -3px var(--marker); +} + +.vals-tbl td.vals-now { + background: var(--marker-bg); + box-shadow: none; +} +.embed-pane-label .badge, +.share-badges .badge { + margin-left: 6px; +} + +.share-badges { + display: inline-flex; + flex-wrap: wrap; + gap: 4px; +} + +.practices { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 8px; +} + +.practice { + border: 1px solid var(--line); + border-radius: 6px; + padding: 8px 10px; + cursor: pointer; +} + +.practice:hover { + border-color: var(--ink-2); +} + +.practice p { + margin: 4px 0; +} + +.practice-head { + display: flex; + justify-content: space-between; + gap: 8px; +} + +.practice-diff { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.practice-diff pre { + margin: 0; + padding: 6px 8px; + border-radius: 4px; + overflow: auto; + background: var(--panel, transparent); + border: 1px solid var(--line); +} + +.practice-after { + border-color: var(--ok, currentColor); +} + +.problem-origin { + font-size: 12px; + color: var(--ink-2); +} + +.idiomatic { + flex-basis: 100%; + margin: 4px 0 0; +} + +.idiomatic-head { + display: flex; + align-items: center; + gap: 8px; +} + +.idiomatic-code { + margin: 4px 0 0; + padding: 6px 8px; + max-height: 240px; + overflow: auto; + border: 1px solid var(--line); + border-radius: 4px; +} + +.btn-on { + color: var(--ok); +} + +.banner { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 14px; + background: var(--warn-bg); + color: var(--warn); + border-bottom: 1px solid var(--line); + font-size: 13px; +} + +.versions { + position: relative; +} + +.versions-menu { + position: absolute; + z-index: 30; + top: calc(100% + 4px); + left: 0; + width: min(420px, 90vw); + max-height: 60vh; + overflow: auto; + padding: 6px; + background: var(--paper); + border: 1px solid var(--line-2); + border-radius: 8px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18); +} + +.version-row { + display: flex; + align-items: center; + gap: 4px; + padding: 2px 4px; + border-radius: 4px; +} + +.version-row.on { + background: var(--ok-bg); +} + +.version-pick { + flex: 1; + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; + border: 0; + background: none; + color: inherit; + font: inherit; + padding: 4px; + cursor: pointer; + min-width: 0; +} + +.version-pick:hover .version-name { + text-decoration: underline; +} + +.version-name { + font-weight: 600; + overflow-wrap: anywhere; +} + +.version-none, +.version-warn { + padding: 4px 8px; + margin: 0; +} + +.version-warn { + color: var(--warn); +} + +.version-save { + border-top: 1px solid var(--line); + margin-top: 4px; + padding-top: 6px; +} + +/* ---------- the Hardware area: the code on the left, the board on the right (src/ui/hw/board.ts) ---------- */ +.workspace.workspace-board { grid-template-rows: minmax(0, 1fr); } +.board-side { overflow: auto; padding: 10px 12px 24px; } +.board { display: flex; flex-direction: column; gap: 0.5rem; } +.board-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; position: sticky; top: -10px; z-index: 2; background: var(--paper); padding: 6px 0; } +.board-blurb { margin: 0; } +.board-add-menu { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--paper-2); } +.board-add-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.board-add-name { font-size: 12px; color: var(--ink-2); min-width: 10.5rem; } +.board-grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); gap: 10px; align-items: start; } +.board-card { min-width: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--paper-2); grid-column: span 6; } +.board-card.wide { grid-column: 1 / -1; } +/* The machine code listing and the encoding of the instruction it marks, side by side (board.ts marks the pair). + The listing needs two thirds of the row to show its operands; on a narrow board the two stack, the encoding under + the listing. Either way the listing scrolls on its own, as tall as the encoding, and keeps the instruction about + to run in view, so the row and its bytes are always on screen together. */ +.board-grid.is-roomy .board-card.pair-code { grid-column: span 8; } +.board-grid.is-roomy .board-card.pair-enc { grid-column: span 4; } +.board-grid:not(.is-roomy) .board-card.pair-code, .board-grid:not(.is-roomy) .board-card.pair-enc { grid-column: 1 / -1; } +.board-card.pair-code .board-card-body { max-height: var(--pair-h, 420px); overflow: auto; } +.board-grid:not(.is-roomy) .board-card.pair-code .board-card-body { max-height: 300px; } +.board-card-head { display: flex; align-items: center; gap: 6px; padding: 4px 6px 4px 8px; border-bottom: 1px solid var(--line); cursor: grab; user-select: none; font-size: 13px; font-weight: 600; } +.board-card-head:active { cursor: grabbing; } +.board-grip { color: var(--ink-3); } +.board-tool { border: 0; background: transparent; color: var(--ink-2); cursor: pointer; padding: 0 5px; font-size: 13px; border-radius: 4px; } +.board-tool:hover:not(:disabled) { background: var(--paper-3); color: var(--ink); } +.board-tool:disabled { opacity: 0.35; cursor: default; } +.board-card-body { padding: 8px 10px; min-width: 0; overflow-x: auto; } +.board-card-body .view, .board-card-body .setup { padding: 0; } +.board-card.dragging { opacity: 0.45; } +.board-card.drop-before { box-shadow: inset 0 3px 0 var(--accent); } +.board-card.drop-after { box-shadow: inset 0 -3px 0 var(--accent); } +.board-card.wide.drop-before { box-shadow: 0 -3px 0 var(--accent); } +.board-card.flash { outline: 2px solid var(--accent); outline-offset: 2px; transition: outline-color 0.6s; } +.board-note { margin: 0; color: var(--ink-2); font-size: 13px; } +.board-empty { grid-column: 1 / -1; } +/* inside a card the course view needs no frame of its own: the card is the frame */ +.board-card-body .board-a86 { font-size: 0.9rem; } +.board-card-body .board-a86 .a86-panel { border: 0; padding: 0; background: transparent; } +.board-card-body .board-a86 .a86-panel-title { display: none; } +@media (max-width: 1100px) { .board-grid { grid-template-columns: minmax(0, 1fr); } .board-card, .board-card.pair-code, .board-card.pair-enc { grid-column: 1 / -1; } } + +/* the area's name in the toolbar, where the switch is when no other area would show the work as it is */ +.area-name { font-weight: 600; font-size: 0.9rem; padding: 0.25rem 0.7rem; border-radius: 999px; background: var(--paper-3); color: var(--ink); white-space: nowrap; } + +/* ---------- the stepper, docked under the editor (same width, part of the editor column) ---------- */ +.step-dock { + flex-shrink: 0; + background: var(--paper); + border-top: 1px solid var(--line); + box-shadow: 0 -1px 0 var(--paper-3); +} +.step-dock .run-bar { border-bottom: 0; padding: 6px 10px 2px; gap: 6px; } +.step-dock .run-bar .run-controls { flex-direction: column; align-items: stretch; gap: 2px; flex: 1 1 100%; } +.step-dock .run-bar .run-controls .stepper { min-width: 0; } +.step-dock .run-bar .run-status { white-space: normal; flex: 1 1 100%; } +.step-dock .next-host { border-bottom: 0; padding: 0 10px 2px; background: transparent; } +.step-dock .next-host .trace-next { margin-bottom: 6px; padding: 4px 10px; font-size: 12.5px; } +.step-dock .next-host:empty { display: none; } + +.side-split.inspect-only { grid-template-rows: minmax(0, 1fr); } + +/* ---------- the Run view (src/ui/views/run.ts): the run top to bottom, the variables followed as columns ---------- */ +.view-trace { display: flex; flex-direction: column; min-height: 0; padding: 0; } +.run-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; padding: 8px 12px 6px; border-bottom: 1px solid var(--line); background: var(--paper); } +.run-follow { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; flex: 1; min-width: 0; } +.run-follow-label { font-size: 11.5px; font-weight: 600; color: var(--ink-2); text-transform: uppercase; letter-spacing: 0.04em; margin-right: 4px; } +.run-fn { font-size: 11.5px; color: var(--ink-3); margin: 0 2px 0 8px; } +.run-chip { font: 12px var(--mono); padding: 1px 8px; border-radius: 999px; border: 1px dashed var(--line-2); background: transparent; color: var(--ink-2); cursor: pointer; } +.run-chip:hover { border-color: var(--accent); color: var(--ink); } +.run-chip.on { border-style: solid; border-color: var(--accent); background: var(--accent-bg); color: var(--ink); } +.run-filter { color: var(--ink-2); white-space: nowrap; } +.run-now { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--paper-2); max-height: 38%; overflow: auto; flex-shrink: 0; } +.run-now:empty { display: none; } +.run-now > p { margin: 0; } +.run-var { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--paper); max-width: 100%; } +.run-var.run-var-wrote { border-color: var(--marker); background: var(--marker-bg); } +.run-var.run-var-read { box-shadow: inset 0 -2px 0 var(--accent); } +.run-var-name { font-weight: 600; font-size: 12.5px; } +.run-var-type { font-size: 11px; color: var(--ink-3); } +.run-var-value { font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 40ch; } +.run-var .ruler { flex-basis: 100%; } +.run-grid { flex-basis: 100%; border-collapse: collapse; font: 11.5px var(--mono); } +.run-grid td, .run-grid th { border: 1px solid var(--line); padding: 1px 5px; text-align: right; min-width: 1.6em; } +.run-grid th { color: var(--ink-3); font-weight: 400; border: 0; } +.run-scroll { flex: 1; min-height: 0; overflow: auto; position: relative; } +.run-tbl { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12.5px; } +.run-tbl thead th { position: sticky; top: 0; z-index: 1; background: var(--paper); border-bottom: 1px solid var(--line); text-align: left; font-weight: 600; font-size: 11.5px; color: var(--ink-2); padding: 5px 8px; } +.run-tbl th.run-colhead { color: var(--ink); border-left: 1px solid var(--line); } +.run-tbl td { padding: 3px 8px; border-bottom: 1px solid var(--paper-3); vertical-align: top; } +.run-row { cursor: pointer; } +.run-row:hover td { background: var(--paper-3); } +.run-row.row-last td { background: var(--accent-bg); } +.run-row.row-next td { background: var(--marker-bg); } +.run-row.row-next td.run-no { box-shadow: inset 3px 0 0 var(--marker); } +.run-no { width: 3.5em; white-space: nowrap; font-variant-numeric: tabular-nums; } +.run-no .k-dot { margin-right: 4px; } +.run-line { width: 2.5em; } +.run-what { min-width: 14ch; } +.run-indent { display: inline-block; } +.run-note { font-size: 11px; color: var(--ink-3); margin-top: 1px; } +.run-printed { color: var(--ink-2); } +.run-cell { border-left: 1px solid var(--paper-3); color: var(--ink-3); white-space: nowrap; } +.run-cell.wrote { color: var(--ink); font-weight: 600; background: color-mix(in srgb, var(--marker-bg) 70%, transparent); } +.run-cell.read { text-decoration: underline dotted var(--accent); text-underline-offset: 3px; } +.run-cell.out { background: repeating-linear-gradient(135deg, transparent 0 6px, var(--paper-3) 6px 7px); } +.run-life { display: inline-block; margin-right: 4px; font-weight: 700; } +.run-life-made, .run-life-copied { color: #2f8f5b; } +.run-life-moved-in { color: var(--accent); } +.run-life-moved-out { color: #b26a00; } +.run-life-destroyed { color: #c0392b; } +.run-more td { text-align: center; padding: 6px; } +.run-empty, .run-error { padding: 10px 12px; } +.run-now { align-items: flex-start; } +.run-chip { display: inline-flex; align-items: center; gap: 2px; } +.run-chip-fn { color: var(--ink-3); } +.run-chip-x { border: 0; background: transparent; color: var(--ink-3); cursor: pointer; padding: 0 0 0 4px; font-size: 13px; line-height: 1; } +.run-chip-x:hover { color: var(--ink); } +.run-chip-add { border-style: solid; color: var(--accent); } +.run-chip sup { font-size: 9px; color: var(--ink-3); margin-left: 2px; } +.run-picker { flex-basis: 100%; display: flex; flex-direction: column; gap: 4px; padding: 6px 0 2px; border-top: 1px dashed var(--line); max-height: 180px; overflow: auto; } +.run-picker-row { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; } +.run-picker-row .run-fn { min-width: 9ch; margin-left: 0; } +.run-what { overflow-wrap: anywhere; } +.run-what > :not(.run-indent):not(.run-note) { display: -webkit-box; } +.run-at { color: var(--ink-2); font-weight: 400; } +.run-grid td.wrote { background: var(--marker-bg); font-weight: 700; } +.run-grid td.read { box-shadow: inset 0 0 0 1.5px var(--accent); } + +/* ---------- the Tests view: the fuzzer's report (src/ui/views/tests.ts) ---------- */ +.fuzz-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; } +.fuzz-bar .fuzz-seed { width: 7em; max-width: 7em; flex: none; } +.fuzz-unit { border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px 10px; margin-bottom: 10px; background: var(--paper-2); } +.fuzz-unit > summary { cursor: pointer; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 4px 0; } +.fuzz-sig { font-weight: 600; } +.fuzz-unit h5 { margin: 14px 0 6px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-2); } +.fuzz-checks { margin: 0; padding-left: 0; list-style: none; font-size: 13px; } +.fuzz-checks li { padding-left: 1.4em; position: relative; margin: 2px 0; } +.fuzz-checks li::before { content: '✓'; position: absolute; left: 0; color: #2f8f5b; font-weight: 700; } +.fuzz-gens td, .fuzz-gens th { font-size: 12.5px; vertical-align: top; } +.fuzz-strats { margin: 6px 0 0; padding-left: 1.2em; font-size: 12.5px; } +.fuzz-strats li { margin: 2px 0; } +.fuzz-fail { border: 1px solid color-mix(in srgb, #c0392b 40%, var(--line)); border-left: 3px solid #c0392b; border-radius: 6px; padding: 8px 10px; margin: 6px 0; background: var(--paper); } +.fuzz-fail-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.fuzz-msg { margin: 6px 0; font-size: 13px; } +.fuzz-shrink { margin: 4px 0 0; padding-left: 1.6em; font-size: 12.5px; } +.fuzz-shrink li { margin: 1px 0; color: var(--ink-2); } +.fuzz-shrink-last { color: var(--ink) !important; font-weight: 600; } +.fuzz-cov { display: flex; flex-direction: column; gap: 1px; } +.fuzz-cov-row { display: grid; grid-template-columns: 3em 90px 4.5em minmax(0, 1fr); align-items: center; gap: 8px; border: 0; background: transparent; text-align: left; padding: 1px 4px; border-radius: 4px; cursor: pointer; color: var(--ink); font: inherit; font-size: 12.5px; } +.fuzz-cov-row:hover { background: var(--paper-3); } +.fuzz-cov-row.never { background: color-mix(in srgb, #c0392b 10%, transparent); } +.fuzz-cov-line { color: var(--ink-3); text-align: right; } +.fuzz-cov-bar { display: inline-block; height: 8px; background: var(--paper-3); border-radius: 4px; overflow: hidden; } +.fuzz-cov-bar > span { display: block; height: 100%; background: var(--accent); } +.fuzz-cov-n { color: var(--ink-2); } +.fuzz-cov-src { white-space: pre; overflow: hidden; text-overflow: ellipsis; } +.fuzz-results { display: flex; flex-direction: column; gap: 2px; } +.fuzz-result { display: grid; grid-template-columns: minmax(8ch, max-content) 120px 4em; gap: 8px; align-items: center; font-size: 12.5px; } +.fuzz-filter { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 6px; } +.fuzz-cases-wrap { max-height: 360px; overflow: auto; border: 1px solid var(--line); border-radius: 6px; } +.fuzz-cases { width: 100%; font-size: 12px; } +.fuzz-cases thead th { position: sticky; top: 0; background: var(--paper); z-index: 1; } +.fuzz-out { font-size: 11px; padding: 0 6px; border-radius: 999px; } +.fuzz-out-pass { color: #2f8f5b; background: color-mix(in srgb, #2f8f5b 12%, transparent); } +.fuzz-out-fail { color: #c0392b; background: color-mix(in srgb, #c0392b 12%, transparent); } +.fuzz-out-skip { color: var(--ink-2); background: var(--paper-3); } +.fuzz-out-raises { color: #b26a00; background: color-mix(in srgb, #b26a00 12%, transparent); } +.fuzz-new { color: var(--accent); } + +/* ---------- the home page's three areas (src/ui/home.ts) ---------- */ +.area-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-top: 8px; align-items: stretch; } +.area-card { display: flex; flex-direction: column; gap: 8px; padding: 16px 16px 14px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); min-width: 0; } +.area-tagline { margin: 0; color: var(--ink-2); font-size: 14px; } +.area-card .hero-actions { margin-top: auto; padding-top: 6px; } +.area-sample { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: 13px; } +.area-sample .sample { margin: 0; font-size: 11.5px; max-height: 12.5em; overflow: auto; } +.area-step { border-left: 3px solid var(--line-2); padding-left: 8px; min-width: 0; } +.area-step.way-matho { border-left-color: var(--lang-matho); } +.area-step.way-pseudo { border-left-color: var(--lang-pseudo); } +.area-step.way-lingo { border-left-color: var(--lang-lingo); } +.area-step.way-mojo { border-left-color: var(--lang-mojo); } +.area-step-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 2px 0; font-size: 12.5px; } +.area-arrow { color: var(--ink-3); font-size: 12px; font-family: var(--mono); } +.area-badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.area-regs { font-size: 12px; } +.area-regs tr.is-changed td { background: var(--accent-bg); font-weight: 600; } +.area-a86.a86 { font-size: 12px; margin: 0; } +.area-a86 .hw-line-cell { min-height: 1.2rem; line-height: 1.2rem; font-size: 0.6rem; } +.feat-area { margin-top: 22px; } +.feat-area-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; margin-bottom: 10px; } +.feat-area-head h3 { margin: 0; font-size: 18px; } +.feat-area-head p { margin: 0; } +.way-area { font-weight: 400; } +.card { display: flex; flex-direction: column; } +.card-main { color: inherit; display: block; } +.card-main:hover { text-decoration: none; } +.card-areas { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 8px; padding-top: 8px; border-top: 1px dashed var(--line); } +.chip-area { text-decoration: none; } +.chip-area:hover { border-color: var(--accent); text-decoration: none; } +.home-foot p { margin-top: 6px; } +@media (max-width: 1100px) { .area-cards { grid-template-columns: minmax(0, 1fr); } } + +/* ---------- the home page's pitch (src/ui/home.ts): why it exists, then the areas, then why Mojo ---------- */ +.hero.hero-pitch { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 48px; align-items: center; padding: 48px 0 40px; } +.hero-kicker { margin: 0 0 14px; color: var(--accent); font-weight: 600; font-size: 14px; } +.hero.hero-pitch h1 { font-size: 46px; max-width: 16ch; margin-bottom: 20px; text-wrap: balance; } +.hero.hero-pitch .lede { max-width: 58ch; margin-bottom: 26px; } + +/* the sign-off: who made it changes, the sentence at the bottom does not */ +.signoff { margin: 0; padding: 22px 24px 18px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); box-shadow: var(--shadow); } +.signoff-head { font-size: 13px; color: var(--ink-3); margin-bottom: 4px; } +.signoff-makers { list-style: none; margin: 0 0 18px; padding: 0; } +.signoff-makers li { padding: 7px 0; border-bottom: 1px solid var(--line); color: var(--ink-2); font-size: 15px; display: flex; align-items: center; gap: 10px; } +.signoff-makers li::before { content: ''; width: 9px; height: 9px; border-radius: 50%; border: 1.5px solid var(--ink-3); flex: none; } +.signoff-line { margin: 0 0 18px; font-size: 22px; line-height: 1.25; font-weight: 600; letter-spacing: -.015em; color: var(--ink); } +.signoff-sign { display: flex; align-items: flex-end; gap: 10px; margin-bottom: 14px; } +.signoff-rule { flex: 1; height: 28px; border-bottom: 1.5px solid var(--ink); } +.signoff figcaption { margin: 0; } + +.why { padding: 8px 0 40px; border-bottom: 1px solid var(--line); } +.why-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 32px; } +.why-col { border-top: 2px solid var(--ink); padding-top: 14px; } +.why-col h3 { margin: 0 0 8px; font-size: 17px; letter-spacing: -.01em; } +.why-col p { margin: 0; color: var(--ink-2); font-size: 14px; line-height: 1.6; max-width: 60ch; } +.why-example { margin: 28px 0 0; padding: 14px 18px; border-left: 3px solid var(--accent); background: var(--paper-2); border-radius: 0 var(--r) var(--r) 0; color: var(--ink-2); font-size: 14.5px; line-height: 1.6; max-width: 92ch; } +.why-example b { color: var(--ink); } + +.areas { padding: 40px 0; border-bottom: 1px solid var(--line); } +.areas h2, .why-mojo h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.area-card { gap: 10px; } +.area-card h3 { margin: 0; font-size: 20px; letter-spacing: -.01em; } +.area-tagline { min-height: 3em; } +/* every card's sample sits in a window of the same height, so the three read as a set */ +.area-window { height: 400px; overflow: hidden; padding: 10px; border: 1px solid var(--line); border-radius: var(--r); background: var(--paper); -webkit-mask-image: linear-gradient(#000 88%, transparent); mask-image: linear-gradient(#000 88%, transparent); } +.area-window .area-sample .sample { max-height: none; overflow: hidden; } +.area-card .hero-actions { margin-top: 4px; } + +.why-mojo { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); gap: 48px; align-items: start; padding: 40px 0; border-bottom: 1px solid var(--line); } +.why-mojo-points { margin: 0 0 14px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 2px; } +.why-mojo-points dt { font-weight: 600; margin-top: 10px; } +.why-mojo-points dd { margin: 0; color: var(--ink-2); max-width: 62ch; } +/* the range of one language, a real sequence from the first program to the far end */ +.mojo-range { list-style: none; margin: 8px 0 0; padding: 0; counter-reset: rung; position: relative; } +.mojo-range::before { content: ''; position: absolute; left: 11px; top: 14px; bottom: 14px; width: 2px; background: linear-gradient(var(--lang-lingo), var(--lang-mojo)); border-radius: 2px; } +.mojo-range li { counter-increment: rung; position: relative; padding: 8px 0 14px 40px; display: flex; flex-direction: column; gap: 2px; } +.mojo-range li::before { content: counter(rung); position: absolute; left: 0; top: 7px; width: 24px; height: 24px; border-radius: 50%; background: var(--paper-2); border: 2px solid var(--lang-mojo); display: grid; place-items: center; font-size: 12px; font-weight: 700; color: var(--ink); } +.mojo-range li span { font-size: 13px; } + +/* the notations: six even boxes, two rows of three */ +.ways.ways-even { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; } +.ways-even .way { display: flex; flex-direction: column; padding: 14px 14px 12px; } +.ways-even .way h3 { display: flex; align-items: center; gap: 8px; font-size: 15px; margin-bottom: 4px; } +.ways-even .way-area { font-size: 11px; font-weight: 500; padding: 1px 8px; } +.ways-even .way > p { min-height: 4.5em; } +.ways-even .way pre { height: 150px; max-height: none; font-size: 11.5px; } +.ways-even .way-body { height: 158px; border-top: 1px solid var(--line); padding-top: 8px; } +.ways-even .way-body pre { height: auto; border-top: 0; padding-top: 0; -webkit-mask-image: none; mask-image: none; margin-bottom: 10px; } +.ways-even .way .way-note { min-height: 0; margin: 0; font-size: 12px; } + +@media (max-width: 900px) { + .hero.hero-pitch, .why-mojo { grid-template-columns: 1fr; gap: 28px; } + .hero.hero-pitch h1 { font-size: 34px; } + .why-grid { grid-template-columns: 1fr; gap: 20px; } + .ways.ways-even { grid-template-columns: 1fr 1fr; } + .area-window { height: auto; max-height: 420px; } +} +@media (max-width: 560px) { + .ways.ways-even { grid-template-columns: 1fr; } +} + +/* the Run view: a string or list with no ruler yet keeps the ruler's height */ +.ruler.ruler-placeholder { visibility: hidden; } + +/* ---------- With Quarto (#/quarto, src/ui/quarto.ts) and its teaser on the home page ---------- + The extension's own stylesheet (quarto/_extensions/pplus/pplus.css) draws the views as a Quarto page does; it + reads Bootstrap's variables, which here are the app's tokens. */ +.qg, .quarto-teaser { + --bs-body-color: var(--ink); + --bs-body-bg: var(--paper-2); + --bs-secondary-color: var(--ink-3); + --bs-link-color: var(--accent); + --bs-font-monospace: var(--mono); +} +.qg-hero { padding: 40px 0 18px; } +.qg-hero h1 { font-size: 42px; line-height: 1.1; letter-spacing: -.025em; margin: 0 0 16px; max-width: 22ch; text-wrap: balance; } +.qg-hero .lede { font-size: 17px; color: var(--ink-2); max-width: 70ch; line-height: 1.55; margin: 0 0 22px; } +.qg-kinds { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; padding: 8px 0 36px; border-bottom: 1px solid var(--line); } +.qg-kindcard { padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); } +.qg-kindcard p { margin: 8px 0 0; } +.qg-kind { display: inline-block; font-size: 11.5px; font-weight: 600; padding: 1px 9px; border-radius: 10px; line-height: 1.6; } +.qg-kind-chip-rendered { background: var(--ok-bg); color: var(--ok); } +.qg-kind-chip-live { background: var(--accent-bg); color: var(--accent); } +.qg-kind-chip-machine { background: color-mix(in srgb, var(--lang-asm) 16%, var(--paper-2)); color: var(--ink); } +.qg-index a.qg-kind-machine { color: var(--ink); } +.qg-explore { font-family: var(--mono); max-width: 100%; } +.qg-kind-chip-text { background: var(--paper-3); color: var(--ink-2); } +.qg h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.qg-gallery-sec { padding: 36px 0 12px; } +.qg-index { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 0 0 12px; font: 12.5px var(--mono); } +.qg-index a { color: var(--ink-2); } +.qg-index a.qg-kind-rendered { color: var(--ok); } +.qg-index a.qg-kind-live { color: var(--accent); } +.qg-gallery { display: flex; flex-direction: column; gap: 22px; margin-top: 14px; } +.qg-card { scroll-margin-top: 16px; padding: 18px 18px 14px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper); } +.qg-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.qg-card-head h3 { margin: 0; font-size: 17px; order: -1; flex-basis: 100%; } +.qg-name { font: 600 14px var(--mono); color: var(--ink); } +.qg-summary { margin: 8px 0 12px; color: var(--ink-2); max-width: 80ch; } +.qg-note { margin: -6px 0 12px; max-width: 80ch; } +.qg-label { font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-3); margin: 10px 0 6px; } +.qg-tabbar { display: flex; flex-wrap: wrap; gap: 2px; border-bottom: 1px solid var(--line); margin-bottom: 8px; } +.qg-tab { font: 12.5px var(--mono); padding: 5px 10px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ink-2); cursor: pointer; } +.qg-tab:hover { color: var(--ink); } +.qg-tab.on { color: var(--ink); border-bottom-color: var(--accent); } +.qg-codeblock, .qg-codeblock.pplus-static { position: relative; padding: 0; } +.qg-codeblock .pplus-code { max-height: 22rem; overflow: auto; } +.qg-codeblock .qg-copy { position: absolute; top: 6px; right: 6px; } +.qg-plain { padding: .55rem .8rem !important; white-space: pre-wrap; } +.qg-out .pplus-figure, .qg-out figure.pplus-embed { margin: 0; } +.qg-out .pplus-static { background: var(--paper-2); } +.qg-tabs.pplus-static, .qg-listings.pplus-static { padding: 0; } +.qg-tabs .qg-tabbody { padding: 2px 0 0; } +.qg-listings { display: flex; flex-direction: column; gap: 8px; } +.qg-opts { margin-top: 12px; font-size: 13px; } +.qg-opts summary { cursor: pointer; color: var(--ink-2); } +.qg-opts dl, .qg-optlist { display: grid; grid-template-columns: max-content 1fr; gap: 3px 14px; margin: 8px 0 0; } +.qg-opts dt, .qg-optlist dt { font-weight: 400; } +.qg-opts dd, .qg-optlist dd { margin: 0; color: var(--ink-2); } +.qg-setup, .qg-ref { padding: 36px 0 12px; border-top: 1px solid var(--line); margin-top: 24px; } +.qg-steps { list-style: none; padding: 0; margin: 12px 0 0; display: flex; flex-direction: column; gap: 20px; } +.qg-step { display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: 12px; } +.qg-step-n { width: 28px; height: 28px; border-radius: 50%; display: grid; place-items: center; font-weight: 700; background: var(--accent-bg); color: var(--accent); } +.qg-step h3 { margin: 3px 0 6px; font-size: 16px; } +.qg-step p { margin: 0 0 8px; color: var(--ink-2); max-width: 80ch; } +.qg-step .qg-codeblock { margin-bottom: 8px; max-width: 760px; } +.qg-files { display: flex; flex-wrap: wrap; gap: 4px; } +.qg-files .chip { font-family: var(--mono); } +.qg-tbl td:first-child { white-space: nowrap; } +.qg-ref h3 { margin: 22px 0 4px; font-size: 16px; } + +.quarto-teaser { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 36px; align-items: start; padding: 40px 0; border-bottom: 1px solid var(--line); } +.quarto-teaser h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.quarto-teaser .qg-chips { display: flex; flex-wrap: wrap; gap: 4px; margin: 0 0 18px; } +.quarto-teaser .qg-chips a { font-family: var(--mono); } +.quarto-teaser .pplus-figure { margin: 0; } +.quarto-teaser .qg-codeblock { margin-bottom: 10px; } + +@media (max-width: 900px) { + .qg-kinds, .quarto-teaser { grid-template-columns: 1fr; } + .qg-hero h1 { font-size: 32px; } +} diff --git a/styles/course/README.md b/styles/course/README.md new file mode 100644 index 0000000..24be0a8 --- /dev/null +++ b/styles/course/README.md @@ -0,0 +1,26 @@ +# styles/course + +Stylesheets from the course site (`static/css/` in its repository), copied here unchanged so the vendored engines' widgets (`src/engines/asm86/views.js` and `hwviews.js`: registers, memory, caches, pipeline, the out-of-order core) can be shown in the app with the look they have on the course pages. `index.html` loads them, and the Hardware area's machine board (`src/ui/hw/board.ts`) is what uses them. + +| File here | Course path | What it holds | sha256 | +|---|---|---|---| +| `tokens.css` | `static/css/base/tokens.css` | `--course-*` roles and the `--viz-*` chart palette that `shared/viz.js` and the hardware views read | `b2f40ca21e0f0a38aaf3dd096ec91e8afeb2455742f1fe255577cbaecd01a745` | +| `kit.css` | `static/css/widgets/kit.css` | the `--w-*` tokens and controls shared by the widget families | `51b46da837fcf64d20fd497458d2328a1e896913a2d2fededab198b58e889790` | +| `asm86.css` | `static/css/widgets/asm86.css` | every `.a86-*` rule the x86-64 widgets use (needs `kit.css` first) | `dba269f466b33be7621a2156a0db386d24b89927cf3bfa00397b8af58759e576` | +| `bridge.css` | (ours) | gives the course files the page colors and fonts they expect, from the app's tokens | | + +The Quarto extension ships the same three files in `quarto/_extensions/pplus/course/`, with the board's adjustments from `bridge.css` (its `:root` block left out, since a Quarto page has those colors already) as `pplus-hw.css`; `pixi run quarto-css` copies them, and `tests/quarto.test.mjs` fails while the copies differ. + +`tests/course-css.test.mjs` checks that each copied file still has the hash above, so a local edit cannot slip in: a change belongs in the course repository, then copy the file again and update its hash here. + +## Using them + +Load in this order, after `styles.css`: `bridge.css`, `tokens.css`, `kit.css`, `asm86.css`. Then: + +- **The theme.** The course files switch to dark on `body.quarto-dark`, and they follow the operating system only when the body has neither `quarto-light` nor `quarto-dark`. The app therefore puts exactly one of those classes on ``, matching the theme it shows: `syncBodyTheme()` in `src/ui/theme.ts` (the choice itself is the pure `themeBodyClass()`, tested in `tests/hardware.test.mjs`) runs at load, on every theme change, on a host page's forced theme, and when the system preference changes. Without that, a light app on a dark system would draw dark widgets. +- **The root class.** The widgets build their own `.a86` root, so their rules cannot touch the rest of the app. +- **The pseudocode lab** (`pseudo-lab.css`) is not copied: the app draws its own views for pseudo and does not use the engine's `views.js` for it. + +## Updating + +Copy the three files from the course repository's `static/css/` (paths in the table), run `sha256sum styles/course/*.css`, put the new hashes in the table above, and run `pixi run test`. diff --git a/styles/course/asm86.css b/styles/course/asm86.css new file mode 100644 index 0000000..e252773 --- /dev/null +++ b/styles/course/asm86.css @@ -0,0 +1,2773 @@ +/* widgets/asm86.css -- styling for the x86-64 teaching widgets. + + Load AFTER widgets/kit.css, which holds the color roles (amber = something + changed on this step, blue = a memory load, green = a recorded match, + purple = a memory store, red = a mismatch or a branch mispredicting often + enough to cost time), dark mode, and the rules shared with the pseudocode + lab. + + The hardware views keep those meanings. A cache hit is green and a miss + is red, read the same way as a match and a mismatch; a load's path + through the memory hierarchy is blue and a store's is purple. Machine + code needs more categories than five, so the encoding view has its own + small palette (--a86-enc-*), and always writes each byte's role under it + so color is never the only signal. */ + +.a86 { + --a86-enc-prefix: #6b6f76; + --a86-enc-rex: #9a3f7a; + --a86-enc-opcode: #8a5c05; + --a86-enc-modrm: #17618f; + --a86-enc-sib: #266a41; + --a86-enc-disp: #6a4299; + --a86-enc-imm: #93291f; +} + +body.quarto-dark .a86, +[data-bs-theme="dark"] .a86 { + --a86-enc-prefix: #a9aeb5; + --a86-enc-rex: #e39acb; + --a86-enc-opcode: #e0a93a; + --a86-enc-modrm: #6fb4e3; + --a86-enc-sib: #74c391; + --a86-enc-disp: #c0a0e0; + --a86-enc-imm: #e08a80; + + /* a touch stronger than the shared 22%, so green reads against a dark page */ + --w-match-bg: color-mix(in srgb, var(--w-match) 24%, var(--w-page)); +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + .a86 { + --w-surface: #ffffff; + } + + .a86-enc-part { + background: var(--w-surface-2); + } + + body.quarto-dark .a86 { + --w-surface: #1a1e23; + } +} + + +/* --------------------------------------------------- inherited code style + Quarto styles bare with its own background, padding, and color. + Inside a widget every register value, letter, and instruction is a , + so that styling turns each one into a little tinted chip fighting the + panel it sits in. The :not() raises specificity above Quarto's + `code:not(.sourceCode)` regardless of which stylesheet loads first. */ + + + + + + +/* controls -------------------------------------------------------------- */ + + +/* Quarto adds .btn.btn-quarto to buttons in OJS output, and base/site.css + themes those from --bs-btn-*. These rules are the standalone fallback and + deliberately lose to it, so a widget inside the site matches every other + button on the site. */ + + +/* Kept at one class so site styling still wins on padding and background, + while the primary action stays marked. */ + + + +/* layout ---------------------------------------------------------------- */ + + +/* The program listing needs more width than any state panel, because its + longest line is fixed and cannot reflow. An even split clipped + `movzx r8d, byte ptr [rdi + rcx*1]` mid-operand. */ +@media (min-width: 720px) { + .a86-two-column .a86-grid { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); + } + + .a86-two-column .a86-span-2, + .a86-two-column .a86-mem-panel, + .a86-two-column .a86-vec-panel, + .a86-two-column .a86-flow-panel, + .a86-two-column .a86-path-panel, + .a86-two-column .a86-code-panel.is-wide, + .a86-two-column .a86-bits-panel, + .a86-two-column .a86-cache-panel, + .a86-two-column .a86-pipe-panel, + .a86-two-column .a86-tl-panel, + .a86-two-column .a86-core-panel, + .a86-two-column .a86-chip-panel, + .a86-two-column .a86-uops-panel, + .a86-two-column .a86-bn-panel { + grid-column: 1 / -1; + } +} + +/* ------------------------------------------------------------ fullscreen + A fixed overlay rather than the browser's own fullscreen mode: it behaves + the same in every browser, needs no permission, and leaves the page + exactly as it was on the way out. Above Bootstrap's fixed navbar at 1030. + + The extra room goes to the text first: the widget's one font size grows + with the window, from the page size on a laptop to about 1.3 times it on a + large monitor. The panels then share each row with flexbox rather than a + grid. A grid with a full-width listing keeps every column it made alive, + so three panels in a row of five sat at a fifth of the width each and + left the rest blank; flex rows always fill. */ + + + + +.a86.is-fullscreen .a86-grid>* { + flex: 1 1 calc(var(--w-fs) * 21); +} + +/* A diagram asks for the width at which its labels match the text around + it (see the diagram sizes below), so it shares a row only when there is + room for that, and otherwise takes a row of its own. */ +.a86.is-fullscreen .a86-grid>.a86-path-panel, +.a86.is-fullscreen .a86-grid>.a86-flow-panel { + flex-basis: calc(var(--w-fs) * 60); +} + +.a86.is-fullscreen .a86-grid>.a86-cache-panel, +.a86.is-fullscreen .a86-grid>.a86-mem-panel, +.a86.is-fullscreen .a86-grid>.a86-stack-panel { + flex-basis: calc(var(--w-fs) * 32); +} + +.a86.is-fullscreen .a86-grid>.a86-code-panel, +.a86.is-fullscreen .a86-grid>.a86-pipe-panel, +.a86.is-fullscreen .a86-grid>.a86-tl-panel, +.a86.is-fullscreen .a86-grid>.a86-chip-panel, +.a86.is-fullscreen .a86-grid>.a86-core-panel, +.a86.is-fullscreen .a86-grid>.a86-bits-panel, +.a86.is-fullscreen .a86-grid>.a86-span-2 { + flex-basis: 100%; +} + +/* Never so tall that a diagram pushes the rest of the widget off screen. */ +.a86.is-fullscreen .a86-path-svg, +.a86.is-fullscreen .a86-flow-svg, +.a86.is-fullscreen .a86-chip-svg, +.a86.is-fullscreen .a86-tl-svg { + max-height: 70vh; +} + +/* Diagram sizes. Each diagram is drawn about 700 units wide with 12-unit + labels, so capping it near 58 times the widget's font size makes a label + come out close to the size of the text around it, at any zoom, in the + page or in fullscreen. A fixed pixel cap made the labels shrink to half + the text size in a wide panel. */ +.a86 .a86-path-svg, +.a86 .a86-flow-svg, +.a86 .a86-tl-svg { + max-width: calc(var(--w-fs) * 58); +} + +.a86 .a86-chip-svg { + max-width: calc(var(--w-fs) * 62); +} + + + +.a86-panel { + background: var(--w-surface); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.55rem 0.65rem; + min-width: 0; + overflow: hidden; +} + + +/* code listing ---------------------------------------------------------- */ + +.a86-code { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + line-height: 1.55; + overflow-x: auto; + + /* Set by codeView from the longest instruction in the program, in + characters. The instruction column is therefore exactly wide enough + and never clips, and comments line up in a column across every row. */ + --a86-code-cols: 48ch; +} + +.a86-code-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) var(--a86-code-cols) minmax(0, 1fr); + align-items: baseline; + border-left: 2px solid transparent; + padding-left: 0.15rem; + background: color-mix(in srgb, var(--w-change-bg) calc(var(--heat, 0) * 70%), transparent); +} + +/* A comment on a line of its own takes the width of both remaining cells. */ +.a86-code-row.is-note { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-count { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.85); + text-align: right; + padding-right: 0.3rem; +} + + +.a86-code-text { + white-space: pre; + font-size: inherit; +} + +/* The comment takes whatever width is left and wraps into it, so a narrow + panel costs a comment an extra line rather than costing the instruction + its tail. */ +.a86-code-comment { + color: var(--w-dim); + font-weight: 400; + white-space: normal; + padding-left: 0.5rem; + text-indent: 0; +} + +.a86-code-row.is-note .a86-code-comment { + padding-left: 0; + white-space: pre-wrap; +} + +/* With addresses and bytes, two more columns sit before the instruction, + as in objdump's output. Label and note rows leave them empty. */ +.a86-code.has-machine .a86-code-row { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) var(--a86-addr-cols) var(--a86-bytes-cols) var(--a86-code-cols) minmax(0, 1fr); +} + +.a86-code.has-machine .a86-code-row.is-note, +.a86-code.has-machine .a86-code-row.a86-code-label { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-addr { + color: var(--w-dim); +} + +.a86-code-bytes { + color: var(--w-read); + white-space: pre; +} + +.a86-code-addr, +.a86-code-bytes { + font-size: inherit; +} + + +.a86-code-row.is-error .a86-code-marker { + color: var(--w-miss); +} + +.a86-code-failed .a86-code-row { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-blank .a86-code-text { + color: var(--w-dim); +} + +.a86-code-label .a86-code-text { + color: var(--w-read); +} + + +.a86-code-row.is-next { + border-left-color: var(--w-change); + background: var(--w-change-bg); + font-weight: 600; +} + +/* registers ------------------------------------------------------------- */ + +.a86-regs { + display: grid; + /* Wide enough for 0x and 16 hex digits on one line in the value's own + monospace size (about 0.6em a character), plus the card's padding. */ + grid-template-columns: repeat(auto-fill, minmax(calc(var(--w-fs) * 10.2 + 1.1rem), 1fr)); + gap: 0.35rem; +} + +.a86-reg { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.3rem 0.4rem; + background: var(--w-surface-2); + display: flex; + flex-direction: column; + gap: 0.05rem; + min-width: 0; +} + +.a86-reg-name { + font-family: var(--w-mono); + font-weight: 700; + font-size: calc(var(--w-fs) * 0.95); +} + +.a86-reg-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.86); + color: var(--w-dim); +} + +.a86-reg-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + overflow-wrap: anywhere; + line-height: 1.3; +} + +.a86-reg-prev { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + min-height: 0.8rem; +} + +.a86-reg.is-changed { + border-color: var(--w-change); + background: var(--w-change-bg); + animation: a86-pulse 420ms ease-out; +} + +.a86-reg.is-changed .a86-reg-value { + color: var(--w-change); + font-weight: 700; +} + +.a86-reg-widths { + margin-top: 0.3rem; + border-top: 1px dashed var(--w-rule); + padding-top: 0.25rem; +} + +.a86-width-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.83) 1fr auto; + gap: 0.3rem; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-width-name { + font-family: var(--w-mono); + color: var(--w-read); +} + +.a86-width-bits { + font-family: var(--w-mono); +} + +.a86-width-size { + font-family: var(--w-sans); + color: var(--w-dim); +} + +@keyframes a86-pulse { + from { + box-shadow: 0 0 0 3px var(--w-change-bg); + } + + to { + box-shadow: 0 0 0 0 transparent; + } +} + +@media (prefers-reduced-motion: reduce) { + + .a86-reg.is-changed, + .a86-flag.is-changed, + .a86-cell.is-read { + animation: none; + } +} + +.a86-explain-fault { + color: var(--w-miss); + background: var(--w-miss-bg); + border-left: 3px solid var(--w-miss); + padding: 0.3rem 0.5rem; +} + +/* flags ----------------------------------------------------------------- */ + +.a86-flags { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.a86-flag { + display: flex; + align-items: center; + gap: 0.3rem; + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.25rem 0.45rem; + background: var(--w-surface-2); + cursor: help; +} + +.a86-flag-name { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-flag-dot { + width: calc(var(--w-fs) * 0.65); + height: 0.55rem; + border-radius: 50%; + border: 1px solid var(--w-rule); + background: transparent; +} + +.a86-flag-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); +} + +.a86-flag.is-on { + border-color: var(--w-change); +} + +.a86-flag.is-on .a86-flag-dot { + background: var(--w-change); + border-color: var(--w-change); +} + +.a86-flag.is-changed { + background: var(--w-change-bg); + animation: a86-pulse 420ms ease-out; +} + +/* A flag the last conditional instruction consulted gets a solid read-blue + ring; one the next instruction will consult, a dashed one. */ +.a86-flag.is-consulted { + box-shadow: 0 0 0 2px var(--w-read); +} + +.a86-flag.is-wanted { + outline: 1px dashed var(--w-read); + outline-offset: 2px; +} + +.a86-flag-reading { + color: var(--w-read); +} + +.a86-flag-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; + min-height: 1.1rem; +} + +/* memory strip ---------------------------------------------------------- */ + +.a86-mem { + display: flex; + flex-direction: column; + gap: 0.6rem; +} + +.a86-strip-wrap { + display: flex; + align-items: flex-start; + gap: 0.5rem; + min-width: 0; +} + +.a86-strip-label { + display: flex; + flex-direction: column; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + padding-top: 0.15rem; +} + +.a86-strip-addr { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-strip { + display: flex; + overflow-x: auto; + padding-bottom: 0.15rem; +} + +.a86-cell { + display: flex; + flex-direction: column; + align-items: center; + min-width: calc(var(--w-fs) * 1.59); + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface); +} + +.a86-cell:last-child { + border-right-width: 1px; +} + +.a86-cell-letter { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.98); + line-height: 1.5; +} + +.a86-cell-pos { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.8); + color: var(--w-dim); + border-top: 1px solid var(--w-rule); + width: 100%; + text-align: center; +} + +.a86-cell.in-window { + background: var(--w-surface-2); +} + +.a86-cell.is-match { + background: var(--w-match-bg); +} + +.a86-cell.is-match .a86-cell-letter { + color: var(--w-match); + font-weight: 700; +} + +.a86-cell.is-read { + background: var(--w-read-bg); + border-color: var(--w-read); + border-right-width: 1px; + margin-right: -1px; + position: relative; + z-index: 1; + animation: a86-pulse 420ms ease-out; +} + +.a86-cell.is-read .a86-cell-letter { + color: var(--w-read); + font-weight: 700; +} + +.a86-cell.is-write { + background: var(--w-write-bg); + border-color: var(--w-write); +} + +.a86-cell.is-write .a86-cell-letter { + color: var(--w-write); + font-weight: 700; +} + +/* address arithmetic ---------------------------------------------------- */ + +.a86-addr-sum { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 0.3rem; +} + +.a86-addr-part { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.25rem 0.4rem; + background: var(--w-surface-2); + display: flex; + flex-direction: column; + min-width: 0; +} + +.a86-addr-part.is-result { + border-color: var(--w-read); + background: var(--w-read-bg); +} + +.a86-addr-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-addr-expr { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); +} + +.a86-addr-val { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.91); + font-weight: 600; +} + +.a86-addr-op { + align-self: center; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 1); +} + +.a86-addr-note { + font-size: calc(var(--w-fs) * 0.91); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* data flow ------------------------------------------------------------- */ + +/* Both diagrams are drawn at a fixed size in their viewBox. Stretched to a + full-width panel they scaled up by a third, which made their labels + larger than the body text around them. Capping the width keeps them in + proportion; the font sizes below are set for that capped size. */ +.a86-flow-svg { + display: block; + width: 100%; + max-width: 820px; + height: auto; + margin: 0 auto; +} + +.a86-flow-box rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-flow-box.is-source rect { + stroke: var(--w-read); +} + +.a86-flow-box.is-dest rect { + fill: var(--w-change-bg); + stroke: var(--w-change); +} + +.a86-flow-box.is-flags rect { + fill: var(--w-surface-2); + stroke: var(--w-change); + stroke-dasharray: 3 2; +} + +.a86-flow-box.is-control rect { + fill: var(--w-match-bg); + stroke: var(--w-match); +} + +.a86-flow-label { + font-family: var(--w-mono); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-flow-value { + font-family: var(--w-mono); + font-size: 14px; + fill: var(--w-ink); + font-weight: 600; +} + +/* Only the flow arrows get the flow marker. The earlier combined rule also + matched .a86-path-edge and pointed it at a marker that exists in a + different svg, which silently removed every datapath arrowhead. */ +.a86-flow-arrow { + stroke: var(--w-dim); + stroke-width: 1.2; + fill: none; +} + +.a86-flow-svg path[marker-end] { + fill: none; +} + +.a86-flow-svg marker path { + fill: var(--w-dim); + stroke: none; +} + +.a86-flow-op rect { + fill: var(--w-surface); + stroke: var(--w-ink); + stroke-width: 1.4; +} + +.a86-flow-opname { + font-family: var(--w-mono); + font-size: 16px; + font-weight: 700; + fill: var(--w-ink); +} + +.a86-flow-opkind { + font-family: var(--w-sans); + font-size: 11px; + fill: var(--w-dim); +} + +.a86-flow-gloss { + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + margin: 0.3rem 0 0; +} + +/* datapath -------------------------------------------------------------- */ + +.a86-path-svg { + display: block; + width: 100%; + max-width: 860px; + height: auto; + margin: 0 auto; +} + +.a86-path-node rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-path-label { + font-family: var(--w-sans); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-path-node.is-active rect { + fill: var(--w-change-bg); + stroke: var(--w-change); + stroke-width: 1.6; +} + +.a86-path-node.is-active .a86-path-label { + fill: var(--w-ink); + font-weight: 600; +} + +.a86-path-edge { + stroke: var(--w-rule); + stroke-width: 1.2; + fill: none; +} + +.a86-path-svg marker path { + fill: var(--w-rule); + stroke: none; +} + +.a86-path-edge.is-active { + stroke: var(--w-change); + stroke-width: 2; +} + +.a86-path-caption { + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + margin: 0.35rem 0 0; +} + +/* explanation ----------------------------------------------------------- */ + +.a86-explain p { + margin: 0 0 0.4rem; +} + +.a86-explain-instr { + font-family: var(--w-mono); + background: var(--w-surface-2); + padding: 0.05rem 0.3rem; + border-radius: 2px; + white-space: pre; +} + +.a86-explain-effect { + color: var(--w-change); +} + +/* counters -------------------------------------------------------------- */ + +.a86-counters { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(calc(var(--w-fs) * 7.3), 1fr)); + gap: 0.4rem; +} + +.a86-counter { + display: flex; + flex-direction: column; + padding: 0.3rem 0.45rem; + border: 1px solid var(--w-rule); + border-radius: 3px; + background: var(--w-surface-2); +} + +.a86-counter-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 1.22); + font-weight: 700; +} + +.a86-counter-label { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + line-height: 1.25; +} + +/* tables ---------------------------------------------------------------- */ + +.a86-table { + width: 100%; + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-table th { + font-family: var(--w-sans); + text-align: left; + font-weight: 600; + color: var(--w-dim); + border-bottom: 1px solid var(--w-rule); + padding: 0.18rem 0.35rem 0.25rem; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-table td { + padding: 0.14rem 0.35rem; + border-bottom: 1px solid var(--w-surface-2); +} + +.a86-table tr.is-current { + background: var(--w-change-bg); +} + +.a86-table tr.is-current code { + font-weight: 700; +} + +.a86-table tr.is-costly td { + color: var(--w-miss); +} + +.a86-trace-wrap { + max-height: 15rem; + overflow-y: auto; +} + +.a86-trace-step { + color: var(--w-dim); + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.87); +} + +/* vector registers ------------------------------------------------------ */ + +.a86-vecs { + display: flex; + flex-direction: column; + gap: 0.45rem; +} + +.a86-vec-row { + display: flex; + align-items: flex-start; + gap: 0.5rem; + min-width: 0; +} + +.a86-vec-label { + display: flex; + flex-direction: column; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + min-width: calc(var(--w-fs) * 4.95); + padding-top: 0.15rem; +} + +.a86-vec-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.82); + color: var(--w-dim); + line-height: 1.2; +} + +.a86-vec-strip { + display: flex; + overflow-x: auto; +} + +.a86-vec-cell { + display: flex; + flex-direction: column; + align-items: center; + min-width: calc(var(--w-fs) * 1.53); + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface); +} + +.a86-vec-cell:last-child { + border-right-width: 1px; +} + +.a86-vec-val { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.94); + line-height: 1.45; +} + +.a86-vec-lane { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.78); + color: var(--w-dim); + border-top: 1px solid var(--w-rule); + width: 100%; + text-align: center; +} + +.a86-vec-cell.is-yes { + background: var(--w-match-bg); +} + +.a86-vec-cell.is-yes .a86-vec-val { + color: var(--w-match); + font-weight: 700; +} + +.a86-vec-cell.is-no .a86-vec-val { + color: var(--w-dim); +} + +.a86-vec-cell.is-letter .a86-vec-val { + color: var(--w-ink); +} + +.a86-vec-cell.is-bit { + background: var(--w-surface-2); +} + +.a86-vec-cell.is-changed { + border-color: var(--w-change); + border-right-width: 1px; + margin-right: -1px; +} + + +.a86-vec-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.35rem 0 0; + min-height: 1.1rem; +} + +/* ================================================================ hardware + Views from hwviews.js. Same tokens, same rules: everything neutral is + mixed from the page, only the accents are stated. */ + +.a86-hw-machine { + font-size: calc(var(--w-fs) * 0.87); + color: var(--w-dim); + margin: 0.5rem 0 0; +} + +.a86-legend { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.9rem; + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +.a86-legend-item { + display: inline-flex; + align-items: center; + gap: 0.3rem; +} + +.a86-swatch { + display: inline-block; + width: calc(var(--w-fs) * 0.94); + height: 0.65rem; + border-radius: 2px; + border: 1px solid var(--w-rule); + background: var(--w-surface-2); +} + +.a86-hier-label { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.88); + font-weight: 600; + color: var(--w-dim); + margin: 0.6rem 0 0.3rem; +} + +/* encoding -------------------------------------------------------------- */ + +.a86-enc-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.6rem; + margin: 0 0 0.5rem; +} + +.a86-enc-addr { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.93); +} + +.a86-enc-text { + font-weight: 600; +} + +.a86-enc-strip { + display: flex; + flex-wrap: wrap; + gap: 0.3rem; + margin-bottom: 0.6rem; +} + +.a86-enc-part { + --part: var(--a86-enc-prefix); + display: flex; + flex-direction: column; + align-items: center; + border: 1px solid var(--part); + border-radius: 3px; + background: color-mix(in srgb, var(--part) 12%, var(--w-page)); + padding: 0.2rem 0.3rem 0.15rem; +} + +.a86-enc-part.is-rex, +.a86-enc-detail.is-rex { + --part: var(--a86-enc-rex); +} + +.a86-enc-part.is-opcode, +.a86-enc-detail.is-opcode { + --part: var(--a86-enc-opcode); +} + +.a86-enc-part.is-modrm, +.a86-enc-detail.is-modrm { + --part: var(--a86-enc-modrm); +} + +.a86-enc-part.is-sib, +.a86-enc-detail.is-sib { + --part: var(--a86-enc-sib); +} + +.a86-enc-part.is-disp, +.a86-enc-detail.is-disp, +.a86-enc-part.is-rel, +.a86-enc-detail.is-rel { + --part: var(--a86-enc-disp); +} + +.a86-enc-part.is-imm, +.a86-enc-detail.is-imm { + --part: var(--a86-enc-imm); +} + +.a86-enc-bytes { + display: flex; + gap: 0.25rem; +} + +.a86-enc-byte { + font-size: calc(var(--w-fs) * 1.17); + font-weight: 700; + color: var(--part); +} + +.a86-enc-kind { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); + font-family: var(--w-sans); +} + +.a86-enc-details { + display: grid; + gap: 0.4rem; +} + +.a86-enc-detail { + --part: var(--a86-enc-prefix); + border-left: 3px solid var(--part); + padding: 0.15rem 0 0.2rem 0.5rem; +} + +.a86-enc-detail-head { + display: flex; + gap: 0.5rem; + align-items: baseline; +} + +.a86-enc-detail-name { + font-weight: 600; + font-size: calc(var(--w-fs) * 0.93); + color: var(--part); +} + +.a86-enc-detail-bytes { + font-size: calc(var(--w-fs) * 0.9); +} + +.a86-enc-detail-text { + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-enc-bits { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-top: 0.3rem; +} + +.a86-enc-field { + display: flex; + flex-direction: column; + min-width: calc(var(--w-fs) * 3.53); +} + +.a86-enc-field-bits { + display: flex; +} + +.a86-enc-bit { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.95); + width: calc(var(--w-fs) * 1.35); + text-align: center; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-enc-bit:last-child { + border-right-width: 1px; +} + +.a86-enc-field-name { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + color: var(--part); + font-weight: 600; +} + +.a86-enc-field-meaning { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + max-width: 16rem; +} + +/* bits ------------------------------------------------------------------ */ + +.a86-bits-title { + margin: 0 0 0.45rem; +} + +.a86-bits-grid { + overflow-x: auto; + padding-bottom: 0.2rem; +} + +.a86-bits-row { + display: flex; + align-items: center; + gap: 0.5rem; + white-space: nowrap; +} + +.a86-bits-label { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + width: calc(var(--w-fs) * 11.19); + flex: none; + text-align: right; + color: var(--w-dim); + overflow: hidden; + text-overflow: ellipsis; +} + +.a86-bits-cells { + display: inline-flex; + flex: none; +} + +.a86-bits-cell { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + width: calc(var(--w-fs) * 0.92); + text-align: center; + line-height: 1.45; + color: var(--w-dim); +} + +.a86-bits-cell.is-nibble { + margin-left: 0.28rem; +} + +.a86-bits-extra { + width: calc(var(--w-fs) * 1.3); + color: var(--w-change); + font-weight: 700; + margin-right: calc(var(--w-fs) * 0.24); + border-right: 1px dashed var(--w-rule); +} + +.a86-bits-row.is-result .a86-bits-cell { + color: var(--w-ink); + border-top: 1px solid var(--w-ink); +} + +.a86-bits-row.is-result .a86-bits-extra { + border-top: 0; +} + +.a86-bits-cell.is-one { + color: var(--w-ink); + font-weight: 700; +} + +.a86-bits-cell.is-top { + background: var(--w-surface-2); +} + +.a86-bits-cell.is-carry { + color: var(--w-change); + font-weight: 700; +} + +.a86-bits-row.is-carries .a86-bits-cell { + font-size: calc(var(--w-fs) * 0.84); +} + +.a86-bits-row.is-muted .a86-bits-cell { + text-decoration: line-through; + opacity: 0.6; +} + +.a86-bits-cell.is-out { + color: var(--w-miss); + font-weight: 700; + outline: 1px solid var(--w-miss); + outline-offset: -1px; +} + +.a86-bits-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + flex: none; + min-width: 7rem; +} + +.a86-bits-note { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + white-space: normal; +} + +.a86-bits-flags { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.15rem; +} + +.a86-bits-flagname { + font-weight: 700; + color: var(--w-dim); +} + +.a86-bits-flagname.is-on { + color: var(--w-change); +} + +.a86-bits-wide p { + margin: 0 0 0.3rem; +} + +/* stack ----------------------------------------------------------------- */ + +.a86-stack-list { + display: flex; + flex-direction: column; +} + +.a86-stack-slot { + /* Address, value, and pointer tag stay on one line; the note takes the + rest of the line, and drops to its own line when the panel is narrow, + instead of being squeezed into a column one word wide. */ + display: flex; + flex-wrap: wrap; + align-items: baseline; + column-gap: 0.8rem; + row-gap: 0.05rem; + border: 1px solid var(--w-rule); + border-bottom-width: 0; + padding: 0.2rem 0.45rem; + font-size: calc(var(--w-fs) * 0.9); +} + +.a86-stack-addr, +.a86-stack-val { + flex: none; +} + +.a86-stack-tags { + order: 2; +} + +.a86-stack-note { + order: 3; + flex: 1 1 calc(var(--w-fs) * 16.49); +} + +.a86-stack-tags:empty { + display: none; +} + +.a86-stack-slot:last-child { + border-bottom-width: 1px; +} + +.a86-stack-addr { + color: var(--w-dim); +} + +.a86-stack-note { + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + min-width: 0; +} + +.a86-stack-slot.is-free { + opacity: 0.5; + background: repeating-linear-gradient(135deg, transparent 0 6px, var(--w-surface-2) 6px 7px); +} + +.a86-stack-slot.is-write { + background: var(--w-write-bg); + border-color: var(--w-write); + opacity: 1; +} + +.a86-stack-slot.is-write .a86-stack-val { + color: var(--w-write); + font-weight: 700; +} + +.a86-stack-slot.is-read { + background: var(--w-read-bg); + border-color: var(--w-read); +} + +.a86-stack-slot.is-read .a86-stack-val { + color: var(--w-read); + font-weight: 700; +} + +.a86-stack-tags { + display: flex; + gap: 0.25rem; +} + +.a86-stack-ptr { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + font-weight: 700; + padding: 0 0.3rem; + border-radius: 2px; + color: var(--w-page); + background: var(--w-change); +} + +.a86-stack-ptr.is-rbp { + background: var(--w-dim); +} + +.a86-stack-more { + font-size: calc(var(--w-fs) * 0.87); + color: var(--w-dim); + padding: 0 0 0.2rem 0.4rem; +} + +.a86-stack-foot { + font-size: calc(var(--w-fs) * 0.9); + margin: 0.45rem 0 0; +} + +/* cache ----------------------------------------------------------------- */ + +.a86-cache-shape { + font-size: calc(var(--w-fs) * 0.93); + margin: 0 0 0.5rem; +} + +.a86-cache-access { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.6rem; + margin-bottom: 0.55rem; +} + +.a86-cache-access-what { + font-size: calc(var(--w-fs) * 0.93); +} + +.a86-split { + display: inline-flex; +} + +.a86-split-part { + display: flex; + flex-direction: column; + align-items: center; + padding: 0.1rem 0.35rem; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-split-part:last-child { + border-right-width: 1px; +} + +.a86-split-part code { + font-size: calc(var(--w-fs) * 0.93); + letter-spacing: 0.04em; +} + +.a86-split-part span { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-split-part.is-index { + background: var(--w-read-bg); + border-color: var(--w-read); +} + +.a86-split-part.is-index code { + color: var(--w-read); + font-weight: 700; +} + +.a86-split-part.is-offset code { + color: var(--w-dim); +} + +.a86-cache-wrap { + overflow-x: auto; +} + +.a86-cache-grid { + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.89); +} + +.a86-cache-grid th { + font-family: var(--w-sans); + font-weight: 600; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.85); + padding: 0.1rem 0.35rem; + text-align: left; +} + +.a86-cache-grid tbody th { + text-align: right; + font-family: var(--w-mono); +} + +.a86-cache-grid tr.is-active th { + color: var(--w-read); +} + +.a86-cache-grid tr.is-active td { + border-top-color: var(--w-read); + border-bottom-color: var(--w-read); +} + +.a86-cache-cell { + border: 1px solid var(--w-rule); + padding: 0.15rem 0.35rem; + min-width: calc(var(--w-fs) * 11.19); + vertical-align: top; + background: var(--w-surface); +} + +.a86-cache-cell>* { + display: block; +} + +.a86-cache-cell.is-empty { + background: var(--w-surface-2); +} + +.a86-cache-cell.is-hit { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-cache-cell.is-hit .a86-cache-tag { + color: var(--w-match); + font-weight: 700; +} + +.a86-cache-cell.is-fill { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-cache-cell.is-fill .a86-cache-tag { + color: var(--w-change); + font-weight: 700; +} + +.a86-cache-cell.is-prefetch { + background: var(--w-surface-2); + border-style: dashed; + border-color: var(--w-change); +} + +.a86-cache-data { + font-size: calc(var(--w-fs) * 0.94); + letter-spacing: 0.06em; +} + +.a86-cache-data.is-hex { + font-size: calc(var(--w-fs) * 0.87); + letter-spacing: 0; + color: var(--w-dim); +} + +.a86-cache-meta { + display: flex !important; + gap: 0.4rem; + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-cache-dirty { + color: var(--w-write); + font-weight: 700; +} + +.a86-cache-pf { + color: var(--w-change); +} + +.a86-cache-events { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.2rem; +} + +.a86-cache-events li { + border-left: 3px solid var(--w-rule); + padding-left: 0.45rem; +} + +.a86-cache-events li.is-hit { + border-left-color: var(--w-match); +} + +.a86-cache-events li.is-miss { + border-left-color: var(--w-miss); +} + +.a86-cache-events li.is-prefetch { + border-left-color: var(--w-change); + border-left-style: dashed; +} + +.a86-cache-stats { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; +} + +/* hierarchy ------------------------------------------------------------- */ + +.a86-hier-ladder { + display: flex; + flex-direction: column; + gap: 0.25rem; + container-type: inline-size; +} + +.a86-hier-name { + grid-area: name; +} + +.a86-hier-shape { + grid-area: shape; +} + +.a86-hier-lat { + grid-area: lat; +} + +.a86-hier-count { + grid-area: count; +} + +.a86-hier-row { + display: grid; + /* level | shape (may wrap) | latency bar and label | counts. The latency + column never goes below what "200 cycles" and a short bar need, and + the counts take exactly their own width, so the two cannot overlap. */ + grid-template-areas: "name shape lat count"; + grid-template-columns: calc(var(--w-fs) * 5.5) minmax(0, 1fr) minmax(calc(var(--w-fs) * 9.5), 1.2fr) max-content; + gap: 0.5rem; + align-items: center; + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.45rem; + font-size: calc(var(--w-fs) * 0.9); + background: var(--w-surface); +} + +/* In a narrow panel the shape moves under the level's name, so the latency + and the counts keep enough room to stay on one line. */ +@container (max-width: 34rem) { + .a86-hier-row { + grid-template-areas: "name lat count" "shape lat count"; + grid-template-columns: minmax(0, 1fr) minmax(calc(var(--w-fs) * 8), 1.2fr) max-content; + row-gap: 0; + } +} + +.a86-hier-name { + display: flex; + flex-direction: column; +} + +.a86-hier-name span, +.a86-hier-shape { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); +} + +.a86-hier-lat { + display: flex; + align-items: center; + gap: 0.35rem; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-hier-lat span { + white-space: nowrap; +} + +.a86-hier-bar { + flex: 0 1 auto; + min-width: 0.3rem; + max-width: 65%; +} + +.a86-hier-bar { + height: 0.45rem; + border-radius: 2px; + background: var(--w-rule); +} + +.a86-hier-count { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + text-align: right; +} + +.a86-hier-row.is-hit { + border-color: var(--w-match); + background: var(--w-match-bg); +} + +.a86-hier-row.is-hit .a86-hier-bar { + background: var(--w-match); +} + +.a86-hier-row.is-miss { + border-color: var(--w-miss); + background: var(--w-miss-bg); +} + +.a86-hier-row.is-miss .a86-hier-bar { + background: var(--w-miss); +} + +.a86-hier-paths { + list-style: none; + padding: 0; + margin: 0; + font-size: calc(var(--w-fs) * 0.9); + display: grid; + gap: 0.2rem; +} + +.a86-hier-paths li { + border-left: 3px solid var(--w-read); + padding-left: 0.45rem; +} + +.a86-hier-paths li.is-far { + border-left-color: var(--w-miss); +} + +.a86-hier-paths li.is-near { + border-left-color: var(--w-match); +} + +.a86-hier-cost { + font-family: var(--w-mono); + color: var(--w-dim); +} + +.a86-hier-total, +.a86-hier-tlb { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* paging ---------------------------------------------------------------- */ + +.a86-pg-head { + margin: 0 0 0.35rem; + font-size: calc(var(--w-fs) * 0.94); +} + +.a86-pg-split { + display: flex; + flex-wrap: wrap; +} + +.a86-pg-field { + display: flex; + flex-direction: column; + align-items: center; + padding: 0.1rem 0.4rem; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-pg-field:last-child { + border-right-width: 1px; +} + +.a86-pg-field code { + font-size: calc(var(--w-fs) * 0.9); + letter-spacing: 0.03em; +} + +.a86-pg-field span { + font-size: calc(var(--w-fs) * 0.84); + color: var(--w-dim); +} + +.a86-pg-field.is-offset code { + color: var(--w-dim); +} + +.a86-pg-tlb { + font-size: calc(var(--w-fs) * 0.91); + border-left: 3px solid var(--w-rule); + padding-left: 0.45rem; + margin: 0.5rem 0; +} + +.a86-pg-tlb.is-hit { + border-left-color: var(--w-match); +} + +.a86-pg-tlb.is-miss { + border-left-color: var(--w-miss); +} + +.a86-pg-walk { + display: grid; + gap: 0.25rem; +} + +.a86-pg-step { + display: grid; + grid-template-columns: calc(var(--w-fs) * 7.66) calc(var(--w-fs) * 8.01) minmax(0, 1fr); + gap: 0.1rem 0.5rem; + font-size: calc(var(--w-fs) * 0.89); + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.4rem; +} + +.a86-pg-step>.a86-muted, +.a86-pg-step>strong { + grid-column: 2 / -1; +} + +.a86-pg-table { + font-weight: 600; +} + +.a86-pg-frame { + color: var(--w-read); +} + +.a86-pg-result { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.5rem 0 0; +} + +.a86-pg-tlbtable { + max-width: calc(var(--w-fs) * 30.62); +} + +/* pipeline -------------------------------------------------------------- */ + +.a86-pipe-wrap { + overflow-x: auto; +} + +.a86-pipe-grid { + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.88); +} + +.a86-pipe-grid th { + font-family: var(--w-mono); + font-weight: 400; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.82); + padding: 0 0.1rem 0.15rem; + text-align: center; +} + +.a86-pipe-grid th.is-now { + color: var(--w-change); + font-weight: 700; +} + +.a86-pipe-instr { + text-align: left !important; + white-space: nowrap; + padding-right: 0.6rem !important; +} + +/* One line per instruction, whatever the page does to inline code; a long + one ends in an ellipsis rather than making its row three lines tall. */ +.a86 .a86-pipe-instr code { + display: inline-block; + max-width: calc(var(--w-fs) * 11); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: bottom; +} + +.a86-pipe-cell { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.82); + width: calc(var(--w-fs) * 1.95); + min-width: calc(var(--w-fs) * 1.95); + height: calc(var(--w-fs) * 1.35); + text-align: center; + border: 1px solid var(--w-surface-2); + color: var(--w-ink); +} + +.a86-pipe-cell.is-if, +.a86-pipe-cell.is-id, +.a86-pipe-cell.is-ex, +.a86-pipe-cell.is-mem, +.a86-pipe-cell.is-wb { + background: var(--w-surface-2); + border-color: var(--w-rule); +} + +.a86-pipe-cell.is-mem { + background: var(--w-read-bg); +} + +.a86-pipe-cell.is-busy { + color: var(--w-dim); +} + +.a86-pipe-cell.is-stall { + background: var(--w-change-bg); + border-color: var(--w-change); + color: var(--w-change); +} + +.a86-pipe-cell.is-squashed { + background: var(--w-miss-bg); + border-color: var(--w-miss); + color: var(--w-miss); + text-decoration: line-through; +} + +.a86-pipe-cell.is-now { + box-shadow: inset 0 0 0 1px var(--w-change); +} + +.a86-pipe-grid tr.is-current .a86-pipe-instr { + font-weight: 700; +} + +.a86-pipe-grid tr.is-current .a86-pipe-instr code { + color: var(--w-change); +} + +.a86-pipe-grid tr.is-future { + opacity: 0.55; +} + +.a86-pipe-grid tr.is-ghost .a86-pipe-instr { + color: var(--w-miss); +} + +.a86-pipe-grid tr.is-mispredicted .a86-pipe-instr code { + text-decoration: underline wavy var(--w-miss); +} + +.a86-swatch.is-stage { + background: var(--w-surface-2); +} + +.a86-swatch.is-stall { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-swatch.is-squashed { + background: var(--w-miss-bg); + border-color: var(--w-miss); +} + +.a86-pipe-now { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 0.3rem; + margin-top: 0.55rem; +} + +.a86-pipe-stage { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.35rem; + display: flex; + flex-direction: column; + min-width: 0; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-pipe-stage code { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.a86-pipe-stage-name { + font-weight: 700; + font-size: calc(var(--w-fs) * 0.84); + color: var(--w-dim); +} + +.a86-pipe-notes { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.2rem; +} + +.a86-pipe-notes li { + border-left: 3px solid var(--w-change); + padding-left: 0.45rem; +} + +.a86-pipe-notes li.is-control { + border-left-color: var(--w-miss); +} + +.a86-pipe-notes li.is-memory { + border-left-color: var(--w-read); +} + +.a86-pipe-notes li.a86-muted { + border-left-color: var(--w-rule); +} + +.a86-pipe-total { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* uops ------------------------------------------------------------------ */ + +.a86-uops-wrap { + overflow-x: auto; +} + +.a86-uops-table td { + vertical-align: top; +} + +.a86-uops-note { + color: var(--w-dim); + min-width: calc(var(--w-fs) * 16.49); +} + +.a86-uops-table tr.is-load td:nth-child(2) { + color: var(--w-read); + font-weight: 600; +} + +.a86-uops-table tr.is-store-data td:nth-child(2), +.a86-uops-table tr.is-store-addr td:nth-child(2) { + color: var(--w-write); + font-weight: 600; +} + +.a86-uops-table tr.is-eliminated td:nth-child(2) { + color: var(--w-match); + font-weight: 600; +} + +/* timeline -------------------------------------------------------------- */ + +.a86-tl-svg { + display: block; + width: 100%; + max-width: 980px; + height: auto; +} + +.a86-tl-grid { + stroke: var(--w-surface-2); + stroke-width: 1; +} + +.a86-tl-tick { + font-family: var(--w-mono); + font-size: 11px; + fill: var(--w-dim); +} + +.a86-tl-label { + font-family: var(--w-mono); + font-size: 12px; + fill: var(--w-ink); +} + +.a86-tl-row.is-future .a86-tl-label { + fill: var(--w-dim); +} + +.a86-tl-row.is-future rect { + opacity: 0.45; +} + +.a86-tl-row.is-current .a86-tl-label { + font-weight: 700; +} + +.a86-tl-highlight { + fill: var(--w-change-bg); +} + +.a86-tl-wait { + fill: var(--w-surface-2); + stroke: var(--w-rule); + stroke-width: 0.5; +} + +.a86-tl-exec { + fill: var(--w-change); +} + +.a86-tl-exec.is-load { + fill: var(--w-read); +} + +.a86-tl-exec.is-miss { + fill: var(--w-miss); +} + +.a86-tl-exec.is-elim { + fill: var(--w-match); +} + +.a86-tl-exec.is-store { + fill: var(--w-write); +} + +.a86-swatch.is-tl-store { + background: var(--w-write); +} + +.a86-tl-done { + fill: var(--w-match-bg); + stroke: var(--w-match); + stroke-width: 0.5; +} + +.a86-tl-retire { + stroke: var(--w-ink); + stroke-width: 1.5; +} + +.a86-tl-now { + stroke: var(--w-change); + stroke-width: 1.5; + stroke-dasharray: 3 2; +} + +.a86-tl-refill { + fill: var(--w-miss-bg); + opacity: 0.8; +} + +.a86-tl-flag { + font-family: var(--w-sans); + font-size: 10px; + fill: var(--w-miss); +} + +.a86-swatch.is-tl-wait { + background: var(--w-surface-2); +} + +.a86-swatch.is-tl-exec { + background: var(--w-change); +} + +.a86-swatch.is-tl-load { + background: var(--w-read); +} + +.a86-swatch.is-tl-miss { + background: var(--w-miss); +} + +.a86-swatch.is-tl-done { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-swatch.is-tl-refill { + background: var(--w-miss-bg); +} + +.a86-tl-caption { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.45rem 0 0; +} + +.a86-tl-total { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.25rem 0 0; +} + +/* bottleneck ------------------------------------------------------------ */ + +.a86-bn-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 10.01) minmax(0, 1fr) calc(var(--w-fs) * 5.3); + gap: 0.1rem 0.5rem; + align-items: center; + font-size: calc(var(--w-fs) * 0.9); + margin-bottom: 0.3rem; +} + +.a86-bn-track { + height: 0.7rem; + background: var(--w-surface-2); + border-radius: 2px; + overflow: hidden; +} + +.a86-bn-bar { + height: 100%; +} + +.a86-bn-bar.is-actual { + background: var(--w-change); +} + +.a86-bn-bar.is-bound { + background: color-mix(in srgb, var(--w-ink) 40%, transparent); +} + +.a86-bn-value { + font-family: var(--w-mono); + text-align: right; +} + +.a86-bn-note { + grid-column: 2 / -1; + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); +} + +.a86-bn-verdict { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.5rem 0 0; +} + +.a86-bn-ports { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; +} + +.a86-bn-port { + display: flex; + flex-direction: column; + align-items: center; + font-size: calc(var(--w-fs) * 0.85); + width: calc(var(--w-fs) * 3.06); +} + +.a86-bn-port-track { + width: calc(var(--w-fs) * 1.3); + height: 3.5rem; + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + display: flex; + align-items: flex-end; +} + +.a86-bn-port-fill { + width: 100%; + background: var(--w-change); +} + +/* core ------------------------------------------------------------------ */ + +.a86-core-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem; + margin-bottom: 0.45rem; +} + +.a86-core-cols { + display: grid; + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr); + gap: 0.8rem; +} + +@media (max-width: 760px) { + .a86-core-cols { + grid-template-columns: 1fr; + } +} + +.a86-core-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + gap: 0.12rem; + font-size: calc(var(--w-fs) * 0.88); +} + +.a86-core-list li { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.83) calc(var(--w-fs) * 4.95) minmax(0, 1fr) calc(var(--w-fs) * 4.24); + gap: 0.3rem; + align-items: baseline; + border: 1px solid var(--w-rule); + border-radius: 2px; + padding: 0.05rem 0.3rem; +} + +.a86-core-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.a86-core-id { + color: var(--w-dim); +} + +.a86-core-kind { + color: var(--w-dim); +} + +.a86-core-state { + font-size: calc(var(--w-fs) * 0.84); + text-align: right; +} + +.a86-core-list li.is-running { + border-color: var(--w-change); + background: var(--w-change-bg); +} + +.a86-core-list li.is-done { + background: var(--w-match-bg); +} + +.a86-core-list li.is-retiring { + background: var(--w-match-bg); + border-color: var(--w-match); + font-weight: 700; +} + +.a86-core-list li.is-waiting .a86-core-state { + color: var(--w-dim); +} + +.a86-core-portgrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.25rem; +} + +.a86-core-port { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.15rem 0.3rem; + display: flex; + flex-direction: column; + font-size: calc(var(--w-fs) * 0.85); + min-width: 0; +} + +.a86-core-portname { + font-weight: 700; +} + +.a86-core-units { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.82); +} + +.a86-core-portuop { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--w-dim); +} + +.a86-core-port.is-busy { + border-color: var(--w-change); + background: var(--w-change-bg); +} + +.a86-core-port.is-busy .a86-core-portuop { + color: var(--w-ink); +} + +.a86-core-port.is-start .a86-core-portname { + color: var(--w-change); +} + +.a86-core-rat .a86-table td { + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-core-rat tr.is-pending td { + color: var(--w-change); +} + +.a86-core-ready { + white-space: nowrap; +} + +.a86-core-note { + font-size: calc(var(--w-fs) * 0.91); + margin: 0.5rem 0 0; +} + +/* console --------------------------------------------------------------- */ + +.a86-console-screen { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.95); + background: #16191d; + color: #e6e9ec; + border-radius: 4px; + padding: 0.5rem 0.65rem; + min-height: 3.2rem; + margin: 0; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.a86-console-cursor { + display: inline-block; + width: 0.55em; + background: #e6e9ec; + animation: a86-blink 1s steps(1) infinite; +} + +@keyframes a86-blink { + 50% { + opacity: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .a86-console-cursor { + animation: none; + } +} + +.a86-console-log { + font-size: calc(var(--w-fs) * 0.9); + margin: 0.45rem 0 0; + padding-left: 1.4rem; +} + +.a86-console-log li.is-current code { + color: var(--w-change); + font-weight: 700; +} + +.a86-console-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; +} + +/* perf ------------------------------------------------------------------ */ + +.a86-perf-out { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + line-height: 1.5; + background: var(--w-surface-2); + border-radius: 3px; + padding: 0.5rem 0.6rem; + overflow-x: auto; + margin: 0 0 0.4rem; + white-space: pre; +} + +/* the whole chip -------------------------------------------------------- */ + +.a86-chip-svg { + display: block; + width: 100%; + max-width: 980px; + height: auto; + margin: 0 auto; +} + +.a86-chip-group { + fill: none; + stroke: var(--w-rule); + stroke-dasharray: 4 3; +} + +.a86-chip-grouplabel { + font-family: var(--w-sans); + font-size: 11px; + fill: var(--w-dim); + letter-spacing: 0.04em; +} + +.a86-chip-node rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-chip-label { + font-family: var(--w-sans); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-chip-sub { + font-family: var(--w-sans); + font-size: 9px; + fill: var(--w-dim); +} + +.a86-chip-node.is-active rect { + fill: var(--w-change-bg); + stroke: var(--w-change); + stroke-width: 1.6; +} + +.a86-chip-node.is-active .a86-chip-label { + fill: var(--w-ink); + font-weight: 600; +} + +.a86-chip-node.is-hit rect { + fill: var(--w-match-bg); + stroke: var(--w-match); +} + +.a86-chip-node.is-miss rect, +.a86-chip-node.is-bad rect { + fill: var(--w-miss-bg); + stroke: var(--w-miss); +} + +.a86-chip-node.is-far rect { + fill: var(--w-read-bg); + stroke: var(--w-read); +} + +.a86-chip-node.is-store rect { + fill: var(--w-write-bg); + stroke: var(--w-write); +} + +.a86-chip-edge { + stroke: var(--w-rule); + stroke-width: 1.2; + fill: none; +} + +.a86-chip-svg marker path { + fill: var(--w-rule); + stroke: none; +} + +.a86-chip-edge.is-active { + stroke: var(--w-change); + stroke-width: 2; +} + +.a86-chip-edge.is-load { + stroke: var(--w-read); +} + +.a86-chip-edge.is-store { + stroke: var(--w-write); +} + +.a86-chip-caption { + font-size: calc(var(--w-fs) * 0.94); + margin: 0.4rem 0 0; +} + +.a86-swatch.is-chip-active { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-swatch.is-chip-hit { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-swatch.is-chip-miss { + background: var(--w-miss-bg); + border-color: var(--w-miss); +} + +.a86-swatch.is-chip-load { + background: var(--w-read); +} + +.a86-swatch.is-chip-store { + background: var(--w-write); +} + + + + +/* sandbox --------------------------------------------------------------- */ + +.a86-sandbox { + margin: 1rem 0 2rem; +} + +.a86-sb-grid { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); + gap: 0.9rem; + margin-bottom: 0.8rem; +} + +@media (max-width: 760px) { + .a86-sb-grid { + grid-template-columns: 1fr; + } +} + +.a86-sb-label { + display: block; + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.88); + font-weight: 600; + color: var(--w-dim); + margin: 0.5rem 0 0.2rem; +} + +.a86-sb-code, +.a86-sb-setup { + width: 100%; + box-sizing: border-box; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.94); + line-height: 1.5; + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.5rem 0.6rem; + resize: vertical; + tab-size: 8; +} + +.a86-sb-code:focus, +.a86-sb-setup:focus { + outline: 2px solid var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-sb-row { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + align-items: center; + margin-bottom: 0.35rem; +} + +.a86-sb-select { + font: inherit; + font-size: calc(var(--w-fs) * 0.94); + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.35rem; + max-width: 100%; +} + +.a86-sb-check { + font-size: calc(var(--w-fs) * 0.93); + display: inline-flex; + align-items: center; + gap: 0.2rem; + cursor: pointer; +} + +.a86-sb-check input { + accent-color: var(--w-change); +} + +.a86-sb-actions { + margin-top: 0.6rem; +} + +.a86-sb-status { + display: block; + font-size: calc(var(--w-fs) * 0.91); + color: var(--w-dim); + min-height: 1.1rem; + margin-top: 0.3rem; +} + +.a86-sb-status.is-error { + color: var(--w-miss); +} + +.a86-sb-help { + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + margin: 0.6rem 0 0; +} + +.a86-sb-spec { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.5rem 0.6rem; + overflow-x: auto; + white-space: pre; + margin: 0 0 0.8rem; +} + +.a86-sb-out>.a86 { + margin-top: 0.4rem; +} + +/* ------------------------------------------------------- outside Quarto + A page that never declares a theme may still have an OS preference worth + honoring. Gated on both Quarto classes being absent, so it can never + contradict a page that has chosen. */ + +@media (prefers-color-scheme: dark) { + body:not(.quarto-light):not(.quarto-dark) .a86 { + --w-page: #1a1e23; + --w-ink: #e6e9ec; + --w-change: #e0a93a; + --w-read: #6fb4e3; + --w-write: #c0a0e0; + --w-match: #74c391; + --w-miss: #e08a80; + --a86-enc-prefix: #a9aeb5; + --a86-enc-rex: #e39acb; + --a86-enc-opcode: #e0a93a; + --a86-enc-modrm: #6fb4e3; + --a86-enc-sib: #74c391; + --a86-enc-disp: #c0a0e0; + --a86-enc-imm: #e08a80; + --w-rule: color-mix(in srgb, var(--w-ink) 28%, transparent); + --w-surface-2: color-mix(in srgb, var(--w-ink) 9%, var(--w-page)); + --w-change-bg: color-mix(in srgb, var(--w-change) 22%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 22%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 22%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 24%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 22%, var(--w-page)); + } +} + +/* Fullscreen pipeline: wider, taller cells, so the diagram uses the room. */ +.a86.is-fullscreen .a86-pipe-cell { + width: calc(var(--w-fs) * 2.5); + min-width: calc(var(--w-fs) * 2.5); + height: calc(var(--w-fs) * 1.6); +} + +.a86.is-fullscreen .a86 .a86-pipe-instr code, +.a86.is-fullscreen .a86-pipe-instr code { + max-width: calc(var(--w-fs) * 16); +} + +/* An instruction quoted inside a sentence keeps the listing's column + padding under Quarto's pre-wrap ("push rbp"); in prose one space + between the mnemonic and its operands reads better. */ +.a86 .a86-explain code { + white-space: nowrap; +} diff --git a/styles/course/bridge.css b/styles/course/bridge.css new file mode 100644 index 0000000..318d156 --- /dev/null +++ b/styles/course/bridge.css @@ -0,0 +1,142 @@ +/* ============================================================================ + styles/course/bridge.css -- the app's side of the course stylesheets. + + tokens.css, kit.css and asm86.css are the course site's own files, copied + unchanged (styles/course/README.md). They were written for Quarto pages and + read three things a Quarto page provides: + + --bs-body-bg, --bs-body-color the page colors every neutral is mixed from + --bs-font-monospace, --bs-font-sans-serif + body.quarto-light / body.quarto-dark which theme the page shows + + This file supplies the first two from the app's own tokens (styles.css), + which already swap with the theme, so nothing here needs a dark rule. + The body classes are set from script (src/ui/theme.ts), because the app's + theme can be "system" and a class cannot be chosen by CSS alone. + + Load order: styles.css, bridge.css, tokens.css, kit.css, asm86.css. + ==========================================================================*/ + +:root { + --bs-body-bg: var(--paper-2); + --bs-body-color: var(--ink); + --bs-font-monospace: var(--mono); + --bs-font-sans-serif: var(--sans); +} + +/* --------------------------------------------------------------------------- + The Hardware area's machine board (src/ui/hw/board.ts) puts the course's + views in the app's dock. Adjustments for that home, never in the course files. + ------------------------------------------------------------------------ */ + +/* A register card that also shows its narrower names needs room for the + name, sixteen hex digits, and the width on one line. */ +.board-a86 .a86-regs { + grid-template-columns: repeat(auto-fill, minmax(calc(var(--w-fs) * 17), 1fr)); +} + +.board-a86 .a86-width-row { + grid-template-columns: calc(var(--w-fs) * 2.83) minmax(0, 1fr) auto; +} +.board-a86 .a86-regs { align-items: start; } + +/* The "was ..." line under a register's value is empty until the register + changes. asm86.css gives it a min-height (0.8rem) shorter than its own line + box, so a card grew a few pixels the step it changed and shrank on the next, + moving every card below it. Reserve the whole line, filled or not. */ +.board-a86 .a86-reg-prev { + line-height: 1.35; + min-height: 1.35em; +} + +.board-a86.a86 { + margin: 0; +} + +/* The board's own "Cache lines" view (src/ui/hw/lines.ts): a line as a row of + byte cells, in the course's load, store and match colors. */ +.hw-line + .hw-line { + margin-top: 0.6rem; + padding-top: 0.6rem; + border-top: 1px dashed var(--w-rule); +} + +.hw-line-head, +.hw-line-use { + margin: 0.2rem 0; +} + +.hw-line-cells { + display: grid; + grid-template-columns: repeat(var(--hw-line, 16), minmax(0, 1fr)); + gap: 2px; + max-width: calc(var(--hw-line, 16) * 1.9rem); +} + +.hw-line-cell { + display: block; + min-height: 1.6rem; + border: 1px solid var(--w-rule); + border-radius: 2px; + background: var(--w-surface); + color: var(--w-dim); + font-family: var(--w-mono); + font-size: 0.7rem; + line-height: 1.6rem; + text-align: center; + overflow: hidden; +} + +.hw-line-cell.is-read { background: var(--w-read-bg); border-color: var(--w-read); color: var(--w-read); } +.hw-line-cell.is-write { background: var(--w-write-bg); border-color: var(--w-write); color: var(--w-write); } +.hw-line-cell.is-used { background: var(--w-match-bg); } +.hw-line-cell.is-later { background: var(--w-surface-2); border-style: dashed; } + +.hw-swatch { + display: inline-block; + width: 1rem; + min-height: 0.9rem; + height: 0.9rem; + vertical-align: middle; + margin-right: 0.3rem; +} + +.hw-hit { color: var(--w-match); font-weight: 600; } +.hw-miss { color: var(--w-miss); font-weight: 600; } + +/* The whole core (machineView in hwviews.js): a lit edge's arrowhead takes the + edge's color, so the head shows which way that instruction's data moved. */ +.a86-chip-svg marker.is-active path { fill: var(--w-change); } +.a86-chip-svg marker.is-load path { fill: var(--w-read); } +.a86-chip-svg marker.is-store path { fill: var(--w-write); } +.a86-chip-edge.is-active { stroke-width: 2.2; } + +/* The sentence under the core is one line for some instructions and two for + others; hold two, so the legend under it stays put while stepping. */ +.board-a86 .a86-chip-caption { + line-height: 1.45; + min-height: 4.35em; +} + +/* A port's box is 29 units wide; at 9px "alu mul" fits only in a narrow face, + and spills into the next port in the wider fallback fonts. */ +.a86-chip-node.is-port .a86-chip-sub { font-size: 7px; } + +/* Address arithmetic is one line ("named no memory address") on most steps and + a two-row sum with a note on the others. Hold the taller shape, so the card + and everything below it keep their place. */ +.board-a86 .a86-addr { min-height: calc(var(--w-fs) * 14.5); } + +/* The cache-line view lists the lines the last access touched: none before the + first access, one or two after. Hold two, so the legend under it stays put. */ +.board-a86 .hw-lines { min-height: 78px; } + +/* A listing row's trailing comment takes what width is left. In a narrow card + that is nothing, and a wrapping comment then stood one character per line, + leaving tall blank rows. Cut it with an ellipsis instead (a comment on its + own line still wraps). */ +.board-a86 .a86-code-row:not(.is-note) > .a86-code-comment { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} diff --git a/styles/course/kit.css b/styles/course/kit.css new file mode 100644 index 0000000..f76ae6a --- /dev/null +++ b/styles/course/kit.css @@ -0,0 +1,302 @@ +/* ============================================================================ + widgets/kit.css -- what the two teaching-widget families have in common. + + Two families of interactive widgets are built by static/js: + .a86 the x86-64 assembly widgets (js/asm86, css/widgets/asm86.css) + .pl the pseudocode lab (js/pseudo, css/widgets/pseudo-lab.css) + They were written as twins and shared a design system by copy and paste. + This file holds the shared half, written once, so a change to a color + role or a button reaches both. The two family stylesheets keep only what + is specific to them and must be loaded AFTER this one. + + Color roles carry meaning, so they are worth learning once: + amber the step about to run, and anything the last step changed + blue a value that was read + purple a value that was written + green a match, a pass, a proof + red a mismatch, an error, a claim a run broke + The roles are stated once per theme below. Everything neutral is mixed + from the page colors (--bs-body-bg / --bs-body-color), so a widget sits + on whatever background the page gives it. + + Dark mode keys off `body.quarto-dark`, which is what Quarto actually sets. + `[data-bs-theme="dark"]` is grouped in only as a fallback. Reading the OS + preference (prefers-color-scheme) on a Quarto page is the bug that once + made a light page render a dark widget, so nothing here does. + + Tokens (--w-*) + --w-page --w-ink --w-dim --w-rule --w-surface --w-surface-2 + --w-change --w-read --w-write --w-match --w-miss and their -bg washes + --w-mono --w-sans --w-fs + --w-fs is the one size that drives every piece of text in a widget. Each + rule states its size as a multiple of it, so fullscreen raises them all at + once. At 0.95rem a widget reads a step below the page's body text. + ==========================================================================*/ + + +/* ------------------------------------------------------------------ tokens */ + +:is(.a86, .pl) { + --w-page: var(--bs-body-bg, #ffffff); + --w-ink: var(--bs-body-color, #1b1f24); + + /* 70%, matching the muted gray in base/site.css and bio.css: at 60% the + result fails WCAG AA for normal-size text on a white background. */ + --w-dim: color-mix(in srgb, var(--w-ink) 70%, transparent); + --w-rule: color-mix(in srgb, var(--w-ink) 20%, transparent); + --w-surface: var(--w-page); + --w-surface-2: color-mix(in srgb, var(--w-ink) 6%, var(--w-page)); + + --w-change: #8a5c05; + --w-read: #17618f; + --w-write: #6a4299; + --w-match: #266a41; + --w-miss: #93291f; + + --w-change-bg: color-mix(in srgb, var(--w-change) 13%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 13%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 13%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 15%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 13%, var(--w-page)); + + --w-mono: var(--bs-font-monospace, ui-monospace, "SF Mono", Menlo, Consolas, monospace); + --w-sans: var(--bs-font-sans-serif, system-ui, sans-serif); + --w-fs: 0.95rem; + + color: var(--w-ink); + font-size: var(--w-fs); + line-height: 1.45; + margin: 1.4rem 0; + outline: none; +} + +/* A tinted panel needs a stronger wash to read against a dark page, and the + accents have to lighten to stay legible on it. */ +body.quarto-dark :is(.a86, .pl), +[data-bs-theme="dark"] :is(.a86, .pl) { + --w-change: #e0a93a; + --w-read: #6fb4e3; + --w-write: #c0a0e0; + --w-match: #74c391; + --w-miss: #e08a80; + + --w-rule: color-mix(in srgb, var(--w-ink) 28%, transparent); + --w-surface-2: color-mix(in srgb, var(--w-ink) 9%, var(--w-page)); + + --w-change-bg: color-mix(in srgb, var(--w-change) 22%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 22%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 22%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 22%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 22%, var(--w-page)); +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + :is(.a86, .pl) { + --w-dim: #666f78; + --w-rule: #d5dae0; + --w-surface-2: #f4f6f8; + --w-change-bg: #fdf1d8; + --w-read-bg: #e1eef9; + --w-write-bg: #efe6f7; + --w-match-bg: #dcefe2; + --w-miss-bg: #f8e3e1; + } + + body.quarto-dark :is(.a86, .pl) { + --w-dim: #98a2ab; + --w-rule: #3a424b; + --w-surface-2: #21262c; + --w-change-bg: #453518; + --w-read-bg: #1b3348; + --w-write-bg: #33254a; + --w-match-bg: #1d3a28; + --w-miss-bg: #3f2320; + } +} + + +/* ------------------------------------------------------------- shared rules + Each rule below was identical in both stylesheets. Rules that differ + between the families (panels, code rows, cells, legends...) stay in the + family file that owns them. */ + +/* --- Widget shell ------------------------------------------------------ */ + +.a86:focus-visible, +.pl:focus-visible { + box-shadow: 0 0 0 3px var(--w-change-bg); + border-radius: 4px; +} + +.a86 code, +.a86 code:not(.sourceCode), +.pl code, +.pl code:not(.sourceCode) { + background: none; + border: 0; + padding: 0; + border-radius: 0; + font-size: inherit; + color: inherit; + font-family: var(--w-mono); +} + +/* --- Text -------------------------------------------------------------- */ + +.a86-title, +.pl-title { + font-size: calc(var(--w-fs) * 1.13); + margin: 0 0 0.2rem; +} + +.a86-blurb, +.pl-blurb { + color: var(--w-dim); + margin: 0 0 0.7rem; + max-width: 62ch; +} + +.a86-muted, +.pl-muted { + color: var(--w-dim); +} + +.a86-error, +.pl-error { + color: var(--w-miss); + background: var(--w-miss-bg); + border-left: 3px solid var(--w-miss); + padding: 0.4rem 0.6rem; + margin: 0.5rem 0; +} + +/* --- Controls ---------------------------------------------------------- */ + +.a86-controls, +.pl-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem; + padding: 0.4rem 0.5rem; + margin-bottom: 0.7rem; + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; +} + +.a86-btn, +.pl-btn { + font: inherit; + font-size: calc(var(--w-fs) * 0.96); + padding: 0.22rem 0.62rem; + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 3px; + cursor: pointer; +} + +.a86-btn:hover, +.pl-btn:hover { + border-color: var(--w-change); +} + +.a86-btn-primary, +.pl-btn-primary { + border-color: var(--w-change); + font-weight: 600; +} + +.a86-slider, +.pl-slider { + flex: 1 1 140px; + min-width: 110px; + accent-color: var(--w-change); +} + +.a86-readout, +.pl-readout { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + white-space: nowrap; +} + +.a86-btn-full, +.pl-btn-full { + margin-left: auto; +} + +/* --- Layout ------------------------------------------------------------ */ + +.a86-grid, +.pl-grid { + display: grid; + gap: 0.7rem; + grid-template-columns: 1fr; +} + +.a86-panel-title, +.pl-panel-title { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.89); + font-weight: 600; + letter-spacing: 0.02em; + color: var(--w-dim); + margin: 0 0 0.45rem; +} + +/* --- Fullscreen -------------------------------------------------------- */ + +.a86.is-fullscreen, +.pl.is-fullscreen { + --w-fs: clamp(1rem, 0.35rem + 0.62vw, 1.3rem); + position: fixed; + inset: 0; + z-index: 1090; + margin: 0; + padding: 0.9rem 1.1rem 2rem; + background: var(--w-page); + overflow: auto; + overscroll-behavior: contain; +} + +.a86.is-fullscreen .a86-controls, +.pl.is-fullscreen .pl-controls { + position: sticky; + top: 0; + z-index: 2; +} + +.a86.is-fullscreen .a86-grid, +.pl.is-fullscreen .pl-grid { + display: flex; + flex-wrap: wrap; + align-items: stretch; +} + +.a86.is-fullscreen .a86-trace-wrap, +.pl.is-fullscreen .pl-trace-wrap { + max-height: 28rem; +} + +/* --- Code listing ------------------------------------------------------ */ + +.a86-code-marker, +.pl-code-marker { + color: var(--w-change); + font-weight: 700; +} + +.a86-code-row.is-last, +.pl-code-row.is-last { + background: var(--w-surface-2); +} + +.a86-code-row.is-error, +.pl-code-row.is-error { + background: var(--w-miss-bg); + border-left-color: var(--w-miss); +} diff --git a/styles/course/tokens.css b/styles/course/tokens.css new file mode 100644 index 0000000..535f83e --- /dev/null +++ b/styles/course/tokens.css @@ -0,0 +1,99 @@ +/* ============================================================================ + base/tokens.css -- design tokens shared by the course kit + (blocks, algorithms, worked examples, page furniture, figures and the + viz.js chart helpers). Custom properties only: loading this file changes + nothing on a page that does not use them. + + Everything is derived from --bs-body-color / --bs-body-bg, which Quarto + sets for each theme and swaps on the light/dark toggle, so a token that + mixes them needs no dark-mode rule of its own. Hue tokens (role colors, + the categorical palette) do have a dark value, set on body.quarto-dark. + ==========================================================================*/ + +:root { + /* ---- surfaces and text ---- */ + --course-ink: var(--bs-body-color, #212529); + --course-paper: var(--bs-body-bg, #fff); + --course-muted: color-mix(in srgb, var(--course-ink) 68%, transparent); + --course-rule: color-mix(in srgb, var(--course-ink) 18%, transparent); + --course-wash: color-mix(in srgb, var(--course-ink) 4%, var(--course-paper)); + --course-radius: 6px; + + /* ---- role colors: which kind of block a reader is looking at ---- */ + --course-key: #2563eb; + /* key idea, definition, theorem */ + --course-intuition: #7c3aed; + /* intuition, why it matters */ + --course-caution: #b45309; + /* pitfall, misconception */ + --course-practice: #047857; + /* in practice, worked example, checkpoint */ + --course-algorithm: #0f766e; + /* algorithm cards */ + --course-history: #78716c; + /* history, going deeper */ + --course-draft: #c026d3; + /* author notes, never shown to students */ + + /* ---- categorical palette (Okabe & Ito), safe for color-vision deficiency. + viz.js and any hand-written figure take colors from here, in order. ---- */ + --viz-1: #0072b2; + /* blue */ + --viz-2: #d55e00; + /* vermillion */ + --viz-3: #009e73; + /* bluish green */ + --viz-4: #cc79a7; + /* reddish purple */ + --viz-5: #e69f00; + /* orange */ + --viz-6: #56b4e9; + /* sky blue */ + --viz-7: #f0e442; + /* yellow */ + --viz-8: #000000; + /* black */ + + /* diverging (negative .. positive) and the single-hue ramp for magnitudes */ + --viz-neg: #0072b2; + --viz-pos: #d55e00; + --viz-ramp: #0072b2; + + /* axes, gridlines, labels inside a chart */ + --viz-ink: var(--course-ink); + --viz-muted: var(--course-muted); + --viz-grid: color-mix(in srgb, var(--course-ink) 12%, transparent); + --viz-bg: var(--course-paper); +} + +body.quarto-dark { + --course-key: #7aa2ff; + --course-intuition: #b79cff; + --course-caution: #f0a04b; + --course-practice: #4cc9a0; + --course-algorithm: #4fd1c5; + --course-history: #b4aca5; + --course-draft: #e879f9; + + --viz-1: #56b4e9; + --viz-2: #f28e4b; + --viz-3: #2fc99a; + --viz-4: #e9a3c8; + --viz-5: #f5b942; + --viz-6: #8fd0f5; + --viz-7: #f5ec6a; + --viz-8: #e5e5e5; + --viz-neg: #56b4e9; + --viz-pos: #f28e4b; + --viz-ramp: #56b4e9; +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + :root { + --course-muted: rgba(33, 37, 41, 0.68); + --course-rule: rgba(128, 128, 128, 0.3); + --course-wash: rgba(128, 128, 128, 0.06); + --viz-grid: rgba(128, 128, 128, 0.25); + } +} diff --git a/tests/areas.test.mjs b/tests/areas.test.mjs new file mode 100644 index 0000000..160e8ce --- /dev/null +++ b/tests/areas.test.mjs @@ -0,0 +1,151 @@ +// Stage 9: three areas, each with its own route, panes, views and layout. A problem is one state shared by all +// three; the area comes from the route. Anything that is not a route in the plan is home. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { areasFor, AREAS, AREA_ORDER, defaultAreaFor, paneForArea, isAreaId, areaHasPane } from '../dist/core/areas.js'; +import { parseRoute, routeFor, normalize, emptyState, applyEmbedParams } from '../dist/core/state.js'; +import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js'; +import { Session } from '../dist/core/session.js'; +import { EXERCISES } from '../dist/exercises/index.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; + +test('every route shape parses and prints back', () => { + for (const area of AREA_ORDER) { + assert.deepEqual(parseRoute(`#/${area}/p/count-base`), { kind: 'problem', area, id: 'count-base' }); + assert.equal(routeFor({ kind: 'problem', area, id: 'count-base' }), `#/${area}/p/count-base`); + assert.deepEqual(parseRoute(`#/${area}/s/~abc`), { kind: 'shared', area, blob: '~abc' }); + assert.equal(routeFor({ kind: 'shared', area, blob: '~abc' }), `#/${area}/s/~abc`); + } + assert.deepEqual(parseRoute(''), { kind: 'home' }); + assert.deepEqual(parseRoute('#/'), { kind: 'home' }); + const e = parseRoute('#/embed/trace/p/match?t=12'); + assert.equal(e.kind, 'embed'); assert.equal(e.view, 'trace'); assert.equal(e.problem, 'match'); assert.equal(e.params.get('t'), '12'); + const b = parseRoute('#/embed/life/~blob?area=dev'); + assert.equal(b.kind, 'embed'); assert.equal(b.blob, '~blob'); assert.equal(b.params.get('area'), 'dev'); + assert.equal(routeFor(b), '#/embed/life/~blob?area=dev'); + assert.equal(routeFor(parseRoute('#/embed/playground/p/demo?panel=life')), '#/embed/playground/p/demo?panel=life'); + assert.deepEqual(parseRoute('#/bridge/p/a%20b'), { kind: 'problem', area: 'bridge', id: 'a b' }); +}); + +test('an unknown route is home: the old links and the retired names do not work', () => { + for (const h of ['#/p/count-base', '#/s/~abc', '#/learn', '#/learn/loops', '#/playground/p/demo', '#/bridge', '#/bridge/p', '#/bridge/x/y', '#/dev/s', '#/nowhere', '#/#problems', '#/#reference']) + assert.deepEqual(parseRoute(h), { kind: 'home' }, h); +}); + +test('the area table: three areas with the panes, views and docks of the plan', () => { + assert.deepEqual(AREA_ORDER, ['bridge', 'dev', 'hw']); + assert.ok(AREA_ORDER.every(isAreaId) && !isAreaId('learn') && !isAreaId('playground')); + for (const id of AREA_ORDER) { assert.equal(AREAS[id].id, id); assert.equal(AREAS[id].route, id); assert.ok(AREAS[id].name && AREAS[id].tagline); } + assert.deepEqual(AREAS.bridge.panes, ['lingo', 'matho', 'pseudo', 'speco', 'mojo']); + assert.deepEqual(AREAS.dev.panes, ['mojo']); + assert.deepEqual(AREAS.hw.panes, ['mojo', 'asm']); + assert.ok(AREAS.dev.inspect.includes('trace') && AREAS.bridge.inspect.includes('trace'), 'both have the Run view, which shows the variables and their lifetimes'); + assert.ok(!AREAS.dev.inspect.includes('table') && !AREAS.dev.inspect.includes('life') && !AREAS.bridge.inspect.includes('table'), 'the Run view replaces the table of values and the lifetimes'); + assert.ok(AREAS.bridge.inspect.includes('proof') && !AREAS.dev.inspect.includes('proof')); + assert.equal(AREAS.hw.workspace, 'board', 'Hardware is two panes: the code, and the board'); + assert.ok(AREAS.bridge.workspace === 'ide' && AREAS.dev.workspace === 'ide'); + assert.deepEqual([AREAS.hw.inspect, AREAS.hw.dock], [[], []], 'its views are cards on the board, not tabs'); + assert.ok(!AREAS.bridge.dock.includes('asm') && !AREAS.dev.dock.includes('asm')); + assert.ok(areaHasPane(AREAS.hw, 'asm') && !areaHasPane(AREAS.dev, 'pseudo')); +}); + +test('each problem names its area: Hardware for asm-*, Developer for Mojo-only, Bridge otherwise', () => { + for (const e of EXERCISES) { + const p = PROBLEMS.find((x) => x.id === e.id); + assert.ok(isAreaId(p.area), e.id); + const raw = (l) => !!(e.sources[l] ?? '').trim(); + if (e.area) assert.equal(p.area, e.area, e.id); + else if (e.id.startsWith('asm-')) assert.equal(p.area, 'hw', e.id); + else if ((raw('mojo') || e.mojoProgram) && !raw('pseudo') && !raw('lingo') && !raw('matho')) assert.equal(p.area, 'dev', e.id); + else assert.equal(p.area, 'bridge', e.id); + } + assert.ok(PROBLEMS.some((p) => p.area === 'bridge') && PROBLEMS.some((p) => p.area === 'hw')); + assert.equal(defaultAreaFor({ id: 'x', sources: { pseudo: 'OUTPUT 1' }, area: 'hw' }), 'hw', 'an exercise that says so wins'); +}); + +test('the pane a state opens on follows the area', () => { + const count = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + assert.equal(count.lang, 'mojo', 'the exercise\'s own default is its Mojo'); + assert.equal(paneForArea(AREAS.bridge, count, true), 'pseudo', 'a problem opening in the Bridge begins with the idea'); + assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'speco' }, true), 'speco', 'a linked pane the student left open is kept'); + assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'mojo' }), 'mojo', 'a shared link at the Mojo tab keeps it'); + assert.equal(paneForArea(AREAS.dev, { ...count, lang: 'pseudo' }), 'mojo'); + const asm = stateForProblem(PROBLEMS.find((p) => p.id.startsWith('asm-'))); + assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'pseudo' }), 'asm'); + assert.equal(paneForArea(AREAS.hw, { ...count, lang: 'pseudo', sources: { ...count.sources, asm: '' } }), 'mojo', 'no assembly: Mojo'); + assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'mojo' }), 'mojo', 'a pane of the area is kept'); +}); + +test('layout is kept per area, and a state normalizes it that way', () => { + const s = normalize({ v: 3, layout: { bridge: { split: 0.4, dockTab: 'problems' }, dev: { split: 0.7, dockCollapsed: true }, hw: { dock: 0.5, right: 7 }, nowhere: { split: 0.1 }, split: 0.9 } }); + assert.deepEqual(Object.keys(s.layout).sort(), ['bridge', 'dev', 'hw']); + assert.equal(s.layout.bridge.split, 0.4); assert.equal(s.layout.bridge.dockTab, 'problems'); + assert.equal(s.layout.dev.split, 0.7); assert.equal(s.layout.dev.dockCollapsed, true); + assert.equal(s.layout.hw.dock, 0.5); assert.equal(s.layout.hw.right, undefined, 'a fraction outside 0..1 is dropped'); + assert.equal(normalize({ v: 3, layout: { split: 0.5, dockTab: 'output' } }).layout, undefined, 'a layout that is not per area is not read'); + assert.equal(emptyState().layout, undefined); +}); + +test('a session lays out the area it is open in, and the other areas keep their own', () => { + const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + const bridge = new Session(st, { area: 'bridge', storageId: null }); + bridge.setLayout({ split: 0.3 }); + assert.equal(bridge.layout().split, 0.3); + const dev = new Session(st, { area: 'dev', storageId: null }); + assert.equal(dev.layout().split, undefined, 'the Developer area has not been arranged yet'); + dev.setLayout({ split: 0.7, dockTab: 'compiler' }); + assert.equal(bridge.layout().split, 0.3, 'the same state: the Bridge arrangement is still there'); + assert.equal(st.layout.dev.dockTab, 'compiler'); + assert.equal(new Session(st, { storageId: null }).area, null, 'a session with no area is not a workspace: every pane counts'); +}); + +test('an embed query arranges one area, chosen with area=', () => { + const s = applyEmbedParams(emptyState(), new URLSearchParams('editor=0.6&dock=closed'), 'dev'); + assert.deepEqual(s.layout, { dev: { split: 0.6, dockCollapsed: true } }); +}); + +test('allDiagnostics reports only the panes of the area', () => { + const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + st.sources.mojo = 'def main(:\n'; + st.sources.pseudo = 'FUNCTION BROKEN(\n'; + const dev = new Session(structuredClone(st), { area: 'dev', storageId: null }); + assert.ok(dev.allDiagnostics().every((d) => d.lang === 'mojo'), 'Developer: Mojo only'); + assert.ok(dev.allDiagnostics().length); + const bridge = new Session(structuredClone(st), { area: 'bridge', storageId: null }); + assert.ok(bridge.allDiagnostics().some((d) => d.lang === 'pseudo')); + const hw = new Session(structuredClone(st), { area: 'hw', storageId: null }); + assert.ok(hw.allDiagnostics().every((d) => d.lang === 'mojo' || d.lang === 'asm')); +}); + +test('the toolbar offers only the areas that would show the open pane exactly as it is', async () => { + const { safeSwitches } = await import('../dist/core/areas.js'); + const open = (id, area) => { const st = stateForProblem(PROBLEMS.find((p) => p.id === id)); return new Session(st, { area, storageId: null }); }; + const s = open('count-base', 'dev'); + const shown = (a, l) => s.shownIn(a, l); + assert.deepEqual(safeSwitches('dev', 'mojo', shown), ['hw'], 'Developer and Hardware share the Mojo'); + assert.deepEqual(safeSwitches('hw', 'mojo', shown), ['dev']); + assert.deepEqual(safeSwitches('hw', 'asm', shown), [], 'only Hardware has x86-64'); + assert.deepEqual(safeSwitches('hw', 'mojo', () => ''), [], 'an empty pane offers no switch: the move would show other work'); + for (const l of ['lingo', 'matho', 'pseudo', 'speco']) assert.deepEqual(safeSwitches('bridge', l, shown), [], `only the Bridge has ${l}`); + assert.notEqual(s.shownIn('bridge', 'mojo'), s.shownIn('dev', 'mojo'), 'the exercise\'s own Mojo is not the translation of its pseudo'); + assert.deepEqual(safeSwitches('bridge', 'mojo', shown), [], 'so the Bridge\'s Mojo tab does not offer Developer'); + // once the generated Mojo is copied into the Developer area, the Bridge and the others show the same text + const b = open('count-base', 'bridge'); + assert.ok(b.adoptGeneratedMojo()); + assert.deepEqual(safeSwitches('bridge', 'mojo', (a, l) => b.shownIn(a, l)), ['dev', 'hw']); + assert.deepEqual(safeSwitches('dev', 'lingo', shown), [], 'a pane the area does not have offers nothing'); +}); + +test('each problem opens in its own area first, then every other area it has something to show in', () => { + for (const p of PROBLEMS) { + const a = areasFor(p); + assert.equal(a[0], p.area, p.id); + assert.equal(new Set(a).size, a.length, `${p.id}: each area once`); + assert.equal(a.includes('hw'), p.area === 'hw' || !!(p.sources.asm ?? '').trim(), `${p.id}: Hardware when it has x86-64`); + assert.equal(a.includes('bridge'), p.area === 'bridge' || ['pseudo', 'lingo', 'matho', 'speco'].some((l) => (p.sources[l] ?? '').trim()), `${p.id}: the Bridge when it has an idea to translate`); + } + assert.deepEqual(areasFor({ area: 'bridge', sources: { pseudo: 'OUTPUT 1', mojo: 'def main(): pass', asm: 'ret' } }), ['bridge', 'dev', 'hw']); + assert.deepEqual(areasFor({ area: 'hw', sources: { asm: 'ret' } }), ['hw']); + assert.deepEqual(areasFor({ area: 'dev', sources: {}, mojo: { source: 'def main(): pass' } }), ['dev']); +}); diff --git a/tests/asm-coverage.test.mjs b/tests/asm-coverage.test.mjs new file mode 100644 index 0000000..e5d05f2 --- /dev/null +++ b/tests/asm-coverage.test.mjs @@ -0,0 +1,67 @@ +// The assembly census (scripts/asm-census.mjs) as a ratchet: every function the +// real compiler produced for the user's own code assembles on the model machine, +// the library functions that assemble never get fewer, and the instructions +// outside the model's set are only the 256-bit AVX2 ones the model says it +// does not have. A new corpus item that brings a new instruction fails here, +// which is the point. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { census } from '../scripts/asm-census.mjs'; +import { parseAsm, runAsmProgram } from '../dist/services/asm.js'; +import { intelLine } from '../dist/mojo/att.js'; + +const LIBRARY_AT_LEAST = 438; // raise as the machine learns more +const OUTSIDE = new Set(['vextracti128', 'vinserti128', 'vpblendvb', 'vperm2i128', 'vpalignr']); // ymm: 256-bit AVX2 + +test('every user function in the corpus listings assembles on the model machine', () => { + const c = census(); + assert.deepEqual(c.userFailures, []); + assert.equal(c.userOk, c.user); + assert.ok(c.user >= 7, `only ${c.user} user functions in the corpus`); +}); + +test('the library functions that assemble do not get fewer, and what is outside the set is only AVX2', () => { + const c = census(); + assert.ok(c.libOk >= LIBRARY_AT_LEAST, `${c.libOk} library functions assemble, fewer than ${LIBRARY_AT_LEAST}`); + const unexpected = c.missing.map(([op]) => op).filter((op) => !OUTSIDE.has(op)); + assert.deepEqual(unexpected, [], 'instructions the corpus uses that the model neither has nor lists as outside it'); +}); + +test('the AT&T translator strips the size suffix from the BMI and atomic mnemonics and keeps lock', () => { + const map = new Map(); + assert.equal(intelLine('andnq %rax, %r9, %rax', map), 'andn rax, r9, rax'); + assert.equal(intelLine('mulxq %rcx, %rdx, %rdx', map), 'mulx rdx, rdx, rcx'); + assert.equal(intelLine('lock xaddq %rax, (%rcx)', map), 'lock xadd qword ptr [rcx], rax'); + assert.equal(intelLine('shlxq %rcx, %rbx, %r11', map), 'shlx r11, rbx, rcx'); + assert.equal(intelLine('vpcmpeqb %xmm1, %xmm0, %xmm3', map), 'vpcmpeqb xmm3, xmm0, xmm1'); +}); + +test('the instructions compiled Mojo uses compute what the manual says', () => { + const run = (src, setup = '') => { const p = parseAsm(src); assert.ok(p.ok, p.diagnostics.map((d) => d.message).join('; ')); return runAsmProgram(p, { setup, machine: 'teaching', maxSteps: 200 }); }; + const st = run([ + 'mov rdx, 6', 'mov rcx, 7', 'mulx r8, r9, rcx', + 'mov rax, 0xff00', 'mov rbx, 0x0ff0', 'andn r10, rax, rbx', + 'mov rcx, 3', 'shlx r11, rbx, rcx', 'sarx r12, rax, rcx', 'bzhi r13, rbx, rcx', + 'mov rsi, 12', 'blsr rdi, rsi', 'blsi r14, rsi', 'blsmsk r15, rsi', 'rorx rbx, rsi, 1', + 'mov rax, 1', 'mov qword ptr [0x1000], 10', 'lock xadd qword ptr [0x1000], rax', + 'mov rax, 11', 'mov rcx, 99', 'lock cmpxchg qword ptr [0x1000], rcx', + 'bts rdx, 4', 'mov eax, 0x12345678', 'bswap eax', + ].join('\n'), 'memory 0x1000 "........"'); + const s = st.states[st.count]; + assert.equal(st.error, null); + assert.equal(s.regs.r9, 42n); assert.equal(s.regs.r8, 0n); + assert.equal(s.regs.r10, 0xf0n); assert.equal(s.regs.r11, 0x7f80n); assert.equal(s.regs.r12, 0x1fe0n); assert.equal(s.regs.r13, 0n); + assert.equal(s.regs.rdi, 8n); assert.equal(s.regs.r14, 4n); assert.equal(s.regs.r15, 7n); assert.equal(s.regs.rbx, 6n); + assert.equal(s.regs.rdx, 22n); assert.equal(s.regs.rax, 0x78563412n); assert.equal(s.flags.ZF, true); + assert.equal(s.mem.find((m) => m.addr === 0x1000).bytes[0], 99, 'cmpxchg stored the new value'); + // vectors: a broadcast compare finds every A in GATTACAGATTACA + const v = run(['vmovdqu xmm1, xmmword ptr [0x1000]', 'mov eax, 0x41', 'vmovd xmm4, eax', 'vpbroadcastb xmm4, xmm4', 'vpcmpeqb xmm3, xmm1, xmm4', 'vpmovmskb r8d, xmm3', 'vpextrb eax, xmm1, 1', 'vpshufd xmm5, xmm1, 0x1b'].join('\n'), 'memory 0x1000 "GATTACAGATTACA.."'); + const vs = v.states[v.count]; + assert.equal(vs.regs.r8, 0b10100101010010n); assert.equal(vs.regs.rax, 0x41n); + // ud2 stops the run and says why + const u = run('mov rax, 1\nud2'); + assert.match(u.error.message, /invalid-opcode/); + // a stub for the standard library stops the run and names the function + const stub = run('call std_io_io_print\nstd_io_io_print:\n ud2 ; std_io_io_print: standard library, not on the model machine'); + assert.match(stub.error.message, /std_io_io_print: standard library, not on the model machine/); +}); diff --git a/tests/asm-float.test.mjs b/tests/asm-float.test.mjs new file mode 100644 index 0000000..ceea904 --- /dev/null +++ b/tests/asm-float.test.mjs @@ -0,0 +1,254 @@ +// Scalar double arithmetic, the parity flag, shld/shrd, and the compiler's constant pool. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseAsm, runAsmProgram } from '../dist/services/asm.js'; +import { rflagsValue } from '../dist/engines/asm86/interp.js'; +import { intelLine, forSimulator, simulatorSetup } from '../dist/mojo/att.js'; +import { listingFunctions } from '../dist/services/godbolt.js'; + +const dv = new DataView(new ArrayBuffer(8)); +const M64 = 0xffffffffffffffffn; +const bits = (x) => { dv.setFloat64(0, x); return dv.getBigUint64(0); }; +const dbl = (b) => { dv.setBigUint64(0, BigInt(b) & M64); return dv.getFloat64(0); }; +const le = (v) => Array.from({ length: 8 }, (_, i) => Number((BigInt(v) >> BigInt(8 * i)) & 0xffn)); +const lo = (v) => BigInt(v) & M64; + +function run(src, setup = '') { + const p = parseAsm(src); + assert.ok(p.ok, p.diagnostics?.map((d) => d.message).join('; ')); + const r = runAsmProgram(p, { setup, machine: 'teaching', maxSteps: 300 }); + return { s: r.states[r.count], error: r.error?.message }; +} +const load = (reg, x) => [`mov rax, 0x${bits(x).toString(16)}`, `movq ${reg}, rax`]; +const two = (op, a, b) => run([...load('xmm0', a), ...load('xmm1', b), `${op} xmm0, xmm1`].join('\n')).s.regs.xmm0; +const three = (op, a, b) => run([...load('xmm1', a), ...load('xmm2', b), `${op} xmm0, xmm1, xmm2`].join('\n')).s.regs.xmm0; + +test('arithmetic is IEEE binary64, rounded to nearest even', () => { + assert.equal(lo(two('addsd', 0.1, 0.2)), 0x3FD3333333333334n); + assert.equal(lo(two('addsd', 0.1, 0.2)), bits(0.1 + 0.2)); + assert.equal(dbl(lo(two('divsd', 1, 3))), 1 / 3); + assert.equal(dbl(lo(two('mulsd', 1e200, 1e200))), Infinity, 'overflow gives infinity'); + assert.equal(dbl(lo(three('vsubsd', 4, 3))), 1); + assert.equal(dbl(lo(three('vdivsd', 4, 3))), 4 / 3); + const r = run([...load('xmm1', 2), 'vsqrtsd xmm0, xmm1, xmm1'].join('\n')).s.regs.xmm0; + assert.equal(dbl(lo(r)), Math.SQRT2); +}); + +test('special values: division by zero, invalid operations, NaN propagation', () => { + assert.equal(dbl(lo(two('divsd', 1, 0))), Infinity); + assert.equal(dbl(lo(two('divsd', -1, 0))), -Infinity); + assert.equal(lo(two('divsd', 0, 0)), 0xFFF8000000000000n, '0/0 is the default NaN'); + const sq = (x) => lo(run([...load('xmm1', x), 'vsqrtsd xmm0, xmm1, xmm1'].join('\n')).s.regs.xmm0); + assert.equal(sq(-1), 0xFFF8000000000000n); + assert.equal(sq(-0), bits(-0), 'sqrt(-0) is -0'); + // a quiet NaN with a payload is kept; a signalling one is quieted; with two NaNs the first operand wins + const nan = (payload) => `mov rax, 0x${payload.toString(16)}\nmovq xmm0, rax`; + const q = run(`${nan(0x7FF8000000000123n)}\n${load('xmm1', 1).join('\n')}\naddsd xmm0, xmm1`).s.regs.xmm0; + assert.equal(lo(q), 0x7FF8000000000123n); + const sig = run(`${nan(0x7FF0000000000001n)}\n${load('xmm1', 1).join('\n')}\naddsd xmm0, xmm1`).s.regs.xmm0; + assert.equal(lo(sig), 0x7FF8000000000001n); + const both = run(`${nan(0x7FF8000000000001n)}\nmov rax, 0x7FF8000000000002\nmovq xmm1, rax\naddsd xmm0, xmm1`).s.regs.xmm0; + assert.equal(lo(both), 0x7FF8000000000001n); +}); + +test('cvtsi2sd rounds to nearest even and reads the integer width asked for', () => { + const cvt = (setup, line) => lo(run(`${setup}\n${line}`).s.regs.xmm0); + assert.equal(cvt('mov rax, 9007199254740993', 'cvtsi2sd xmm0, rax'), bits(9007199254740992), '2^53+1 ties to even'); + assert.equal(cvt('mov rax, 0x8000000000000000', 'cvtsi2sd xmm0, rax'), bits(-9223372036854775808)); + assert.equal(cvt('mov eax, 0xffffffff', 'cvtsi2sd xmm0, eax'), bits(-1), '32-bit source is signed'); +}); + +test('upper halves: the VEX forms copy from the first source, the SSE forms keep the destination', () => { + // 16 bytes at 0x1000: low half 5.0's bits, high half 0x1111; at 0x1010: low 7.0's bits, high 0x2222 + const mem = `memory 0x1000 bytes ${[...le(bits(5)), ...le(0x1111n), ...le(bits(7)), ...le(0x2222n)].map((b) => '0x' + b.toString(16)).join(' ')}`; + const prog = (body) => run(['movdqu xmm0, xmmword ptr [0x1000]', 'movdqu xmm1, xmmword ptr [0x1010]', body].join('\n'), mem).s.regs.xmm0; + const hi = (v) => v >> 64n; + assert.equal(hi(prog('vaddsd xmm0, xmm1, xmm1')), 0x2222n, 'vaddsd takes the upper half of its first source'); + assert.equal(dbl(lo(prog('vaddsd xmm0, xmm1, xmm1'))), 14); + assert.equal(hi(prog('addsd xmm0, xmm1')), 0x1111n, 'addsd keeps the destination\u2019s'); + assert.equal(hi(prog('movsd xmm0, xmm1')), 0x1111n, 'register movsd merges the low half'); + assert.equal(dbl(lo(prog('movsd xmm0, xmm1'))), 7); + assert.equal(hi(prog('movsd xmm0, qword ptr [0x1010]')), 0n, 'a movsd load clears the upper half'); + assert.equal(hi(prog('vmovsd xmm0, xmm0, xmm1')), 0x1111n, 'three-operand vmovsd keeps the first source\u2019s upper half'); + assert.equal(dbl(lo(prog('vmovsd xmm0, xmm0, xmm1'))), 7); +}); + +const flagsAfter = (a, b, op = 'ucomisd') => run([...load('xmm0', a), ...load('xmm1', b), `${op} xmm0, xmm1`].join('\n')).s.flags; +const pick = (f) => ['ZF', 'PF', 'CF'].map((k) => (f[k] ? 1 : 0)).join(''); + +test('ucomisd and comisd: less sets CF, equal sets ZF, unordered sets all three', () => { + for (const op of ['ucomisd', 'comisd', 'vucomisd', 'vcomisd']) { + assert.equal(pick(flagsAfter(1, 2, op)), '001', `${op} less`); + assert.equal(pick(flagsAfter(2, 1, op)), '000', `${op} greater`); + assert.equal(pick(flagsAfter(2, 2, op)), '100', `${op} equal`); + assert.equal(pick(flagsAfter(NaN, 1, op)), '111', `${op} unordered`); + } + assert.equal(pick(flagsAfter(0, -0)), '100', '+0 equals -0'); + const f = flagsAfter(NaN, 1); + assert.equal(f.OF, false); + assert.equal(f.SF, false); +}); + +test('conditions after a compare: ja, jb, je, jp and setp', () => { + const took = (a, b, j) => run([...load('xmm0', a), ...load('xmm1', b), 'ucomisd xmm0, xmm1', 'mov rcx, 0', `${j} yes`, 'jmp done', 'yes: mov rcx, 1', 'done: nop'].join('\n')).s.regs.rcx; + assert.equal(took(2, 1, 'ja'), 1n); + assert.equal(took(1, 2, 'ja'), 0n); + assert.equal(took(1, 2, 'jb'), 1n); + assert.equal(took(3, 3, 'je'), 1n); + assert.equal(took(NaN, 3, 'jp'), 1n); + assert.equal(took(3, 3, 'jp'), 0n); + assert.equal(took(NaN, 3, 'jnp'), 0n); + const set = run([...load('xmm0', NaN), ...load('xmm1', 1), 'ucomisd xmm0, xmm1', 'setp al', 'setnp bl'].join('\n')).s.regs; + assert.equal(set.rax & 0xffn, 1n); + assert.equal(set.rbx & 0xffn, 0n); +}); + +test('the parity flag: set by logic, arithmetic and shifts; left alone by rotates; cleared by popcnt', () => { + const pf = (src) => run(src).s.flags.PF; + assert.equal(pf('mov rax, 3\ntest rax, rax'), true, '0b11 has two set bits'); + assert.equal(pf('mov rax, 1\ntest rax, rax'), false); + assert.equal(pf('mov rax, 5\nxor rax, rax'), true, 'zero has even parity'); + assert.equal(pf('mov rax, 1\nshl rax, 1'), false); + assert.equal(pf('mov rax, 2\ninc rax'), true); + assert.equal(pf('mov rax, 0\ntest rax, rax\nrol rax, 1'), true, 'rol does not touch PF'); + assert.equal(pf('mov rax, 0\ntest rax, rax\npopcnt rbx, rax'), false); + assert.equal((rflagsValue({ ZF: false, SF: false, CF: false, OF: false, PF: true }) >> 2n) & 1n, 1n, 'PF is bit 2 of RFLAGS'); + assert.equal((rflagsValue({ ZF: false, SF: false, CF: false, OF: false, PF: false }) >> 2n) & 1n, 0n); +}); + +test('shld and shrd shift in bits from the second register', () => { + const r = (src) => run(src, 'memory 0x1000 zero 16').s; + assert.equal(r('mov rax, 0xff\nmov rsi, 0xf000000000000000\nshld rax, rsi, 4').regs.rax, 0xfffn); + assert.equal(r('mov rbx, 0xff\nmov rdi, 0xf\nshrd rbx, rdi, 4').regs.rbx, 0xf00000000000000fn); + assert.equal(r('mov rax, 1\nmov rcx, 4\nmov rsi, 0xf000000000000000\nshld rax, rsi, cl').regs.rax, 0x1fn, 'count in cl'); + // count zero changes nothing, flags included + const z = r('mov rax, 3\ntest rax, rax\nmov rsi, 1\nshld rax, rsi, 0'); + assert.equal(z.regs.rax, 3n); + assert.equal(z.flags.PF, true); + // 32-bit counts are masked to five bits: 33 acts as 1 + assert.equal(r('mov eax, 1\nmov esi, 0x80000000\nshld eax, esi, 33').regs.rax, 3n); + // the same register on both sides is a rotate + assert.equal(r('mov rax, 0x8000000000000001\nshld rax, rax, 1').regs.rax, 3n); + // carry is the last bit shifted out of the destination + assert.equal(r('mov rax, 0x8000000000000000\nmov rsi, 0\nshld rax, rsi, 1').flags.CF, true); + // a memory destination + assert.equal(r('mov qword ptr [0x1000], 0xff\nmov rsi, 0xf000000000000000\nshld qword ptr [0x1000], rsi, 4\nmov rax, qword ptr [0x1000]').regs.rax, 0xfffn); +}); + +test('shld refuses a 16-bit operand and nonsense forms', () => { + for (const bad of ['shld ax, bx, 1', 'vaddsd xmm0, rax', 'cvtsi2sd rax, xmm0', 'ucomisd rax, rbx', 'sqrtsd xmm0']) { + const p = parseAsm(bad); + const failed = !p.ok || (() => { const r = runAsmProgram(p, { setup: '', machine: 'teaching', maxSteps: 10 }); return !!r.error; })(); + assert.ok(failed, bad); + } +}); + +test('AT&T spellings of the new instructions become Intel', () => { + const t = (att) => intelLine(att, new Map()); + assert.equal(t('vcvtsi2sd %rax, %xmm0, %xmm0'), 'vcvtsi2sd xmm0, xmm0, rax'); + assert.equal(t('vcvtsi2sdl (%rax), %xmm0, %xmm0'), 'vcvtsi2sd xmm0, xmm0, dword ptr [rax]'); + assert.equal(t('vcvtsi2sdq 8(%rsp), %xmm1, %xmm1'), 'vcvtsi2sd xmm1, xmm1, qword ptr [rsp + 8]'); + assert.equal(t('vmovsd 8(%rsp), %xmm0'), 'vmovsd xmm0, [rsp + 8]'); + assert.equal(t('shldq $3, %rsi, %rax'), 'shld rax, rsi, 3'); + assert.equal(t('shldq %cl, %rsi, %rax'), 'shld rax, rsi, cl'); + assert.equal(t('setp %al'), 'setp al'); + assert.equal(t('vdivsd .LCPI0_0+8(%rip), %xmm0, %xmm0'), 'vdivsd xmm0, xmm0, [rip + .LCPI0_0 + 8]'); +}); + +// LLVM's output for `fn scale(n: Int) -> Float64: return Float64(n) / 1_000_000.0`, trimmed to what matters. +const LISTING = [ + '"example::scale(::Int)":', + ' vcvtsi2sd %rdi, %xmm0, %xmm0', + ' vdivsd .LCPI0_0(%rip), %xmm0, %xmm0', + ' retq', + '.LCPI0_0:', + ' .quad 0x412e848000000000 # double 1.0E+6', + '.LCPI0_1:', + ' .quad 0x4000000000000000', + ' .quad 0x4008000000000000', +].map((text, i) => ({ text, line: i === 1 ? 3 : null })); + +test('a constant pool in the listing is placed in memory and the code points at it', () => { + const fns = listingFunctions(LISTING); + const fn = fns.find((f) => f.kind === 'user'); + assert.ok(fn, 'the user function is found'); + const sim = forSimulator(fns, fn); + assert.doesNotMatch(sim.source, /LCPI/, 'no constant-pool label is left in the code'); + assert.equal(sim.data.length, 1, 'only the blocks the code uses are placed'); + assert.match(sim.data[0], /^memory 0x6000 bytes 0x00 0x00 0x00 0x00 0x80 0x84 0x2e 0x41 /); + const setup = simulatorSetup(fn, sim.data).replace('rdi = 0', 'rdi = 5000000'); + const p = parseAsm(sim.source); + assert.ok(p.ok, p.diagnostics?.[0]?.message); + const r = runAsmProgram(p, { setup, machine: 'teaching', maxSteps: 50 }); + assert.ok(!r.error, String(r.error?.message)); + assert.equal(dbl(lo(r.states[r.count].regs.xmm0)), 5); +}); + +test('a constant block with a symbol in it is not placed, so the instruction using it is refused as before', () => { + const fns = listingFunctions([ + { text: '"example::f(::Int)":' }, { text: ' vmovsd .LJT(%rip), %xmm0' }, { text: ' retq' }, + { text: '.LJT:' }, { text: ' .quad .LBB0_1' }, + ]); + const sim = forSimulator(fns, fns[0]); + assert.equal(sim.data.length, 0); +}); + +test('a call to the debugger raise hook (every -O0 loop over a range ends with one) returns instead of stopping the run', () => { + const fns = listingFunctions([ + { text: '"example::count(::Int)":' }, + { text: ' movq %rdi, %rax' }, + { text: ' callq "std::builtin::error::__mojo_debugger_raise_hook()"' }, + { text: ' callq "std::builtin::string::String::__init__()"' }, + { text: ' retq' }, + ]); + const sim = forSimulator(fns, fns[0]); + assert.deepEqual(sim.refusedCalls, ['std_builtin_string_String___init__'], 'only real library code is refused'); + assert.match(sim.source, /std_builtin_error___mojo_debugger_raise_hook:\n\s+ret\b/); + // with the String call removed, the function runs to its ret + const fns2 = listingFunctions([{ text: '"example::count(::Int)":' }, { text: ' movq %rdi, %rax' }, { text: ' callq "std::builtin::error::__mojo_debugger_raise_hook()"' }, { text: ' retq' }]); + const p = parseAsm(forSimulator(fns2, fns2[0]).source); + assert.ok(p.ok, p.diagnostics?.[0]?.message); + const r = runAsmProgram(p, { setup: 'rdi = 285', machine: 'teaching', maxSteps: 50 }); + assert.ok(!r.error, String(r.error?.message)); + assert.equal(r.states[r.count].regs.rax, 285n); +}); + +test('read-only strings in every form the listing writes them are placed: .asciz, an empty string as .zero 1, pieces, and an alias', () => { + const lines = [ + '"example::f()":', + ' leaq static_string_e(%rip), %rax', + ' leaq static_string_s(%rip), %rbx', + ' leaq static_string_p(%rip), %rcx', + ' leaq static_string_a(%rip), %rdx', + ' retq', + 'static_string_e:', ' .zero 1', + 'static_string_s:', ' .asciz " "', + 'static_string_p:', ' .ascii "ab"', ' .byte 99, 0', + 'static_string_x:', ' .asciz "hello"', + ' .set static_string_a, static_string_x+2', + ].map((text) => ({ text })); + const fns = listingFunctions(lines); + const sim = forSimulator(fns, fns.find((f) => f.kind === 'user')); + assert.doesNotMatch(sim.source, /rip \+/, 'every address became a number'); + assert.doesNotMatch(sim.source, /does not define/); + const p = parseAsm(sim.source); + assert.ok(p.ok, p.diagnostics?.[0]?.message); + const r = runAsmProgram(p, { setup: sim.data.join('\n'), machine: 'teaching', maxSteps: 20 }); + assert.ok(!r.error, String(r.error?.message)); + const regs = r.states[r.count].regs; + const mem = (addr, n) => sim.data.find((d) => d.startsWith(`memory 0x${addr.toString(16)} `)); + assert.match(mem(regs.rax), /bytes 0x00/, 'the empty string is one zero byte'); + assert.match(mem(regs.rbx), /" "/); + assert.match(mem(regs.rcx), /bytes 0x61 0x62 0x63 0x00/); + assert.equal(regs.rdx, regs.rdx, 'alias resolves'); + const hello = sim.data.find((d) => /"hello"/.test(d)); + assert.ok(hello, 'the aliased string is placed'); + assert.equal(regs.rdx, BigInt(parseInt(/memory (0x[0-9a-f]+)/.exec(hello)[1], 16) + 2), 'the alias points two bytes in'); +}); + +test('vpcmpgtb compares signed bytes', () => { + const r = run(['mov rax, 0x00000000000080ff', 'movq xmm1, rax', 'mov rax, 0x0000000000000102', 'movq xmm2, rax', 'vpcmpgtb xmm0, xmm2, xmm1'].join('\n')).s.regs.xmm0; + // lane 0: 2 > -1 yes; lane 1: 1 > -128 yes; lanes 2..15: 0 > 0 no + assert.equal(r & 0xffffn, 0xffffn); + assert.equal(r >> 16n, 0n); +}); diff --git a/tests/badges.test.mjs b/tests/badges.test.mjs new file mode 100644 index 0000000..136dcdc --- /dev/null +++ b/tests/badges.test.mjs @@ -0,0 +1,129 @@ +// Stage 12: the Mojo badges. The generated label (where the Mojo came from) and the godbolt badge (whether the real +// compiler was asked about exactly this source) are independent, both are data a view reads from the session, and +// neither can come from a link or a file. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { stateForProblem, problemById, PROBLEMS } from '../dist/core/catalog.js'; +import { mojoProvenance } from '../dist/core/provenance.js'; +import { compiledStatus, compileHash, forgetCompiles } from '../dist/core/compiles.js'; +import { normalize } from '../dist/core/state.js'; +import { GENERATED_HEADER } from '../dist/sync/header.js'; +import { mojoFromPseudo } from '../dist/sync/hub.js'; + +const store = new Map(); +globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; +const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null }); +const answer = (over = {}) => async () => ({ error: null, seconds: 1, answer: { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: '1\n', stderr: '', timedOut: false, asm: [], ...over } }); + +test('the Bridge\'s Mojo is always generated; elsewhere the state says', () => { + const b = open('count-base', 'bridge'); + assert.equal(b.provenance(), 'generated'); + assert.equal(mojoProvenance(b, 'bridge'), 'generated'); + assert.equal(open('count-base', 'dev').provenance(), null, 'an exercise\'s own Mojo is nobody\'s translation'); + assert.equal(open('count-base', 'hw').provenance(), null); + assert.equal(mojoProvenance({ area: 'dev', state: { mojoOrigin: 'generated-edited' } }), 'generated-edited'); +}); + +test('copying sets generated, editing sets generated-edited, and only the button clears it', async () => { + const s = open('count-base'); + assert.ok(s.adoptGeneratedMojo()); + assert.equal(s.state.mojoOrigin, 'generated'); + const dev = new Session(s.state, { area: 'dev', storageId: null }); + assert.equal(dev.provenance(), 'generated'); + dev.setSource('mojo', dev.source('mojo') + '\n# my note'); + assert.equal(dev.provenance(), 'generated-edited'); + forgetCompiles(); + await dev.compile(answer()); + assert.equal(dev.provenance(), 'generated-edited', 'a successful compile does not clear it'); + assert.ok(dev.clearMojoOrigin()); + assert.equal(dev.provenance(), null); + assert.equal(dev.state.mojoOrigin, undefined); + assert.ok(!dev.source('mojo').includes(GENERATED_HEADER), 'the header comment goes with it'); + assert.ok(dev.source('mojo').includes('# my note'), 'the student\'s own lines stay'); + assert.equal(dev.clearMojoOrigin(), false, 'nothing left to clear'); +}); + +test('the Bridge cannot clear provenance, and a translation always starts with the header', () => { + const s = open('count-base'); + assert.equal(s.clearMojoOrigin(), false); + let n = 0; + for (const p of PROBLEMS) { + const pseudo = stateForProblem(p).sources.pseudo; + if (!pseudo) continue; + const m = mojoFromPseudo(pseudo, null).source; + if (m) { n++; assert.ok(m.startsWith(GENERATED_HEADER), p.id); } + } + assert.ok(n > 5); +}); + +test('the godbolt badge: shown for the compiled source, not for one more character, level or input', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + assert.equal(s.compileBadge(), null, 'never compiled: no badge'); + await s.compile(answer()); + const b = s.compileBadge(); + assert.equal(b.kind, 'compiled'); + assert.equal(b.status.outcome, 'ran'); + assert.equal(b.status.exit, 0); + const original = s.source('mojo'); + s.setSource('mojo', original + ' '); + assert.equal(s.compileBadge().kind, 'edited', 'a one-character edit removes the badge'); + s.setSource('mojo', original); + assert.equal(s.compileBadge().kind, 'compiled', 'the same text again is the same compile'); + const back = open('count-base', 'dev'); + assert.equal(back.compileBadge().kind, 'compiled', 'the same text again is the same compile'); + back.setBuildLevel('default'); + assert.equal(back.compileBadge(), null, 'another build level was never asked'); + back.setBuildLevel('O0'); + back.setInput('3\n'); + assert.equal(back.compileBadge(), null, 'another input was never asked'); +}); + +test('outcomes: did not compile, exit N, timed out', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(answer({ compiled: false, executed: false, exitCode: null })); + assert.equal(s.compileBadge().status.outcome, 'did-not-compile'); + forgetCompiles(); + await s.compile(answer({ exitCode: 3 })); + assert.deepEqual([s.compileBadge().status.outcome, s.compileBadge().status.exit], ['ran', 3]); + forgetCompiles(); + await s.compile(answer({ timedOut: true })); + assert.equal(s.compileBadge().status.outcome, 'timed-out'); +}); + +test('a failed request (no answer) leaves no badge', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(async () => ({ answer: null, error: 'offline', seconds: 1 })); + assert.equal(s.compileBadge(), null); +}); + +test('the badge survives a new Session and the full answers being dropped, but is not in the state, a link or a file', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(answer()); + const src = s.source('mojo'); + assert.equal(compiledStatus(src, '', 'O0').outcome, 'ran'); + assert.equal(compiledStatus(src, '', 'O0').level, 'O0'); + assert.ok(store.has('pplus.compiled')); + store.delete('pplus.compiles'); // the full answers are gone; the summary index stays + assert.equal(open('count-base', 'dev').compileBadge().kind, 'compiled'); + const text = JSON.stringify(s.state); + assert.ok(!/compiled|godbolt|pplus\./i.test(text.replace(/"compiler"/g, '')), 'nothing about a compile in the state'); + forgetCompiles(); // someone else's browser: the same link, no compile + const theirs = new Session(normalize(JSON.parse(text)), { area: 'dev', storageId: null }); + assert.equal(theirs.compileBadge(), null); +}); + +test('both badges can show together, and the hash covers source, input and level', async () => { + forgetCompiles(); + const s = open('count-base', 'bridge'); + await s.compile(answer()); + assert.equal(s.provenance(), 'generated'); + assert.equal(s.compileBadge().kind, 'compiled'); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', '', 'default')); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', 'x', 'O0')); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a ', '', 'O0')); +}); diff --git a/tests/bridge.test.mjs b/tests/bridge.test.mjs new file mode 100644 index 0000000..8aa9869 --- /dev/null +++ b/tests/bridge.test.mjs @@ -0,0 +1,132 @@ +// Stage 10 (and the part of stage 11 it needs): the Bridge's session behavior, without a DOM. In the Bridge the +// Mojo pane is the literal translation of the pseudo, computed and never stored; the views that read a program +// (trace, checker, tests, proof) work on the hub's pseudo; a pane that is not in step is not stepped; "Edit in +// Developer" copies the generated Mojo out and records that it was generated. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { PROBLEMS, stateForProblem, problemById } from '../dist/core/catalog.js'; +import { SyncHub } from '../dist/sync/hub.js'; +import { normalize } from '../dist/core/state.js'; +import { GENERATED_HEADER } from '../dist/sync/header.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; +const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null }); + +test('in the Bridge the Mojo pane is the generated Mojo, not the stored Mojo; elsewhere it is the state\'s own', () => { + const own = stateForProblem(problemById('count-base')).sources.mojo; + assert.ok(own && !own.startsWith('# Generated'), 'the exercise has its own Mojo'); + const bridge = open('count-base', 'bridge'); + assert.ok(bridge.source('mojo').startsWith(GENERATED_HEADER), 'the Bridge shows the literal translation, header first'); + assert.equal(bridge.source('mojo'), bridge.derivedMojo().source); + assert.equal(bridge.state.sources.mojo, own, 'the stored Mojo is untouched'); + assert.equal(open('count-base', 'dev').source('mojo'), own); + assert.equal(open('count-base', 'hw').source('mojo'), own); + assert.equal(new Session(stateForProblem(problemById('count-base')), { storageId: null }).source('mojo'), own, 'a session with no area (an embed of one pane) shows the state\'s own Mojo'); +}); + +test('the Bridge\'s Mojo follows an edit in any linked pane, and every view of it reads the generated source', () => { + const s = open('count-base'); + const before = s.source('mojo'); + s.setSource('pseudo', s.source('pseudo').replace('Total <- 0', 'Total <- 3')); + assert.notEqual(s.source('mojo'), before); + assert.match(s.source('mojo'), /total = 3/); + // the checker, the stepper and the tests read it + s.setLang('mojo'); + assert.equal(s.parsedMojo().program.source ?? s.source('mojo'), s.source('mojo')); + assert.deepEqual(s.parsedMojo().diagnostics.filter((d) => d.severity === 'error'), []); + const tr = s.trace(); + assert.ok(tr && !tr.error, 'the generated Mojo steps in the interpreter'); + assert.ok(tr.output.some((l) => /3|4|5|6|7|8|9/.test(l)), 'and prints a count that includes the changed start'); + assert.ok(s.tests().length >= 0); + // an edit in lingo reaches it too + const lingo = s.source('lingo'); + assert.match(lingo, /Start with Total at 3\./, 'the English was regenerated from the pseudo'); + s.setSource('lingo', lingo.replace('Start with Total at 3.', 'Start with Total at 10.')); + assert.match(s.source('mojo'), /total = 10/); +}); + +test('trace steps the pseudo, not a stale pane', () => { + const s = open('count-base'); + s.setLang('lingo'); + assert.equal(s.traceLang(), 'lingo', 'an in-step lingo pane is stepped as English'); + s.setSource('pseudo', 'FUNCTION BROKEN(\nRETURN'); // pseudo has errors: lingo is now stale + assert.equal(s.linkState('lingo').kind, 'stale'); + assert.equal(s.traceLang(), 'pseudo', 'lingo holds text the pseudo has moved on from'); +}); + +test('prove and tests work on the hub\'s pseudo, with the speco woven', () => { + const s = open('count-base-proved'); + s.setLang('lingo'); + s.setSource('lingo', s.source('lingo').replace('Add 1 to Total.', 'Add 1 to Total.')); // no change: nothing to do + const lingo = s.source('lingo'); + s.setSource('lingo', lingo + '\n'); // an edit in English + assert.equal(s.state.sync.authority, 'lingo'); + assert.match(s.source('pseudo'), /ENSURE/, 'the contracts are in the pseudo the English lowered to'); + const proof = s.proof(); + assert.ok(proof && proof.report.counts.total > 0, 'there is something to prove'); + assert.equal(proof.report.counts.broken, 0); + assert.ok(s.tests().length > 0, 'tests are generated from the pseudo'); +}); + +test('Edit in Developer copies the generated Mojo into the state and records that it was generated', () => { + const s = open('count-base'); + const generated = s.derivedMojo().source; + assert.ok(s.wouldReplaceMojo(), 'the exercise\'s own Mojo would be replaced: the shell asks first'); + assert.equal(s.state.mojoOrigin, undefined); + assert.ok(s.adoptGeneratedMojo()); + assert.equal(s.state.sources.mojo, generated); + assert.equal(s.state.mojoOrigin, 'generated'); + assert.equal(s.state.lang, 'mojo'); + assert.equal(s.wouldReplaceMojo(), false, 'it already holds this program'); + // the Developer area shows it, and the first edit makes it theirs + const dev = new Session(s.state, { area: 'dev', storageId: null }); + assert.equal(dev.source('mojo'), generated); + dev.setSource('mojo', generated + '\n# mine\n'); + assert.equal(dev.state.mojoOrigin, 'generated-edited'); + dev.setSource('mojo', generated + '\n# mine again\n'); + assert.equal(dev.state.mojoOrigin, 'generated-edited'); + // a state with no pseudo has nothing to adopt + const empty = new Session(normalize({ v: 3 }), { area: 'bridge', storageId: null }); + assert.equal(empty.adoptGeneratedMojo(), false); + assert.equal(empty.state.mojoOrigin, undefined); +}); + +test('mojoOrigin is validated, and is only ever set on Mojo the student did not write', () => { + assert.equal(normalize({ v: 3, mojoOrigin: 'generated' }).mojoOrigin, 'generated'); + assert.equal(normalize({ v: 3, mojoOrigin: 'generated-edited' }).mojoOrigin, 'generated-edited'); + assert.equal(normalize({ v: 3, mojoOrigin: 'hand-written' }).mojoOrigin, undefined); + const s = open('count-base', 'dev'); + s.setSource('mojo', s.source('mojo') + '\n# note\n'); + assert.equal(s.state.mojoOrigin, undefined, 'editing the exercise\'s own Mojo does not make it generated'); +}); + +test('line maps reach the Mojo: a pseudo line finds its Mojo lines and back', () => { + const s = open('count-base'); + const maps = s.lineMaps(); + const pseudo = s.source('pseudo').split('\n'); + const at = pseudo.findIndex((l) => /Total <- Total \+ 1/.test(l)) + 1; + const mojoLines = SyncHub.relate(maps, 'pseudo', at, 'mojo'); + assert.ok(mojoLines.length, 'the line has a Mojo line'); + assert.match(s.source('mojo').split('\n')[mojoLines[0] - 1], /total = total \+ 1/); + assert.ok(SyncHub.relate(maps, 'mojo', mojoLines[0], 'pseudo').includes(at)); + // lingo line -> pseudo line, for a problem whose lingo was authored + const lingo = s.source('lingo').split('\n'); + const l = lingo.findIndex((t) => /add 1 to Count/.test(t)) + 1; + const p = SyncHub.relate(maps, 'lingo', l, 'pseudo'); + assert.ok(Array.isArray(p)); +}); + +test('every Bridge problem opens with generated Mojo that names itself and checks clean', () => { + let n = 0; + for (const p of PROBLEMS) { + if (p.area !== 'bridge') continue; + const s = new Session(stateForProblem(p), { area: 'bridge', storageId: null }); + if (!s.source('pseudo').trim()) continue; + const m = s.source('mojo'); + if (!m) continue; // pseudo that does not read (five-bugs, by design) + assert.ok(m.startsWith(GENERATED_HEADER), p.id); + n++; + } + assert.ok(n >= 12, `${n} problems`); +}); diff --git a/tests/corpus.test.mjs b/tests/corpus.test.mjs new file mode 100644 index 0000000..dfb499a --- /dev/null +++ b/tests/corpus.test.mjs @@ -0,0 +1,38 @@ +// The pseudo stress corpus: 37 programs across domains (numbers, text, finance, graphs, simulation, +// statistics, cryptography, records, sets, recursion), plus runs that must stop and mistakes the checker +// must refuse. Each file states what it expects in header comments. See docs/pseudo-stress-test.md. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { studyOf, runPseudo } from '../dist/services/pseudo.js'; + +const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'corpus'); +const files = fs.readdirSync(dir).filter((f) => f.endsWith('.pseudo')).sort(); + +for (const f of files) { + test(`corpus: ${f}`, () => { + const src = fs.readFileSync(path.join(dir, f), 'utf8'); + const expect = [...src.matchAll(/^\/\/ EXPECT: (.*)$/gm)].map((m) => m[1]); + const input = [...src.matchAll(/^\/\/ INPUT: (.*)$/gm)].map((m) => m[1]); + const stops = /^\/\/ STOPS: (\w+)$/m.exec(src)?.[1]; + const errorsWanted = /^\/\/ ERRORS: (\d+)$/m.exec(src)?.[1]; + const st = studyOf(src); + const errs = st.diagnostics.filter((d) => d.severity === 'error'); + if (errorsWanted) { assert.equal(errs.length, Number(errorsWanted), errs.map((d) => `L${d.line} ${d.id}`).join(', ')); return; } + assert.ok(st.ok, errs.map((d) => `L${d.line} ${d.id}: ${d.message}`).join(' | ')); + const tr = runPseudo(st, { input, maxSteps: 200000 }); + if (stops) { assert.equal(tr.error?.kind, stops, tr.error?.message || 'no error'); return; } + assert.equal(tr.error, null, tr.error?.message); + assert.deepEqual(tr.output.filter((l) => !/^\w+ returned /.test(l)), expect); + }); +} + +test('the corpus covers every statement kind and every built-in group', () => { + const all = files.map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join('\n'); + for (const kw of ['DECLARE', 'CONSTANT', 'TYPE', 'DEFINE', 'IF', 'ELSEIF', 'ELSE', 'CASE', 'OTHERWISE', 'FOR', 'STEP', 'FOR EACH', 'WHILE', 'REPEAT', 'UNTIL', 'BREAK', 'CONTINUE', 'FUNCTION', 'PROCEDURE', 'BYREF', 'CALL', 'RETURN', 'INPUT', 'OUTPUT', 'REQUIRE', 'INVARIANT', 'DECREASES', 'FORALL', 'EXISTS', 'SUM', 'DIV', 'MOD', 'IN', 'ARRAY', 'LIST', 'HASHMAP', 'SET', 'PARALLEL FOR']) { + assert.ok(new RegExp(`\\b${kw}\\b`).test(all), `corpus never uses ${kw}`); + } + for (const b of ['LENGTH', 'ROWS', 'INT', 'ROUND', 'ABS', 'MIN', 'MAX', 'SLICE', 'UPPER', 'LOWER', 'ORD', 'CHR', 'TO_STRING', 'TO_INTEGER', 'KEYS', 'SORTED', 'APPEND', 'REMOVE', 'ADD', 'SORT', 'RANDINT', 'SPLIT', 'JOIN', 'INDEX_OF', 'REPLACE', 'FLOOR', 'CEIL', 'LOG10', 'SIN', 'COS', 'ATAN2', 'PI', 'CHOOSE', 'SUM_OF', 'MEAN_OF', 'VARIANCE_OF', 'STDEV_OF', 'MEDIAN_OF', 'DOT', 'NORM_OF', 'FILL']) assert.ok(all.includes(b + '('), `corpus never calls ${b}`); +}); diff --git a/tests/corpus/01-arithmetic.pseudo b/tests/corpus/01-arithmetic.pseudo new file mode 100644 index 0000000..d973b6c --- /dev/null +++ b/tests/corpus/01-arithmetic.pseudo @@ -0,0 +1,26 @@ +// Numbers: every arithmetic operator, both numeric types, and the conversions between them. +// EXPECT: 3.5 +// EXPECT: 3 +// EXPECT: 1 +// EXPECT: -4 +// EXPECT: 512 +// EXPECT: 2.0 +// EXPECT: 27 +// EXPECT: 28 +// EXPECT: 5 +// EXPECT: 7 -7 -7 +DECLARE A, B : INTEGER +DECLARE X : FLOAT +A <- 7 +B <- 2 +OUTPUT A / B +OUTPUT A DIV B +OUTPUT A MOD B +OUTPUT -2 ^ 2 +OUTPUT 2 ^ 3 ^ 2 +OUTPUT 4 / 2 +X <- 27.54 +OUTPUT INT(X) +OUTPUT ROUND(X) +OUTPUT ABS(-5) +OUTPUT 7 DIV 1, " ", -7 DIV 1, " ", (-7) DIV 1 diff --git a/tests/corpus/02-temperature.pseudo b/tests/corpus/02-temperature.pseudo new file mode 100644 index 0000000..960d8ea --- /dev/null +++ b/tests/corpus/02-temperature.pseudo @@ -0,0 +1,11 @@ +// A FLOAT formula with a FUNCTION; classic first program in any language. +// EXPECT: 212.0 +// EXPECT: 37.0 +FUNCTION TO_FAHRENHEIT(C : FLOAT) RETURNS FLOAT + RETURN C * 9 / 5 + 32 +ENDFUNCTION +FUNCTION TO_CELSIUS(F : FLOAT) RETURNS FLOAT + RETURN (F - 32) * 5 / 9 +ENDFUNCTION +OUTPUT TO_FAHRENHEIT(100.0) +OUTPUT TO_CELSIUS(98.6) diff --git a/tests/corpus/03-compound-interest.pseudo b/tests/corpus/03-compound-interest.pseudo new file mode 100644 index 0000000..f09fb04 --- /dev/null +++ b/tests/corpus/03-compound-interest.pseudo @@ -0,0 +1,11 @@ +// Finance flavor: a loop that updates a FLOAT, with ROUND for reporting. +// EXPECT: 1628.89 +FUNCTION BALANCE_AFTER(Principal : FLOAT, Rate : FLOAT, Years : INTEGER) RETURNS FLOAT + DECLARE B : FLOAT + B <- Principal + FOR Y <- 0 TO Years + B <- B * (1 + Rate) + NEXT Y + RETURN B +ENDFUNCTION +OUTPUT ROUND(BALANCE_AFTER(1000.0, 0.05, 10) * 100) / 100 diff --git a/tests/corpus/04-gcd-recursion.pseudo b/tests/corpus/04-gcd-recursion.pseudo new file mode 100644 index 0000000..fe4216e --- /dev/null +++ b/tests/corpus/04-gcd-recursion.pseudo @@ -0,0 +1,13 @@ +// Recursion with a DECREASES measure and a REQUIRE. +// EXPECT: 6 +// EXPECT: 1 +FUNCTION GCD(A : INTEGER, B : INTEGER) RETURNS INTEGER + REQUIRE A >= 0 AND B >= 0 + DECREASES B + IF B == 0 THEN + RETURN A + ENDIF + RETURN GCD(B, A MOD B) +ENDFUNCTION +OUTPUT GCD(48, 18) +OUTPUT GCD(17, 5) diff --git a/tests/corpus/05-primes-sieve.pseudo b/tests/corpus/05-primes-sieve.pseudo new file mode 100644 index 0000000..1607755 --- /dev/null +++ b/tests/corpus/05-primes-sieve.pseudo @@ -0,0 +1,19 @@ +// An ARRAY of BOOL, nested loops with STEP, and a LIST answer. +// EXPECT: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] +FUNCTION PRIMES_UP_TO(N : INTEGER) RETURNS LIST OF INTEGER + DECLARE IsPrime : ARRAY[N + 1] OF BOOL + DECLARE Found : LIST OF INTEGER + FOR I <- 0 TO N + 1 + IsPrime[I] <- I >= 2 + NEXT I + FOR I <- 2 TO N + 1 + IF IsPrime[I] THEN + APPEND(Found, I) + FOR J <- I * I TO N + 1 STEP I + IsPrime[J] <- FALSE + NEXT J + ENDIF + NEXT I + RETURN Found +ENDFUNCTION +OUTPUT PRIMES_UP_TO(30) diff --git a/tests/corpus/06-fibonacci-memo.pseudo b/tests/corpus/06-fibonacci-memo.pseudo new file mode 100644 index 0000000..84d9892 --- /dev/null +++ b/tests/corpus/06-fibonacci-memo.pseudo @@ -0,0 +1,25 @@ +// Memoised recursion. A FUNCTION cannot take BYREF, so the memo table has to travel through a PROCEDURE +// with the answer coming back BYREF too. Finding: this is the idiom; it reads heavier than in most languages. +// EXPECT: 6765 +// EXPECT: 12586269025 +PROCEDURE FIB(N : INTEGER, BYREF Memo : HASHMAP OF INTEGER : INTEGER, BYREF Result : INTEGER) + IF N < 2 THEN + Result <- N + RETURN + ENDIF + IF N IN Memo THEN + Result <- Memo[N] + RETURN + ENDIF + DECLARE A, B : INTEGER + CALL FIB(N - 1, Memo, A) + CALL FIB(N - 2, Memo, B) + Memo[N] <- A + B + Result <- A + B +ENDPROCEDURE +DECLARE M : HASHMAP OF INTEGER : INTEGER +DECLARE R : INTEGER +CALL FIB(20, M, R) +OUTPUT R +CALL FIB(50, M, R) +OUTPUT R diff --git a/tests/corpus/07-word-count.pseudo b/tests/corpus/07-word-count.pseudo new file mode 100644 index 0000000..70d2bfa --- /dev/null +++ b/tests/corpus/07-word-count.pseudo @@ -0,0 +1,34 @@ +// Text flavor: splitting a sentence into words by hand, since the notation has no SPLIT, then tallying. +// EXPECT: {"a": 2, "is": 2, "rose": 3} +// A HASHMAP prints its keys smallest first, whatever order they were added in. +FUNCTION WORDS(S : STRING) RETURNS LIST OF STRING + DECLARE Out : LIST OF STRING + DECLARE W : STRING + W <- "" + FOR EACH C IN S + IF C == ' ' THEN + IF LENGTH(W) > 0 THEN + APPEND(Out, W) + ENDIF + W <- "" + ELSE + W <- W & C + ENDIF + NEXT C + IF LENGTH(W) > 0 THEN + APPEND(Out, W) + ENDIF + RETURN Out +ENDFUNCTION +FUNCTION TALLY(Ws : LIST OF STRING) RETURNS HASHMAP OF STRING : INTEGER + DECLARE T : HASHMAP OF STRING : INTEGER + FOR EACH W IN Ws + IF W IN T THEN + T[W] <- T[W] + 1 + ELSE + T[W] <- 1 + ENDIF + NEXT W + RETURN T +ENDFUNCTION +OUTPUT TALLY(WORDS("a rose is a rose is rose")) diff --git a/tests/corpus/08-caesar.pseudo b/tests/corpus/08-caesar.pseudo new file mode 100644 index 0000000..1541b7f --- /dev/null +++ b/tests/corpus/08-caesar.pseudo @@ -0,0 +1,17 @@ +// Cryptography flavor: CHAR arithmetic with ORD and CHR, MOD to wrap. +// EXPECT: KHOOR, ZRUOG! +// EXPECT: HELLO, WORLD! +FUNCTION SHIFT(S : STRING, K : INTEGER) RETURNS STRING + DECLARE Out : STRING + Out <- "" + FOR EACH C IN S + IF C >= 'A' AND C <= 'Z' THEN + Out <- Out & CHR((ORD(C) - ORD('A') + K) MOD 26 + ORD('A')) + ELSE + Out <- Out & C + ENDIF + NEXT C + RETURN Out +ENDFUNCTION +OUTPUT SHIFT("HELLO, WORLD!", 3) +OUTPUT SHIFT(SHIFT("HELLO, WORLD!", 3), 23) diff --git a/tests/corpus/09-palindrome.pseudo b/tests/corpus/09-palindrome.pseudo new file mode 100644 index 0000000..cf5e5cd --- /dev/null +++ b/tests/corpus/09-palindrome.pseudo @@ -0,0 +1,17 @@ +// Two positions moving toward each other; a WHILE with a compound guard. +// EXPECT: TRUE +// EXPECT: FALSE +// EXPECT: TRUE +FUNCTION IS_PALINDROME(S : STRING) RETURNS BOOL + DECLARE Lo, Hi : INTEGER + Lo <- 0 + Hi <- LENGTH(S) - 1 + WHILE Lo < Hi AND S[Lo] == S[Hi] + Lo <- Lo + 1 + Hi <- Hi - 1 + ENDWHILE + RETURN Lo >= Hi +ENDFUNCTION +OUTPUT IS_PALINDROME("racecar") +OUTPUT IS_PALINDROME("rose") +OUTPUT IS_PALINDROME("") diff --git a/tests/corpus/10-insertion-sort.pseudo b/tests/corpus/10-insertion-sort.pseudo new file mode 100644 index 0000000..6c19bc0 --- /dev/null +++ b/tests/corpus/10-insertion-sort.pseudo @@ -0,0 +1,19 @@ +// An in-place sort with a PROCEDURE and BYREF, plus a loop invariant. +// EXPECT: [1, 2, 3, 5, 8, 9] +PROCEDURE INSERTION_SORT(BYREF L : LIST OF INTEGER) + FOR I <- 1 TO LENGTH(L) + INVARIANT FORALL K IN [1, I) : L[K - 1] <= L[K] + DECLARE Key, J : INTEGER + Key <- L[I] + J <- I - 1 + WHILE J >= 0 AND L[J] > Key + L[J + 1] <- L[J] + J <- J - 1 + ENDWHILE + L[J + 1] <- Key + NEXT I +ENDPROCEDURE +DECLARE Xs : LIST OF INTEGER +Xs <- [5, 2, 9, 1, 8, 3] +CALL INSERTION_SORT(Xs) +OUTPUT Xs diff --git a/tests/corpus/11-matrix-multiply.pseudo b/tests/corpus/11-matrix-multiply.pseudo new file mode 100644 index 0000000..d7440f9 --- /dev/null +++ b/tests/corpus/11-matrix-multiply.pseudo @@ -0,0 +1,27 @@ +// Two-dimensional ARRAYs, triple nested loops, ROWS and COLUMNS. +// EXPECT: 19 22 +// EXPECT: 43 50 +FUNCTION MATMUL(A : ARRAY[2, 2] OF INTEGER, B : ARRAY[2, 2] OF INTEGER) RETURNS ARRAY[2, 2] OF INTEGER + DECLARE C : ARRAY[ROWS(A), COLUMNS(B)] OF INTEGER + FOR I <- 0 TO ROWS(A) + FOR J <- 0 TO COLUMNS(B) + C[I, J] <- 0 + FOR K <- 0 TO COLUMNS(A) + C[I, J] <- C[I, J] + A[I, K] * B[K, J] + NEXT K + NEXT J + NEXT I + RETURN C +ENDFUNCTION +DECLARE A, B, C : ARRAY[2, 2] OF INTEGER +A[0, 0] <- 1 +A[0, 1] <- 2 +A[1, 0] <- 3 +A[1, 1] <- 4 +B[0, 0] <- 5 +B[0, 1] <- 6 +B[1, 0] <- 7 +B[1, 1] <- 8 +C <- MATMUL(A, B) +OUTPUT C[0, 0], " ", C[0, 1] +OUTPUT C[1, 0], " ", C[1, 1] diff --git a/tests/corpus/12-records.pseudo b/tests/corpus/12-records.pseudo new file mode 100644 index 0000000..17aa54f --- /dev/null +++ b/tests/corpus/12-records.pseudo @@ -0,0 +1,37 @@ +// Records in a LIST, a FUNCTION over them, and "find the best". +// EXPECT: Bob +// EXPECT: 86.5 +TYPE Student + DECLARE Name : STRING + DECLARE Marks : LIST OF INTEGER +ENDTYPE +FUNCTION MEAN(Xs : LIST OF INTEGER) RETURNS FLOAT + REQUIRE LENGTH(Xs) >= 1 + DECLARE Total : INTEGER + Total <- 0 + FOR EACH X IN Xs + Total <- Total + X + NEXT X + RETURN Total / LENGTH(Xs) +ENDFUNCTION +FUNCTION TOP(Ss : LIST OF Student) RETURNS Student + REQUIRE LENGTH(Ss) >= 1 + DECLARE Best : Student + Best <- Ss[0] + FOR EACH S IN Ss + IF MEAN(S.Marks) > MEAN(Best.Marks) THEN + Best <- S + ENDIF + NEXT S + RETURN Best +ENDFUNCTION +DECLARE A, B : Student +DECLARE Class : LIST OF Student +A.Name <- "Ann" +A.Marks <- [70, 80, 90] +B.Name <- "Bob" +B.Marks <- [88, 85] +APPEND(Class, A) +APPEND(Class, B) +OUTPUT TOP(Class).Name +OUTPUT MEAN(TOP(Class).Marks) diff --git a/tests/corpus/13-stack-brackets.pseudo b/tests/corpus/13-stack-brackets.pseudo new file mode 100644 index 0000000..a8b6890 --- /dev/null +++ b/tests/corpus/13-stack-brackets.pseudo @@ -0,0 +1,25 @@ +// A LIST used as a stack: APPEND to push, REMOVE the last to pop. Balanced brackets. +// EXPECT: TRUE +// EXPECT: FALSE +// EXPECT: FALSE +FUNCTION BALANCED(S : STRING) RETURNS BOOL + DECLARE Stack : LIST OF CHAR + DECLARE Pairs : HASHMAP OF CHAR : CHAR + Pairs[')'] <- '(' + Pairs[']'] <- '[' + Pairs['}'] <- '{' + FOR EACH C IN S + IF C == '(' OR C == '[' OR C == '{' THEN + APPEND(Stack, C) + ELSEIF C IN Pairs THEN + IF LENGTH(Stack) == 0 OR Stack[LENGTH(Stack) - 1] != Pairs[C] THEN + RETURN FALSE + ENDIF + REMOVE(Stack, LENGTH(Stack) - 1) + ENDIF + NEXT C + RETURN LENGTH(Stack) == 0 +ENDFUNCTION +OUTPUT BALANCED("{[()()]}") +OUTPUT BALANCED("([)]") +OUTPUT BALANCED("((") diff --git a/tests/corpus/14-queue-bfs.pseudo b/tests/corpus/14-queue-bfs.pseudo new file mode 100644 index 0000000..26b296e --- /dev/null +++ b/tests/corpus/14-queue-bfs.pseudo @@ -0,0 +1,30 @@ +// Graph flavor: breadth-first search with a LIST as a queue (REMOVE at 0) and a SET of seen nodes. +// Finding: a neighbour cannot be called Next, because names ignore case and NEXT is a keyword. +// EXPECT: [0, 1, 2, 3, 4] +FUNCTION BFS(Adj : HASHMAP OF INTEGER : LIST OF INTEGER, Start : INTEGER) RETURNS LIST OF INTEGER + DECLARE Queue, Order : LIST OF INTEGER + DECLARE Seen : SET OF INTEGER + APPEND(Queue, Start) + ADD(Seen, Start) + WHILE LENGTH(Queue) > 0 + DECLARE Node : INTEGER + Node <- Queue[0] + REMOVE(Queue, 0) + APPEND(Order, Node) + IF Node IN Adj THEN + FOR EACH Nb IN Adj[Node] + IF NOT (Nb IN Seen) THEN + ADD(Seen, Nb) + APPEND(Queue, Nb) + ENDIF + NEXT Nb + ENDIF + ENDWHILE + RETURN Order +ENDFUNCTION +DECLARE G : HASHMAP OF INTEGER : LIST OF INTEGER +G[0] <- [1, 2] +G[1] <- [3] +G[2] <- [3, 4] +G[3] <- [4] +OUTPUT BFS(G, 0) diff --git a/tests/corpus/15-game-of-life.pseudo b/tests/corpus/15-game-of-life.pseudo new file mode 100644 index 0000000..260b930 --- /dev/null +++ b/tests/corpus/15-game-of-life.pseudo @@ -0,0 +1,49 @@ +// Simulation flavor: one step of Conway's Life on a small two-dimensional ARRAY; a blinker turns. +// Finding: the function cannot be called STEP, nor the new grid Next: both are keywords, whatever their case. +// EXPECT: 0 1 0 +// EXPECT: 0 1 0 +// EXPECT: 0 1 0 +FUNCTION NEIGHBOURS(G : ARRAY[3, 3] OF INTEGER, R : INTEGER, C : INTEGER) RETURNS INTEGER + DECLARE N : INTEGER + N <- 0 + FOR DR <- -1 TO 2 + FOR DC <- -1 TO 2 + IF NOT (DR == 0 AND DC == 0) THEN + IF R + DR >= 0 AND R + DR < ROWS(G) AND C + DC >= 0 AND C + DC < COLUMNS(G) THEN + N <- N + G[R + DR, C + DC] + ENDIF + ENDIF + NEXT DC + NEXT DR + RETURN N +ENDFUNCTION +FUNCTION LIFE_STEP(G : ARRAY[3, 3] OF INTEGER) RETURNS ARRAY[3, 3] OF INTEGER + DECLARE After : ARRAY[3, 3] OF INTEGER + FOR R <- 0 TO 3 + FOR C <- 0 TO 3 + DECLARE N : INTEGER + N <- NEIGHBOURS(G, R, C) + IF G[R, C] == 1 AND (N == 2 OR N == 3) THEN + After[R, C] <- 1 + ELSEIF G[R, C] == 0 AND N == 3 THEN + After[R, C] <- 1 + ELSE + After[R, C] <- 0 + ENDIF + NEXT C + NEXT R + RETURN After +ENDFUNCTION +DECLARE G : ARRAY[3, 3] OF INTEGER +FOR R <- 0 TO 3 + FOR C <- 0 TO 3 + G[R, C] <- 0 + NEXT C +NEXT R +G[1, 0] <- 1 +G[1, 1] <- 1 +G[1, 2] <- 1 +G <- LIFE_STEP(G) +FOR R <- 0 TO 3 + OUTPUT G[R, 0], " ", G[R, 1], " ", G[R, 2] +NEXT R diff --git a/tests/corpus/16-running-stats.pseudo b/tests/corpus/16-running-stats.pseudo new file mode 100644 index 0000000..0ba569a --- /dev/null +++ b/tests/corpus/16-running-stats.pseudo @@ -0,0 +1,29 @@ +// Statistics flavor: mean and variance in one pass (Welford), returning two values through a record. +// EXPECT: 5.0 +// EXPECT: 4.0 +TYPE Stats + DECLARE Mean : FLOAT + DECLARE Variance : FLOAT +ENDTYPE +FUNCTION RUNNING(Xs : LIST OF FLOAT) RETURNS Stats + REQUIRE LENGTH(Xs) >= 2 + DECLARE N : INTEGER + DECLARE Mean, M2, Delta : FLOAT + DECLARE Out : Stats + N <- 0 + Mean <- 0.0 + M2 <- 0.0 + FOR EACH X IN Xs + N <- N + 1 + Delta <- X - Mean + Mean <- Mean + Delta / N + M2 <- M2 + Delta * (X - Mean) + NEXT X + Out.Mean <- Mean + Out.Variance <- M2 / N + RETURN Out +ENDFUNCTION +DECLARE S : Stats +S <- RUNNING([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]) +OUTPUT S.Mean +OUTPUT S.Variance diff --git a/tests/corpus/17-case-grades.pseudo b/tests/corpus/17-case-grades.pseudo new file mode 100644 index 0000000..69f8100 --- /dev/null +++ b/tests/corpus/17-case-grades.pseudo @@ -0,0 +1,17 @@ +// CASE with half-open ranges on a FLOAT, and OTHERWISE. +// EXPECT: A +// EXPECT: B +// EXPECT: F +FUNCTION GRADE(Score : FLOAT) RETURNS STRING + DECLARE G : STRING + CASE OF Score + 90 TO 101 : G <- "A" + 80 TO 90 : G <- "B" + 70 TO 80 : G <- "C" + OTHERWISE : G <- "F" + ENDCASE + RETURN G +ENDFUNCTION +OUTPUT GRADE(95.5) +OUTPUT GRADE(80.0) +OUTPUT GRADE(12.0) diff --git a/tests/corpus/18-repeat-input.pseudo b/tests/corpus/18-repeat-input.pseudo new file mode 100644 index 0000000..9dd50e4 --- /dev/null +++ b/tests/corpus/18-repeat-input.pseudo @@ -0,0 +1,10 @@ +// REPEAT ... UNTIL with INPUT, validating until a legal value arrives. +// INPUT: 55 +// INPUT: -3 +// INPUT: 20 +// EXPECT: 20 +DECLARE Threshold : INTEGER +REPEAT + INPUT Threshold +UNTIL Threshold >= 0 AND Threshold <= 40 +OUTPUT Threshold diff --git a/tests/corpus/19-max-subarray.pseudo b/tests/corpus/19-max-subarray.pseudo new file mode 100644 index 0000000..4534448 --- /dev/null +++ b/tests/corpus/19-max-subarray.pseudo @@ -0,0 +1,16 @@ +// Kadane: find the best, with an early return for the empty case. +// EXPECT: 6 +// EXPECT: -1 +FUNCTION MAX_SUBARRAY(Xs : LIST OF INTEGER) RETURNS INTEGER + REQUIRE LENGTH(Xs) >= 1 + DECLARE Best, Here : INTEGER + Best <- Xs[0] + Here <- Xs[0] + FOR I <- 1 TO LENGTH(Xs) + Here <- MAX(Xs[I], Here + Xs[I]) + Best <- MAX(Best, Here) + NEXT I + RETURN Best +ENDFUNCTION +OUTPUT MAX_SUBARRAY([-2, 1, -3, 4, -1, 2, 1, -5, 4]) +OUTPUT MAX_SUBARRAY([-1]) diff --git a/tests/corpus/20-two-sum.pseudo b/tests/corpus/20-two-sum.pseudo new file mode 100644 index 0000000..77963a0 --- /dev/null +++ b/tests/corpus/20-two-sum.pseudo @@ -0,0 +1,18 @@ +// A HASHMAP from value to position: the lookup pattern every interview asks for. +// EXPECT: [0, 2] +// EXPECT: [] +FUNCTION TWO_SUM(Xs : LIST OF INTEGER, Target : INTEGER) RETURNS LIST OF INTEGER + DECLARE Seen : HASHMAP OF INTEGER : INTEGER + DECLARE Answer : LIST OF INTEGER + FOR I <- 0 TO LENGTH(Xs) + IF Target - Xs[I] IN Seen THEN + APPEND(Answer, Seen[Target - Xs[I]]) + APPEND(Answer, I) + RETURN Answer + ENDIF + Seen[Xs[I]] <- I + NEXT I + RETURN Answer +ENDFUNCTION +OUTPUT TWO_SUM([3, 5, 7, 9], 10) +OUTPUT TWO_SUM([1, 2], 10) diff --git a/tests/corpus/21-sets.pseudo b/tests/corpus/21-sets.pseudo new file mode 100644 index 0000000..11ccc41 --- /dev/null +++ b/tests/corpus/21-sets.pseudo @@ -0,0 +1,17 @@ +// SETs: fixed with DEFINE, growing with ADD, membership, LENGTH, SORTED. +// EXPECT: TRUE +// EXPECT: FALSE +// EXPECT: 4 +// EXPECT: ["ACG", "CGT", "GTA", "TAC"] +TYPE BaseSet = SET OF CHAR +DEFINE Purines ('A', 'G') : BaseSet +OUTPUT 'A' IN Purines +OUTPUT 'C' IN Purines +DECLARE Seen : SET OF STRING +DECLARE T : STRING +T <- "ACGTACG" +FOR I <- 0 TO LENGTH(T) - 3 + 1 + ADD(Seen, SLICE(T, I, I + 3)) +NEXT I +OUTPUT LENGTH(Seen) +OUTPUT SORTED(Seen) diff --git a/tests/corpus/22-binary-to-decimal.pseudo b/tests/corpus/22-binary-to-decimal.pseudo new file mode 100644 index 0000000..4fcb091 --- /dev/null +++ b/tests/corpus/22-binary-to-decimal.pseudo @@ -0,0 +1,25 @@ +// Number bases: a STRING of digits read left to right, and the reverse with DIV and MOD. +// EXPECT: 13 +// EXPECT: 1101 +FUNCTION FROM_BINARY(S : STRING) RETURNS INTEGER + DECLARE V : INTEGER + V <- 0 + FOR EACH C IN S + V <- V * 2 + TO_INTEGER(C) + NEXT C + RETURN V +ENDFUNCTION +FUNCTION TO_BINARY(N : INTEGER) RETURNS STRING + REQUIRE N >= 1 + DECLARE S : STRING + DECLARE M : INTEGER + S <- "" + M <- N + WHILE M > 0 + S <- TO_STRING(M MOD 2) & S + M <- M DIV 2 + ENDWHILE + RETURN S +ENDFUNCTION +OUTPUT FROM_BINARY("1101") +OUTPUT TO_BINARY(13) diff --git a/tests/corpus/23-dice.pseudo b/tests/corpus/23-dice.pseudo new file mode 100644 index 0000000..f703bc8 --- /dev/null +++ b/tests/corpus/23-dice.pseudo @@ -0,0 +1,17 @@ +// Randomness: RANDINT in a loop and a tally; the lab seeds its random numbers so a run repeats. +// EXPECT: 100 +DECLARE Tally : ARRAY[7] OF INTEGER +DECLARE Total : INTEGER +FOR F <- 0 TO 7 + Tally[F] <- 0 +NEXT F +FOR Roll <- 0 TO 100 + DECLARE Face : INTEGER + Face <- RANDINT(1, 7) + Tally[Face] <- Tally[Face] + 1 +NEXT Roll +Total <- 0 +FOR F <- 1 TO 7 + Total <- Total + Tally[F] +NEXT F +OUTPUT Total diff --git a/tests/corpus/24-string-builtins.pseudo b/tests/corpus/24-string-builtins.pseudo new file mode 100644 index 0000000..7017559 --- /dev/null +++ b/tests/corpus/24-string-builtins.pseudo @@ -0,0 +1,17 @@ +// What the notation offers for text: SLICE, &, UPPER, LOWER, ORD, CHR, TO_STRING, TO_INTEGER. +// EXPECT: ATT +// EXPECT: GATTACA! +// EXPECT: hello +// EXPECT: DNA +// EXPECT: 65 +// EXPECT: B +// EXPECT: 42 apples +// EXPECT: 43 +OUTPUT SLICE("GATTACA", 1, 4) +OUTPUT "GATTACA" & "!" +OUTPUT LOWER("HeLLo") +OUTPUT UPPER("dna") +OUTPUT ORD('A') +OUTPUT CHR(66) +OUTPUT TO_STRING(42) & " apples" +OUTPUT TO_INTEGER("42") + 1 diff --git a/tests/corpus/25-nested-collections.pseudo b/tests/corpus/25-nested-collections.pseudo new file mode 100644 index 0000000..1f25d91 --- /dev/null +++ b/tests/corpus/25-nested-collections.pseudo @@ -0,0 +1,20 @@ +// A HASHMAP of LISTs built up, then printed in sorted key order with KEYS. +// Finding: the list cannot be called Keys, because built-in names are reserved whatever their case. +// EXPECT: a: [1, 3] +// EXPECT: b: [2] +DECLARE Groups : HASHMAP OF STRING : LIST OF INTEGER +DECLARE Ks : LIST OF STRING +DECLARE Names : LIST OF STRING +DECLARE Values : LIST OF INTEGER +Names <- ["a", "b", "a"] +Values <- [1, 2, 3] +FOR I <- 0 TO LENGTH(Names) + IF NOT (Names[I] IN Groups) THEN + Groups[Names[I]] <- [] + ENDIF + APPEND(Groups[Names[I]], Values[I]) +NEXT I +Ks <- KEYS(Groups) +FOR EACH K IN Ks + OUTPUT K & ": " & TO_STRING(Groups[K]) +NEXT K diff --git a/tests/corpus/26-swap-byref.pseudo b/tests/corpus/26-swap-byref.pseudo new file mode 100644 index 0000000..3fd1c9e --- /dev/null +++ b/tests/corpus/26-swap-byref.pseudo @@ -0,0 +1,22 @@ +// BYREF versus by value, side by side. +// EXPECT: 2 1 +// EXPECT: 2 1 +PROCEDURE SWAP(BYREF X : INTEGER, BYREF Y : INTEGER) + DECLARE Temp : INTEGER + Temp <- X + X <- Y + Y <- Temp +ENDPROCEDURE +PROCEDURE TRY_SWAP(X : INTEGER, Y : INTEGER) + DECLARE Temp : INTEGER + Temp <- X + X <- Y + Y <- Temp +ENDPROCEDURE +DECLARE A, B : INTEGER +A <- 1 +B <- 2 +CALL SWAP(A, B) +OUTPUT A, " ", B +CALL TRY_SWAP(A, B) +OUTPUT A, " ", B diff --git a/tests/corpus/27-quantifiers.pseudo b/tests/corpus/27-quantifiers.pseudo new file mode 100644 index 0000000..4d06ae7 --- /dev/null +++ b/tests/corpus/27-quantifiers.pseudo @@ -0,0 +1,11 @@ +// The reasoning sublanguage used as values: FORALL, EXISTS, SUM, and a set written by rule. +// EXPECT: TRUE +// EXPECT: FALSE +// EXPECT: 15 +// EXPECT: 3 +DECLARE L : LIST OF INTEGER +L <- [1, 2, 3, 4, 5] +OUTPUT FORALL K IN [0, LENGTH(L)) : L[K] > 0 +OUTPUT EXISTS K IN [0, LENGTH(L)) : L[K] > 10 +OUTPUT SUM K IN [0, LENGTH(L)) : L[K] +OUTPUT LENGTH({ K IN [0, LENGTH(L)) : L[K] MOD 2 == 1 }) diff --git a/tests/corpus/28-float-trap.pseudo b/tests/corpus/28-float-trap.pseudo new file mode 100644 index 0000000..147414f --- /dev/null +++ b/tests/corpus/28-float-trap.pseudo @@ -0,0 +1,7 @@ +// What FLOAT does and does not promise. +// EXPECT: FALSE +// EXPECT: TRUE +// EXPECT: 0.30000000000000004 +OUTPUT 0.1 + 0.2 == 0.3 +OUTPUT ABS((0.1 + 0.2) - 0.3) < 0.000001 +OUTPUT 0.1 + 0.2 diff --git a/tests/corpus/29-early-exit-flag.pseudo b/tests/corpus/29-early-exit-flag.pseudo new file mode 100644 index 0000000..26b6156 --- /dev/null +++ b/tests/corpus/29-early-exit-flag.pseudo @@ -0,0 +1,38 @@ +// Linear search three ways: with a flag, with BREAK, with RETURN; all three agree. +// EXPECT: 2 2 2 +// EXPECT: -1 -1 -1 +FUNCTION FIND_FLAG(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER + DECLARE Found, I : INTEGER + Found <- -1 + I <- 0 + WHILE I < LENGTH(Xs) AND Found == -1 + IF Xs[I] == X THEN + Found <- I + ENDIF + I <- I + 1 + ENDWHILE + RETURN Found +ENDFUNCTION +FUNCTION FIND_BREAK(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER + DECLARE Found : INTEGER + Found <- -1 + FOR I <- 0 TO LENGTH(Xs) + IF Xs[I] == X THEN + Found <- I + BREAK + ENDIF + NEXT I + RETURN Found +ENDFUNCTION +FUNCTION FIND_RETURN(Xs : LIST OF INTEGER, X : INTEGER) RETURNS INTEGER + FOR I <- 0 TO LENGTH(Xs) + IF Xs[I] == X THEN + RETURN I + ENDIF + NEXT I + RETURN -1 +ENDFUNCTION +DECLARE L : LIST OF INTEGER +L <- [4, 8, 15, 16] +OUTPUT FIND_FLAG(L, 15), " ", FIND_BREAK(L, 15), " ", FIND_RETURN(L, 15) +OUTPUT FIND_FLAG(L, 7), " ", FIND_BREAK(L, 7), " ", FIND_RETURN(L, 7) diff --git a/tests/corpus/30-state-machine.pseudo b/tests/corpus/30-state-machine.pseudo new file mode 100644 index 0000000..a5d4c6a --- /dev/null +++ b/tests/corpus/30-state-machine.pseudo @@ -0,0 +1,37 @@ +// A state machine over a STRING: does a token look like a decimal number? CASE on a STRING state. +// EXPECT: TRUE +// EXPECT: TRUE +// EXPECT: FALSE +// EXPECT: FALSE +FUNCTION IS_NUMBER(S : STRING) RETURNS BOOL + DECLARE State : STRING + State <- "start" + FOR EACH C IN S + CASE OF State + "start" : IF C >= '0' AND C <= '9' THEN + State <- "int" + ELSE + State <- "bad" + ENDIF + "int" : IF C == '.' THEN + State <- "dot" + ELSEIF NOT (C >= '0' AND C <= '9') THEN + State <- "bad" + ENDIF + "dot" : IF C >= '0' AND C <= '9' THEN + State <- "frac" + ELSE + State <- "bad" + ENDIF + "frac" : IF NOT (C >= '0' AND C <= '9') THEN + State <- "bad" + ENDIF + OTHERWISE : State <- "bad" + ENDCASE + NEXT C + RETURN State == "int" OR State == "frac" +ENDFUNCTION +OUTPUT IS_NUMBER("42") +OUTPUT IS_NUMBER("3.14") +OUTPUT IS_NUMBER("3.") +OUTPUT IS_NUMBER("x1") diff --git a/tests/corpus/31-edges.pseudo b/tests/corpus/31-edges.pseudo new file mode 100644 index 0000000..ab55d10 --- /dev/null +++ b/tests/corpus/31-edges.pseudo @@ -0,0 +1,20 @@ +// Edge semantics every reader should know: chained comparisons, string order, MIN of a list, SORT of text, nested lists. +// EXPECT: TRUE +// EXPECT: TRUE +// EXPECT: 1 +// EXPECT: ["apple", "fig", "pear"] +// EXPECT: 6 +// EXPECT: FALSE +DECLARE I : INTEGER +I <- 3 +OUTPUT 0 <= I < 5 +OUTPUT "apple" < "banana" +OUTPUT MIN([4, 1, 9]) +DECLARE Fruit : LIST OF STRING +Fruit <- ["pear", "apple", "fig"] +SORT(Fruit) +OUTPUT Fruit +DECLARE Grid : LIST OF LIST OF INTEGER +Grid <- [[1, 2, 3], [4, 5, 6]] +OUTPUT Grid[1][2] +OUTPUT "" IN Fruit diff --git a/tests/corpus/32-stops.pseudo b/tests/corpus/32-stops.pseudo new file mode 100644 index 0000000..1d6ce00 --- /dev/null +++ b/tests/corpus/32-stops.pseudo @@ -0,0 +1,7 @@ +// A run that stops: reading one past the end. The lab names the position and the length. +// STOPS: index +DECLARE T : STRING +T <- "GATTACA" +FOR I <- 0 TO LENGTH(T) + 1 + OUTPUT T[I] +NEXT I diff --git a/tests/corpus/33-stops-div.pseudo b/tests/corpus/33-stops-div.pseudo new file mode 100644 index 0000000..8220d00 --- /dev/null +++ b/tests/corpus/33-stops-div.pseudo @@ -0,0 +1,11 @@ +// A run that stops: dividing by zero inside a function; the lab blames the line and shows the values. +// STOPS: divide +FUNCTION MEAN(Xs : LIST OF INTEGER) RETURNS FLOAT + DECLARE Total : INTEGER + Total <- 0 + FOR EACH X IN Xs + Total <- Total + X + NEXT X + RETURN Total / LENGTH(Xs) +ENDFUNCTION +OUTPUT MEAN([]) diff --git a/tests/corpus/34-stops-depth.pseudo b/tests/corpus/34-stops-depth.pseudo new file mode 100644 index 0000000..d967663 --- /dev/null +++ b/tests/corpus/34-stops-depth.pseudo @@ -0,0 +1,6 @@ +// A run that stops: recursion with no base case. +// STOPS: depth +FUNCTION DOWN(N : INTEGER) RETURNS INTEGER + RETURN DOWN(N - 1) +ENDFUNCTION +OUTPUT DOWN(10) diff --git a/tests/corpus/35-stops-unset.pseudo b/tests/corpus/35-stops-unset.pseudo new file mode 100644 index 0000000..9a1defc --- /dev/null +++ b/tests/corpus/35-stops-unset.pseudo @@ -0,0 +1,4 @@ +// A run that stops: a declared name read before anything is stored in it. +// STOPS: unset +DECLARE Total : INTEGER +OUTPUT Total + 1 diff --git a/tests/corpus/36-stops-counter.pseudo b/tests/corpus/36-stops-counter.pseudo new file mode 100644 index 0000000..8ca7402 --- /dev/null +++ b/tests/corpus/36-stops-counter.pseudo @@ -0,0 +1,6 @@ +// A run that stops: a FOR counter read after its loop. +// STOPS: unset +DECLARE I : INTEGER +FOR I <- 0 TO 3 +NEXT I +OUTPUT I diff --git a/tests/corpus/37-static-errors.pseudo b/tests/corpus/37-static-errors.pseudo new file mode 100644 index 0000000..94517d9 --- /dev/null +++ b/tests/corpus/37-static-errors.pseudo @@ -0,0 +1,14 @@ +// What the checker refuses before anything runs. Each line below is one mistake the guide names. +// ERRORS: 5 +DECLARE T : STRING +DECLARE N : INTEGER +T <- "GATTACA" +N <- 7 / 2 +T[0] <- 'C' +IF T[0] == "G" THEN + OUTPUT "g" +ENDIF +FOR I <- 0 TO 3 + I <- I + 1 +NEXT I +N = 5 diff --git a/tests/corpus/38-continue.pseudo b/tests/corpus/38-continue.pseudo new file mode 100644 index 0000000..1833f18 --- /dev/null +++ b/tests/corpus/38-continue.pseudo @@ -0,0 +1,11 @@ +// CONTINUE skips a pass; here, unknown bases are not evidence. +// EXPECT: 6 +DECLARE Total : INTEGER +Total <- 0 +FOR EACH B IN "GATNACA" + IF B == 'N' THEN + CONTINUE + ENDIF + Total <- Total + 1 +NEXT B +OUTPUT Total diff --git a/tests/corpus/39-constants-codons.pseudo b/tests/corpus/39-constants-codons.pseudo new file mode 100644 index 0000000..61fa79b --- /dev/null +++ b/tests/corpus/39-constants-codons.pseudo @@ -0,0 +1,29 @@ +// CONSTANT names a number once; STEP walks codon starts; a HASHMAP codon table; a SET of stops. +// EXPECT: MAK +CONSTANT BasesPerCodon = 3 +FUNCTION TRANSLATE(T : STRING) RETURNS STRING + DECLARE Table : HASHMAP OF STRING : CHAR + DECLARE Stops : SET OF STRING + DECLARE Out : STRING + Table["ATG"] <- 'M' + Table["GCC"] <- 'A' + Table["AAA"] <- 'K' + ADD(Stops, "TAG") + ADD(Stops, "TAA") + ADD(Stops, "TGA") + Out <- "" + FOR I <- 0 TO LENGTH(T) - BasesPerCodon + 1 STEP BasesPerCodon + DECLARE Codon : STRING + Codon <- SLICE(T, I, I + BasesPerCodon) + IF Codon IN Stops THEN + BREAK + ENDIF + IF Codon IN Table THEN + Out <- Out & Table[Codon] + ELSE + Out <- Out & '?' + ENDIF + NEXT I + RETURN Out +ENDFUNCTION +OUTPUT TRANSLATE("ATGGCCAAATAGTTT") diff --git a/tests/corpus/40-text-builtins.pseudo b/tests/corpus/40-text-builtins.pseudo new file mode 100644 index 0000000..1fc74a3 --- /dev/null +++ b/tests/corpus/40-text-builtins.pseudo @@ -0,0 +1,24 @@ +// The four text built-ins added after the stress test: SPLIT, JOIN, INDEX_OF, REPLACE. +// EXPECT: ["the", "quick", "", "brown", "fox"] +// EXPECT: the quick brown fox +// EXPECT: 3 -1 2 +// EXPECT: GAUUACA +// EXPECT: read_1:GAT +FUNCTION WORDS(S : STRING) RETURNS LIST OF STRING + DECLARE Out : LIST OF STRING + FOR EACH W IN SPLIT(S, " ") + IF LENGTH(W) > 0 THEN + APPEND(Out, W) + ENDIF + NEXT W + RETURN Out +ENDFUNCTION +DECLARE S : STRING +S <- "the quick brown fox" +OUTPUT SPLIT(S, " ") +OUTPUT JOIN(WORDS(S), " ") +OUTPUT INDEX_OF("GATTACA", "TAC"), " ", INDEX_OF("GATTACA", 'N'), " ", INDEX_OF([4, 8, 15], 15) +OUTPUT REPLACE("GATTACA", "T", "U") +DECLARE Fields : LIST OF STRING +Fields <- SPLIT("read_1\tGAT\t30", "\t") +OUTPUT Fields[0], ":", Fields[1] diff --git a/tests/corpus/41-reserved-name.pseudo b/tests/corpus/41-reserved-name.pseudo new file mode 100644 index 0000000..4845b62 --- /dev/null +++ b/tests/corpus/41-reserved-name.pseudo @@ -0,0 +1,7 @@ +// A keyword used as a name is one error per name, not a cascade: the rest of the program still parses. +// ERRORS: 2 +DECLARE Step : INTEGER +Step <- 1 +FOR EACH Next IN [1, 2] + OUTPUT Next + Step +NEXT Next diff --git a/tests/corpus/42-numerics.pseudo b/tests/corpus/42-numerics.pseudo new file mode 100644 index 0000000..e5aa8c0 --- /dev/null +++ b/tests/corpus/42-numerics.pseudo @@ -0,0 +1,17 @@ +// The numeric built-ins added for mathematics, physics, chemistry and statistics. +// EXPECT: 2 3 -3 +// EXPECT: 1.0 1.0 +// EXPECT: 10 120 +// EXPECT: 6 2.5 2.0 2.5 +// EXPECT: 4.571428571428571 2.138089935299395 +// EXPECT: 32 5.0 +// EXPECT: [0.0, 0.0, 0.0] 4 +// EXPECT: 3.0 3.142 +OUTPUT FLOOR(2.7), " ", CEIL(2.1), " ", FLOOR(-2.3) +OUTPUT ROUND(SIN(PI() / 2) * 1000) / 1000, " ", ROUND(COS(0.0) * 1000) / 1000 +OUTPUT CHOOSE(5, 2), " ", CHOOSE(10, 3) +OUTPUT SUM_OF([1, 2, 3]), " ", MEAN_OF([1, 2, 3, 4]), " ", MEDIAN_OF([3, 1, 2]), " ", MEDIAN_OF([4, 1, 3, 2]) +OUTPUT VARIANCE_OF([2, 4, 4, 4, 5, 5, 7, 9]), " ", STDEV_OF([2, 4, 4, 4, 5, 5, 7, 9]) +OUTPUT DOT([1, 2, 3], [4, 5, 6]), " ", NORM_OF([3.0, 4.0]) +OUTPUT FILL(3, 0.0), " ", LENGTH(FILL(4, 'A')) +OUTPUT LOG10(1000.0), " ", ROUND(ATAN2(1.0, 1.0) * 4 * 1000) / 1000 diff --git a/tests/corpus/43-parallel-map.pseudo b/tests/corpus/43-parallel-map.pseudo new file mode 100644 index 0000000..88cae22 --- /dev/null +++ b/tests/corpus/43-parallel-map.pseudo @@ -0,0 +1,30 @@ +// GPU thinking: a PARALLEL FOR whose passes each own one slot (a map), then a sequential reduce. +// EXPECT: [1.0, 4.0, 9.0, 16.0] +// EXPECT: 30.0 +// EXPECT: [5, 7, 9] +FUNCTION SQUARES(Xs : LIST OF FLOAT) RETURNS LIST OF FLOAT + DECLARE Out : LIST OF FLOAT + Out <- FILL(LENGTH(Xs), 0.0) + PARALLEL FOR I <- 0 TO LENGTH(Xs) + DECLARE X : FLOAT + X <- Xs[I] + Out[I] <- X * X + NEXT I + RETURN Out +ENDFUNCTION + +FUNCTION ADD_VECTORS(A : LIST OF INTEGER, B : LIST OF INTEGER) RETURNS LIST OF INTEGER + REQUIRE LENGTH(A) == LENGTH(B) + DECLARE C : LIST OF INTEGER + C <- FILL(LENGTH(A), 0) + PARALLEL FOR I <- 0 TO LENGTH(A) + C[I] <- A[I] + B[I] + NEXT I + RETURN C +ENDFUNCTION + +DECLARE Sq : LIST OF FLOAT +Sq <- SQUARES([1.0, 2.0, 3.0, 4.0]) +OUTPUT Sq +OUTPUT SUM_OF(Sq) +OUTPUT ADD_VECTORS([1, 2, 3], [4, 5, 6]) diff --git a/tests/corpus/44-parallel-race.pseudo b/tests/corpus/44-parallel-race.pseudo new file mode 100644 index 0000000..795b7b1 --- /dev/null +++ b/tests/corpus/44-parallel-race.pseudo @@ -0,0 +1,10 @@ +// A shared running total inside a PARALLEL FOR is a data race, and the lab says so. +// STOPS: race +DECLARE Xs : LIST OF FLOAT +DECLARE Acc : FLOAT +Xs <- [1.0, 2.0, 3.0] +Acc <- 0.0 +PARALLEL FOR I <- 0 TO LENGTH(Xs) + Acc <- Acc + Xs[I] +NEXT I +OUTPUT Acc diff --git a/tests/corpus/45-parallel-neighbour-race.pseudo b/tests/corpus/45-parallel-neighbour-race.pseudo new file mode 100644 index 0000000..9ba399b --- /dev/null +++ b/tests/corpus/45-parallel-neighbour-race.pseudo @@ -0,0 +1,8 @@ +// Reading a neighbour that another pass writes is also a race, even with no shared scalar. +// STOPS: race +DECLARE A : LIST OF INTEGER +A <- [5, 6, 7, 8] +PARALLEL FOR I <- 0 TO 3 + A[I] <- A[I + 1] +NEXT I +OUTPUT A diff --git a/tests/corpus/46-projectile.pseudo b/tests/corpus/46-projectile.pseudo new file mode 100644 index 0000000..eb01ba0 --- /dev/null +++ b/tests/corpus/46-projectile.pseudo @@ -0,0 +1,25 @@ +// Physics: where a projectile lands, by stepping Newton's laws, against the closed form. +// EXPECT: 10.2 10.2 +FUNCTION RANGE_BY_STEPS(Speed : FLOAT, Angle : FLOAT, Dt : FLOAT) RETURNS FLOAT + DECLARE X, Y, Vx, Vy, G : FLOAT + G <- 9.81 + X <- 0.0 + Y <- 0.0 + Vx <- Speed * COS(Angle) + Vy <- Speed * SIN(Angle) + REPEAT + X <- X + Vx * Dt + Y <- Y + Vy * Dt + Vy <- Vy - G * Dt + UNTIL Y <= 0.0 + RETURN X +ENDFUNCTION + +FUNCTION RANGE_EXACT(Speed : FLOAT, Angle : FLOAT) RETURNS FLOAT + RETURN Speed * Speed * SIN(2.0 * Angle) / 9.81 +ENDFUNCTION + +DECLARE Angle : FLOAT +Angle <- PI() / 4 +// Stepping forward overshoots a little, so compare to one decimal place. +OUTPUT ROUND(RANGE_BY_STEPS(10.0, Angle, 0.0001) * 10) / 10, " ", ROUND(RANGE_EXACT(10.0, Angle) * 10) / 10 diff --git a/tests/corpus/47-binomial-and-ph.pseudo b/tests/corpus/47-binomial-and-ph.pseudo new file mode 100644 index 0000000..fa67a97 --- /dev/null +++ b/tests/corpus/47-binomial-and-ph.pseudo @@ -0,0 +1,22 @@ +// Probability and chemistry: a binomial probability from CHOOSE, and pH from LOG10. +// EXPECT: 0.2461 +// EXPECT: 1.0 +// EXPECT: 3.0 7.0 +FUNCTION BINOMIAL(N : INTEGER, K : INTEGER, P : FLOAT) RETURNS FLOAT + REQUIRE 0 <= K AND K <= N + RETURN CHOOSE(N, K) * P ^ K * (1.0 - P) ^ (N - K) +ENDFUNCTION + +FUNCTION PH(Concentration : FLOAT) RETURNS FLOAT + REQUIRE Concentration > 0.0 + RETURN -LOG10(Concentration) +ENDFUNCTION + +DECLARE Sum : FLOAT +Sum <- 0.0 +FOR K <- 0 TO 11 + Sum <- Sum + BINOMIAL(10, K, 0.5) +NEXT K +OUTPUT ROUND(BINOMIAL(10, 5, 0.5) * 10000) / 10000 +OUTPUT ROUND(Sum * 1000) / 1000 +OUTPUT PH(0.001), " ", PH(0.0000001) diff --git a/tests/corpus/48-declare-with-value.pseudo b/tests/corpus/48-declare-with-value.pseudo new file mode 100644 index 0000000..823d086 --- /dev/null +++ b/tests/corpus/48-declare-with-value.pseudo @@ -0,0 +1,32 @@ +// Declaring with a starting value on one line, beside the two-line form, at the top, in a routine, and in a loop. +// EXPECT: 3 +// EXPECT: 7 3 +// EXPECT: a <- b +// EXPECT: 6 +// EXPECT: 2 +FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER + DECLARE N : INTEGER <- LENGTH(T) + DECLARE Total : INTEGER <- 0 // the running total + FOR I <- 0 TO N + IF T[I] == B THEN + Total <- Total + 1 + ENDIF + NEXT I + RETURN Total +ENDFUNCTION +DECLARE Seq : STRING <- "GATTACA" +DECLARE Count : INTEGER +Count <- COUNT_BASE('A', Seq) +OUTPUT Count +DECLARE Len : INTEGER <- LENGTH(Seq) +OUTPUT Len, " ", Count +DECLARE Arrow : STRING <- "a <- b" +OUTPUT Arrow +DECLARE Sum : INTEGER <- 0 +FOR K <- 0 TO 3 + DECLARE Twice : INTEGER <- 2 * K + Sum <- Sum + Twice +NEXT K +OUTPUT Sum +DECLARE Xs : LIST OF INTEGER <- [4, 9] +OUTPUT LENGTH(Xs) diff --git a/tests/course-css.test.mjs b/tests/course-css.test.mjs new file mode 100644 index 0000000..b36ed2b --- /dev/null +++ b/tests/course-css.test.mjs @@ -0,0 +1,27 @@ +// The course stylesheets in styles/course/ are copies of the course site's files. +// Each must still have the hash its README records, so a change is made upstream and copied, not edited here. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import crypto from 'node:crypto'; + +const DIR = new URL('../styles/course/', import.meta.url); + +test('the course stylesheets are the course site\'s files, unchanged', () => { + const readme = fs.readFileSync(new URL('README.md', DIR), 'utf8'); + const rows = [...readme.matchAll(/^\| `([\w-]+\.css)` \| `static\/css\/[^`]+` \|[^|]*\| `([0-9a-f]{64})` \|$/gm)]; + assert.deepEqual(rows.map((r) => r[1]).sort(), ['asm86.css', 'kit.css', 'tokens.css']); + for (const [, file, want] of rows) { + const got = crypto.createHash('sha256').update(fs.readFileSync(new URL(file, DIR))).digest('hex'); + assert.equal(got, want, `styles/course/${file} differs from the copy the README records`); + } +}); + +test('the bridge supplies every page variable the course stylesheets read', () => { + const bridge = fs.readFileSync(new URL('bridge.css', DIR), 'utf8'); + const read = new Set(); + for (const f of ['tokens.css', 'kit.css', 'asm86.css']) { + for (const m of fs.readFileSync(new URL(f, DIR), 'utf8').matchAll(/var\((--bs-[\w-]+)/g)) read.add(m[1]); + } + for (const v of read) assert.match(bridge, new RegExp(`${v}\\s*:`), `bridge.css does not set ${v}`); +}); diff --git a/tests/curriculum.test.mjs b/tests/curriculum.test.mjs new file mode 100644 index 0000000..f3588e5 --- /dev/null +++ b/tests/curriculum.test.mjs @@ -0,0 +1,117 @@ +// The lesson corpus verifies the interpreter: the dependency map must be strict and every program must run. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { LESSONS, CONCEPTS, CONCEPT_BY_ID, FLAVORS, teacherOf, prerequisitesOf, depthOf, allPrerequisitesOf, statusOf, solutionOf, starterOf } from '../dist/curriculum/index.js'; +import { studyOf, runPseudo } from '../dist/services/pseudo.js'; +import { problemById } from '../dist/core/catalog.js'; + +const conceptIds = new Set(CONCEPTS.map((c) => c.id)); +const flavorIds = new Set(FLAVORS.map((f) => f.id)); + +test('lesson ids are unique and every concept id is real', () => { + const ids = new Set(); + for (const L of LESSONS) { + assert.ok(!ids.has(L.id), `duplicate lesson id ${L.id}`); ids.add(L.id); + for (const c of [...L.teaches, ...L.requires]) assert.ok(conceptIds.has(c), `${L.id} names unknown concept ${c}`); + assert.ok(L.teaches.length >= 1, `${L.id} teaches nothing`); + assert.ok(L.purpose.length > 20 && L.explanation.length >= 3 && L.checks.length >= 2 && L.flavors.length >= 2, `${L.id} is thin`); + for (const f of L.flavors) assert.ok(flavorIds.has(f.id), `${L.id} has unknown flavor ${f.id}`); + for (const c of L.checks) assert.ok(c.answer >= 0 && c.answer < c.options.length, `${L.id} check answer out of range`); + for (const p of L.problems || []) assert.ok(problemById(p), `${L.id} points at missing problem ${p}`); + if (L.showAsmOf) assert.ok(problemById(L.showAsmOf)?.sources.asm, `${L.id} shows asm of a problem without any`); + } +}); + +test('every concept is taught by exactly one lesson, and every concept is used', () => { + for (const c of CONCEPTS) { + const teachers = LESSONS.filter((l) => l.teaches.includes(c.id)); + assert.equal(teachers.length, 1, `${c.id} is taught by ${teachers.map((l) => l.id).join(', ') || 'nobody'}`); + } + // every foundations and core concept must feed a later lesson; only advanced concepts may be frontier + const required = new Set(LESSONS.flatMap((l) => l.requires)); + for (const L of LESSONS.filter((l) => l.stage !== 'advanced')) for (const c of L.teaches) assert.ok(required.has(c), `${c} (from ${L.id}) is never required by a later lesson`); +}); + +test('the dependency map is strict: every requirement is taught by an earlier lesson, and there are no cycles', () => { + const seen = new Set(); + for (const L of LESSONS) { + for (const c of L.requires) { + const t = teacherOf(c); + assert.ok(t, `${L.id} requires ${c}, which nothing teaches`); + assert.ok(seen.has(t.id), `${L.id} requires ${c}, taught by ${t.id}, which comes later in the order`); + assert.ok(!L.teaches.includes(c), `${L.id} both teaches and requires ${c}`); + } + seen.add(L.id); + } + for (const L of LESSONS) assert.ok(depthOf(L) >= 0, `${L.id} is in a cycle`); + const roots = LESSONS.filter((l) => l.requires.length === 0); + assert.equal(roots.length, 1, `exactly one lesson should assume nothing: ${roots.map((l) => l.id).join(', ')}`); + for (const L of LESSONS.slice(1)) assert.ok(allPrerequisitesOf(L).some((p) => p.id === roots[0].id), `${L.id} does not trace back to ${roots[0].id}`); +}); + +test('a lesson is available exactly when every prerequisite lesson is done', () => { + const none = { done: [], checks: {} }; + const first = LESSONS[0]; + assert.equal(statusOf(first, none), 'available'); + assert.equal(statusOf(LESSONS[LESSONS.length - 1], none), 'locked'); + const last = LESSONS[LESSONS.length - 1]; + const all = { done: allPrerequisitesOf(last).map((l) => l.id), checks: {} }; + assert.equal(statusOf(last, all), 'available'); + const direct = prerequisitesOf(last)[0].id; + const butOne = { done: all.done.filter((id) => id !== direct), checks: {} }; + assert.notEqual(statusOf(last, butOne), 'available'); + const order = ['foundations', 'core', 'advanced']; + for (const L of LESSONS) for (const p of prerequisitesOf(L)) assert.ok(order.indexOf(p.stage) <= order.indexOf(L.stage), `${L.id} depends on a later stage`); +}); + +function runProgram(label, prog) { + const st = studyOf(solutionOf(prog)); + const errs = st.diagnostics.filter((d) => d.severity === 'error'); + assert.equal(errs.length, 0, `${label}: ${errs.map((d) => `L${d.line} ${d.id}: ${d.message}`).join(' | ')}`); + const tr = runPseudo(st, { input: prog.input || [], maxSteps: 200000 }); + const out = tr.output.filter((l) => !/^\w+ returned /.test(l)); + if (prog.stops) { assert.equal(tr.error?.kind, prog.stops, `${label}: expected a ${prog.stops} stop, got ${tr.error?.kind || 'none'}`); } + else assert.equal(tr.error, null, `${label}: ${tr.error?.message}`); + assert.deepEqual(out, prog.expect, label); + return st; +} + +for (const L of LESSONS) { + test(`lesson ${L.id}: the example and every flavor run and print what they say`, () => { + runProgram(`${L.id}/example`, L.example); + for (const f of L.flavors) { + runProgram(`${L.id}/${f.id}`, f.solution); + const starter = f.starter ?? starterOf(f.solution); + assert.ok(starter.length > 0); + if (!f.starter) assert.ok(/\/\/ TODO:/.test(starter) || !/\/\/ ~/.test(f.solution.pseudo), `${L.id}/${f.id}: starter has no blanks`); + assert.ok(!/\/\/ ~/.test(starter), `${L.id}/${f.id}: marker leaked into the starter`); + assert.ok(!/\/\/ ~/.test(solutionOf(f.solution)), `${L.id}/${f.id}: marker leaked into the solution`); + } + }); +} + +test('a starter blanks exactly the marked lines', () => { + const p = { pseudo: 'A <- 1\nB <- 2 // ~ set B\nC <- 3', expect: [] }; + assert.equal(starterOf(p), 'A <- 1\n// TODO: set B\nC <- 3'); + assert.equal(solutionOf(p), 'A <- 1\nB <- 2\nC <- 3'); +}); + +test('every lesson uses only keywords its prerequisites (or it) have introduced', () => { + // a rough but real check: the statement keyword that introduces a concept must not appear + // in a lesson that neither teaches nor (transitively) requires that concept + const introduces = { + 'IF': 'selection', 'FOR': 'for-loop', 'WHILE': 'while', 'REPEAT': 'repeat', 'FUNCTION': 'function', 'PROCEDURE': 'procedure-sub', 'BYREF': 'byref', 'CASE': 'case', + 'HASHMAP': 'hashmap', 'SET': 'set', 'TYPE': 'record', 'ARRAY': 'array', 'INVARIANT': 'invariant', 'ENSURE': 'specification', 'BREAK': 'early-exit', 'CONTINUE': 'early-exit', 'INPUT': 'io', + }; + const exempt = { 'sets': ['TYPE'], 'what-stops-a-run': ['FUNCTION'] }; + const violations = []; // TYPE … = SET OF is the set lesson's own form; the stops lesson reviews a function + for (const L of LESSONS) { + const held = new Set([...L.teaches, ...allPrerequisitesOf(L).flatMap((p) => p.teaches), ...L.requires]); + const programs = [L.example.pseudo, ...L.flavors.flatMap((f) => [f.solution.pseudo, f.starter || ''])].join('\n'); + for (const [kw, concept] of Object.entries(introduces)) { + if ((exempt[L.id] || []).includes(kw)) continue; + if (new RegExp(`(^|[^\\w])${kw}\\b`, 'm').test(programs.replace(/"[^"]*"/g, '""').replace(/\/\/.*$/gm, '')) && !held.has(concept)) violations.push(`${L.id} uses ${kw} but neither teaches nor requires ${concept}`); + } + } + assert.deepEqual(violations, []); +}); diff --git a/tests/editor.test.mjs b/tests/editor.test.mjs new file mode 100644 index 0000000..e5101bc --- /dev/null +++ b/tests/editor.test.mjs @@ -0,0 +1,31 @@ +// Every code pane is the CodeMirror editor (src/ui/editor.ts), never a plain